polotno 4.16.1 → 4.18.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/element.js +1 -1
- package/canvas/figure-element.js +1 -1
- package/canvas/gif-element.js +1 -1
- package/canvas/html-element.js +1 -1
- package/canvas/image-element.d.ts +15 -2
- package/canvas/image-element.js +1 -1
- package/canvas/line-element.js +1 -1
- package/canvas/page.js +1 -1
- package/canvas/placed-node.d.ts +22 -0
- package/canvas/placed-node.js +1 -0
- package/canvas/render-tag-element.js +1 -1
- package/canvas/rich-editor.js +2 -2
- package/canvas/table-element.js +1 -1
- package/canvas/text-element/auto-delete-empty-text.d.ts +15 -0
- package/canvas/text-element/auto-delete-empty-text.js +1 -0
- package/canvas/text-element/font-specs-loader.js +1 -1
- package/canvas/text-element.js +1 -1
- package/canvas/use-color.d.ts +2 -4
- package/canvas/use-color.js +1 -1
- package/canvas/use-image.js +1 -1
- package/canvas/video-element.js +1 -1
- package/canvas/workspace-canvas.js +1 -1
- package/model/group-model.d.ts +7 -0
- package/model/group-model.js +1 -1
- package/model/history.js +1 -1
- package/model/page-model.d.ts +15 -0
- package/model/page-model.js +1 -1
- package/model/store.d.ts +10 -7
- package/model/store.js +1 -1
- package/model/table-model.d.ts +3 -0
- package/model/table-model.js +1 -1
- package/package.json +20 -19
- package/pages-timeline/element-track.js +1 -1
- package/pages-timeline/page-preview.d.ts +9 -2
- package/pages-timeline/page-preview.js +1 -1
- package/polotno.bundle.js +171 -171
- package/side-panel/animations-panel.js +1 -1
- package/side-panel/text-panel.js +1 -1
- package/side-panel/text-template.js +1 -1
- package/utils/duplicate.js +1 -1
- package/utils/fonts.js +1 -1
- package/utils/from-svg.js +1 -1
- package/utils/image-dpi.js +1 -1
- package/utils/loader.js +1 -1
- package/utils/px.d.ts +1 -0
- package/utils/px.js +1 -1
- package/utils/ref-counted.d.ts +5 -0
- package/utils/ref-counted.js +1 -0
- package/utils/validate-key.js +1 -1
- package/utils/wait.d.ts +0 -1
- package/utils/wait.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
var t=this&&this.__rest||function(t,e){var o={};for(var r in t){Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(o[r]=t[r])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(r=Object.getOwnPropertySymbols(t);n<r.length;n++){e.indexOf(r[n])<0&&Object.prototype.propertyIsEnumerable.call(t,r[n])&&(o[r[n]]=t[r[n]])}}return o};import{jsx as e,Fragment as o,jsxs as r}from"react/jsx-runtime";import{elementOpacity as n}from"./paint-opacity.js";import i from"react";import{observer as a}from"mobx-react-lite";import{Group as l,Path as s,Rect as c,Shape as d}from"react-konva";import{nodeAutorun as u}from"../utils/mobx.js";import{isAlive as h}from"mobx-state-tree";import{Html as f}from"react-konva-utils";import{drawLayout as g}from"render-tag";import{drawTextOnPathLayout as m}from"render-tag/path";import{activeAnchorOf as b,isCornerAnchor as p,scaledFontSizeAttrs as x,scaledFontSizeBounds as y,roundedFontSizeAttrs as v,roundedTextDecorationAttrs as w,scaledStyleAttrs as z,roundedGeometryPx as E,roundedPosition as O,textMinResizeWidth as j}from"../utils/px.js";import{flags as S}from"../utils/flags.js";import{editorTextSizing as M,textOverflowOf as k,textResizeFloorFontSize as R}from"../utils/text-sizing.js";import{curvedBoxWidth as F,layoutCurvedTextSizing as Y,layoutTextSizing as X,renderTagLayoutAt as C}from"@polotno/core/text-sizing";import{curveLayoutAt as I}from"@polotno/core/curve-glyphs";import{applyFilter as P}from"./apply-filters.js";import{getLineHeight as B,usePrevious as T}from"./text-element.js";import{useFontSpecsLoader as A}from"./text-element/font-specs-loader.js";import{getHtml as H,getCurveTextHeight as N,letterSpacingOverhang as D}from"@polotno/core/text-html";import{useColor as W,withDisplayTextPaints as $}from"./use-color.js";import{toDisplayColor as _}from"@polotno/core/color";import{detectSize as J}from"@polotno/core/measure-html";import{generateBackgroundShapeFromRects as L,trimTrailingLetterSpace as V}from"@polotno/core/background-shape";import{useFadeIn as q}from"./use-fadein.js";import{incrementLoader as G}from"../utils/loader.js";import{removeTags as K}from"@polotno/core/text";import{shadowCastByBackground as Q}from"@polotno/core/filters";import{applyOpacityToColor as U}from"@polotno/core/svg";import{isTouchDevice as Z}from"../utils/screen.js";import{getLimitedFontSize as tt}from"./text-element/max-font-size.js";import{normalizeRichTextHtml as et,extractFontSpecsFromHtml as ot,scaleRichTextFontSizesInHtml as rt}from"../utils/rich-text-html.js";import{RichEditor as nt}from"./rich-editor.js";import{visiblePlaceholder as it}from"./text-element/placeholder.js";import{wrapHtmlForRenderTag as at}from"@polotno/core/reset-style";import{xmlEscape as lt}from"@polotno/core/xml";import{hasMeasuredHeight as st,resolveTextBoxHeight as ct}from"@polotno/core/text-types";export{at as wrapHtmlForRenderTag};function dt(t,e){return t!==e&&(!S.textVerticalResizeEnabled||t<e)}export const RenderTagElement=a(({element:a,store:at})=>{var ut,ht,ft,gt,mt,bt,pt,xt,yt,vt,wt;const zt=i.useRef(null),Et=i.useRef(null),[Ot,jt]=i.useState(!1),St=i.useRef(a.height),Mt=i.useRef(null),kt=a.isSelected,Rt=T(kt),{textVerticalResizeEnabled:Ft}=S,Yt=S.autoDeleteEmptyText,Xt=T(a.fontFamily),Ct=i.useMemo(()=>et(a.text,{fontSize:a.fontSize,fontFamily:a.fontFamily}),[a.text,a.fontSize,a.fontFamily]),It=i.useMemo(()=>ot(Ct,{fontFamily:a.fontFamily,fontWeight:a.fontWeight,fontStyle:a.fontStyle}),[Ct,a.fontFamily,a.fontWeight,a.fontStyle]),[Pt]=A(at,It,a.text||a.placeholder),Bt=a._editModeEnabled;q(zt);const Tt=Pt?a.fontFamily:Xt&&Xt!==a.fontFamily?Xt:"Arial",At=W(a).fill,Ht=it(a.placeholder),Nt=!!Ht&&!K(a.text),Dt=Nt?lt(Ht):Ct,Wt=Nt?.6:n(a),$t=H($(a),{fontFamily:Tt,color:At,forEditor:!0,text:Dt,textIsNormalized:!0}),_t=a.width||1,Jt=t=>C($(t),{getHtmlOptions:{fontFamily:Tt,color:At,forEditor:!0,text:Dt,textIsNormalized:!0}}),Lt=k(a),Vt=M(a),qt=a.curveEnabled,Gt=JSON.stringify(Vt),Kt="fixed"===Vt.box?a.height:0,Qt=Ot?Mt.current:null,Ut=i.useMemo(()=>{if(Qt){return Qt.sized}const t=Nt?Object.assign(Object.assign({},a),{text:Dt}):a;try{return qt?Object.assign({curved:!0},Y({element:t,sizing:Vt,layoutAt:I($(a),{getHtmlOptions:{fontFamily:Tt,color:At,text:Dt,textIsNormalized:!0}})})):Object.assign({curved:!1},X({element:t,sizing:Vt,layoutAt:Jt(a)}))}catch(e){return console.error("render-tag layout failed:",e),null}},[$t,_t,Pt,qt,Gt,Kt,a.curvePower,a.fontSize,a.width,Qt]),Zt=null!==(ut=null==Qt?void 0:Qt.width)&&void 0!==ut?ut:_t,te=Qt?a.width/Qt.width:1,ee=!1===(null==Ut?void 0:Ut.curved)?Ut.layout:null,oe=(null==Ut?void 0:Ut.curved)?Ut.layout:null,re=null!==(ht=null==Ut?void 0:Ut.fontSize)&&void 0!==ht?ht:a.fontSize,ne=null!==(ft=null==Ut?void 0:Ut.scale)&&void 0!==ft?ft:1,ie=D(a.letterSpacing,re),ae=null!==(gt=null==Qt?void 0:Qt.overhang)&&void 0!==gt?gt:ie,le=B({fontLoaded:Pt,fontFamily:a.fontFamily,fontSize:re,lineHeight:a.lineHeight}),se=qt?0:Math.max(null!==(mt=null==ee?void 0:ee.height)&&void 0!==mt?mt:0,re*le),ce=oe?oe.bounds:null,de=ce?(a.width-ce.width)/2-ce.x:0,ue=i.useMemo(()=>{var t;if(oe&&ce){const t=oe.paintBounds;return Object.assign(Object.assign({},t),{x:t.x+de,y:t.y-ce.y})}return null!==(t=null==ee?void 0:ee.paintBounds)&&void 0!==t?t:null},[ee,oe,ce,de]),he=i.useMemo(()=>ee?ee.lines.map(t=>V({left:t.bounds.x,right:t.bounds.x+t.bounds.width,top:t.bounds.y,bottom:t.bounds.y+t.bounds.height},ae)):[],[ee,ae]),fe=i.useRef([]),ge=i.useRef(null),me=i.useRef(!0),[,be]=i.useReducer(t=>t+1,0);i.useEffect(()=>{const t=fe.current;t.length>0&&(fe.current=[],t.forEach(t=>t()))});const pe=i.useCallback((t,e,o,r)=>{const n=G(`text ${a.id}`),i=()=>{at.history.ignore(t,e,o).then(()=>{me.current?(fe.current.push(n),be()):n()})};r?queueMicrotask(i):i()},[a.id,at]),xe=i.useCallback(t=>{const e=null!==ge.current;ge.current=t,e||pe(()=>{const t=ge.current;ge.current=null,h(a)&&dt(a.height,t)&&a.set({height:t})},!1,!0)},[a,pe]),ye=i.useRef(Ut);ye.current=Ut,i.useEffect(()=>{if(!Pt){return}if(!ee){return}if(!st(a)){return void pe(()=>{h(a)&&(st(a)||a.set({height:se}))},void 0,void 0,!0)}if(at.isPlaying){return}const t=dt(a.height,se),e=()=>xe(se);if("change-font-size"!==Lt||Ot||Bt||a.curveEnabled){"resize"===Lt&&t&&!Ot&&e()}else if(Ut&&Ut.fontSize!==a.fontSize){const{fontSize:t,text:e}=Ut;pe(()=>{if(!h(a)){return}if(ye.current!==Ut||"change-font-size"!==k(a)||a._editModeEnabled){return}const o=x(a,t);Nt||e===a.text||(o.text=e),a.set(o)},!1,!0)}else{t&&e()}}),i.useEffect(()=>()=>{me.current=!1;const t=fe.current;t.length>0&&(fe.current=[],t.forEach(t=>t()))},[]),i.useLayoutEffect(()=>{if(!Pt||!a.curveEnabled||Ot){return}if(!ce||!ce.width){return}const t=t=>t&&Ft?Math.max(t,ce.height):ce.height,e=t=>F(Vt,{width:t},ce.width);Math.abs(e(a.width)-a.width)<1&&Math.abs(t(a.height)-a.height)<1||pe(()=>{if(!h(a)){return}const o=e(a.width),r=o-a.width,n=t(a.height),i=n-a.height;if(Math.abs(r)<1&&Math.abs(i)<1){return}const l=a.a.rotation*Math.PI/180,s=-r/2*Math.cos(l),c=-r/2*Math.sin(l);a.set({width:o,height:n,x:a.a.x+s,y:a.a.y+c})},!1,!0,!0)},[Pt,a.curveEnabled,Lt,ce,Ot,Ft,pe]),i.useEffect(()=>{Rt&&!kt&&Yt&&""===K(a.text)&&a.removable&&!it(a.placeholder)&&at.deleteElements([a.id])},[Yt,a.placeholder,a.removable,a.text,kt,Rt]),i.useEffect(()=>u(a,()=>{const t=zt.current;t&&P(t,a)}),[ee,oe,a.a.width,a.a.height,a.shadowColor,a.shadowOffsetX,a.shadowOffsetY,a.shadowOpacity]);const ve=ct(a,se),we=qt||!Pt||Ot||at.isPlaying||"resize"!==Lt?a.a.height:Ft?Math.max(a.a.height,se):se;let ze=0;qt||"middle"!==a.verticalAlign?qt||"bottom"!==a.verticalAlign||(ze=ve-se*te):ze=(ve-se*te)/2;const Ee=null!==(bt=null==Qt?void 0:Qt.backgroundPadding)&&void 0!==bt?bt:a.backgroundPadding*(re*le*.5),Oe=null!==(pt=null==Qt?void 0:Qt.backgroundCornerRadius)&&void 0!==pt?pt:a.backgroundCornerRadius*(re*le*.5),je=a.backgroundEnabled||a.borderSize>0,Se=i.useMemo(()=>!je||a.curveEnabled||a.legacyBackground||0===he.length?"":L({rects:he,padding:Ee,cornerRadius:Oe}),[je,a.curveEnabled,a.legacyBackground,he,Ee,Oe]),Me=Z(),ke=i.useRef(null),Re=i.useRef(a.width),Fe=i.useRef(null),Ye=i.useRef(null),Xe=i.useRef(""),Ce=i.useRef(0),Ie=i.useRef(0),Pe=i.useRef({fontSize:a.fontSize}),Be=a.width>0?a.a.width/a.width:1,Te=Be*te,Ae=null!==(xt=null==Qt?void 0:Qt.shadow)&&void 0!==xt?xt:{shadowBlur:a.shadowBlur*ne,shadowOffsetX:a.shadowOffsetX*ne,shadowOffsetY:a.shadowOffsetY*ne},He=Object.assign(Object.assign({},Ae),{shadowColor:_(a.shadowColor),shadowOpacity:a.shadowOpacity}),Ne=Object.assign(Object.assign({},He),{shadowEnabled:a.shadowEnabled&&je});return r(o,{children:[a.curveEnabled||a.legacyBackground?e(c,Object.assign({x:a.a.x,y:a.a.y,offsetX:Ee/Be,offsetY:Ee/Be,rotation:a.a.rotation,scaleX:Te,scaleY:Te,hideInExport:!a.showInExport,listening:!1,visible:je,opacity:Wt,fillEnabled:a.backgroundEnabled,fill:U(a.backgroundColor,a.backgroundOpacity),strokeEnabled:a.borderSize>0,stroke:_(a.borderColor),strokeWidth:null!==(yt=null==Qt?void 0:Qt.borderSize)&&void 0!==yt?yt:a.borderSize},Ne,{width:Zt+2*Ee,height:(null!==(vt=null==Qt?void 0:Qt.boxHeight)&&void 0!==vt?vt:ve)+2*Ee,cornerRadius:Oe})):e(s,Object.assign({name:"rendertag-background",x:a.a.x,y:a.a.y,offsetY:-ze/Te,rotation:a.a.rotation,scaleX:Te,scaleY:Te,hideInExport:!a.showInExport,listening:!1,visible:je&&Se.length>0,opacity:Wt,fillEnabled:a.backgroundEnabled,fill:U(a.backgroundColor,a.backgroundOpacity),strokeEnabled:a.borderSize>0,stroke:_(a.borderColor),strokeWidth:null!==(wt=null==Qt?void 0:Qt.borderSize)&&void 0!==wt?wt:a.borderSize,lineJoin:Oe>0?"round":"miter"},Ne,{data:Se})),e(d,Object.assign({ref:zt,selfRectFunc:ue?()=>ue:void 0,name:"rendertag-text",x:a.a.x,y:a.a.y,rotation:a.a.rotation,scaleX:Te,scaleY:Te,offsetY:Te>0?-ze/Te:0,width:Zt,height:Math.max(a.height,se),listening:!1,visible:!Bt&&!!(qt?oe:ee),editModeEnabled:Bt,opacity:Wt,shadowEnabled:a.shadowEnabled&&!Q(a)},He,{hideInExport:!a.showInExport,sceneFunc:(t,e)=>{const o=t._context;if(o){try{if(qt){if(!oe||!ce){return}o.save(),o.translate(de,-ce.y),m({layout:oe,ctx:o}),o.restore()}else{if(!ee){return}g({layout:ee,width:Zt,ctx:o,pixelRatio:1})}}catch(r){console.error("render-tag draw failed:",r)}}}})),e(c,{ref:Et,name:"element",x:a.a.x,y:a.a.y,listening:a.selectable,rotation:a.a.rotation,width:a.a.width,height:we,visible:!Bt,draggable:Me?a.draggable&&kt:a.draggable,preventDefault:!Me||kt,opacity:0,hideInExport:!0,id:a.id,onDragMove:t=>{a.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{a.set(O(t.target))},onDblClick:t=>{a.contentEditable&&(Ye.current={x:t.evt.clientX,y:t.evt.clientY},a.toggleEditMode(!0))},onDblTap:t=>{var e;if(a.contentEditable){const o=null===(e=t.evt.changedTouches)||void 0===e?void 0:e[0];Ye.current=o?{x:o.clientX,y:o.clientY}:null,a.toggleEditMode(!0)}},onTransformStart:t=>{St.current=a.height,Re.current=a.width,Fe.current=null,ke.current=t.target.position(),Xe.current=b(t.target),Ce.current=a.a.rotation,Ie.current=a.height,Pe.current={fontSize:a.fontSize,minFontSize:a.minFontSize,maxFontSize:a.maxFontSize},Mt.current=!a.curveEnabled&&["top-left","top-right","bottom-left","bottom-right"].includes(Xe.current)?{sized:Ut,width:_t,boxHeight:ve,backgroundPadding:Ee,backgroundCornerRadius:Oe,borderSize:a.borderSize,overhang:ie,shadow:Ae}:null,jt(!0)},onTransform:e=>{const o=e.target,r=Xe.current,n="middle-left"===r||"middle-right"===r,i="top-center"===r||"bottom-center"===r,l=o.scaleX();if(n){const e=o.scaleX(),r=o.width()*e;let n=Math.max(r,j(Re.current,R(a)));const i=a.toJSON();let l=0;if("fit"===Lt){l=St.current}else if(a.curveEnabled){l=N(Object.assign(Object.assign({},i),{width:n}))}else{const{x:e,y:o,width:r,height:a}=i,s=t(i,["x","y","width","height"]),c=`${JSON.stringify(s)}|${Tt}|${Pt}|${At}`;if(Fe.current&&Fe.current.signature===c&&n<=Fe.current.width){n=Fe.current.width,l=Fe.current.height}else{const t=t=>{const e=Object.assign(Object.assign({},i),{width:t});try{return X({element:Object.assign(Object.assign({},e),{text:Dt}),sizing:Object.assign(Object.assign({},Vt),{fit:{mode:"off"},cutAtBox:!1}),layoutAt:Jt(e)}).layout}catch(ut){const o=H(e,{fontFamily:Tt,color:At,forEditor:!0,text:Dt,textIsNormalized:!0});return{height:J(o).height,lines:[]}}};let e=t(n);const o=Math.max(0,...e.lines.map(t=>t.bounds.x+t.bounds.width-ie));o>n+.5&&o<=Re.current+.5&&(n=Math.min(Math.ceil(o),Re.current),e=t(n),Fe.current={signature:c,width:n,height:e.height}),l=e.height}}n>r&&ke.current&&o.position(ke.current),o.width(n),o.scaleX(1),o.scaleY(1);let s=S.textVerticalResizeEnabled?Math.max(l,St.current):l;"ellipsis"!==Lt&&"fit"!==Lt||(s=St.current),o.height(s),a.set({width:o.width(),height:s,x:o.x(),y:o.y()})}else if(i){const t="resize"===Lt?qt?(null==ce?void 0:ce.height)||a.fontSize:se:le*("fit"===Vt.fit.mode?Vt.fit.min:a.fontSize),e=o.height()*o.scaleY();if(e<t){if(o.height(t),ke.current){if("top-center"===Xe.current){const e=Ce.current*Math.PI/180,r=Ie.current-t;o.x(ke.current.x-r*Math.sin(e)),o.y(ke.current.y+r*Math.cos(e))}else{o.position(ke.current)}}}else{o.height(e)}o.scaleY(1),o.scaleX(1),Ie.current=Math.max(t,e),a.set({x:o.x(),y:o.y(),height:o.height(),rotation:o.rotation()})}else{o.scaleX(1),o.scaleY(1);const t=a.fontSize*l;a.set(Object.assign(Object.assign(Object.assign({},y(Pe.current,t/Pe.current.fontSize)),{letterSpacing:a.letterSpacing,width:o.width()*l,x:o.x(),y:o.y(),rotation:o.rotation(),height:o.height()*l}),z(a,l)))}ke.current=e.target.position()},onTransformEnd:t=>{Mt.current=null,jt(!1);const e=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1);const o=v(a,a.fontSize*e),r=Pe.current,n=Xe.current;a.set(Object.assign(Object.assign(Object.assign({},o),p(n)&&"rotater"!==n?y(r,o.fontSize/r.fontSize,!0):{}),{width:E(t.target.width()*e),x:E(t.target.x()),y:E(t.target.y()),rotation:E(t.target.rotation()),text:rt(a.text,e)}))}}),Bt&&e(l,{x:a.a.x,y:a.a.y,rotation:a.a.rotation,offsetY:-ze,children:e(f,{divProps:{style:{zIndex:20}},children:e(nt,{element:a,fitScale:ne,fitScaleFor:t=>{if(qt){return ne}try{return X({element:Object.assign(Object.assign({},a),{text:t}),sizing:Vt,layoutAt:C($(a),{getHtmlOptions:{fontFamily:Tt,color:At,forEditor:!0,text:t}})}).scale}catch(ut){return ne}},onChange:t=>{if("fit"===Lt){return void a.set({text:t})}const e=tt({oldText:K(a.text),newText:K(t),element:a});a.set(Object.assign({text:t},x(a,e)))},onBlur:()=>{h(a)&&(a.set(w(a)),a.toggleEditMode(!1))},clickCoords:Ye.current})})})]})});
|
|
1
|
+
var t=this&&this.__rest||function(t,e){var o={};for(var r in t){Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(o[r]=t[r])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(r=Object.getOwnPropertySymbols(t);n<r.length;n++){e.indexOf(r[n])<0&&Object.prototype.propertyIsEnumerable.call(t,r[n])&&(o[r[n]]=t[r[n]])}}return o};import{jsx as e,Fragment as o,jsxs as r}from"react/jsx-runtime";import{elementOpacity as n}from"./paint-opacity.js";import i from"react";import{observer as l}from"mobx-react-lite";import{Group as s,Path as a,Rect as c,Shape as d}from"react-konva";import{nodeAutorun as u}from"../utils/mobx.js";import{isAlive as h}from"mobx-state-tree";import{Html as f}from"react-konva-utils";import{drawLayout as g}from"render-tag";import{drawTextOnPathLayout as m}from"render-tag/path";import{activeAnchorOf as b,isCornerAnchor as p,scaledFontSizeAttrs as x,scaledFontSizeBounds as y,roundedFontSizeAttrs as w,roundedTextDecorationAttrs as v,scaledStyleAttrs as z,roundedGeometryPx as O,roundedPosition as j,textMinResizeWidth as E,transformScale as S}from"../utils/px.js";import{flags as M}from"../utils/flags.js";import{editorTextSizing as k,textOverflowOf as R,textResizeFloorFontSize as F}from"../utils/text-sizing.js";import{curvedBoxWidth as Y,layoutCurvedTextSizing as C,layoutTextSizing as I,renderTagLayoutAt as X}from"@polotno/core/text-sizing";import{curveLayoutAt as P}from"@polotno/core/curve-glyphs";import{applyFilter as B}from"./apply-filters.js";import{getLineHeight as A,usePrevious as T}from"./text-element.js";import{useFontSpecsLoader as H}from"./text-element/font-specs-loader.js";import{getHtml as N,getCurveTextHeight as D,letterSpacingOverhang as W}from"@polotno/core/text-html";import{useColor as $,withDisplayTextPaints as _}from"./use-color.js";import{toDisplayColor as J}from"@polotno/core/color";import{detectSize as L}from"@polotno/core/measure-html";import{generateBackgroundShapeFromRects as V,trimTrailingLetterSpace as q}from"@polotno/core/background-shape";import{useFadeIn as G}from"./use-fadein.js";import{incrementLoader as K}from"../utils/loader.js";import{removeTags as Q}from"@polotno/core/text";import{shadowCastByBackground as U}from"@polotno/core/filters";import{applyOpacityToColor as Z}from"@polotno/core/svg";import{isTouchDevice as tt}from"../utils/screen.js";import{getLimitedFontSize as et}from"./text-element/max-font-size.js";import{normalizeRichTextHtml as ot,extractFontSpecsFromHtml as rt,scaleRichTextFontSizesInHtml as nt}from"../utils/rich-text-html.js";import{RichEditor as it}from"./rich-editor.js";import{visiblePlaceholder as lt}from"./text-element/placeholder.js";import{PlacedNode as st}from"./placed-node.js";import{AutoDeleteEmptyText as at}from"./text-element/auto-delete-empty-text.js";import{wrapHtmlForRenderTag as ct}from"@polotno/core/reset-style";import{xmlEscape as dt}from"@polotno/core/xml";import{hasMeasuredHeight as ut,resolveTextBoxHeight as ht}from"@polotno/core/text-types";export{ct as wrapHtmlForRenderTag};function ft(t,e){return t!==e&&(!M.textVerticalResizeEnabled||t<e)}export const RenderTagElement=l(({element:l,store:ct})=>{var gt,mt,bt,pt,xt,yt,wt,vt,zt,Ot,jt;const Et=i.useRef(null),St=i.useRef(null),[Mt,kt]=i.useState(!1),Rt=i.useRef(l.height),Ft=i.useRef(null),Yt=tt(),{textVerticalResizeEnabled:Ct}=M,It=T(l.fontFamily),Xt=i.useMemo(()=>ot(l.text,{fontSize:l.fontSize,fontFamily:l.fontFamily}),[l.text,l.fontSize,l.fontFamily]),Pt=i.useMemo(()=>rt(Xt,{fontFamily:l.fontFamily,fontWeight:l.fontWeight,fontStyle:l.fontStyle}),[Xt,l.fontFamily,l.fontWeight,l.fontStyle]),[Bt]=H(ct,Pt,l.text||l.placeholder),At=l._editModeEnabled;G(Et);const Tt=Bt?l.fontFamily:It&&It!==l.fontFamily?It:"Arial",Ht=$(l).fill,Nt=lt(l.placeholder),Dt=!!Nt&&!Q(l.text),Wt=Dt?dt(Nt):Xt,$t=Dt?.6:n(l),_t=N(_(l),{fontFamily:Tt,color:Ht,forEditor:!0,text:Wt,textIsNormalized:!0}),Jt=l.width||1,Lt=t=>X(_(t),{getHtmlOptions:{fontFamily:Tt,color:Ht,forEditor:!0,text:Wt,textIsNormalized:!0}}),Vt=R(l),qt=k(l),Gt=l.curveEnabled,Kt=JSON.stringify(qt),Qt="fixed"===qt.box?l.height:0,Ut=Mt?Ft.current:null,Zt=i.useMemo(()=>{if(Ut){return Ut.sized}const t=Dt?Object.assign(Object.assign({},l),{text:Wt}):l;try{return Gt?Object.assign({curved:!0},C({element:t,sizing:qt,layoutAt:P(_(l),{getHtmlOptions:{fontFamily:Tt,color:Ht,text:Wt,textIsNormalized:!0}})})):Object.assign({curved:!1},I({element:t,sizing:qt,layoutAt:Lt(l)}))}catch(e){return console.error("render-tag layout failed:",e),null}},[_t,Jt,Bt,Gt,Kt,Qt,l.curvePower,l.fontSize,l.width,Ut]),te=null!==(gt=null==Ut?void 0:Ut.width)&&void 0!==gt?gt:Jt,ee=Ut?l.width/Ut.width:1,oe=!1===(null==Zt?void 0:Zt.curved)?Zt.layout:null,re=(null==Zt?void 0:Zt.curved)?Zt.layout:null,ne=null!==(mt=null==Zt?void 0:Zt.fontSize)&&void 0!==mt?mt:l.fontSize,ie=null!==(bt=null==Zt?void 0:Zt.scale)&&void 0!==bt?bt:1,le=W(l.letterSpacing,ne),se=null!==(pt=null==Ut?void 0:Ut.overhang)&&void 0!==pt?pt:le,ae=A({fontLoaded:Bt,fontFamily:l.fontFamily,fontSize:ne,lineHeight:l.lineHeight}),ce=Gt?0:Math.max(null!==(xt=null==oe?void 0:oe.height)&&void 0!==xt?xt:0,ne*ae),de=re?re.bounds:null,ue=de?(l.width-de.width)/2-de.x:0,he=i.useMemo(()=>{var t;if(re&&de){const t=re.paintBounds;return Object.assign(Object.assign({},t),{x:t.x+ue,y:t.y-de.y})}return null!==(t=null==oe?void 0:oe.paintBounds)&&void 0!==t?t:null},[oe,re,de,ue]),fe=i.useMemo(()=>oe?oe.lines.map(t=>q({left:t.bounds.x,right:t.bounds.x+t.bounds.width,top:t.bounds.y,bottom:t.bounds.y+t.bounds.height},se)):[],[oe,se]),ge=i.useRef([]),me=i.useRef(null),be=i.useRef(!0),[,pe]=i.useReducer(t=>t+1,0);i.useEffect(()=>{const t=ge.current;t.length>0&&(ge.current=[],t.forEach(t=>t()))});const xe=i.useCallback((t,e,o,r)=>{const n=K(`text ${l.id}`),i=()=>{ct.history.ignore(t,e,o).then(()=>{be.current?(ge.current.push(n),pe()):n()})};r?queueMicrotask(i):i()},[l.id,ct]),ye=i.useCallback(t=>{const e=null!==me.current;me.current=t,e||xe(()=>{const t=me.current;me.current=null,h(l)&&ft(l.height,t)&&l.set({height:t})},!1,!0)},[l,xe]),we=i.useRef(Zt);we.current=Zt,i.useEffect(()=>{if(!Bt){return}if(!oe){return}if(!ut(l)){return void xe(()=>{h(l)&&(ut(l)||l.set({height:ce}))},void 0,void 0,!0)}if(ct.isPlaying){return}const t=ft(l.height,ce),e=()=>ye(ce);if("change-font-size"!==Vt||Mt||At||l.curveEnabled){"resize"===Vt&&t&&!Mt&&e()}else if(Zt&&Zt.fontSize!==l.fontSize){const{fontSize:t,text:e}=Zt;xe(()=>{if(!h(l)){return}if(we.current!==Zt||"change-font-size"!==R(l)||l._editModeEnabled){return}const o=x(l,t);Dt||e===l.text||(o.text=e),l.set(o)},!1,!0)}else{t&&e()}}),i.useEffect(()=>()=>{be.current=!1;const t=ge.current;t.length>0&&(ge.current=[],t.forEach(t=>t()))},[]),i.useLayoutEffect(()=>{if(!Bt||!l.curveEnabled||Mt){return}if(!de||!de.width){return}const t=t=>t&&Ct?Math.max(t,de.height):de.height,e=t=>Y(qt,{width:t},de.width);Math.abs(e(l.width)-l.width)<1&&Math.abs(t(l.height)-l.height)<1||xe(()=>{if(!h(l)){return}const o=e(l.width),r=o-l.width,n=t(l.height),i=n-l.height;if(Math.abs(r)<1&&Math.abs(i)<1){return}const s=l.a.rotation*Math.PI/180,a=-r/2*Math.cos(s),c=-r/2*Math.sin(s);l.set({width:o,height:n,x:l.a.x+a,y:l.a.y+c})},!1,!0,!0)},[Bt,l.curveEnabled,Vt,de,Mt,Ct,xe]),i.useEffect(()=>u(l,()=>{const t=Et.current;t&&B(t,l)}),[oe,re,l.a.width,l.a.height,l.shadowColor,l.shadowOffsetX,l.shadowOffsetY,l.shadowOpacity]);const ve=ht(l,ce),ze=Gt||!Bt||Mt||ct.isPlaying||"resize"!==Vt?l.a.height:Ct?Math.max(l.a.height,ce):ce;let Oe=0;Gt||"middle"!==l.verticalAlign?Gt||"bottom"!==l.verticalAlign||(Oe=ve-ce*ee):Oe=(ve-ce*ee)/2;const je=null!==(yt=null==Ut?void 0:Ut.backgroundPadding)&&void 0!==yt?yt:l.backgroundPadding*(ne*ae*.5),Ee=null!==(wt=null==Ut?void 0:Ut.backgroundCornerRadius)&&void 0!==wt?wt:l.backgroundCornerRadius*(ne*ae*.5),Se=l.backgroundEnabled||l.borderSize>0,Me=i.useMemo(()=>!Se||l.curveEnabled||l.legacyBackground||0===fe.length?"":V({rects:fe,padding:je,cornerRadius:Ee}),[Se,l.curveEnabled,l.legacyBackground,fe,je,Ee]),ke=i.useRef(null),Re=i.useRef(l.width),Fe=i.useRef(null),Ye=i.useRef(null),Ce=i.useRef(""),Ie=i.useRef(0),Xe=i.useRef(0),Pe=i.useRef({fontSize:l.fontSize}),Be=l.width>0?l.a.width/l.width:1,Ae=Be*ee,Te=null!==(vt=null==Ut?void 0:Ut.shadow)&&void 0!==vt?vt:{shadowBlur:l.shadowBlur*ie,shadowOffsetX:l.shadowOffsetX*ie,shadowOffsetY:l.shadowOffsetY*ie},He=Object.assign(Object.assign({},Te),{shadowColor:J(l.shadowColor),shadowOpacity:l.shadowOpacity}),Ne=Object.assign(Object.assign({},He),{shadowEnabled:l.shadowEnabled&&Se});return r(o,{children:[e(at,{element:l,store:ct}),Se?l.curveEnabled||l.legacyBackground?e(st,Object.assign({as:c,element:l,offsetX:je/Be,offsetY:je/Be,scaleX:Ae,scaleY:Ae,hideInExport:!l.showInExport,listening:!1,opacity:$t,fillEnabled:l.backgroundEnabled,fill:Z(l.backgroundColor,l.backgroundOpacity),strokeEnabled:l.borderSize>0,stroke:J(l.borderColor),strokeWidth:null!==(zt=null==Ut?void 0:Ut.borderSize)&&void 0!==zt?zt:l.borderSize},Ne,{width:te+2*je,height:(null!==(Ot=null==Ut?void 0:Ut.boxHeight)&&void 0!==Ot?Ot:ve)+2*je,cornerRadius:Ee})):e(st,Object.assign({as:a,element:l,name:"rendertag-background",offsetY:-Oe/Ae,scaleX:Ae,scaleY:Ae,hideInExport:!l.showInExport,listening:!1,visible:Me.length>0,opacity:$t,fillEnabled:l.backgroundEnabled,fill:Z(l.backgroundColor,l.backgroundOpacity),strokeEnabled:l.borderSize>0,stroke:J(l.borderColor),strokeWidth:null!==(jt=null==Ut?void 0:Ut.borderSize)&&void 0!==jt?jt:l.borderSize,lineJoin:Ee>0?"round":"miter"},Ne,{data:Me})):null,e(st,Object.assign({as:d,nodeRef:Et,element:l,selfRectFunc:he?()=>he:void 0,name:"rendertag-text",scaleX:Ae,scaleY:Ae,offsetY:Ae>0?-Oe/Ae:0,width:te,height:Math.max(l.height,ce),listening:!1,visible:!At&&!!(Gt?re:oe),editModeEnabled:At,opacity:$t,shadowEnabled:l.shadowEnabled&&!U(l)},He,{hideInExport:!l.showInExport,sceneFunc:(t,e)=>{const o=t._context;if(o){try{if(Gt){if(!re||!de){return}o.save(),o.translate(ue,-de.y),m({layout:re,ctx:o}),o.restore()}else{if(!oe){return}g({layout:oe,width:te,ctx:o,pixelRatio:1})}}catch(r){console.error("render-tag draw failed:",r)}}}})),e(st,{as:c,nodeRef:St,element:l,name:"element",listening:l.selectable,width:l.a.width,height:ze,visible:!At,draggable:Yt?l.draggable&&l.isSelected:l.draggable,preventDefault:!Yt||l.isSelected,opacity:0,hideInExport:!0,id:l.id,onDragMove:t=>{l.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{l.set(j(t.target))},onDblClick:t=>{l.contentEditable&&(Ye.current={x:t.evt.clientX,y:t.evt.clientY},l.toggleEditMode(!0))},onDblTap:t=>{var e;if(l.contentEditable){const o=null===(e=t.evt.changedTouches)||void 0===e?void 0:e[0];Ye.current=o?{x:o.clientX,y:o.clientY}:null,l.toggleEditMode(!0)}},onTransformStart:t=>{Rt.current=l.height,Re.current=l.width,Fe.current=null,ke.current=t.target.position(),Ce.current=b(t.target),Ie.current=l.a.rotation,Xe.current=l.height,Pe.current={fontSize:l.fontSize,minFontSize:l.minFontSize,maxFontSize:l.maxFontSize},Ft.current=!l.curveEnabled&&["top-left","top-right","bottom-left","bottom-right"].includes(Ce.current)?{sized:Zt,width:Jt,boxHeight:ve,backgroundPadding:je,backgroundCornerRadius:Ee,borderSize:l.borderSize,overhang:le,shadow:Te}:null,kt(!0)},onTransform:e=>{const o=e.target,r=Ce.current,n="middle-left"===r||"middle-right"===r,i="top-center"===r||"bottom-center"===r,s=S(o.scaleX());if(n){const e=o.width()*s;let r=Math.max(e,E(Re.current,F(l)));const n=l.toJSON();let i=0;if("fit"===Vt){i=Rt.current}else if(l.curveEnabled){i=D(Object.assign(Object.assign({},n),{width:r}))}else{const{x:e,y:o,width:l,height:s}=n,a=t(n,["x","y","width","height"]),c=`${JSON.stringify(a)}|${Tt}|${Bt}|${Ht}`;if(Fe.current&&Fe.current.signature===c&&r<=Fe.current.width){r=Fe.current.width,i=Fe.current.height}else{const t=t=>{const e=Object.assign(Object.assign({},n),{width:t});try{return I({element:Object.assign(Object.assign({},e),{text:Wt}),sizing:Object.assign(Object.assign({},qt),{fit:{mode:"off"},cutAtBox:!1}),layoutAt:Lt(e)}).layout}catch(gt){const o=N(e,{fontFamily:Tt,color:Ht,forEditor:!0,text:Wt,textIsNormalized:!0});return{height:L(o).height,lines:[]}}};let e=t(r);const o=Math.max(0,...e.lines.map(t=>t.bounds.x+t.bounds.width-le));o>r+.5&&o<=Re.current+.5&&(r=Math.min(Math.ceil(o),Re.current),e=t(r),Fe.current={signature:c,width:r,height:e.height}),i=e.height}}r>e&&ke.current&&o.position(ke.current),o.width(r),o.scaleX(1),o.scaleY(1);let a=M.textVerticalResizeEnabled?Math.max(i,Rt.current):i;"ellipsis"!==Vt&&"fit"!==Vt||(a=Rt.current),o.height(a),l.set({width:o.width(),height:a,x:o.x(),y:o.y()})}else if(i){const t="resize"===Vt?Gt?(null==de?void 0:de.height)||l.fontSize:ce:ae*("fit"===qt.fit.mode?qt.fit.min:l.fontSize),e=o.height()*o.scaleY();if(e<t){if(o.height(t),ke.current){if("top-center"===Ce.current){const e=Ie.current*Math.PI/180,r=Xe.current-t;o.x(ke.current.x-r*Math.sin(e)),o.y(ke.current.y+r*Math.cos(e))}else{o.position(ke.current)}}}else{o.height(e)}o.scaleY(1),o.scaleX(1),Xe.current=Math.max(t,e),l.set({x:o.x(),y:o.y(),height:o.height(),rotation:o.rotation()})}else{o.scaleX(1),o.scaleY(1);const t=l.fontSize*s;l.set(Object.assign(Object.assign(Object.assign({},y(Pe.current,t/Pe.current.fontSize)),{letterSpacing:l.letterSpacing,width:o.width()*s,x:o.x(),y:o.y(),rotation:o.rotation(),height:o.height()*s}),z(l,s)))}ke.current=e.target.position()},onTransformEnd:t=>{Ft.current=null,kt(!1);const e=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1);const o=w(l,l.fontSize*e),r=Pe.current,n=Ce.current;l.set(Object.assign(Object.assign(Object.assign({},o),p(n)&&"rotater"!==n?y(r,o.fontSize/r.fontSize,!0):{}),{width:O(t.target.width()*e),x:O(t.target.x()),y:O(t.target.y()),rotation:O(t.target.rotation()),text:nt(l.text,e)}))}}),At&&e(st,{as:s,element:l,offsetY:-Oe,children:e(f,{divProps:{style:{zIndex:20}},children:e(it,{element:l,fitScale:ie,fitScaleFor:t=>{if(Gt){return ie}try{return I({element:Object.assign(Object.assign({},l),{text:t}),sizing:qt,layoutAt:X(_(l),{getHtmlOptions:{fontFamily:Tt,color:Ht,forEditor:!0,text:t}})}).scale}catch(gt){return ie}},onChange:t=>{if("fit"===Vt){return void l.set({text:t})}const e=et({oldText:Q(l.text),newText:Q(t),element:l});l.set(Object.assign({text:t},x(l,e)))},onBlur:()=>{h(l)&&(l.set(v(l)),l.toggleEditMode(!1))},clickCoords:Ye.current})})})]})});
|
package/canvas/rich-editor.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var t=this&&this.__rest||function(t,e){var o={};for(var n in t){Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(o[n]=t[n])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(t);r<n.length;r++){e.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(t,n[r])&&(o[n[r]]=t[n[r]])}}return o};import{jsx as e}from"react/jsx-runtime";import o from"react";import n from"quill";import*as r from"mobx";import{nodeReaction as i}from"../utils/mobx.js";import{isAlive as l}from"mobx-state-tree";import{getDir as s,getMeasureCtx as a,getQuillEditorHtml as c,textLayoutWidth as d}from"@polotno/core/text-html";import{quillHtmlToModelText as u,isQuillFormatMixed as f,isBoldWeight as p,detachNativeColorsInHtml as m}from"../utils/rich-text-html.js";import{toDisplayColor as h}from"@polotno/core/color";import{resetStyleContent as g,wrapHtmlForRenderTag as b}from"@polotno/core/reset-style";import{layout as v,lineBaselineOffset as y}from"render-tag";import{removeTags as x}from"@polotno/core/text";import{cssFontFamily as w}from"@polotno/core/fonts";import{isGradient as S,firstStopColor as k}from"@polotno/core/gradient";import{getOptimalCaretColor as T}from"./text-element/caret-color.js";import{visiblePlaceholder as q}from"./text-element/placeholder.js";import{registerQuillUnrestrictedFontFormats as E,PRESERVED_INLINE_STYLES as C,PRESERVED_BLOCK_STYLES as O}from"./quill-font-formats.js";import{ALL_QUILL_MIXED_KEYS as R,setActiveTextEditor as F,updateActiveTextFormat as L,clearActiveTextEditor as $,getActiveTextEditor as N}from"../utils/text-format-state.js";import j from"../utils/styled.js";import{applyOpacityToColor as
|
|
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{getDir as s,getMeasureCtx as a,getQuillEditorHtml as c,textLayoutWidth as d}from"@polotno/core/text-html";import{quillHtmlToModelText as u,isQuillFormatMixed as f,isBoldWeight as p,detachNativeColorsInHtml as m}from"../utils/rich-text-html.js";import{toDisplayColor as h}from"@polotno/core/color";import{resetStyleContent as g,wrapHtmlForRenderTag as b}from"@polotno/core/reset-style";import{layout as v,lineBaselineOffset as y}from"render-tag";import{removeTags as x}from"@polotno/core/text";import{cssFontFamily as w}from"@polotno/core/fonts";import{isGradient as S,firstStopColor as k}from"@polotno/core/gradient";import{getOptimalCaretColor as T}from"./text-element/caret-color.js";import{visiblePlaceholder as q}from"./text-element/placeholder.js";import{registerQuillUnrestrictedFontFormats as E,PRESERVED_INLINE_STYLES as C,PRESERVED_BLOCK_STYLES as O}from"./quill-font-formats.js";import{ALL_QUILL_MIXED_KEYS as R,setActiveTextEditor as F,updateActiveTextFormat as L,clearActiveTextEditor as $,getActiveTextEditor as N}from"../utils/text-format-state.js";import j from"../utils/styled.js";import{applyOpacityToColor as z}from"@polotno/core/svg";import{elementDropShadow as M,shadowCastByBackground as P}from"@polotno/core/filters";export{z as applyOpacityToColor};export const quillRef=r.observable({enabled:!1,currentFormat:{},pendingToolbarInteraction:!1,editor:r.observable.object({instance:null},{},{deep:!1})});const D=R;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 D){f(n,r)&&(o[r]=!0)}return o}(t,e);r.runInAction(()=>{quillRef.currentFormat=o}),L(o,n,e)}const H="polotno-saved-selection";function I(){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(H,new Highlight(e)),Q()}function A(){"undefined"!=typeof CSS&&CSS.highlights&&CSS.highlights.delete(H)}function Q(){setTimeout(()=>{"undefined"!=typeof CSS&&CSS.highlights&&CSS.highlights.has(H)&&(document.querySelector(".polotno-portal")||tt(document.activeElement)?Q():A())},300)}if("undefined"!=typeof document&&"undefined"!=typeof CSS&&CSS.highlights&&!document.querySelector("[data-polotno-highlight]")){const et=document.createElement("style");et.setAttribute("data-polotno-highlight",""),et.textContent=`::highlight(${H}) { background-color: Highlight; }`,document.head.appendChild(et)}function _(t,e){"text"===t.type&&e.push(t);for(const o of t.children||[]){_(o,e)}}export function computeMarkerVars(t){var e,o,n;const r=t.fontSize;if(!r||r<=0){return null}const i=w(t.fontFamily),l=p(t.fontWeight)?700:400,s="italic"===t.fontStyle?"italic":"normal",c=a();c.fontKerning="normal",c.font=`${r}px ${i}`;const d=c.measureText("M"),u=(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:${s};line-height:${t.lineHeight};letter-spacing:${t.letterSpacing}em`,h=b(`<div style="${m}"><ul><li>x</li></ul><ol><li>x</li></ol></div>`);let g;try{g=v({html:h,width:Math.max(12*r,600)})}catch(E){return null}const x=[];_(g.layoutRoot,x);const S=x.find(t=>"•"===t.text),k=x.find(t=>/^\d/.test(t.text));if(!S){return null}const T=S.style.fontSize,q=2.1*r;return{bulletLeft:S.x,bulletTop:S.y-y(T,T*u,T*f),bulletFontSize:T,numberGap:k?Math.max(0,q-k.x-(null!==(n=k.width)&&void 0!==n?n:0)):0}}export const RichTextContainer=j("div",o.forwardRef)`
|
|
2
2
|
.ql-editor {
|
|
3
3
|
outline: none;
|
|
4
4
|
/* anchor for the absolutely-positioned ::before placeholder below */
|
|
@@ -163,4 +163,4 @@ var t=this&&this.__rest||function(t,e){var o={};for(var n in t){Object.prototype
|
|
|
163
163
|
.ql-editor [style*='background-clip'] {
|
|
164
164
|
-webkit-text-stroke-width: 0;
|
|
165
165
|
}
|
|
166
|
-
`;const W=[...C,...O,"header"];let B=["background","font-weight","color","gradient","font","italic","size","script","strike","underline","text-transform","indent","list","direction",...W];export const setQuillFormats=t=>{B=t};let X=!1;function G(){X||(X=!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 V(t){return t?"700":"400"}const Y=n.import("delta"),U="data-polotno-rich-text";export const createQuill=(e,o)=>{E();const r=new n(e,{toolbar:!1,keyboard:!1,placeholder:(null==o?void 0:o.placeholder)||void 0,clipboard:{matchVisual:!1},formats:B});!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?(G(),o("font-weight",V(e),n)):o(t,e,n),e.formatText=(e,o,r,i,l)=>{if(r&&"object"==typeof r){if("bold"in r){G();const{bold:l}=r,s=t(r,["bold"]);return n(e,o,Object.assign(Object.assign({},s),{"font-weight":V(l)}),i)}return n(e,o,r,i)}return"bold"===r?(G(),n(e,o,"font-weight",V(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=p(e["font-weight"])),e}}(r);const i=(t,e)=>e.compose((new Y).retain(e.length(),{"font-weight":"700"}));r.clipboard.addMatcher("STRONG",i),r.clipboard.addMatcher("B",i);const l=r.clipboard,s=l.onPaste.bind(l);return l.onPaste=(t,e)=>{var o;if(null===(o=e.html)||void 0===o?void 0:o.includes(U)){return Z(r,()=>s(t,e))}const n=l.convert;l.convert=(...t)=>((t,e)=>{for(const o of t.ops){if(o.attributes){for(const t of e){delete o.attributes[t]}}}return t})(n.apply(l,t),W);try{return s(t,e)}finally{l.convert=n}},r};const K=(t,e)=>e.insert(t.data),J=(t,e)=>{const o=e.ops[0];return parseFloat(t.style.textIndent)>0&&"string"==typeof(null==o?void 0:o.insert)&&o.insert.startsWith("\t")?e.compose((new Y).delete(1)):e};function Z(t,e){const{matchers:o}=t.clipboard,n=o.findIndex(([t])=>t===Node.TEXT_NODE),r=o[n];-1!==n&&(o[n]=[Node.TEXT_NODE,K]),o.push([Node.ELEMENT_NODE,J]);try{return e()}finally{o.pop(),-1!==n&&(o[n]=r)}}export const setQuillContent=(t,e)=>{const o=Z(t,()=>t.clipboard.convert({html:"<div class='ql-editor' style='outline: none;'>"+e+"<p><br></p></div>",text:""}));t.setContents(o),t.history.clear()};export const editorHtml=t=>c(Object.assign(Object.assign({},t),{text:m(t.text)}),t.fontFamily);export const RichEditor=({onBlur:t,onChange:n,element:a,clickCoords:c,fitScale:f=1,fitScaleFor:p})=>{const m=o.useRef(null),g=o.useRef(!1),b=o.useRef(f);b.current=f;const[v,y]=o.useState(null),E=null!=v?v:f,C=o.useRef(p);C.current=p;const O=t=>({width:d(a.a.width/t,a.letterSpacing,a.fontSize),
|
|
166
|
+
`;const W=[...C,...O,"header"];let B=["background","font-weight","color","gradient","font","italic","size","script","strike","underline","text-transform","indent","list","direction",...W];export const setQuillFormats=t=>{B=t};let X=!1;function G(){X||(X=!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 V(t){return t?"700":"400"}const Y=n.import("delta"),U="data-polotno-rich-text";export const createQuill=(e,o)=>{E();const r=new n(e,{toolbar:!1,keyboard:!1,placeholder:(null==o?void 0:o.placeholder)||void 0,clipboard:{matchVisual:!1},formats:B});!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?(G(),o("font-weight",V(e),n)):o(t,e,n),e.formatText=(e,o,r,i,l)=>{if(r&&"object"==typeof r){if("bold"in r){G();const{bold:l}=r,s=t(r,["bold"]);return n(e,o,Object.assign(Object.assign({},s),{"font-weight":V(l)}),i)}return n(e,o,r,i)}return"bold"===r?(G(),n(e,o,"font-weight",V(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=p(e["font-weight"])),e}}(r);const i=(t,e)=>e.compose((new Y).retain(e.length(),{"font-weight":"700"}));r.clipboard.addMatcher("STRONG",i),r.clipboard.addMatcher("B",i);const l=r.clipboard,s=l.onPaste.bind(l);return l.onPaste=(t,e)=>{var o;if(null===(o=e.html)||void 0===o?void 0:o.includes(U)){return Z(r,()=>s(t,e))}const n=l.convert;l.convert=(...t)=>((t,e)=>{for(const o of t.ops){if(o.attributes){for(const t of e){delete o.attributes[t]}}}return t})(n.apply(l,t),W);try{return s(t,e)}finally{l.convert=n}},r};const K=(t,e)=>e.insert(t.data),J=(t,e)=>{const o=e.ops[0];return parseFloat(t.style.textIndent)>0&&"string"==typeof(null==o?void 0:o.insert)&&o.insert.startsWith("\t")?e.compose((new Y).delete(1)):e};function Z(t,e){const{matchers:o}=t.clipboard,n=o.findIndex(([t])=>t===Node.TEXT_NODE),r=o[n];-1!==n&&(o[n]=[Node.TEXT_NODE,K]),o.push([Node.ELEMENT_NODE,J]);try{return e()}finally{o.pop(),-1!==n&&(o[n]=r)}}export const setQuillContent=(t,e)=>{const o=Z(t,()=>t.clipboard.convert({html:"<div class='ql-editor' style='outline: none;'>"+e+"<p><br></p></div>",text:""}));t.setContents(o),t.history.clear()};export const editorHtml=t=>c(Object.assign(Object.assign({},t),{text:m(t.text)}),t.fontFamily);export const RichEditor=({onBlur:t,onChange:n,element:a,clickCoords:c,fitScale:f=1,fitScaleFor:p})=>{const m=o.useRef(null),g=o.useRef(!1),b=o.useRef(f);b.current=f;const[v,y]=o.useState(null),E=null!=v?v:f,C=o.useRef(p);C.current=p;const O=t=>({width:d(a.a.width/t,a.letterSpacing,a.fontSize),zoom:1!==t?t:void 0}),R=o.useRef(null),L=o.useRef(void 0),j=()=>`${a.text}\0${a.fontSize}\0${a.fontFamily}`,z=t=>u(t,{fontSize:a.fontSize,fontFamily:a.fontFamily}),D=t=>{setQuillContent(t,editorHtml(a)),R.current=z(t.root.innerHTML),L.current=j()},H=o.useRef(()=>{}),Q=()=>{H.current(),t()};o.useLayoutEffect(()=>{let t,e,o=!1,i=null,s=null,d=null,u=null,f=null;const p=()=>{if(!o&&m.current){try{t=createQuill(m.current,{placeholder:q(a.placeholder)}),r.runInAction(()=>{quillRef.editor.instance=t}),quillRef.pendingToolbarInteraction=!1,window.__polotnoQuill=t,F({instance:t,store:a.store,element:a});const o=e=>{e&&syncQuillFormatState(t,e)},p=()=>{let e=t.root;if(e.querySelector(".ql-cursor")){e=e.cloneNode(!0);const t=e.querySelector(".ql-cursor");t.replaceWith(t.textContent.replace(/\uFEFF/g,""))}return z(e.innerHTML)},h=()=>{const t=C.current;t&&l(a)&&(t=>{const e=m.current;if(!e){return}const o=O(t);e.style.width=`${o.width}px`,e.style.zoom=void 0===o.zoom?"":String(o.zoom)})(t(p()))},v=()=>{var o,r;if(clearTimeout(e),e=void 0,!l(a)){return}const i=p();if(i===R.current){return}R.current=i,g.current=!0,n(i);const s=t.getContents(),c=a.fill;let d=null,u=!0;for(const t of s.ops){if("string"!=typeof t.insert||"\n"===t.insert){continue}if(null===(o=t.attributes)||void 0===o?void 0:o.gradient){u=!1;break}const e=(null===(r=t.attributes)||void 0===r?void 0:r.color)||c;if(null===d){d=e}else if(e!==d){u=!1;break}}u&&d&&a.set({fill:d})};H.current=()=>{(void 0!==e||t.composition.isComposing)&&v()},t.on("text-change",()=>{const n=N(),r=n&&n.instance===t?n.lastSelection:null;o(t.getSelection()||r),t.composition.isComposing||h(),void 0===e&&(e=setTimeout(v,10))}),t.on("selection-change",o),t.on("composition-start",()=>y(b.current)),t.on("composition-end",()=>{h(),y(null)}),D(t);const x=m.current.closest(".polotno-workspace-inner"),w=null==x?void 0:x.scrollLeft,S=null==x?void 0:x.scrollTop;c?setCursorFromCoords(t,c):t.setSelection(0,0,"api"),x&&void 0!==w&&void 0!==S&&(x.scrollLeft=w,x.scrollTop=S);const k=t.root;u=t=>{const e=t.relatedTarget;(null==e?void 0:e.classList.contains("ql-clipboard"))||(tt(e)||quillRef.pendingToolbarInteraction?I():setTimeout(()=>{quillRef.pendingToolbarInteraction||tt(document.activeElement)?I():(A(),Q())},0))},f=()=>{A()},k.addEventListener("blur",u),k.addEventListener("focus",f),i=k,s=e=>{var o,n;const r=t.getSelection();if(!r||0===r.length){return}const i=t.getText(r.index,r.length).replace(/\n$/,""),l=window.getSelection();let s="";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!==k&&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),s=r.innerHTML}if(null===(o=e.clipboardData)||void 0===o||o.setData("text/plain",i),s){const t=`<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>\x3c!--StartFragment--\x3e<div ${U} style="white-space: pre-wrap; overflow-wrap: break-word;">`+s+"</div>\x3c!--EndFragment--\x3e</body></html>";null===(n=e.clipboardData)||void 0===n||n.setData("text/html",t)}e.preventDefault()},d=e=>{s&&s(e);const o=t.getSelection();o&&o.length>0&&t.deleteText(o.index,o.length)},i.addEventListener("copy",s),i.addEventListener("cut",d)}catch(p){console.error("RichEditor init failed:",p)}}};return m.current?p():queueMicrotask(p),()=>{o=!0,clearTimeout(e),i&&u&&i.removeEventListener("blur",u),i&&f&&i.removeEventListener("focus",f),A(),i&&s&&d&&(i.removeEventListener("copy",s),i.removeEventListener("cut",d)),r.runInAction(()=>{quillRef.editor.instance=null,quillRef.currentFormat={}}),$(t),delete window.__polotnoQuill}},[]),o.useEffect(()=>i(a,j,t=>{const e=quillRef.editor.instance;if(!e){return}if(g.current){return g.current=!1,void(L.current=t)}if(t===L.current){return}const o=e.getSelection();D(e),o&&(e.setSelection(o.index,o.length),syncQuillFormatState(e,e.getSelection()))},{fireImmediately:!0}),[]),o.useEffect(()=>i(a,()=>`${a.fontFamily}\0${a.fontSize}\0${a.fontWeight}\0${a.fontStyle}\0${a.lineHeight}\0${a.letterSpacing}\0${s(x(a.text))}`,()=>{const t=m.current;if(!t){return}const e="ltr"===s(x(a.text)),o=computeMarkerVars(a);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",Q);const t=t=>{var e;const o=t.target;"number"==typeof(null==o?void 0:o.nodeType)&&(null===(e=m.current)||void 0===e?void 0:e.contains(o))||tt(o)||quillRef.pendingToolbarInteraction||(A(),Q())};return window.addEventListener("mousedown",t),window.addEventListener("touchstart",t),()=>{window.removeEventListener("blur",Q),window.removeEventListener("mousedown",t),window.removeEventListener("touchstart",t)}},[]);const _=h(a.fill),W={color:_};_.indexOf("gradient")>=0&&(W["--polotno-gradient"]=_,W.color="transparent"),a.strokeWidth>0&&(W.WebkitTextStroke=`${a.strokeWidth}px ${k(a.stroke)}`,W.paintOrder="stroke fill");const B=S(a.fill)?k(a.fill):T(a),X=a.shadowEnabled&&!P(a);return e(RichTextContainer,{ref:m,style:Object.assign(Object.assign(Object.assign(Object.assign({},W),{fontSize:a.fontSize,fontFamily:w(a.fontFamily),fontWeight:a.fontWeight,fontStyle:a.fontStyle,"--polotno-text-decoration":a.textDecoration||"none",textTransform:a.textTransform}),O(E)),{lineHeight:a.lineHeight,letterSpacing:a.letterSpacing*a.fontSize+"px",textAlign:a.align,opacity:Math.max(a.a.opacity,.2),filter:X?M({shadowOffsetX:a.shadowOffsetX,shadowOffsetY:a.shadowOffsetY,shadowBlur:a.shadowBlur,shadowColor:a.shadowColor,shadowOpacity:a.shadowOpacity,rotation:a.a.rotation}):void 0,caretColor:B}),dir:s(x(a.text))})};function tt(t){const e=t;return!("function"!=typeof(null==e?void 0:e.closest)||!e.closest(".sketch-picker")&&!e.closest("[data-polotno-keep-focus]")&&!e.closest(".polotno-portal")&&!e.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/table-element.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as t,Fragment as e,jsxs as o}from"react/jsx-runtime";import{elementOpacity as i}from"./paint-opacity.js";import n from"react";import{observer as r}from"mobx-react-lite";import{observable as l,runInAction as s}from"mobx";import{nodeAutorun as h}from"../utils/mobx.js";import{Group as a,Rect as c,Line as d,Circle as g}from"react-konva";import{Html as u}from"react-konva-utils";import{toDisplayColor as w}from"@polotno/core/color";import{ROLES as p}from"../model/store.js";import{isTouchDevice as f}from"../utils/screen.js";import{roundedGeometryPx as x,roundedPosition as y}from"../utils/px.js";import{TextElement as
|
|
1
|
+
import{jsx as t,Fragment as e,jsxs as o}from"react/jsx-runtime";import{elementOpacity as i}from"./paint-opacity.js";import n from"react";import{observer as r}from"mobx-react-lite";import{observable as l,runInAction as s}from"mobx";import{nodeAutorun as h}from"../utils/mobx.js";import{Group as a,Rect as c,Line as d,Circle as g}from"react-konva";import{Html as u}from"react-konva-utils";import{toDisplayColor as w}from"@polotno/core/color";import{ROLES as p}from"../model/store.js";import{isTouchDevice as f}from"../utils/screen.js";import{roundedGeometryPx as x,roundedPosition as y,transformScale as v}from"../utils/px.js";import{TextElement as m}from"./text-element.js";import{PlacedNode as b}from"./placed-node.js";const C="#0d83dd",k=(t,e)=>{const o=t.target.getStage();o&&(o.container().style.cursor=e)},S=r(({axis:i,hovered:n,pillX:r,pillY:l,pillW:s,pillH:h,hitX:a,hitY:d,hitW:g,hitH:u,tint:w,hoverKind:p,idx:f,onSelect:x,onHoverChange:y})=>o(e,{children:[n&&t(c,{x:w.x,y:w.y,width:w.width,height:w.height,fill:"rgba(13, 131, 221, 0.08)",listening:!1}),t(c,{x:r,y:l,width:s,height:h,cornerRadius:Math.min(s,h)/2,fill:n?C:"#9ca3af",opacity:n?.55:.18,listening:!1}),t(c,{x:a,y:d,width:g,height:u,fill:"transparent",onMouseEnter:t=>{y({kind:p,idx:f}),k(t,"pointer")},onMouseLeave:t=>{y(null),k(t,"")},onClick:x})]})),E=r(({x:i,y:n,hovered:r,hoverKind:l,idx:s,isTouch:h,sizes:u,onInsert:w,onHoverChange:p})=>{const{hit:f,r:x,halo:y,stroke:v}=u,m=r||h;return o(a,{x:i,y:n,onMouseEnter:t=>{p({kind:l,idx:s}),k(t,"pointer")},onMouseLeave:t=>{p(null),k(t,"")},onClick:t=>{t.cancelBubble=!0,w()},children:[t(c,{x:-f/2,y:-f/2,width:f,height:f,fill:"transparent"}),m&&o(e,{children:[t(g,{radius:x+y,fill:"white",listening:!1}),t(g,{radius:x,fill:C,listening:!1}),t(d,{points:[.55*-x,0,.55*x,0],stroke:"white",strokeWidth:v,lineCap:"round",listening:!1}),t(d,{points:[0,.55*-x,0,.55*x],stroke:"white",strokeWidth:v,lineCap:"round",listening:!1})]})]})}),I=r(({element:o,store:i,inv:n,isTouch:r,hover:l,setHover:s})=>{const h=16*n,a=2*n,c=10*n,d={hit:22*n,r:7*n,halo:2*n,stroke:2*n},g=(t,e)=>null!==l&&l.kind===t&&l.idx===e,u=(t,e)=>i=>{i.cancelBubble=!0;const n=o._anchorCellId?o.cells.find(t=>t.id===o._anchorCellId):void 0;i.evt.shiftKey&&n?"col"===t?o.selectColumnRange(n.col,e):o.selectRowRange(n.row,e):"col"===t?o.selectColumn(e):o.selectRow(e)},w=[0],p=[0];for(let t=0;t<o.cols;t++){w.push(w[t]+o.colWidths[t]*o.a.width)}for(let t=0;t<o.rows;t++){p.push(p[t]+o.rowHeights[t]*o.a.height)}const f=[];for(let e=0;e<o.cols;e++){const i=Math.max(0,w[e+1]-w[e]-6);i<=0||f.push(t(S,{axis:"col",hovered:g("colSelect",e),pillX:w[e]+3,pillY:-a-c,pillW:i,pillH:a,hitX:w[e]+1,hitY:-h-c+a,hitW:i+4,hitH:h,tint:{x:w[e],y:0,width:w[e+1]-w[e],height:o.a.height},hoverKind:"colSelect",idx:e,onSelect:u("col",e),onHoverChange:s},`col-pill-${e}`))}for(let e=0;e<=o.cols;e++){f.push(t(E,{x:w[e],y:-c-a/2,hovered:g("colInsert",e),hoverKind:"colInsert",idx:e,isTouch:r,sizes:d,onInsert:()=>i.history.transaction(()=>o.addColumn(e)),onHoverChange:s},`col-insert-${e}`))}for(let e=0;e<o.rows;e++){const i=Math.max(0,p[e+1]-p[e]-6);i<=0||f.push(t(S,{axis:"row",hovered:g("rowSelect",e),pillX:-a-c,pillY:p[e]+3,pillW:a,pillH:i,hitX:-h-c+a,hitY:p[e]+1,hitW:h,hitH:i+4,tint:{x:0,y:p[e],width:o.a.width,height:p[e+1]-p[e]},hoverKind:"rowSelect",idx:e,onSelect:u("row",e),onHoverChange:s},`row-pill-${e}`))}for(let e=0;e<=o.rows;e++){f.push(t(E,{x:-c-a/2,y:p[e],hovered:g("rowInsert",e),hoverKind:"rowInsert",idx:e,isTouch:r,sizes:d,onInsert:()=>i.history.transaction(()=>o.addRow(e)),onHoverChange:s},`row-insert-${e}`))}return t(e,{children:f})});export const TableElement=r(({element:r,store:g})=>{const C=n.useRef(null),k=n.useRef(null),S=r.selectable||g.role===p.ADMIN,E=f(),R=r.isSelected,H=r._focusedCellIds.length>0,M=r.editingCell,W=R?1/Math.max(.01,g.scale):1,[T,B]=n.useState(null);n.useEffect(()=>{R||(r.clearCellFocus(),B(null))},[R]);const $=null==M?void 0:M._editModeEnabled;n.useEffect(()=>{r._editingCellId&&M&&!M._editModeEnabled&&r.exitCellEdit()},[$]),n.useEffect(()=>{H&&!r._editingCellId&&setTimeout(()=>{var t;return null===(t=k.current)||void 0===t?void 0:t.focus()},0)},[H,r._editingCellId]);const _=n.useMemo(()=>l.box(!1),[]);n.useEffect(()=>h(r,()=>{_.get()||r._fitRowsToContent&&g.history.ignore(()=>{r._applyFitRowsToContent()})}),[r,g,_]);const j=t=>{const e=t.target.getStage();if(!e){return}const o=e.getPointerPosition();if(!o){return}const i=C.current;if(!i){return}const n=i.getAbsoluteTransform().copy().invert().point(o);for(const l of r.visibleCells){const t=r.getCellRect(l.row,l.col,l.rowSpan,l.colSpan);if(n.x>=t.x&&n.x<=t.x+t.width&&n.y>=t.y&&n.y<=t.y+t.height){return l}}},D=(t,e)=>"dashed"===t?[4*e,2*e]:"dotted"===t?[e,e]:void 0,z=[];for(const e of r.visibleCells){const o=r.getCellRect(e.row,e.col,e.rowSpan,e.colSpan),i=0===e.row,n=e.row+e.rowSpan===r.rows,l=0===e.col,s=e.col+e.colSpan===r.cols;if(0===e.row){const i=e.getEffectiveBorder("top");if("none"!==i.style&&i.width>0){const n=o.y+i.width/2,r=o.x-(l?0:i.width/2),h=o.x+o.width+(s?0:i.width/2);z.push(t(d,{points:[r,n,h,n],stroke:w(i.color),strokeWidth:i.width,dash:D(i.style,i.width),listening:!1},`bt-${e.id}`))}}if(0===e.col){const r=e.getEffectiveBorder("left");if("none"!==r.style&&r.width>0){const l=o.x+r.width/2,s=o.y-(i?0:r.width/2),h=o.y+o.height+(n?0:r.width/2);z.push(t(d,{points:[l,s,l,h],stroke:w(r.color),strokeWidth:r.width,dash:D(r.style,r.width),listening:!1},`bl-${e.id}`))}}{const i=e.getEffectiveBorder("bottom");if("none"!==i.style&&i.width>0){const r=n?o.y+o.height-i.width/2:o.y+o.height,h=o.x-(l?0:i.width/2),a=o.x+o.width+(s?0:i.width/2);z.push(t(d,{points:[h,r,a,r],stroke:w(i.color),strokeWidth:i.width,dash:D(i.style,i.width),listening:!1},`bb-${e.id}`))}}{const r=e.getEffectiveBorder("right");if("none"!==r.style&&r.width>0){const l=s?o.x+o.width-r.width/2:o.x+o.width,h=o.y-(i?0:r.width/2),a=o.y+o.height+(n?0:r.width/2);z.push(t(d,{points:[l,h,l,a],stroke:w(r.color),strokeWidth:r.width,dash:D(r.style,r.width),listening:!1},`br-${e.id}`))}}}return o(e,{children:[t(b,{as:c,element:r,id:r.id,name:"element",width:r.a.width,height:r.a.height,fill:"transparent",opacity:i(r),hideInExport:!r.showInExport,listening:S,draggable:E?r.draggable&&R:r.draggable,onClick:t=>{if(!R){return}if(r.locked||!r.contentEditable){return}const e=j(t);e&&(t.evt.shiftKey&&H?(t.cancelBubble=!0,r.focusCellRange(e.row,e.col)):r.focusCell(e.id))},onDblClick:t=>{if(!R){return}if(r.locked||!r.contentEditable){return}const e=j(t);e&&r.enterCellEdit(e.id)},onDragMove:t=>{var e;const o=t.target;r.set({x:o.x(),y:o.y()}),null===(e=C.current)||void 0===e||e.position({x:o.x(),y:o.y()})},onDragEnd:t=>{r.set(y(t.target))},onTransformStart:()=>{s(()=>_.set(!0))},onTransformEnd:()=>{r.set({x:x(r.x),y:x(r.y),width:x(r.width),rotation:x(r.rotation)}),r._resetBaseRowHeights(),s(()=>_.set(!1))},onTransform:t=>{var e,o;const i=t.target,n=v(i.scaleX()),l=v(i.scaleY());i.scaleX(1),i.scaleY(1);const s=r.width*n,h=r.height*l;i.width(s),i.height(h);const a=i.x(),c=i.y(),d=i.rotation();null===(e=C.current)||void 0===e||e.position({x:a,y:c}),null===(o=C.current)||void 0===o||o.rotation(d),r.set({width:s,x:a,y:c,rotation:d}),r.setHeightRedistribute(h)}}),o(b,{as:a,nodeRef:C,element:r,opacity:i(r),hideInExport:!r.showInExport,scaleX:r.a.width/r.width,scaleY:r.a.height/r.height,children:[r.visibleCells.map(e=>{const o=r.getCellRect(e.row,e.col,e.rowSpan,e.colSpan);return"transparent"===e.cellBackground?null:t(c,{x:o.x,y:o.y,width:o.width,height:o.height,fill:w(e.cellBackground),listening:!1},`bg-${e.id}`)}),z,r.visibleCells.map(e=>t(m,{element:e,store:g},`text-${e.id}`)),R&&r._focusedCellIds.map(e=>{const o=r.cells.find(t=>t.id===e);if(!o){return null}const i=r.getCellRect(o.row,o.col,o.rowSpan,o.colSpan),n=2*W;return t(c,{x:i.x,y:i.y,width:i.width,height:i.height,fill:"rgba(13, 131, 221, 0.1)",stroke:"#0d83dd",strokeWidth:n,listening:!1},`focus-${e}`)}),H&&!M&&t(u,{children:t("div",{ref:k,tabIndex:-1,style:{position:"absolute",opacity:0,width:"1px",height:"1px",pointerEvents:"none",outline:"none"}})}),R&&!M&&!g.isPlaying&&(()=>{const e=[];let o=0;for(let i=0;i<r.cols-1;i++){o+=r.colWidths[i]*r.a.width;const n=o,l=i;e.push(t(d,{x:n,points:[0,0,0,r.a.height],stroke:"transparent",strokeWidth:1,hitStrokeWidth:16,draggable:!0,onMouseEnter:t=>{var e;const o=null===(e=t.target.getStage())||void 0===e?void 0:e.container();o&&(o.style.cursor="col-resize"),B({kind:"colInsert",idx:l+1})},onMouseLeave:t=>{var e;const o=null===(e=t.target.getStage())||void 0===e?void 0:e.container();o&&(o.style.cursor=""),B(null)},onDragStart:t=>{t.cancelBubble=!0,g.history.startTransaction()},onDragMove:t=>{t.cancelBubble=!0;const e=t.target,o=(e.x()-n)/r.width;e.x(n),r.resizeColumn(l,o)},onDragEnd:t=>{t.cancelBubble=!0,t.target.x(n),g.history.endTransaction()}},`col-resize-${i}`))}return e})(),R&&!M&&!g.isPlaying&&(()=>{const e=[];let o=0;for(let i=0;i<r.rows-1;i++){o+=r.rowHeights[i]*r.a.height;const n=o,l=i;e.push(t(d,{y:n,points:[0,0,r.a.width,0],stroke:"transparent",strokeWidth:1,hitStrokeWidth:16,draggable:!0,onMouseEnter:t=>{var e;const o=null===(e=t.target.getStage())||void 0===e?void 0:e.container();o&&(o.style.cursor="row-resize"),B({kind:"rowInsert",idx:l+1})},onMouseLeave:t=>{var e;const o=null===(e=t.target.getStage())||void 0===e?void 0:e.container();o&&(o.style.cursor=""),B(null)},onDragStart:t=>{t.cancelBubble=!0,s(()=>_.set(!0)),g.history.startTransaction()},onDragMove:t=>{t.cancelBubble=!0;const e=t.target,o=(e.y()-n)/r.height;e.y(n),r.resizeRow(l,o)},onDragEnd:t=>{t.cancelBubble=!0,t.target.y(n),r._resetBaseRowHeights(),s(()=>_.set(!1)),g.history.endTransaction()}},`row-resize-${i}`))}return e})(),R&&!M&&!g.isPlaying&&t(I,{element:r,store:g,inv:W,isTouch:E,hover:T,setHover:B})]})]})});
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import React from 'react';
|
|
2
|
+
import { StoreType } from '../../model/store.js';
|
|
3
|
+
import { TextElementType } from '../../model/text-model.js';
|
|
4
|
+
export declare const AutoDeleteEmptyText: (({ element, store }: {
|
|
5
|
+
element: TextElementType;
|
|
6
|
+
store: StoreType;
|
|
7
|
+
}) => null) & React.NamedExoticComponent<{
|
|
8
|
+
element: TextElementType;
|
|
9
|
+
store: StoreType;
|
|
10
|
+
}> & {
|
|
11
|
+
readonly type: ({ element, store }: {
|
|
12
|
+
element: TextElementType;
|
|
13
|
+
store: StoreType;
|
|
14
|
+
}) => null;
|
|
15
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e from"react";import{observer as t}from"mobx-react-lite";import{removeTags as o}from"@polotno/core/text";import{flags as r}from"../../utils/flags.js";import{usePrevious as l}from"../text-element.js";import{visiblePlaceholder as m}from"./placeholder.js";export const AutoDeleteEmptyText=t(({element:t,store:p})=>{const s=t.isSelected,c=l(s),i=r.autoDeleteEmptyText;return e.useEffect(()=>{c&&!s&&i&&""===o(t.text)&&t.removable&&!m(t.placeholder)&&p.deleteElements([t.id])},[i,t.placeholder,t.removable,t.text,s,c]),null});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import r from"react";import{isFontLoaded as t,textChars as e}from"../../utils/fonts.js";import{incrementLoader as n}from"../../utils/loader.js";export const useFontSpecsLoader=(u,c,o)=>{const[,s]=r.useReducer(r=>r+1,0),l=c.map(r=>JSON.stringify([r,u.fonts.find(t=>t.fontFamily===r.family)])).join("|")+e(o),i=r=>r.every(r=>t(r.family,r.style,r.weight,o)),[f]=r.useState(()=>i(c)),a=r.useRef(f),m=r.useRef(null);return r.useLayoutEffect(()=>{const r=a.current;if(a.current=i(c),a.current){return void(r||s())}let t=!0;return(async()=>{r&&s();const e=n(`font specs ${l}`);await Promise.all(c.map(r=>u.loadFont(r.family,r.style,r.weight,o))),t?(m.current=e,a.current=!0,s()):e()})(),()=>{m.current&&(m.current(),m.current=null),t=!1}},[l]),r.useEffect(()=>{var r;a.current&&(null===(r=m.current)||void 0===r||r.call(m),m.current=null)},[a.current]),[a.current]};
|
package/canvas/text-element.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as t,Fragment as e,jsxs as r}from"react/jsx-runtime";import{elementOpacity as o}from"./paint-opacity.js";import n from"react";import{toDisplayColor as i}from"@polotno/core/color";import{observer as a}from"mobx-react-lite";import{Group as l,Path as s,Text as c,TextPath as u}from"react-konva";import{Html as d}from"react-konva-utils";import{nodeAutorun as f}from"../utils/mobx.js";import h from"konva";import{parsePath as g,roundCommands as m}from"svg-round-corners/lib/index.js";import{generateBackgroundShapeFromRects as p,textLinesToRects as x}from"@polotno/core/background-shape";import{useColor as b}from"./use-color.js";import{useWorkspaceStyle as v}from"./workspace-style.js";import{ROLES as w}from"../model/store.js";import{incrementLoader as S}from"../utils/loader.js";import{activeAnchorOf as y,scaledFontSizeAttrs as E,roundedFontSizeAttrs as z,roundedTextDecorationAttrs as k,roundedGeometryPx as R,roundedPosition as j,textMinResizeWidth as F}from"../utils/px.js";import{isFontLoaded as A}from"../utils/fonts.js";import{flags as M}from"../utils/flags.js";import{textOverflowOf as O}from"../utils/text-sizing.js";import{FIT_FONT_SIZE_STEP as L,FIT_HEIGHT_EPSILON as C,legacyTextOverflow as T}from"@polotno/core/text-sizing";import{removeTags as H}from"@polotno/core/text";import{getDir as P,getCurvePath as W,resolveLineHeight as X,normalizeStrokeLineJoin as D}from"@polotno/core/text-html";import{cssFontFamily as Y}from"@polotno/core/fonts";import{shadowCastByBackground as $}from"@polotno/core/filters";import{applyOpacityToColor as I}from"@polotno/core/svg";import{applyFilter as J}from"./apply-filters.js";import{useFadeIn as N}from"./use-fadein.js";import{isTouchDevice as B}from"../utils/screen.js";import{isAlive as _,getParent as V}from"mobx-state-tree";import{getLimitedFontSize as q}from"./text-element/max-font-size.js";import{getOptimalCaretColor as U}from"./text-element/caret-color.js";import{visiblePlaceholder as Z}from"./text-element/placeholder.js";import{hasMeasuredHeight as G,resolveTextBoxHeight as K}from"@polotno/core/text-types";let Q;function tt(){return Q||(Q=document.getElementById("polotno-text-style"),Q||(Q=document.createElement("style"),Q.id="polotno-text-style",document.head.appendChild(Q)),Q)}h._fixTextRendering=!0;const et={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 rt=a(({textNodeRef:e,element:r,onBlur:o,selectAll:i,cursorPosition:a})=>{const[l,s]=n.useState(et),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=U(r);const e=`\n .polotno-input::placeholder {\n color: ${l.color};\n opacity: 0.6;\n }\n `,o=tt();o.innerHTML="",o.appendChild(document.createTextNode(e)),JSON.stringify(t)!==JSON.stringify(l)&&s(t)});const u=n.useRef(null);if(n.useLayoutEffect(()=>{var t;const e=u.current;if(!e){return}null===(t=u.current)||void 0===t||t.focus({preventScroll:!0});const r=a||e.value.length;e.selectionStart=e.selectionEnd=r,i&&(null==e||e.select(),document.execCommand("selectAll",!1,void 0))},[]),n.useEffect(()=>{window.addEventListener("blur",o);const t=t=>{var e;(null===(e=u.current)||void 0===e?void 0:e.contains(t.target))||o()};return window.addEventListener("touchstart",t),()=>{window.removeEventListener("blur",o),window.removeEventListener("touchstart",t)}},[]),!c){return null}let d=0;const f=c.textArr.length*c.lineHeight()*c.fontSize(),h=K(r.a,f);"middle"===r.verticalAlign&&(d=(h-f)/2),"bottom"===r.verticalAlign&&(d=h-f);const g=H(r.text);return t("textarea",{className:"polotno-input",ref:u,dir:P(g),style:Object.assign(Object.assign(Object.assign({},et),l),{paddingTop:d+"px"}),value:g,onChange:t=>{const e=q({oldText:r.text,newText:t.target.value,element:r});r.set(Object.assign({text:t.target.value},E(r,e)))},placeholder:Z(r.placeholder),onBlur:o})}),ot=e=>t(d,{children:t(rt,Object.assign({},e))});export const useFontLoader=(t,e,r,o,i)=>{const[a,l]=n.useReducer(t=>t+1,0),s=n.useRef(A(e,r,o)),c=n.useRef(null);return n.useLayoutEffect(()=>{if(s.current=A(e,r,o),s.current){return}let n=!0;return(async()=>{s.current=!1,l();const a=S(`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=>A(t,r,o))),u=n.useRef(null);return n.useLayoutEffect(()=>{if(c.current=e.every(t=>A(t,r,o)),c.current){return}let n=!0;return(async()=>{c.current=!1,l();const a=S(`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(()=>X({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 nt(t,e,r=!1){const o=t.fontSize(),n=t.height(),i=H(e.text);let a=e.a.fontSize;t.height(void 0);const l=Math.round(2*e.a.fontSize)-1;for(let s=1;s<l;s++){const o=G(e.a)&&t.height()>e.a.height+C;let n=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=n.find(t=>!l.includes(t)||(l=l.replace(t,""),!1));if(!(o||s&&!r)){break}a-=L,t.fontSize(a)}return t.fontSize(o),t.height(n),a}export{getCurvePath}from"@polotno/core/text-html";export const TextElement=a(({element:a,store:d})=>{const{textOverflowIndicatorStyle:h}=v(),A=n.useRef(null),L=n.useRef(null),C=n.useRef(null),X=n.useRef([]),q=n.useRef(!0),[,U]=n.useReducer(t=>t+1,0),{editorEnabled:Q,selectAll:tt}=(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}})(a),[et,rt]=n.useState(!1),[it,at]=n.useState(!1),lt=n.useRef(a.a.height),st=n.useRef(0),ct=n.useRef(""),ut=n.useRef(0),dt=a.isSelected,ft=usePrevious(dt),{textVerticalResizeEnabled:ht}=M,gt=M.autoDeleteEmptyText,mt=usePrevious(a.fontFamily),[pt,xt]=n.useState([]);n.useEffect(()=>{var t,e;const r=null!==(e=null===(t=A.current)||void 0===t?void 0:t.textArr)&&void 0!==e?e:[];JSON.stringify(r)!==JSON.stringify(pt)&&xt(r)}),n.useEffect(()=>{if(a.a.width||"tablecell"===a.type){return}const t=A.current;t.width(600),a.set({width:1.4*t.getTextWidth()})},[]),n.useEffect(()=>{ft&&!dt&>&&""===a.text&&a.removable&&!Z(a.placeholder)&&d.deleteElements([a.id])},[gt,a.placeholder,a.removable,a.text,dt,ft]);const bt=()=>{if(a.curveEnabled){const t=A.current;null==t||t.clearCache(),null==t||t.setAttrs({filters:[]});const e=L.current;e&&J(e,a)}else{const t=A.current;t&&J(t,a)}};n.useLayoutEffect(()=>{if(!it){return f(a,()=>{bt()})}}),n.useEffect(()=>{const t=X.current;t.length>0&&(X.current=[],t.forEach(t=>t()))}),n.useEffect(()=>()=>{q.current=!1;const t=X.current;t.length>0&&(X.current=[],t.forEach(t=>t()))},[]);let vt=H(a.text);"uppercase"===a.textTransform&&(vt=vt.toUpperCase());const[wt]=useFontLoader(d,a.fontFamily,a.fontStyle,a.fontWeight,a.text||a.placeholder),St=()=>{if(a.curveEnabled){const t=L.current;return t.getSelfRect().height||t.fontSize()}const t=A.current.clone({height:void 0}),e=Math.ceil(t.fontSize()*t.lineHeight()*t.textArr.length+1);return t.destroy(),e};n.useLayoutEffect(()=>{if(!wt){return}if("tablecell"===a.type){const t=T(O(a));if("resize"===t){const t=St(),e=_(a)?V(a,2):null;(null==e?void 0:e.setCellContentHeight)&&e.setCellContentHeight(a.id,t)}else if("change-font-size"===t){const t=A.current;if(t){const e=nt(t,a,M.textSplitAllowed);e!==a.fontSize&&d.history.ignore(()=>{a.set({fontSize:e})})}}return}const t=T(O(a)),{textSplitAllowed:e}=M,r=(t,e,r,o)=>{const n=S(`text ${a.id}`),i=()=>{d.history.ignore(t,e,r).then(()=>{q.current?(X.current.push(n),U()):n()})};o?queueMicrotask(i):i()};if(!G(a)){const t=St();return void r(()=>{G(a)||a.set({height:t})},void 0,void 0,!0)}if(!d.isPlaying){if("change-font-size"!==t||et){if("resize"===t){const t=St();ht&&a.height<t&&!et&&r(()=>{var e;_(a)&&a.set({height:t}),null===(e=A.current)||void 0===e||e.height(t)},!1,!0),ht||a.height===t||et||r(()=>{var e;_(a)&&a.set({height:t}),null===(e=A.current)||void 0===e||e.height(t)},!1,!0)}}else{const t=A.current,o=a.curveEnabled?a.fontSize:nt(t,a,e);if(o!==a.fontSize){return void r(()=>{a.set(E(a,o))},!1,!0)}const n=St();a.height===n||ht||r(()=>{a.set({height:n})},!1,!0)}}}),n.useLayoutEffect(()=>{var t;if(wt&&a.curveEnabled){const e=null===(t=L.current)||void 0===t?void 0:t.getSelfRect().width;if(e){const t=e-a.a.width,r=a.a.rotation*Math.PI/180,o=-t/2*Math.cos(r),n=-t/2*Math.sin(r);a.set({width:e,x:a.a.x+o,y:a.a.y+n})}}},[wt,a.curveEnabled,a.curvePower,a.text,a.fontSize,a.fontFamily,a.fontWeight,a.fontStyle,a.letterSpacing]),n.useLayoutEffect(()=>{const t=A.current;t&&(t.width(t.width()+1e-8),t.width(t.width()-1e-8),t._setTextData(),bt())},[wt]);const yt=n.useRef(null),Et=n.useRef(a.width),zt=n.useRef(0),kt=t=>{t.evt.preventDefault();const e=d.selectedShapes.find(t=>t===a);e&&a.contentEditable&&(zt.current=function(t){var e;const r=t.target,o=function(t){var e=t.getAbsoluteTransform().copy();e.invert();var r=t.getStage().getPointerPosition();return e.point(r)}(r),n=r.textArr,i=Math.floor(o.y/(r.fontSize()*r.lineHeight())),a=n.slice(0,i).reduce((t,e)=>t+e.text.length,i),l=null!==(e=n[i])&&void 0!==e?e:n[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((o.x-s)/l.width*l.text.length)}(t),a.toggleEditMode())},Rt=Z(a.placeholder),jt=!vt&&Rt?.6:o(a);N(A,jt);const Ft=getLineHeight({fontLoaded:wt,fontFamily:a.fontFamily,fontSize:a.a.fontSize,lineHeight:a.lineHeight}),At=a.selectable||d.role===w.ADMIN,Mt=b(a),Ot=b(a,a.stroke,"stroke"),Lt=n.useMemo(()=>a.backgroundEnabled||a.borderSize?a.curveEnabled?function({width:t,height:e,padding:r=0,cornerRadius:o=0}){const n=-r,i=-r,a=t+r,l=e+r,s=g(`M ${n} ${i} L ${a} ${i} L ${a} ${l} L ${n} ${l} Z`);return m(s,o).path}({width:a.a.width,height:a.a.height,cornerRadius:a.backgroundCornerRadius*(a.a.fontSize*Ft*.5),padding:a.backgroundPadding*(a.a.fontSize*Ft*.5)}):function({lines:t,lineHeight:e,width:r,align:o="left",padding:n=0,cornerRadius:i=0}){const a=x({lines:t,lineHeight:e,width:r,align:o});return p({rects:a,padding:n,cornerRadius:i})}({lines:JSON.parse(JSON.stringify(pt)),cornerRadius:a.backgroundCornerRadius*(a.a.fontSize*Ft*.5),lineHeight:Ft*a.a.fontSize,padding:a.backgroundPadding*(a.a.fontSize*Ft*.5),width:a.a.width,align:a.align}):"",[a.backgroundEnabled,a.borderSize,a.curveEnabled,a.backgroundCornerRadius,a.a.fontSize,a.a.height,Ft,a.backgroundPadding,a.a.width,a.align,pt]),Ct=B();let Tt=0;if(!a.curveEnabled){const t=pt.length*Ft*a.a.fontSize,e=K(a.a,t);"middle"===a.verticalAlign?Tt=(e-t)/2:"bottom"===a.verticalAlign&&(Tt=e-t)}const Ht=a.curveEnabled?W(a.a.width,a.a.height,a.curvePower,a.a.fontSize):"",Pt=wt?Y(a.fontFamily):mt===a.fontFamily?"Arial":Y(mt),Wt=P(vt),Xt=a.shadowEnabled&&!$(a),Dt={shadowEnabled:a.shadowEnabled&&($(a)||a.borderSize>0),shadowBlur:a.shadowBlur,shadowOffsetX:a.shadowOffsetX,shadowOffsetY:a.shadowOffsetY,shadowColor:i(a.shadowColor),shadowOpacity:a.shadowOpacity};return r(e,{children:[t(s,Object.assign({ref:C,x:a.a.x,y:a.a.y,rotation:a.a.rotation,hideInExport:!a.showInExport,listening:!1,visible:a.backgroundEnabled||a.borderSize>0,opacity:jt,data:Lt,fillEnabled:a.backgroundEnabled,fill:I(a.backgroundColor,a.backgroundOpacity),strokeEnabled:a.borderSize>0,stroke:i(a.borderColor),strokeWidth:a.borderSize,lineJoin:a.backgroundCornerRadius>0?"round":"miter",offsetY:-Tt},Dt)),t(s,{data:Ht,stroke:h.stroke,strokeWidth:1,x:a.a.x,y:a.a.y,rotation:a.a.rotation,visible:!1}),t(u,Object.assign({ref:L,visible:a.curveEnabled,data:Ht,text:vt||Rt,listening:!1,align:"center",textBaseline:"middle",direction:Wt},Mt,Ot,{strokeWidth:a.strokeWidth,lineJoin:D(a.strokeLineJoin),fillAfterStrokeEnabled:!0,fontSize:a.a.fontSize,fontFamily:`${Y(a.fontFamily)}, ${Y(mt)}`,fontStyle:a.fontStyle+" "+a.fontWeight,textDecoration:a.textDecoration.trim(),letterSpacing:a.letterSpacing*a.a.fontSize,x:a.a.x,y:a.a.y,rotation:a.a.rotation,opacity:a._editModeEnabled?.3:jt,hideInExport:!a.showInExport},Dt,{shadowEnabled:Xt})),t(c,Object.assign({ref:A,id:a.selectable?a.id:void 0,name:a.selectable?"element":"",hideInExport:!a.showInExport,editModeEnabled:a._editModeEnabled,x:a.a.x,y:a.a.y,rotation:a.a.rotation,width:a.a.width,height:G(a.a)?a.a.height:void 0,text:vt||Rt,direction:Wt},Mt,Ot,{lineJoin:D(a.strokeLineJoin),strokeWidth:a.strokeWidth,fillAfterStrokeEnabled:!0,fontSize:a.a.fontSize,fontFamily:Pt,fontStyle:a.fontStyle+" "+a.fontWeight,textDecoration:a.textDecoration,align:a.align,verticalAlign:a.verticalAlign,draggable:Ct?a.draggable&&dt:a.draggable,preventDefault:!Ct||dt,opacity:a.curveEnabled?0:jt,visible:!a._editModeEnabled,ellipsis:"ellipsis"===O(a)},Dt,{shadowEnabled:Xt,lineHeight:Ft,letterSpacing:a.letterSpacing*a.a.fontSize,listening:!!a.selectable&&At,onDragStart:()=>{at(!0)},onDragMove:t=>{a.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{at(!1),a.set(j(t.target))},onClick:kt,onTap:kt,onTransformStart:()=>{rt(!0);const t=A.current;lt.current=t.height(),Et.current=a.a.width,yt.current=t.position(),st.current=t.rotation(),ut.current=t.height(),ct.current=y(t)},onTransform:t=>{var e,r;const o=t.target;null===(e=C.current)||void 0===e||e.setAttrs({x:o.x(),y:o.y(),rotation:o.rotation(),scale:o.scale()});const n=ct.current;if("middle-left"===n||"middle-right"===n){const t=o.scaleX(),e=o.width()*t,r=F(Et.current,a.a.fontSize);let n=e;e<r&&(n=r,yt.current&&o.position(yt.current)),o.width(n),o.scaleX(1),o.scaleY(1);let i=St();if("ellipsis"===O(a)){i=lt.current}else{const t=Math.max(i,lt.current);o.height(t),a.set({height:o.height()})}const l=M.textVerticalResizeEnabled?Math.max(i,lt.current):St();a.set({x:o.x(),width:o.width(),rotation:o.rotation(),height:l}),o.skewX(0),o.skewY(0),bt()}if("top-center"===n||"bottom-center"===n){const e="resize"===O(a)?St():Ft*a.a.fontSize,r=t.target.height()*t.target.scaleY();if(r<e){if(t.target.height(e),yt.current){if("top-center"===ct.current){const r=st.current*Math.PI/180,o=ut.current-e;t.target.x(yt.current.x-o*Math.sin(r)),t.target.y(yt.current.y+o*Math.cos(r))}else{t.target.position(yt.current)}}}else{t.target.height(r)}t.target.scaleY(1),t.target.scaleX(1),t.target.rotation(st.current),t.target.skewX(0),t.target.skewY(0),ut.current=Math.max(e,r)}yt.current=t.target.position();const i=t.target.scaleX();null===(r=C.current)||void 0===r||r.setAttrs({scaleX:1,scaleY:1}),t.target.scaleX(1),t.target.scaleY(1),a.set({fontSize:a.a.fontSize*i,width:t.target.width()*i,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),height:t.target.height()*i,shadowBlur:a.shadowBlur*i,shadowOffsetX:a.shadowOffsetX*i,shadowOffsetY:a.shadowOffsetY*i,strokeWidth:a.strokeWidth*i,borderSize:a.borderSize*i})},onTransformEnd:t=>{var e;const r=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),a.set(Object.assign(Object.assign({},z(a,a.fontSize*r)),{width:Math.ceil(t.target.width()*r),x:R(t.target.x()),y:R(t.target.y()),rotation:R(t.target.rotation()),height:R(t.target.height()*r)})),null===(e=C.current)||void 0===e||e.setAttrs({scaleX:1,scaleY:1}),rt(!1)}})),Q&&a.contentEditable&&t(l,{x:a.a.x,y:a.a.y,rotation:a.a.rotation,children:t(ot,{textNodeRef:A,element:a,selectAll:tt,cursorPosition:zt.current,onBlur:()=>{a.set(k(a)),a.toggleEditMode(!1)}})})]})});
|
|
1
|
+
import{jsx as t,Fragment as e,jsxs as r}from"react/jsx-runtime";import{elementOpacity as o}from"./paint-opacity.js";import n from"react";import{toDisplayColor as i}from"@polotno/core/color";import{observer as a}from"mobx-react-lite";import{Group as l,Path as s,Text as c,TextPath as d}from"react-konva";import{Html as u}from"react-konva-utils";import{nodeAutorun as f}from"../utils/mobx.js";import h from"konva";import{parsePath as g,roundCommands as m}from"svg-round-corners/lib/index.js";import{generateBackgroundShapeFromRects as p,textLinesToRects as x}from"@polotno/core/background-shape";import{useColor as b}from"./use-color.js";import{ROLES as v}from"../model/store.js";import{incrementLoader as S}from"../utils/loader.js";import{activeAnchorOf as w,scaledFontSizeAttrs as y,roundedFontSizeAttrs as E,roundedTextDecorationAttrs as z,roundedGeometryPx as k,roundedPosition as R,textMinResizeWidth as F,transformScale as j}from"../utils/px.js";import{isFontLoaded as A}from"../utils/fonts.js";import{flags as M}from"../utils/flags.js";import{textOverflowOf as L}from"../utils/text-sizing.js";import{FIT_FONT_SIZE_STEP as O,FIT_HEIGHT_EPSILON as C,legacyTextOverflow as T}from"@polotno/core/text-sizing";import{removeTags as H}from"@polotno/core/text";import{getDir as P,getCurvePath as W,resolveLineHeight as X,normalizeStrokeLineJoin as D}from"@polotno/core/text-html";import{cssFontFamily as Y}from"@polotno/core/fonts";import{shadowCastByBackground as $}from"@polotno/core/filters";import{applyOpacityToColor as J}from"@polotno/core/svg";import{applyFilter as N}from"./apply-filters.js";import{useFadeIn as B}from"./use-fadein.js";import{isTouchDevice as I}from"../utils/screen.js";import{isAlive as _,getParent as V}from"mobx-state-tree";import{getLimitedFontSize as q}from"./text-element/max-font-size.js";import{getOptimalCaretColor as U}from"./text-element/caret-color.js";import{visiblePlaceholder as Z}from"./text-element/placeholder.js";import{hasMeasuredHeight as G,resolveTextBoxHeight as K}from"@polotno/core/text-types";let Q;function tt(){return Q||(Q=document.getElementById("polotno-text-style"),Q||(Q=document.createElement("style"),Q.id="polotno-text-style",document.head.appendChild(Q)),Q)}h._fixTextRendering=!0;const et={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 rt=a(({textNodeRef:e,element:r,onBlur:o,selectAll:i,cursorPosition:a})=>{const[l,s]=n.useState(et),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=U(r);const e=`\n .polotno-input::placeholder {\n color: ${l.color};\n opacity: 0.6;\n }\n `,o=tt();o.innerHTML="",o.appendChild(document.createTextNode(e)),JSON.stringify(t)!==JSON.stringify(l)&&s(t)});const d=n.useRef(null);if(n.useLayoutEffect(()=>{var t;const e=d.current;if(!e){return}null===(t=d.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=d.current)||void 0===e?void 0:e.contains(t.target))||o()};return window.addEventListener("touchstart",t),()=>{window.removeEventListener("blur",o),window.removeEventListener("touchstart",t)}},[]),!c){return null}let u=0;const f=c.textArr.length*c.lineHeight()*c.fontSize(),h=K(r.a,f);"middle"===r.verticalAlign&&(u=(h-f)/2),"bottom"===r.verticalAlign&&(u=h-f);const g=H(r.text);return t("textarea",{className:"polotno-input",ref:d,dir:P(g),style:Object.assign(Object.assign(Object.assign({},et),l),{paddingTop:u+"px"}),value:g,onChange:t=>{const e=q({oldText:r.text,newText:t.target.value,element:r});r.set(Object.assign({text:t.target.value},y(r,e)))},placeholder:Z(r.placeholder),onBlur:o})}),ot=e=>t(u,{children:t(rt,Object.assign({},e))});export const useFontLoader=(t,e,r,o,n)=>useFontFamiliesLoader(t,[e],r,o,n);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=>A(t,r,o))),d=n.useRef(null);return n.useLayoutEffect(()=>{const n=c.current;if(c.current=e.every(t=>A(t,r,o)),c.current){return void(n||l())}let a=!0;return(async()=>{n&&l();const u=S(`fonts ${s}`);await Promise.all(e.map(e=>t.loadFont(e,r,o,i))),a?(d.current=u,c.current=!0,l()):u()})(),()=>{d.current&&(d.current(),d.current=null),a=!1}},[s,r,o]),n.useEffect(()=>{var t;c.current&&(null===(t=d.current)||void 0===t||t.call(d),d.current=null)},[c.current]),[c.current]};export const getLineHeight=({fontLoaded:t,fontFamily:e,fontSize:r,lineHeight:o})=>n.useMemo(()=>X({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 nt(t,e,r=!1){const o=t.fontSize(),n=t.height(),i=H(e.text);let a=e.a.fontSize;t.height(void 0);const l=Math.round(2*e.a.fontSize)-1;for(let s=1;s<l;s++){const o=G(e.a)&&t.height()>e.a.height+C;let n=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=n.find(t=>!l.includes(t)||(l=l.replace(t,""),!1));if(!(o||s&&!r)){break}a-=O,t.fontSize(a)}return t.fontSize(o),t.height(n),a}export{getCurvePath}from"@polotno/core/text-html";export const TextElement=a(({element:a,store:u})=>{const h=n.useRef(null),A=n.useRef(null),O=n.useRef(null),C=n.useRef([]),X=n.useRef(!0),[,q]=n.useReducer(t=>t+1,0),{editorEnabled:U,selectAll:Q}=(t=>{const[e,r]=n.useState(!1),o=n.useRef(!1);return n.useEffect(()=>{var e=!0;return setTimeout(()=>{e&&(t._editModeEnabled&&(o.current=!0),r(!0),setTimeout(()=>{o.current=!1},50))},50),()=>{e=!1}},[]),{editorEnabled:e&&t._editModeEnabled,selectAll:o.current}})(a),[tt,et]=n.useState(!1),[rt,it]=n.useState(!1),at=n.useRef(a.a.height),lt=n.useRef(0),st=n.useRef(""),ct=n.useRef(0),dt=a.isSelected,ut=usePrevious(dt),{textVerticalResizeEnabled:ft}=M,ht=M.autoDeleteEmptyText,gt=usePrevious(a.fontFamily),[mt,pt]=n.useState([]),xt=a.backgroundEnabled||a.borderSize>0;n.useLayoutEffect(()=>{var t,e;if(!xt){return}const r=null!==(e=null===(t=h.current)||void 0===t?void 0:t.textArr)&&void 0!==e?e:[];JSON.stringify(r)!==JSON.stringify(mt)&&pt(r)}),n.useEffect(()=>{if(a.a.width||"tablecell"===a.type){return}const t=h.current;t.width(600),a.set({width:1.4*t.getTextWidth()})},[]),n.useEffect(()=>{ut&&!dt&&ht&&""===a.text&&a.removable&&!Z(a.placeholder)&&u.deleteElements([a.id])},[ht,a.placeholder,a.removable,a.text,dt,ut]);const bt=()=>{if(a.curveEnabled){const t=h.current;null==t||t.clearCache(),null==t||t.setAttrs({filters:[]});const e=A.current;e&&N(e,a)}else{const t=h.current;t&&N(t,a)}};n.useLayoutEffect(()=>{if(!rt){return f(a,()=>{bt()})}}),n.useEffect(()=>{const t=C.current;t.length>0&&(C.current=[],t.forEach(t=>t()))}),n.useEffect(()=>()=>{X.current=!1;const t=C.current;t.length>0&&(C.current=[],t.forEach(t=>t()))},[]);let vt=H(a.text);"uppercase"===a.textTransform&&(vt=vt.toUpperCase());const[St]=useFontLoader(u,a.fontFamily,a.fontStyle,a.fontWeight,a.text||a.placeholder),wt=()=>{if(a.curveEnabled){const t=A.current;return t.getSelfRect().height||t.fontSize()}const t=h.current.clone({height:void 0}),e=Math.ceil(t.fontSize()*t.lineHeight()*t.textArr.length+1);return t.destroy(),e};n.useLayoutEffect(()=>{if(!St){return}if("tablecell"===a.type){const t=T(L(a));if("resize"===t){const t=wt(),e=_(a)?V(a,2):null;(null==e?void 0:e.setCellContentHeight)&&e.setCellContentHeight(a.id,t)}else if("change-font-size"===t){const t=h.current;if(t){const e=nt(t,a,M.textSplitAllowed);e!==a.fontSize&&u.history.ignore(()=>{a.set({fontSize:e})})}}return}const t=T(L(a)),{textSplitAllowed:e}=M,r=(t,e,r,o)=>{const n=S(`text ${a.id}`),i=()=>{u.history.ignore(t,e,r).then(()=>{X.current?(C.current.push(n),q()):n()})};o?queueMicrotask(i):i()};if(!G(a)){const t=wt();return void r(()=>{G(a)||a.set({height:t})},void 0,void 0,!0)}if(!u.isPlaying){if("change-font-size"!==t||tt){if("resize"===t){const t=wt();ft&&a.height<t&&!tt&&r(()=>{var e;_(a)&&a.set({height:t}),null===(e=h.current)||void 0===e||e.height(t)},!1,!0),ft||a.height===t||tt||r(()=>{var e;_(a)&&a.set({height:t}),null===(e=h.current)||void 0===e||e.height(t)},!1,!0)}}else{const t=h.current,o=a.curveEnabled?a.fontSize:nt(t,a,e);if(o!==a.fontSize){return void r(()=>{a.set(y(a,o))},!1,!0)}const n=wt();a.height===n||ft||r(()=>{a.set({height:n})},!1,!0)}}}),n.useLayoutEffect(()=>{var t;if(St&&a.curveEnabled){const e=null===(t=A.current)||void 0===t?void 0:t.getSelfRect().width;if(e){const t=e-a.a.width,r=a.a.rotation*Math.PI/180,o=-t/2*Math.cos(r),n=-t/2*Math.sin(r);a.set({width:e,x:a.a.x+o,y:a.a.y+n})}}},[St,a.curveEnabled,a.curvePower,a.text,a.fontSize,a.fontFamily,a.fontWeight,a.fontStyle,a.letterSpacing]),n.useLayoutEffect(()=>{const t=h.current;t&&(t.width(t.width()+1e-8),t.width(t.width()-1e-8),t._setTextData(),bt())},[St]);const yt=n.useRef(null),Et=n.useRef(a.width),zt=n.useRef(0),kt=t=>{t.evt.preventDefault();const e=u.selectedShapes.find(t=>t===a);e&&a.contentEditable&&(zt.current=function(t){var e;const r=t.target,o=function(t){var e=t.getAbsoluteTransform().copy();e.invert();var r=t.getStage().getPointerPosition();return e.point(r)}(r),n=r.textArr,i=Math.floor(o.y/(r.fontSize()*r.lineHeight())),a=n.slice(0,i).reduce((t,e)=>t+e.text.length,i),l=null!==(e=n[i])&&void 0!==e?e:n[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((o.x-s)/l.width*l.text.length)}(t),a.toggleEditMode())},Rt=Z(a.placeholder),Ft=!vt&&Rt?.6:o(a);B(h,Ft);const jt=getLineHeight({fontLoaded:St,fontFamily:a.fontFamily,fontSize:a.a.fontSize,lineHeight:a.lineHeight}),At=a.selectable||u.role===v.ADMIN,Mt=b(a),Lt=b(a,a.stroke,"stroke"),Ot=n.useMemo(()=>a.backgroundEnabled||a.borderSize?a.curveEnabled?function({width:t,height:e,padding:r=0,cornerRadius:o=0}){const n=-r,i=-r,a=t+r,l=e+r,s=g(`M ${n} ${i} L ${a} ${i} L ${a} ${l} L ${n} ${l} Z`);return m(s,o).path}({width:a.a.width,height:a.a.height,cornerRadius:a.backgroundCornerRadius*(a.a.fontSize*jt*.5),padding:a.backgroundPadding*(a.a.fontSize*jt*.5)}):function({lines:t,lineHeight:e,width:r,align:o="left",padding:n=0,cornerRadius:i=0}){const a=x({lines:t,lineHeight:e,width:r,align:o});return p({rects:a,padding:n,cornerRadius:i})}({lines:JSON.parse(JSON.stringify(mt)),cornerRadius:a.backgroundCornerRadius*(a.a.fontSize*jt*.5),lineHeight:jt*a.a.fontSize,padding:a.backgroundPadding*(a.a.fontSize*jt*.5),width:a.a.width,align:a.align}):"",[a.backgroundEnabled,a.borderSize,a.curveEnabled,a.backgroundCornerRadius,a.a.fontSize,a.a.height,jt,a.backgroundPadding,a.a.width,a.align,mt]),Ct=I();let Tt=0;if(!a.curveEnabled){const t=mt.length*jt*a.a.fontSize,e=K(a.a,t);"middle"===a.verticalAlign?Tt=(e-t)/2:"bottom"===a.verticalAlign&&(Tt=e-t)}const Ht=a.curveEnabled?W(a.a.width,a.a.height,a.curvePower,a.a.fontSize):"",Pt=St?Y(a.fontFamily):gt===a.fontFamily?"Arial":Y(gt),Wt=P(vt),Xt=a.shadowEnabled&&!$(a),Dt={shadowEnabled:a.shadowEnabled&&($(a)||a.borderSize>0),shadowBlur:a.shadowBlur,shadowOffsetX:a.shadowOffsetX,shadowOffsetY:a.shadowOffsetY,shadowColor:i(a.shadowColor),shadowOpacity:a.shadowOpacity};return r(e,{children:[xt&&t(s,Object.assign({ref:O,x:a.a.x,y:a.a.y,rotation:a.a.rotation,hideInExport:!a.showInExport,listening:!1,opacity:Ft,data:Ot,fillEnabled:a.backgroundEnabled,fill:J(a.backgroundColor,a.backgroundOpacity),strokeEnabled:a.borderSize>0,stroke:i(a.borderColor),strokeWidth:a.borderSize,lineJoin:a.backgroundCornerRadius>0?"round":"miter",offsetY:-Tt},Dt)),a.curveEnabled&&t(d,Object.assign({ref:A,data:Ht,text:vt||Rt,listening:!1,align:"center",textBaseline:"middle",direction:Wt},Mt,Lt,{strokeWidth:a.strokeWidth,lineJoin:D(a.strokeLineJoin),fillAfterStrokeEnabled:!0,fontSize:a.a.fontSize,fontFamily:`${Y(a.fontFamily)}, ${Y(gt)}`,fontStyle:a.fontStyle+" "+a.fontWeight,textDecoration:a.textDecoration.trim(),letterSpacing:a.letterSpacing*a.a.fontSize,x:a.a.x,y:a.a.y,rotation:a.a.rotation,opacity:a._editModeEnabled?.3:Ft,hideInExport:!a.showInExport},Dt,{shadowEnabled:Xt})),t(c,Object.assign({ref:h,id:a.selectable?a.id:void 0,name:a.selectable?"element":"",hideInExport:!a.showInExport,editModeEnabled:a._editModeEnabled,x:a.a.x,y:a.a.y,rotation:a.a.rotation,width:a.a.width,height:G(a.a)?a.a.height:void 0,text:vt||Rt,direction:Wt},Mt,Lt,{lineJoin:D(a.strokeLineJoin),strokeWidth:a.strokeWidth,fillAfterStrokeEnabled:!0,fontSize:a.a.fontSize,fontFamily:Pt,fontStyle:a.fontStyle+" "+a.fontWeight,textDecoration:a.textDecoration,align:a.align,verticalAlign:a.verticalAlign,draggable:Ct?a.draggable&&dt:a.draggable,preventDefault:!Ct||dt,opacity:a.curveEnabled?0:Ft,visible:!a._editModeEnabled,ellipsis:"ellipsis"===L(a)},Dt,{shadowEnabled:Xt,lineHeight:jt,letterSpacing:a.letterSpacing*a.a.fontSize,listening:!!a.selectable&&At,onDragStart:()=>{it(!0)},onDragMove:t=>{a.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{it(!1),a.set(R(t.target))},onClick:kt,onTap:kt,onTransformStart:()=>{et(!0);const t=h.current;at.current=t.height(),Et.current=a.a.width,yt.current=t.position(),lt.current=t.rotation(),ct.current=t.height(),st.current=w(t)},onTransform:t=>{var e,r;const o=t.target;null===(e=O.current)||void 0===e||e.setAttrs({x:o.x(),y:o.y(),rotation:o.rotation(),scale:o.scale()});const n=st.current;if("middle-left"===n||"middle-right"===n){const t=o.scaleX(),e=o.width()*t,r=F(Et.current,a.a.fontSize);let n=e;e<r&&(n=r,yt.current&&o.position(yt.current)),o.width(n),o.scaleX(1),o.scaleY(1);let i=wt();if("ellipsis"===L(a)){i=at.current}else{const t=Math.max(i,at.current);o.height(t),a.set({height:o.height()})}const l=M.textVerticalResizeEnabled?Math.max(i,at.current):wt();a.set({x:o.x(),width:o.width(),rotation:o.rotation(),height:l}),o.skewX(0),o.skewY(0),bt()}if("top-center"===n||"bottom-center"===n){const e="resize"===L(a)?wt():jt*a.a.fontSize,r=t.target.height()*t.target.scaleY();if(r<e){if(t.target.height(e),yt.current){if("top-center"===st.current){const r=lt.current*Math.PI/180,o=ct.current-e;t.target.x(yt.current.x-o*Math.sin(r)),t.target.y(yt.current.y+o*Math.cos(r))}else{t.target.position(yt.current)}}}else{t.target.height(r)}t.target.scaleY(1),t.target.scaleX(1),t.target.rotation(lt.current),t.target.skewX(0),t.target.skewY(0),ct.current=Math.max(e,r)}yt.current=t.target.position();const i=j(t.target.scaleX());null===(r=O.current)||void 0===r||r.setAttrs({scaleX:1,scaleY:1}),t.target.scaleX(1),t.target.scaleY(1),a.set({fontSize:a.a.fontSize*i,width:t.target.width()*i,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),height:t.target.height()*i,shadowBlur:a.shadowBlur*i,shadowOffsetX:a.shadowOffsetX*i,shadowOffsetY:a.shadowOffsetY*i,strokeWidth:a.strokeWidth*i,borderSize:a.borderSize*i})},onTransformEnd:t=>{var e;const r=j(t.target.scaleX());t.target.scaleX(1),t.target.scaleY(1),a.set(Object.assign(Object.assign({},E(a,a.fontSize*r)),{width:Math.ceil(t.target.width()*r),x:k(t.target.x()),y:k(t.target.y()),rotation:k(t.target.rotation()),height:k(t.target.height()*r)})),null===(e=O.current)||void 0===e||e.setAttrs({scaleX:1,scaleY:1}),et(!1)}})),U&&a.contentEditable&&t(l,{x:a.a.x,y:a.a.y,rotation:a.a.rotation,children:t(ot,{textNodeRef:h,element:a,selectAll:Q,cursorPosition:zt.current,onBlur:()=>{a.set(z(a)),a.toggleEditMode(!1)}})})]})});
|
package/canvas/use-color.d.ts
CHANGED
|
@@ -1,14 +1,12 @@
|
|
|
1
1
|
import { AnimatedAttrs } from '../model/shape-model.js';
|
|
2
|
+
import type { TextElementLike } from '@polotno/core/text-types';
|
|
2
3
|
type ColorElement = {
|
|
3
4
|
a: Pick<AnimatedAttrs, 'width' | 'height'>;
|
|
4
5
|
width: number;
|
|
5
6
|
height: number;
|
|
6
7
|
fill?: string;
|
|
7
8
|
};
|
|
8
|
-
export declare const withDisplayTextPaints:
|
|
9
|
-
fill?: string;
|
|
10
|
-
stroke?: string;
|
|
11
|
-
}>(element: T) => T;
|
|
9
|
+
export declare const withDisplayTextPaints: (element: TextElementLike) => TextElementLike;
|
|
12
10
|
export declare const useColor: (element: ColorElement, value?: string, propName?: string) => {
|
|
13
11
|
[x: string]: string;
|
|
14
12
|
fillLinearGradientStartPointX?: undefined;
|
package/canvas/use-color.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import t from"react";import*as
|
|
1
|
+
import t from"react";import*as o from"@polotno/core/gradient";import{toDisplayColor as i}from"@polotno/core/color";import r from"konva";const e=Object.keys({id:!0,text:!0,width:!0,height:!0,fontSize:!0,fontFamily:!0,fontWeight:!0,fontStyle:!0,lineHeight:!0,letterSpacing:!0,textTransform:!0,textDecoration:!0,align:!0,fill:!0,stroke:!0,strokeWidth:!0,strokeLineJoin:!0,curveEnabled:!0,curvePower:!0,shadowBlur:!0,shadowOffsetX:!0,shadowOffsetY:!0,textOverflow:!0,maxLines:!0,minFontSize:!0,maxFontSize:!0,a:!0});export const withDisplayTextPaints=t=>{const o={};for(const r of e){r in t&&(o[r]="fill"===r||"stroke"===r?i(t[r]):t[r])}return o};export const useColor=(e,n,a)=>{var l;return void 0===n&&(n=null!==(l=e.fill)&&void 0!==l?l:""),void 0===a&&(a="fill"),t.useMemo(()=>{if(!o.isGradient(n)){return{[a]:i(n)}}const{stops:t,rotation:l}=o.parseColor(n),s=e.a.width/2,d=e.a.height/2,f=(l%180+180)%180,h=f>45&&f<135?e.a.width:e.a.height,c=r.Util.degToRad(l)-Math.PI/2,p=[];return t.forEach(({offset:t,color:o})=>{p.push(t,o)}),"fill"===a?{fillLinearGradientStartPointX:s-h/2*Math.cos(c),fillLinearGradientStartPointY:d-h/2*Math.sin(c),fillLinearGradientColorStops:p,fillLinearGradientEndPointX:s+h/2*Math.cos(c),fillLinearGradientEndPointY:d+h/2*Math.sin(c),fill:t[1].color,fillPriority:"linear-gradient"}:{strokeLinearGradientStartPointX:s-h/2*Math.cos(c),strokeLinearGradientStartPointY:d-h/2*Math.sin(c),strokeLinearGradientColorStops:p,strokeLinearGradientEndPointX:s+h/2*Math.cos(c),strokeLinearGradientEndPointY:d+h/2*Math.sin(c)}},[n,e.width,e.height])};
|
package/canvas/use-image.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"react";import{DEFAULT_RETRIES as r,isDeterministicUrl as t,retryDelayMs as n}from"@polotno/core/retry";export function useImage(o,
|
|
1
|
+
import e from"react";import{DEFAULT_RETRIES as r,isDeterministicUrl as t,retryDelayMs as n}from"@polotno/core/retry";import{refCountedCache as o}from"../utils/ref-counted.js";const u=o(),c=(e,r,t)=>`${null!=r?r:""}\0${null!=t?t:""}\0${e}`,i=(e,r)=>u.acquire(e,()=>r)[1];export function useImage(o,d,l){const s=e.useRef("loading"),a=e.useRef(void 0),[,f]=e.useState(0),m=e.useRef(void 0),v=e.useRef(void 0),g=e.useRef(void 0);if(m.current!==o||v.current!==d||g.current!==l){const e=o?u.get(c(o,d,l)):void 0;s.current=e?"loaded":"loading",a.current=e,m.current=o,v.current=d,g.current=l}return e.useLayoutEffect(()=>{if(!o){return}const e=c(o,d,l);if("loaded"===s.current&&a.current){return i(e,a.current)}const u=t(o)?1:r;let m,v,g,p=0,E=!1,L=!1;const R=(e,r)=>{s.current=r,a.current=e,f(Math.random())},y=()=>{p+=1;const r=document.createElement("img"),t=()=>{r.decode().catch(()=>{}).finally(()=>{E||(L=!0,g=i(e,r),R(r,"loaded"))})},c=()=>{if(!E){if(!L&&p<u){return null==v||v(),void(m=setTimeout(y,n(p)))}null==g||g(),g=void 0,R(void 0,"failed")}};r.addEventListener("load",t),r.addEventListener("error",c),v=()=>{r.removeEventListener("load",t),r.removeEventListener("error",c)},d&&(r.crossOrigin=d),l&&(r.referrerPolicy=l),r.src=o};return y(),()=>{E=!0,clearTimeout(m),null==v||v(),null==g||g()}},[o,d,l]),[a.current,s.current]}export default useImage;
|
package/canvas/video-element.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as e,jsxs as t,Fragment as r}from"react/jsx-runtime";import{elementOpacity as i}from"./paint-opacity.js";import o from"react";import{toDisplayColor as n}from"@polotno/core/color";import{observer as a}from"mobx-react-lite";import{isAlive as s}from"mobx-state-tree";import{nodeAutorun as d}from"../utils/mobx.js";import{Arc as c,Group as h,Image as l,Rect as u,Text as m}from"react-konva";import{ROLES as p}from"../model/store.js";import{DEFAULT_RETRIES as g,isDeterministicUrl as f,retryDelayMs as v}from"@polotno/core/retry";import w from"konva";import{useWorkspaceStyle as x}from"./workspace-style.js";import{incrementLoader as E,triggerLoadError as y}from"../utils/loader.js";import{polotnoError as M}from"@polotno/core/errors";import{getCropRect as L}from"@polotno/core/image";import*as T from"@polotno/core/svg";import{activeAnchorOf as C,roundedCropFraction as b,roundedGeometryPx as k,roundedPosition as I,isCornerAnchor as R,scaledStyleAttrs as j,roundedStyleAttrs as S}from"../utils/px.js";import{useFilteredSource as P}from"./use-filtered-source.js";import{useEvent as H}from"../hooks/use-event.js";import{useFadeIn as X}from"./use-fadein.js";import{isTouchDevice as Y}from"../utils/screen.js";import{createPlayGate as A,playMedia as W}from"../utils/media.js";import{useMediabunnyVideo as O}from"./use-mediabunny-video.js";import{getElementTimeRange as _,getVideoRestMs as D}from"../utils/timeline.js";import{drawReduced as z,exportKernelEnabled as V,shouldResample as U,sourceSize as Z}from"./downscale.js";import{trySetCanvasSize as B}from"../utils/canvas.js";import{useClipImage as F}from"./image-element.js";import{CropOverlay as N,CROP_CORNER_ANCHORS as $}from"./crop-overlay.js";const q=new window.Image;q.src=T.svgToURL('\n <svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path opacity="0.6" d="M4 5.49683V18.5032C4 20.05 5.68077 21.0113 7.01404 20.227L18.0694 13.7239C19.384 12.9506 19.384 11.0494 18.0694 10.2761L7.01404 3.77296C5.68077 2.98869 4 3.95 4 5.49683Z" fill="white"/>\n <path d="M4 5.49683V18.5032C4 20.05 5.68077 21.0113 7.01404 20.227L18.0694 13.7239C19.384 12.9506 19.384 11.0494 18.0694 10.2761L7.01404 3.77296C5.68077 2.98869 4 3.95 4 5.49683Z" stroke="#323232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n');const G=new window.Image;G.src=T.svgToURL('\n <svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path opacity="0.6" d="M14 19L14 5C14 3.89543 14.8954 3 16 3L17 3C18.1046 3 19 3.89543 19 5L19 19C19 20.1046 18.1046 21 17 21L16 21C14.8954 21 14 20.1046 14 19Z" fill="white"/>\n <path opacity="0.6" d="M10 19L10 5C10 3.89543 9.10457 3 8 3L7 3C5.89543 3 5 3.89543 5 5L5 19C5 20.1046 5.89543 21 7 21L8 21C9.10457 21 10 20.1046 10 19Z" fill="white"/>\n <path d="M14 19L14 5C14 3.89543 14.8954 3 16 3L17 3C18.1046 3 19 3.89543 19 5L19 19C19 20.1046 18.1046 21 17 21L16 21C14.8954 21 14 20.1046 14 19Z" stroke="#323232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n <path d="M10 19L10 5C10 3.89543 9.10457 3 8 3L7 3C5.89543 3 5 3.89543 5 5L5 19C5 20.1046 5.89543 21 7 21L8 21C9.10457 21 10 20.1046 10 19Z" stroke="#323232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n');export const useCornerRadiusAndCrop=(e,t,r,i,n=0,a=!1)=>{var s;const d=Math.floor(Math.max(e.width*i,1)),c=Math.floor(Math.max(e.height*i,1)),h=Math.min(n*i,d/2,c/2),l=Math.max(e.width/r.width,e.height/r.height)*i,u=V(e.page)&&!a&&U(l,d,c),{width:m,height:p}=t?Z(t):{},g=0===r.x&&0===r.y&&r.width===m&&r.height===p,f=o.useMemo(()=>{if(t&&m&&p){return g&&0===h&&!u?void 0:document.createElement("canvas")}},[t,h,u,g,m,p]),v=()=>{if(!f||!t){return}f.width=d,f.height=c;const e=f.getContext("2d");e&&(h&&(e.beginPath(),e.moveTo(h,0),e.lineTo(d-h,0),e.arc(d-h,h,h,3*Math.PI/2,0,!1),e.lineTo(d,c-h),e.arc(d-h,c-h,h,0,Math.PI/2,!1),e.lineTo(h,c),e.arc(h,c-h,h,Math.PI/2,Math.PI,!1),e.lineTo(0,h),e.arc(h,h,h,Math.PI,3*Math.PI/2,!1),e.clip()),u?z(e,t,r,f.width,f.height):e.drawImage(t,r.x,r.y,r.width,r.height,0,0,f.width,f.height))};return o.useLayoutEffect(()=>{v()},[f,e.width,e.height,r.x,r.y,r.width,r.height,n,i,a,null===(s=e.page)||void 0===s?void 0:s._exportingOrRendering,u]),o.useEffect(()=>()=>{f&&"CANVAS"===f.nodeName&&w.Util.releaseCanvas(f)},[f]),[f||t,v]};export const useClip=(e,t,r,i)=>{const[n,a]=F(e.clipSrc||""),s=e.clipSrc?a:"loaded";useLoader(s,e.clipSrc,e.id);const d=!!t&&!!n,c=o.useMemo(()=>d?{canvas:document.createElement("canvas"),mask:document.createElement("canvas"),width:0,height:0}:void 0,[d]),h=null==c?void 0:c.canvas;function l(){if(!c||!h||!t){return}const{width:i,height:o}=Z(t);if(!i||!o){return}const n=Math.min(1e4,Math.max(i,Math.ceil(e.a.width*r),1)),a=Math.min(1e4,Math.max(o,Math.ceil(e.a.height*r),1));c.width===n&&c.height===a||(B(h,n,a),c.width=n,c.height=a);const s=h.getContext("2d");s&&(s.clearRect(0,0,h.width,h.height),s.save(),s.drawImage(c.mask,0,0,h.width,h.height),s.globalCompositeOperation="source-in",s.drawImage(t,0,0,h.width,h.height),s.restore())}return o.useLayoutEffect(()=>{var t;if(!c||!(null==n?void 0:n.width)||!n.height){return}const i=Math.max(e.a.width/n.width*r,e.a.height/n.height*r);B(c.mask,Math.min(1e4,Math.max(n.width*i,1)),Math.min(1e4,Math.max(n.height*i,1))),null===(t=c.mask.getContext("2d"))||void 0===t||t.drawImage(n,0,0,c.mask.width,c.mask.height)},[c,n,e.a.width,e.a.height,r]),o.useLayoutEffect(()=>{l()},[c,t,n,e.a.width,e.a.height,r,...i]),o.useEffect(()=>()=>{c&&w.Util.releaseCanvas(c.canvas,c.mask)},[c]),[d?h:t,l]};const J=document.createElement("canvas"),K=a(({element:r})=>{const n=Math.min(30,r.width/4,r.height/4),a=o.useRef(null);o.useEffect(()=>{const e=a.current;if(!e){return}const t=new w.Animation(t=>{e.rotate(((null==t?void 0:t.timeDiff)||0)/2)},e.getLayer());return t.start(),()=>{t.stop()}});const{mediaLoadingStyle:s}=x();return t(h,{x:r.a.x,y:r.a.y,rotation:r.a.rotation,listening:!1,opacity:i(r),hideInExport:!r.showInExport,children:[e(u,{width:r.width,height:r.height,fill:s.fill}),e(c,{ref:a,x:r.width/2,y:r.height/2,fill:s.textFill,outerRadius:Math.abs(n),innerRadius:Math.max(1,n-5),angle:270})]})}),Q=a(({element:r})=>{const{mediaErrorStyle:o}=x(),n=Math.max(10,Math.min(30,r.width/25));return t(h,{x:r.a.x,y:r.a.y,rotation:r.a.rotation,listening:!1,opacity:i(r),hideInExport:!r.showInExport,children:[e(u,{width:r.width,height:r.height,fill:o.fill}),e(m,{text:"Can not load the video...",fontSize:n,width:r.width,height:r.height,align:"center",fill:o.textFill,verticalAlign:"middle",padding:5})]})});let ee=function(e,t,r){const i=o.useRef("loading"),n=o.useRef(void 0),[a,s]=o.useState(0),d=o.useRef(void 0),c=o.useRef(void 0),h=o.useRef(void 0);return d.current===e&&c.current===t&&h.current===r||(i.current="loading",n.current=void 0,d.current=e,c.current=t,h.current=r),o.useLayoutEffect(()=>{if(!e){return}const o=f(e)?1:g;let a,d,c,h=0,l=!1,u=!1;const m=e=>{e&&(e.removeAttribute("src"),e.load())},p=()=>{h+=1;const g=document.createElement("video");function f(){l||(g.removeEventListener("canplay",f),u=!0,i.current="loaded",n.current=g,g.currentTime=0,s(Math.random()))}function w(e){var t;const r=4===g.readyState,c=g.buffered&&g.buffered.length>0&&g.buffered.end(g.buffered.length-1)/g.duration*100>=100;if(r&&c){return}if(l){return}if(!u&&h<o){return null==d||d(),m(g),void(a=setTimeout(p,v(h)))}const f=e.message||(null===(t=g.error)||void 0===t?void 0:t.message)||"Unknown error";console.error(new Error("Video failed to load: "+f)),i.current="failed",n.current=void 0,s(Math.random())}c=g,g.addEventListener("canplay",f),g.addEventListener("error",w),d=()=>{g.removeEventListener("canplay",f),g.removeEventListener("error",w)},t&&(g.crossOrigin=t),r&&(g.referrerPolicy=r),g.src=e,g.load()};return p(),()=>{l=!0,clearTimeout(a),null==d||d(),u||m(c)}},[e,t,r]),[n.current,i.current]};export const setVideoLoaderHook=e=>{ee=e};function te(e){return!e.seeking&&e.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA}export const useLoader=(e,t,r)=>{const i=o.useRef(void 0),n=()=>{var e;null===(e=i.current)||void 0===e||e.call(i),i.current=void 0};o.useEffect(()=>n,[]),o.useLayoutEffect(()=>{const o=t.slice(0,200),a=`video with id ${r} url: ${o}`;"loading"!==e||i.current||(i.current=E(a)),"loading"!==e&&n(),"failed"===e&&y(M("VIDEO_FAILED",a,{src:o,elementId:r,reason:"load"}))},[e])};export const VideoElement=a(({element:a,store:c})=>{var m,g,f,v,x;const[y,M]=o.useState(!1),T=o.useRef(null),z=a.isSelected,[V,U]=o.useState(!1),[B,F]=ee(a.src,"anonymous"),[re,ie]=o.useState(!1),oe=c.activePage===a.page,ne=(null===(m=a.page)||void 0===m?void 0:m._exportingOrRendering)&&"loaded"===F,ae=O(a,c,ne);useLoader(F,a.src,a.id),B&&(B.playsInline=!0);const se=ne&&ae||B,[de,ce]=((e,t)=>{const{flipX:r,flipY:i}=e,{width:n,height:a}=t?Z(t):{},s=e=>{if(!t){return}const o=e.getContext("2d");o&&(o.clearRect(0,0,e.width,e.height),o.save(),o.scale(r?-1:1,i?-1:1),o.drawImage(t,r?-e.width:0,i?-e.height:0,e.width,e.height),o.restore())},d=o.useMemo(()=>{if(!r&&!i||!n||!a){return}const e=document.createElement("canvas");return e.width=n,e.height=a,s(e),e},[r,i,t,n,a]);return o.useEffect(()=>()=>{d&&w.Util.releaseCanvas(d)},[d]),[d||t,()=>{d&&s(d)}]})(a,se),[he=J,le]=P(a,de||J);o.useEffect(()=>{B&&c.history.ignore(()=>{a.set({duration:1e3*B.duration})})},[B]);const ue=o.useMemo(A,[B]);o.useEffect(()=>{var e;if(!B){return}const t=c.animatedElementsIds,r=(!t.length||t.includes(a.id))&&c.isPlaying;if(!oe||!r&&!V){return void B.pause()}V&&(B.muted=!1,B.currentTime=a.startTime*B.duration,W(B).then(e=>{"refused"===e&&U(!1)}));const i=new w.Animation(()=>{Se()},null===(e=T.current)||void 0===e?void 0:e.getLayer());i.start();const o=()=>{U(!1),B.currentTime=a.startTime*B.duration},n=()=>{B.currentTime>=a.endTime*B.duration&&(B.pause(),B.currentTime=a.startTime*B.duration,U(!1))};return B.addEventListener("ended",o),B.addEventListener("timeupdate",n),()=>{B.pause(),i.stop(),B.removeEventListener("ended",o),B.removeEventListener("timeupdate",n)}},[B,V,c.isPlaying,oe]),o.useEffect(()=>{B&&(B.volume=a.volume)},[B,a.volume]),o.useEffect(()=>{B&&(B.playbackRate=a.speed,B.preservesPitch=!1)},[B,a.speed]);const me=o.useRef(null);o.useEffect(()=>{const e=d(a,()=>{var e,t;if(B){if(ne&&ae){return Se(),void c.currentTime}const r=c.animatedElementsIds;if(r.length&&!r.includes(a.id)){return}const i=c.activePage===a.page,o=c.currentTime>=a.page.startTime&&c.currentTime<a.page.startTime+a.page.duration,n=a.startTime*B.duration*1e3,s=B.duration*(a.endTime-a.startTime)*1e3,{start:d,end:h}=_(a.animations,a.page.duration),l=(c.currentTime||a.page.startTime)-a.page.startTime,u=o?D(c.currentTime,a.page.startTime,d,s,n,a.speed):0,m=u/1e3,p=o&&l>=d&&l<h;V||(B.muted=!p,p&&c.isPlaying&&i?B.paused?(B.currentTime=m,ue.play(B)):Math.abs(1e3*B.currentTime-u)>500&&(B.currentTime=m):(ue.reset(),B.paused||B.pause(),m!==B.currentTime&&(B.currentTime=m),!te(B)&&!c.isPlaying&&!me.current&&(me.current=E(`video ${a.id}`)))),Se(),null===(t=null===(e=T.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()}});return()=>{e(),me.current&&(me.current(),me.current=null)}},[c,B,ne,ae,V]),o.useEffect(()=>{var e,t;if(!B){return}if(ne){return null===(e=me.current)||void 0===e||e.call(me),void(me.current=null)}const r=()=>{var e;te(B)&&(Se(),null===(e=me.current)||void 0===e||e.call(me),me.current=null)};let i;return(null===(t=a.page)||void 0===t?void 0:t._exportingOrRendering)&&(i=setInterval(r,20)),B.addEventListener("timeupdate",r),B.addEventListener("canplay",r),B.addEventListener("seeked",r),()=>{clearInterval(i),B.removeEventListener("timeupdate",r),B.removeEventListener("canplay",r),B.removeEventListener("seeked",r)}},[null===(g=a.page)||void 0===g?void 0:g._exportingOrRendering,B,a.id,E,ne]);let{cropX:pe,cropY:ge,cropWidth:fe,cropHeight:ve}=a;"loaded"!==F&&(pe=ge=0,fe=ve=1);const{width:we,height:xe}=Z(he),Ee=null!==(f=null==B?void 0:B.videoWidth)&&void 0!==f?f:0,ye=null!==(v=null==B?void 0:B.videoHeight)&&void 0!==v?v:0;o.useLayoutEffect(()=>{"loaded"===F&&Ee>0&&ye>0&&a._setSourceSize({width:Ee,height:ye},a.src)},[a,a.src,F,Ee,ye]);const Me=L({stretchEnabled:a.stretchEnabled,cropX:pe,cropY:ge,cropWidth:fe,cropHeight:ve,width:a.a.width,height:a.a.height},{width:we,height:xe}),Le=Me.width,Te=Me.height,Ce=a.stretchEnabled,be=null!==(x=a.cornerRadius)&&void 0!==x?x:0,[ke,Ie]=useCornerRadiusAndCrop(a,he,Me,c._elementsPixelRatio,be,!0);let[Re,je]=useClip(a,ke,c._elementsPixelRatio,[Me,be,c._elementsPixelRatio]);const Se=H(()=>{var e,t;ce(),le(),Ie(),je(),null===(t=null===(e=T.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()});o.useEffect(()=>{Se()});const Pe=()=>{a._cropEnabled&&setTimeout(()=>{s(a)&&a.toggleCropMode(!0)})},He="loading"===F,Xe="failed"===F,Ye=!He&&!Xe,Ae=o.useRef({cropX:0,cropY:0,cropWidth:0,cropHeight:0}),We=o.useRef(!1),Oe=Ye?i(a):0;X(T,Oe);const _e=a.selectable||c.role===p.ADMIN,De=Y();return e(r,{children:t(h,{onMouseEnter:()=>ie(!0),onMouseLeave:()=>ie(!1),children:[He&&e(K,{element:a}),Xe&&e(Q,{element:a}),e(l,{ref:T,name:"element",id:a.id,image:Re,x:a.a.x,y:a.a.y,width:a.a.width||1,height:a.a.height||1,rotation:a.a.rotation,opacity:Oe,shadowEnabled:a.shadowEnabled,shadowBlur:a.shadowBlur,shadowOffsetX:a.shadowOffsetX,shadowOffsetY:a.shadowOffsetY,shadowColor:n(a.shadowColor),shadowOpacity:a.shadowOpacity,customCrop:Me,listening:_e,draggable:De?a.draggable&&z:a.draggable,preventDefault:!De||z,hideInExport:!a.showInExport,onDragMove:e=>{a.set({x:e.target.x(),y:e.target.y()})},onDragEnd:e=>{a.set(I(e.target))},onDblClick:Pe,onDblTap:Pe,onTransformStart:e=>{M(!0),We.current=R(C(e.target)),Ae.current={cropX:a.cropX,cropY:a.cropY,cropWidth:a.cropWidth,cropHeight:a.cropHeight}},onTransform:e=>{const t=e.currentTarget,r=Math.abs(t.scaleX()-1)<1e-7?1:t.scaleX(),i=Math.abs(t.scaleY()-1)<1e-7?1:t.scaleY();t.scaleX(1),t.scaleY(1);const o=1-Le/we,n=Math.min(o,Math.max(0,a.cropX)),s=1-Te/xe,d=Math.min(s,Math.max(0,a.cropY)),c=We.current,h=!c&&r<1&&Ae.current.cropHeight>Te/xe;let l=c?a.cropWidth:a.cropWidth*r;h&&(l=a.cropWidth);const u=!c&&i<1&&Ae.current.cropWidth>Le/we;let m=c?a.cropHeight:a.cropHeight*i;u&&(m=a.cropHeight),Ce&&(l=a.cropWidth,m=a.cropHeight);const p=c?Math.min(r,i):1;a.set(Object.assign({cropX:n,cropY:d,x:t.x(),y:t.y(),width:t.width()*r,height:t.height()*i,rotation:e.target.rotation(),cropWidth:Math.min(l,1-n),cropHeight:Math.min(m,1-d)},1!==p&&j(a,p)))},onTransformEnd:e=>{const t=e.currentTarget;a.set(Object.assign({width:k(t.width()),height:k(t.height()),x:k(t.x()),y:k(t.y()),rotation:k(e.target.rotation()),cropX:b(a.cropX),cropY:b(a.cropY),cropWidth:b(Le/we),cropHeight:b(Te/xe)},S(a))),M(!1)}}),e(u,{x:a.a.x,y:a.a.y,width:Math.max(a.a.width-a.borderSize,0),height:Math.max(a.a.height-a.borderSize,0),opacity:Oe,offsetX:-a.borderSize/2,offsetY:-a.borderSize/2,stroke:n(a.borderColor),strokeWidth:a.borderSize,listening:!1,visible:!!a.borderSize,rotation:a.rotation,cornerRadius:Math.max(0,be-a.borderSize),hideInExport:!a.showInExport}),!c.isPlaying&&e(l,{image:V?re||De?G:void 0:q,x:a.a.x,y:a.a.y,offsetX:-a.a.width/2+15/c.scale,offsetY:-a.a.height/2+15/c.scale,rotation:a.a.rotation,width:30/c.scale,height:30/c.scale,hideInExport:!0,onClick:()=>U(!V),onTap:()=>U(!V)}),a._cropModeEnabled&&"loaded"===F&&e(N,{element:a,store:c,previewImage:Re,sourceImage:he,sourceWidth:we,sourceHeight:xe,cropAbsoluteWidth:Le,cropAbsoluteHeight:Te,innerAnchors:$})]})})});
|
|
1
|
+
import{jsx as e,jsxs as t,Fragment as r}from"react/jsx-runtime";import{elementOpacity as i}from"./paint-opacity.js";import o from"react";import{toDisplayColor as n}from"@polotno/core/color";import{observer as a}from"mobx-react-lite";import{isAlive as s}from"mobx-state-tree";import{nodeAutorun as d}from"../utils/mobx.js";import{Arc as c,Group as h,Image as l,Rect as u,Text as m}from"react-konva";import{ROLES as p}from"../model/store.js";import{DEFAULT_RETRIES as g,isDeterministicUrl as f,retryDelayMs as v}from"@polotno/core/retry";import w from"konva";import{useWorkspaceStyle as x}from"./workspace-style.js";import{incrementLoader as E,triggerLoadError as y}from"../utils/loader.js";import{polotnoError as M}from"@polotno/core/errors";import{getCropRect as L}from"@polotno/core/image";import*as T from"@polotno/core/svg";import{activeAnchorOf as C,roundedCropFraction as b,roundedGeometryPx as k,roundedPosition as I,isCornerAnchor as R,scaledStyleAttrs as j,roundedStyleAttrs as S,transformScale as P}from"../utils/px.js";import{useFilteredSource as H}from"./use-filtered-source.js";import{useEvent as A}from"../hooks/use-event.js";import{useFadeIn as W}from"./use-fadein.js";import{isTouchDevice as X}from"../utils/screen.js";import{createPlayGate as Y,playMedia as O}from"../utils/media.js";import{useMediabunnyVideo as _}from"./use-mediabunny-video.js";import{getElementTimeRange as D,getVideoRestMs as z}from"../utils/timeline.js";import{drawReduced as V,exportKernelEnabled as U,shouldResample as Z,sourceSize as B}from"./downscale.js";import{trySetCanvasSize as F}from"../utils/canvas.js";import{useClipImage as N}from"./image-element.js";import{CropOverlay as $,CROP_CORNER_ANCHORS as q}from"./crop-overlay.js";const G=new window.Image;G.src=T.svgToURL('\n <svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path opacity="0.6" d="M4 5.49683V18.5032C4 20.05 5.68077 21.0113 7.01404 20.227L18.0694 13.7239C19.384 12.9506 19.384 11.0494 18.0694 10.2761L7.01404 3.77296C5.68077 2.98869 4 3.95 4 5.49683Z" fill="white"/>\n <path d="M4 5.49683V18.5032C4 20.05 5.68077 21.0113 7.01404 20.227L18.0694 13.7239C19.384 12.9506 19.384 11.0494 18.0694 10.2761L7.01404 3.77296C5.68077 2.98869 4 3.95 4 5.49683Z" stroke="#323232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n');const J=new window.Image;J.src=T.svgToURL('\n <svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path opacity="0.6" d="M14 19L14 5C14 3.89543 14.8954 3 16 3L17 3C18.1046 3 19 3.89543 19 5L19 19C19 20.1046 18.1046 21 17 21L16 21C14.8954 21 14 20.1046 14 19Z" fill="white"/>\n <path opacity="0.6" d="M10 19L10 5C10 3.89543 9.10457 3 8 3L7 3C5.89543 3 5 3.89543 5 5L5 19C5 20.1046 5.89543 21 7 21L8 21C9.10457 21 10 20.1046 10 19Z" fill="white"/>\n <path d="M14 19L14 5C14 3.89543 14.8954 3 16 3L17 3C18.1046 3 19 3.89543 19 5L19 19C19 20.1046 18.1046 21 17 21L16 21C14.8954 21 14 20.1046 14 19Z" stroke="#323232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n <path d="M10 19L10 5C10 3.89543 9.10457 3 8 3L7 3C5.89543 3 5 3.89543 5 5L5 19C5 20.1046 5.89543 21 7 21L8 21C9.10457 21 10 20.1046 10 19Z" stroke="#323232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n');export const useCornerRadiusAndCrop=(e,t,r,i,n=0,a=!1)=>{var s;const d=Math.floor(Math.max(e.width*i,1)),c=Math.floor(Math.max(e.height*i,1)),h=Math.min(n*i,d/2,c/2),l=Math.max(e.width/r.width,e.height/r.height)*i,u=U(e.page)&&!a&&Z(l,d,c),{width:m,height:p}=t?B(t):{},g=0===r.x&&0===r.y&&r.width===m&&r.height===p,f=o.useMemo(()=>{if(t&&m&&p){return g&&0===h&&!u?void 0:document.createElement("canvas")}},[t,h,u,g,m,p]),v=()=>{if(!f||!t){return}f.width=d,f.height=c;const e=f.getContext("2d");e&&(h&&(e.beginPath(),e.moveTo(h,0),e.lineTo(d-h,0),e.arc(d-h,h,h,3*Math.PI/2,0,!1),e.lineTo(d,c-h),e.arc(d-h,c-h,h,0,Math.PI/2,!1),e.lineTo(h,c),e.arc(h,c-h,h,Math.PI/2,Math.PI,!1),e.lineTo(0,h),e.arc(h,h,h,Math.PI,3*Math.PI/2,!1),e.clip()),u?V(e,t,r,f.width,f.height):e.drawImage(t,r.x,r.y,r.width,r.height,0,0,f.width,f.height))};return o.useLayoutEffect(()=>{v()},[f,e.width,e.height,r.x,r.y,r.width,r.height,n,i,a,null===(s=e.page)||void 0===s?void 0:s._exportingOrRendering,u]),o.useEffect(()=>()=>{f&&"CANVAS"===f.nodeName&&w.Util.releaseCanvas(f)},[f]),[f||t,v]};export const useClip=(e,t,r,i)=>{const[n,a]=N(e.clipSrc||""),s=e.clipSrc?a:"loaded";useLoader(s,e.clipSrc,e.id);const d=!!t&&!!n,c=o.useMemo(()=>d?{canvas:document.createElement("canvas"),mask:document.createElement("canvas"),width:0,height:0}:void 0,[d]),h=null==c?void 0:c.canvas;function l(){if(!c||!h||!t){return}const{width:i,height:o}=B(t);if(!i||!o){return}const n=Math.min(1e4,Math.max(i,Math.ceil(e.a.width*r),1)),a=Math.min(1e4,Math.max(o,Math.ceil(e.a.height*r),1));c.width===n&&c.height===a||(F(h,n,a),c.width=n,c.height=a);const s=h.getContext("2d");s&&(s.clearRect(0,0,h.width,h.height),s.save(),s.drawImage(c.mask,0,0,h.width,h.height),s.globalCompositeOperation="source-in",s.drawImage(t,0,0,h.width,h.height),s.restore())}return o.useLayoutEffect(()=>{var t;if(!c||!(null==n?void 0:n.width)||!n.height){return}const i=Math.max(e.a.width/n.width*r,e.a.height/n.height*r);F(c.mask,Math.min(1e4,Math.max(n.width*i,1)),Math.min(1e4,Math.max(n.height*i,1))),null===(t=c.mask.getContext("2d"))||void 0===t||t.drawImage(n,0,0,c.mask.width,c.mask.height)},[c,n,e.a.width,e.a.height,r]),o.useLayoutEffect(()=>{l()},[c,t,n,e.a.width,e.a.height,r,...i]),o.useEffect(()=>()=>{c&&w.Util.releaseCanvas(c.canvas,c.mask)},[c]),[d?h:t,l]};const K=document.createElement("canvas"),Q=a(({element:r})=>{const n=Math.min(30,r.width/4,r.height/4),a=o.useRef(null);o.useEffect(()=>{const e=a.current;if(!e){return}const t=new w.Animation(t=>{e.rotate(((null==t?void 0:t.timeDiff)||0)/2)},e.getLayer());return t.start(),()=>{t.stop()}});const{mediaLoadingStyle:s}=x();return t(h,{x:r.a.x,y:r.a.y,rotation:r.a.rotation,listening:!1,opacity:i(r),hideInExport:!r.showInExport,children:[e(u,{width:r.width,height:r.height,fill:s.fill}),e(c,{ref:a,x:r.width/2,y:r.height/2,fill:s.textFill,outerRadius:Math.abs(n),innerRadius:Math.max(1,n-5),angle:270})]})}),ee=a(({element:r})=>{const{mediaErrorStyle:o}=x(),n=Math.max(10,Math.min(30,r.width/25));return t(h,{x:r.a.x,y:r.a.y,rotation:r.a.rotation,listening:!1,opacity:i(r),hideInExport:!r.showInExport,children:[e(u,{width:r.width,height:r.height,fill:o.fill}),e(m,{text:"Can not load the video...",fontSize:n,width:r.width,height:r.height,align:"center",fill:o.textFill,verticalAlign:"middle",padding:5})]})});let te=function(e,t,r){const i=o.useRef("loading"),n=o.useRef(void 0),[a,s]=o.useState(0),d=o.useRef(void 0),c=o.useRef(void 0),h=o.useRef(void 0);return d.current===e&&c.current===t&&h.current===r||(i.current="loading",n.current=void 0,d.current=e,c.current=t,h.current=r),o.useLayoutEffect(()=>{if(!e){return}const o=f(e)?1:g;let a,d,c,h=0,l=!1,u=!1;const m=e=>{e&&(e.removeAttribute("src"),e.load())},p=()=>{h+=1;const g=document.createElement("video");function f(){l||(g.removeEventListener("canplay",f),u=!0,i.current="loaded",n.current=g,g.currentTime=0,s(Math.random()))}function w(e){var t;const r=4===g.readyState,c=g.buffered&&g.buffered.length>0&&g.buffered.end(g.buffered.length-1)/g.duration*100>=100;if(r&&c){return}if(l){return}if(!u&&h<o){return null==d||d(),m(g),void(a=setTimeout(p,v(h)))}const f=e.message||(null===(t=g.error)||void 0===t?void 0:t.message)||"Unknown error";console.error(new Error("Video failed to load: "+f)),i.current="failed",n.current=void 0,s(Math.random())}c=g,g.addEventListener("canplay",f),g.addEventListener("error",w),d=()=>{g.removeEventListener("canplay",f),g.removeEventListener("error",w)},t&&(g.crossOrigin=t),r&&(g.referrerPolicy=r),g.src=e,g.load()};return p(),()=>{l=!0,clearTimeout(a),null==d||d(),u||m(c)}},[e,t,r]),[n.current,i.current]};export const setVideoLoaderHook=e=>{te=e};function re(e){return!e.seeking&&e.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA}export const useLoader=(e,t,r)=>{const i=o.useRef(void 0),n=()=>{var e;null===(e=i.current)||void 0===e||e.call(i),i.current=void 0};o.useEffect(()=>n,[]),o.useLayoutEffect(()=>{const o=t.slice(0,200),a=`video with id ${r} url: ${o}`;"loading"!==e||i.current||(i.current=E(a)),"loading"!==e&&n(),"failed"===e&&y(M("VIDEO_FAILED",a,{src:o,elementId:r,reason:"load"}))},[e])};export const VideoElement=a(({element:a,store:c})=>{var m,g,f,v,x;const[y,M]=o.useState(!1),T=o.useRef(null),V=X(),[U,Z]=o.useState(!1),[F,N]=te(a.src,"anonymous"),[ie,oe]=o.useState(!1),ne=c.activePage===a.page,ae=(null===(m=a.page)||void 0===m?void 0:m._exportingOrRendering)&&"loaded"===N,se=_(a,c,ae);useLoader(N,a.src,a.id),F&&(F.playsInline=!0);const de=ae&&se||F,[ce,he]=((e,t)=>{const{flipX:r,flipY:i}=e,{width:n,height:a}=t?B(t):{},s=e=>{if(!t){return}const o=e.getContext("2d");o&&(o.clearRect(0,0,e.width,e.height),o.save(),o.scale(r?-1:1,i?-1:1),o.drawImage(t,r?-e.width:0,i?-e.height:0,e.width,e.height),o.restore())},d=o.useMemo(()=>{if(!r&&!i||!n||!a){return}const e=document.createElement("canvas");return e.width=n,e.height=a,s(e),e},[r,i,t,n,a]);return o.useEffect(()=>()=>{d&&w.Util.releaseCanvas(d)},[d]),[d||t,()=>{d&&s(d)}]})(a,de),[le=K,ue]=H(a,ce||K);o.useEffect(()=>{F&&c.history.ignore(()=>{a.set({duration:1e3*F.duration})})},[F]);const me=o.useMemo(Y,[F]);o.useEffect(()=>{var e;if(!F){return}const t=c.animatedElementsIds,r=(!t.length||t.includes(a.id))&&c.isPlaying;if(!ne||!r&&!U){return void F.pause()}U&&(F.muted=!1,F.currentTime=a.startTime*F.duration,O(F).then(e=>{"refused"===e&&Z(!1)}));const i=new w.Animation(()=>{Pe()},null===(e=T.current)||void 0===e?void 0:e.getLayer());i.start();const o=()=>{Z(!1),F.currentTime=a.startTime*F.duration},n=()=>{F.currentTime>=a.endTime*F.duration&&(F.pause(),F.currentTime=a.startTime*F.duration,Z(!1))};return F.addEventListener("ended",o),F.addEventListener("timeupdate",n),()=>{F.pause(),i.stop(),F.removeEventListener("ended",o),F.removeEventListener("timeupdate",n)}},[F,U,c.isPlaying,ne]),o.useEffect(()=>{F&&(F.volume=a.volume)},[F,a.volume]),o.useEffect(()=>{F&&(F.playbackRate=a.speed,F.preservesPitch=!1)},[F,a.speed]);const pe=o.useRef(null);o.useEffect(()=>{const e=d(a,()=>{var e,t;if(F){if(ae&&se){return Pe(),void c.currentTime}const r=c.animatedElementsIds;if(r.length&&!r.includes(a.id)){return}const i=c.activePage===a.page,o=c.currentTime>=a.page.startTime&&c.currentTime<a.page.startTime+a.page.duration,n=a.startTime*F.duration*1e3,s=F.duration*(a.endTime-a.startTime)*1e3,{start:d,end:h}=D(a.animations,a.page.duration),l=(c.currentTime||a.page.startTime)-a.page.startTime,u=o?z(c.currentTime,a.page.startTime,d,s,n,a.speed):0,m=u/1e3,p=o&&l>=d&&l<h;U||(F.muted=!p,p&&c.isPlaying&&i?F.paused?(F.currentTime=m,me.play(F)):Math.abs(1e3*F.currentTime-u)>500&&(F.currentTime=m):(me.reset(),F.paused||F.pause(),m!==F.currentTime&&(F.currentTime=m),!re(F)&&!c.isPlaying&&!pe.current&&(pe.current=E(`video ${a.id}`)))),Pe(),null===(t=null===(e=T.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()}});return()=>{e(),pe.current&&(pe.current(),pe.current=null)}},[c,F,ae,se,U]),o.useEffect(()=>{var e,t;if(!F){return}if(ae){return null===(e=pe.current)||void 0===e||e.call(pe),void(pe.current=null)}const r=()=>{var e;re(F)&&(Pe(),null===(e=pe.current)||void 0===e||e.call(pe),pe.current=null)};let i;return(null===(t=a.page)||void 0===t?void 0:t._exportingOrRendering)&&(i=setInterval(r,20)),F.addEventListener("timeupdate",r),F.addEventListener("canplay",r),F.addEventListener("seeked",r),()=>{clearInterval(i),F.removeEventListener("timeupdate",r),F.removeEventListener("canplay",r),F.removeEventListener("seeked",r)}},[null===(g=a.page)||void 0===g?void 0:g._exportingOrRendering,F,a.id,E,ae]);let{cropX:ge,cropY:fe,cropWidth:ve,cropHeight:we}=a;"loaded"!==N&&(ge=fe=0,ve=we=1);const{width:xe,height:Ee}=B(le),ye=null!==(f=null==F?void 0:F.videoWidth)&&void 0!==f?f:0,Me=null!==(v=null==F?void 0:F.videoHeight)&&void 0!==v?v:0;o.useLayoutEffect(()=>{"loaded"===N&&ye>0&&Me>0&&a._setSourceSize({width:ye,height:Me},a.src)},[a,a.src,N,ye,Me]);const Le=L({stretchEnabled:a.stretchEnabled,cropX:ge,cropY:fe,cropWidth:ve,cropHeight:we,width:a.a.width,height:a.a.height},{width:xe,height:Ee}),Te=Le.width,Ce=Le.height,be=a.stretchEnabled,ke=null!==(x=a.cornerRadius)&&void 0!==x?x:0,[Ie,Re]=useCornerRadiusAndCrop(a,le,Le,c._elementsPixelRatio,ke,!0);let[je,Se]=useClip(a,Ie,c._elementsPixelRatio,[Le,ke,c._elementsPixelRatio]);const Pe=A(()=>{var e,t;he(),ue(),Re(),Se(),null===(t=null===(e=T.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()});o.useEffect(()=>{Pe()});const He=()=>{a._cropEnabled&&setTimeout(()=>{s(a)&&a.toggleCropMode(!0)})},Ae="loading"===N,We="failed"===N,Xe=!Ae&&!We,Ye=o.useRef({cropX:0,cropY:0,cropWidth:0,cropHeight:0}),Oe=o.useRef(!1),_e=Xe?i(a):0;W(T,_e);const De=a.selectable||c.role===p.ADMIN;return e(r,{children:t(h,{onMouseEnter:()=>oe(!0),onMouseLeave:()=>oe(!1),children:[Ae&&e(Q,{element:a}),We&&e(ee,{element:a}),e(l,{ref:T,name:"element",id:a.id,image:je,x:a.a.x,y:a.a.y,width:a.a.width||1,height:a.a.height||1,rotation:a.a.rotation,opacity:_e,shadowEnabled:a.shadowEnabled,shadowBlur:a.shadowBlur,shadowOffsetX:a.shadowOffsetX,shadowOffsetY:a.shadowOffsetY,shadowColor:n(a.shadowColor),shadowOpacity:a.shadowOpacity,customCrop:Le,listening:De,draggable:V?a.draggable&&a.isSelected:a.draggable,preventDefault:!V||a.isSelected,hideInExport:!a.showInExport,onDragMove:e=>{a.set({x:e.target.x(),y:e.target.y()})},onDragEnd:e=>{a.set(I(e.target))},onDblClick:He,onDblTap:He,onTransformStart:e=>{M(!0),Oe.current=R(C(e.target)),Ye.current={cropX:a.cropX,cropY:a.cropY,cropWidth:a.cropWidth,cropHeight:a.cropHeight}},onTransform:e=>{const t=e.currentTarget,r=P(t.scaleX()),i=P(t.scaleY());t.scaleX(1),t.scaleY(1);const o=1-Te/xe,n=Math.min(o,Math.max(0,a.cropX)),s=1-Ce/Ee,d=Math.min(s,Math.max(0,a.cropY)),c=Oe.current,h=!c&&r<1&&Ye.current.cropHeight>Ce/Ee;let l=c?a.cropWidth:a.cropWidth*r;h&&(l=a.cropWidth);const u=!c&&i<1&&Ye.current.cropWidth>Te/xe;let m=c?a.cropHeight:a.cropHeight*i;u&&(m=a.cropHeight),be&&(l=a.cropWidth,m=a.cropHeight);const p=c?Math.min(r,i):1;a.set(Object.assign({cropX:n,cropY:d,x:t.x(),y:t.y(),width:t.width()*r,height:t.height()*i,rotation:e.target.rotation(),cropWidth:Math.min(l,1-n),cropHeight:Math.min(m,1-d)},1!==p&&j(a,p)))},onTransformEnd:e=>{const t=e.currentTarget;a.set(Object.assign({width:k(t.width()),height:k(t.height()),x:k(t.x()),y:k(t.y()),rotation:k(e.target.rotation()),cropX:b(a.cropX),cropY:b(a.cropY),cropWidth:b(Te/xe),cropHeight:b(Ce/Ee)},S(a))),M(!1)}}),!!a.borderSize&&e(u,{x:a.a.x,y:a.a.y,width:Math.max(a.a.width-a.borderSize,0),height:Math.max(a.a.height-a.borderSize,0),opacity:_e,offsetX:-a.borderSize/2,offsetY:-a.borderSize/2,stroke:n(a.borderColor),strokeWidth:a.borderSize,listening:!1,rotation:a.a.rotation,cornerRadius:Math.max(0,ke-a.borderSize),hideInExport:!a.showInExport}),!c.isPlaying&&e(l,{image:U?ie||V?J:void 0:G,x:a.a.x,y:a.a.y,offsetX:-a.a.width/2+15/c.scale,offsetY:-a.a.height/2+15/c.scale,rotation:a.a.rotation,width:30/c.scale,height:30/c.scale,hideInExport:!0,onClick:()=>Z(!U),onTap:()=>Z(!U)}),a._cropModeEnabled&&"loaded"===N&&e($,{element:a,store:c,previewImage:je,sourceImage:le,sourceWidth:xe,sourceHeight:Ee,cropAbsoluteWidth:Te,cropAbsoluteHeight:Ce,innerAnchors:q})]})})});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as e,jsxs as t}from"react/jsx-runtime";import r from"react";import{observer as o}from"mobx-react-lite";import n from"./page.js";import{TopRules as l}from"./rules.js";import{AudioElement as i}from"./audio.js";import{handleHotkey as s,handleCopyEvent as a,handleCutEvent as c,handlePasteEvent as u}from"./hotkeys.js";import{t as d}from"../utils/l10n.js";import{WorkspaceStyleProvider as h,useResolvedWorkspaceStyle as g}from"./workspace-style.js";const p=(e,t,r)=>Math.max(t,Math.min(r,e)),f=(e,t)=>Math.sqrt(Math.pow(t.clientX-e.clientX,2)+Math.pow(t.clientY-e.clientY,2)),m=({store:r})=>t("div",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",textAlign:"center"},children:[e("p",{children:d("workspace.noPages")}),e("button",{onClick:()=>{r.addPage()},children:d("workspace.addPage")})]}),v=({width:t,height:r,xPadding:o,yPadding:n,backgroundColor:l})=>e("div",{style:{width:t+"px",height:r+"px",backgroundColor:l,paddingLeft:o+"px",paddingRight:o+"px",paddingTop:n+"px",paddingBottom:n+"px",flexShrink:0},children:e("div",{style:{width:" 100%",height:"100%",backgroundColor:"white"}})});export const WorkspaceCanvas=o(({store:o,layout:d="vertical",pageControlsEnabled:w,backgroundColor:x,transparencyBackgroundColor:y,pageBorderColor:L,activePageBorderColor:T,bleedColor:b,snapGuideStroke:k,snapGuideStrokeWidth:S,snapGuideDash:E,selectionRectFill:M,selectionRectStroke:C,selectionRectStrokeWidth:P,transformLabelFill:R,transformLabelTextFill:F,cropOverlayFill:W,cropGridStyle:B,transformerStyle:O,innerImageCropTransformerStyle:z,outerImageCropTransformerStyle:j,highlighterStyle:N,mediaLoadingStyle:H,mediaErrorStyle:G,textOverflowIndicatorStyle:I,distanceGuideStroke:_,distanceLabelFill:Y,distanceLabelTextFill:D,rulerBackgroundColor:X,rulerTextColor:A,rulerBorderColor:K,rulerBorderSize:q,rulerTickColor:V,rulerTickSize:J,components:Q,onKeyDown:U,onPaste:Z,paddingX:$,paddingY:ee,pageGap:te,altCloneEnabled:re=!0,groupSelectionMode:oe="drill",visiblePagesOffset:ne,renderOnlyActivePage:le,scrollToPageThreshold:ie=.5,tooltipSafeArea:se})=>{var ae;const ce="horizontal"===d,ue=null!=$?$:20,de=null!=ee?ee:55,[he,ge]=r.useState({width:100,height:100}),pe=r.useRef(he),fe=r.useRef(null),me=r.useRef(null),ve=r.useRef(0);let we=0,xe=0,ye=0,Le=0;if(o.bleedVisible){for(const e of o.pages){const t=e.computedBleed;we=Math.max(we,t.left),xe=Math.max(xe,t.right),ye=Math.max(ye,t.top),Le=Math.max(Le,t.bottom)}}const Te=Math.max(...o.pages.map(e=>e.computedWidth)),be=Math.max(...o.pages.map(e=>e.computedHeight)),ke=(null===(ae=o.activePage)||void 0===ae?void 0:ae.computedHeight)||0,Se=Te+we+xe,Ee=(le?ke:be)+ye+Le,Me=async({skipTimeout:e}={skipTimeout:!1})=>{if(e||await new Promise(e=>setTimeout(e,50)),null===fe.current){return}if(!Number.isFinite(Se)||!Number.isFinite(Ee)){return}const t=fe.current.getBoundingClientRect();0!==t.width&&0!==t.height||(console.warn("Polotno warning: <Workspace /> component can not automatically detect its size.\nWidth or height of parent elements is equal 0.\nPlease make sure it has non-zero size. You may need to adjust it with your styles. <Workspace /> will automatically fit into parent container.\nFor simpler debugging here is the log of the parent element:"),console.log(fe.current));const r=me.current.clientWidth||t.width,n={width:r,height:t.height};(pe.current.width!==n.width||pe.current.height!==n.height)&&(ge(n),pe.current=n);const l=(r-2*ue)/Se,i=o.pages.length>1?3.1:2,s=(t.height-de*i)/Ee,a=o.pages.length>1?3.1:2,c=(r-ue*a)/Se,u=(t.height-2*de)/Ee,d=o.pages.length?Math.max(Math.min(ce?c:l,ce?u:s),.01):1;o.scaleToFit!==d&&(o.setScale(d),o._setScaleToFit(d))};r.useLayoutEffect(()=>{Me({skipTimeout:!0})},[]),r.useEffect(()=>{Me()},[Se,Ee,ee,$]),r.useLayoutEffect(()=>{Me({skipTimeout:!0})},[o.openedSidePanel]),r.useEffect(()=>{o.__()},[]),r.useEffect(()=>{const e=fe.current;if(window.ResizeObserver){const t=new ResizeObserver(()=>{Me({skipTimeout:!0})});return t.observe(e),()=>t.unobserve(e)}{const e=setInterval(()=>{Me({skipTimeout:!0})},100);return()=>clearInterval(e)}},[Se,Ee]);const Ce=le?1:o.pages.length;let Pe,Re;if(ce){const e=Se*o.scale*Ce;Pe=Math.max(ue,(he.width-e)/Ce/2),Re=Math.max(de,(he.height-Ee*o.scale)/2)}else{Pe=Math.max(ue,(he.width-Se*o.scale)/2);const e=Ee*o.scale*Ce;Re=Math.max(de,(he.height-e)/Ce/2)}Number.isNaN(Pe)&&(Pe=ue),Number.isNaN(Re)&&(Re=de),r.useEffect(()=>{const e=e=>{U?U(e,o):s(e,o,fe.current)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[]),r.useEffect(()=>{const e=e=>a(e,o,fe.current),t=e=>c(e,o,fe.current),r=e=>{Z?Z(e,o):u(e,o,fe.current)};return window.addEventListener("copy",e),window.addEventListener("cut",t),window.addEventListener("paste",r),()=>{window.removeEventListener("copy",e),window.removeEventListener("cut",t),window.removeEventListener("paste",r)}},[Z]),r.useEffect(()=>{const e=e=>{if(e.ctrlKey||e.metaKey){e.preventDefault();const t=Math.max(5,o.scaleToFit);let r=Math.min(.1,o.scaleToFit);ce&&Se>0&&Number.isFinite(Se)&&(r=Math.max(r,300/Se)),r=Math.max(r,.01);const n=.03,l=p(e.deltaY<0?o.scale*(1+n):o.scale/(1+n),r,t);return void o.setScale(l)}},t=me.current;return null==t||t.addEventListener("wheel",e),()=>null==t?void 0:t.removeEventListener("wheel",e)},[ce,Se,o]),r.useEffect(()=>{const e=me.current;if(!e){return}const t=e=>{2===e.touches.length&&(ve.current=f(e.touches[0],e.touches[1]))},r=t=>{if(2===t.touches.length&&ve.current>0){t.preventDefault();const r=f(t.touches[0],t.touches[1]),n=r/ve.current,l=Math.max(5,o.scaleToFit);let i=Math.min(.1,o.scaleToFit);ce&&Se>0&&Number.isFinite(Se)&&(i=Math.max(i,300/Se)),i=Math.max(i,.01);const s=o.scale,a=p(s*n,i,l),c=a/s,u=e.getBoundingClientRect(),d=(t.touches[0].clientX+t.touches[1].clientX)/2-u.left,h=(t.touches[0].clientY+t.touches[1].clientY)/2-u.top,g=e.scrollLeft+d,m=e.scrollTop+h;Ne.current=!0,o.setScale(a),e.scrollLeft=g*c-d,e.scrollTop=m*c-h,ve.current=r}},n=()=>{ve.current=0};return e.addEventListener("touchstart",t,{passive:!0}),e.addEventListener("touchmove",r,{passive:!1}),e.addEventListener("touchend",n,{passive:!0}),()=>{e.removeEventListener("touchstart",t),e.removeEventListener("touchmove",r),e.removeEventListener("touchend",n)}},[ce,Se,o]);const Fe=void 0!==te,We=o.pages.map(e=>{if(ce){const t=(e.computedWidth+we+xe)*o.scale;return Fe?t+te:t+2*Pe}{const t=(e.computedHeight+ye+Le)*o.scale;return Fe?t+te:t+2*Re}}),Be=[];let Oe=Fe?ce?Pe:Re:0;for(let e=0;e<We.length;e++){Be.push(Oe),Oe+=We[e]}const ze=We.reduce((e,t)=>e+t,0),je=Fe?ze+(ce?2*Pe:2*Re):ze,Ne=r.useRef(!1),[,He]=r.useReducer(e=>e+1,0);((e,t,o,n,l)=>{const i=r.useRef(0),s=r.useRef(0),a=r.useRef(null),c=r.useRef(null),u=r.useRef(!1),d=r.useRef(n.pages.length);u.current=d.current!==n.pages.length,d.current=n.pages.length,r.useEffect(()=>{const t=e.current,r=()=>{i.current=t.scrollLeft,s.current=t.scrollTop,a.current=t.scrollWidth,c.current=t.scrollHeight};return t.addEventListener("scroll",r),r(),()=>{t.removeEventListener("scroll",r)}},[]),r.useLayoutEffect(()=>{if(!e.current){return}if(u.current){const t=e.current;return a.current=t.scrollWidth,c.current=t.scrollHeight,i.current=t.scrollLeft,void(s.current=t.scrollTop)}const t=e.current,r=a.current,o=c.current;if(null===r||null===o){return a.current=t.scrollWidth,c.current=t.scrollHeight,i.current=t.scrollLeft,void(s.current=t.scrollTop)}l.current=!0;const n=t.offsetWidth,d=t.offsetHeight,h=(i.current+n/2)/r,g=(s.current+d/2)/o,f=Math.max(0,t.scrollWidth-n),m=Math.max(0,t.scrollHeight-d);t.scrollLeft=p(h*t.scrollWidth-n/2,0,f),t.scrollTop=p(g*t.scrollHeight-d/2,0,m),a.current=t.scrollWidth,c.current=t.scrollHeight,i.current=t.scrollLeft,s.current=t.scrollTop},[o,t])})(me,je,o.scale,o,Ne);const{handleScroll:Ge}=((e,t,o,n,l,i,s,a,c,u)=>{const d=r.useRef(!1),h=r.useRef(null),g=r.useRef(!1),p="horizontal"===c;r.useEffect(()=>{const t=e.current,r=()=>{s.current};return t.addEventListener("scroll",r),()=>{t.removeEventListener("scroll",r)}},[]);const f=n.pages.indexOf(n.activePage);return r.useLayoutEffect(()=>{if(a){return}if(!n.activePage){return}if(!e.current){return}if(d.current){return}const r=e.current,i=n.pages.indexOf(n.activePage),s=t[i]||0,c=p?r.scrollLeft:r.scrollTop,h=p?r.scrollWidth-r.clientWidth:r.scrollHeight-r.clientHeight,f=Math.min(s,Math.max(0,h)),m=o[i]||o[0]||0;let v=()=>{};return(Math.abs(f-c)>m*l||g.current)&&(g.current=!0,v=(({element:e,scrollTop:t,scrollLeft:r,duration:o=300,onFinish:n=()=>{}})=>{const l=void 0!==t,i=l?e.scrollTop:e.scrollLeft,s=l?t:r,a=s-i;let c=0,u=!1;if(0===o){return l?e.scrollTop=s:e.scrollLeft=s,()=>{}}const d=()=>{if(u){return}c+=20;const t=h(c,i,a,o);l?e.scrollTop=t:e.scrollLeft=t,c<o?setTimeout(d,20):n()},h=(e,t,r,o)=>(e/=o/2)<1?r/2*e*e+t:-r/2*(--e*(e-2)-1)+t;return d(),()=>{u=!0}})(Object.assign(Object.assign({element:r},p?{scrollLeft:f}:{scrollTop:f}),{onFinish:()=>{g.current=!1,null==u||u()},duration:n.isPlaying?0:300}))),v},[n.activePage,f,n.isPlaying,a,c]),{handleScroll:e=>{if(a){return}if(g.current){return}d.current=!0,clearTimeout(h.current),h.current=setTimeout(()=>{d.current=!1},300);const r=(p?e.currentTarget.scrollLeft:e.currentTarget.scrollTop)+(p?i.width:i.height)/3;let o=0;for(let n=t.length-1;n>=0;n--){if(r>=t[n]){o=n;break}}const l=n.pages[o];l&&n.activePage!==l&&l.select()}}})(me,Be,We,o,ie,he,Ne,le,d,He),Ie=he.width>=Se*o.scale+2*Pe,_e=he.height>=Ee*o.scale+2*Re,Ye=x||"rgba(232, 232, 232, 0.9)",De=(null==Q?void 0:Q.NoPages)||m,Xe=ce?he.width:he.height,Ae=me.current?ce?me.current.scrollLeft:me.current.scrollTop:0,Ke=e=>{for(let t=Be.length-1;t>=0;t--){if(e>=Be[t]){return t}}return 0},qe=Math.max(0,Ke(Ae)),Ve=Math.min(o.pages.length-1,Ke(Ae+Xe)),Je=null!=ne?ne:1,Qe=Math.max(0,qe-Je),Ue=Math.min(o.pages.length-1,Ve+Je),Ze=g({cropOverlayFill:W,cropGridStyle:B,workspaceBackgroundColor:x,pageBorderColor:L,activePageBorderColor:T,bleedColor:b,transparencyBackgroundColor:y,transformerStyle:O,innerImageCropTransformerStyle:z,outerImageCropTransformerStyle:j,highlighterStyle:N,snapGuideStroke:k,snapGuideStrokeWidth:S,snapGuideDash:E,selectionRectFill:M,selectionRectStroke:C,selectionRectStrokeWidth:P,transformLabelFill:R,transformLabelTextFill:F,distanceGuideStroke:_,distanceLabelFill:Y,distanceLabelTextFill:D,mediaLoadingStyle:H,mediaErrorStyle:G,textOverflowIndicatorStyle:I,rulerBackgroundColor:X,rulerTextColor:A,rulerBorderColor:K,rulerBorderSize:q,rulerTickColor:V,rulerTickSize:J});return e(h,{value:Ze,children:e("div",{ref:fe,style:{width:"100%",height:"100%",position:"relative",outline:"none",flex:1,backgroundColor:Ye,overflow:"hidden"},tabIndex:0,className:"polotno-workspace-container",children:t("div",{ref:me,onScroll:Ge,style:Object.assign({position:"absolute",top:0,left:0,width:"100%",height:"100%",display:"flex",flexDirection:ce?"row":"column",overflow:"auto",overflowX:ce?"auto":Ie?"hidden":"auto",overflowY:ce&&_e?"hidden":"auto"},Fe&&{paddingTop:ce?0:Re,paddingBottom:ce?0:Re,paddingLeft:ce?Pe:0,paddingRight:ce?Pe:0,boxSizing:"border-box"}),className:"polotno-workspace-inner",children:[o.pages.map((t,r)=>{const l=t===o.activePage;if(le&&!l&&!t._exportingOrRendering&&!t._forceMount){return null}const i=l||r>=Qe&&r<=Ue||t._exportingOrRendering||t._forceMount,s=ce?We[r]:Se*o.scale+2*Pe,a=ce?Ee*o.scale+2*Re:We[r];if(!i){return e("div",{style:{flexShrink:0},children:e(v,{width:s,height:a,backgroundColor:Ye,xPadding:Pe,yPadding:Re})},t.id)}const c=e(n,{page:t,xPadding:Pe,yPadding:Re,width:s,height:a,store:o,pageControlsEnabled:w,altCloneEnabled:re,groupSelectionMode:oe,components:Q,viewportSize:he,layout:d,tooltipSafeArea:se},t.id);return(t._exportingOrRendering||t._forceMount)&&!l&&le?e("div",{style:{display:"none",flexShrink:0},children:c},t.id):c}),o.rulesVisible&&e(l,{store:o,xPadding:Pe,yPadding:Re,width:Se*o.scale+2*Pe,height:Ee*o.scale+2*Re,pageSizes:We,layout:d,renderOnlyActivePage:le}),0===o.pages.length&&e(De,{store:o}),o.audios.map(t=>e(i,{audio:t,store:o},t.id))]})})})});export default WorkspaceCanvas;
|
|
1
|
+
import{jsx as e,jsxs as t}from"react/jsx-runtime";import r from"react";import{observer as o}from"mobx-react-lite";import n from"./page.js";import{TopRules as l}from"./rules.js";import{AudioElement as i}from"./audio.js";import{handleHotkey as s,handleCopyEvent as a,handleCutEvent as c,handlePasteEvent as u}from"./hotkeys.js";import{t as d}from"../utils/l10n.js";import{WorkspaceStyleProvider as h,useResolvedWorkspaceStyle as g}from"./workspace-style.js";const p=(e,t,r)=>Math.max(t,Math.min(r,e)),f=(e,t)=>Math.sqrt(Math.pow(t.clientX-e.clientX,2)+Math.pow(t.clientY-e.clientY,2)),m=({store:r})=>t("div",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",textAlign:"center"},children:[e("p",{children:d("workspace.noPages")}),e("button",{onClick:()=>{r.addPage()},children:d("workspace.addPage")})]}),v=({width:t,height:r,xPadding:o,yPadding:n,backgroundColor:l})=>e("div",{style:{width:t+"px",height:r+"px",backgroundColor:l,paddingLeft:o+"px",paddingRight:o+"px",paddingTop:n+"px",paddingBottom:n+"px",flexShrink:0},children:e("div",{style:{width:" 100%",height:"100%",backgroundColor:"white"}})});export const WorkspaceCanvas=o(({store:o,layout:d="vertical",pageControlsEnabled:w,backgroundColor:x,transparencyBackgroundColor:y,pageBorderColor:k,activePageBorderColor:L,bleedColor:T,snapGuideStroke:b,snapGuideStrokeWidth:S,snapGuideDash:M,selectionRectFill:E,selectionRectStroke:C,selectionRectStrokeWidth:P,transformLabelFill:R,transformLabelTextFill:F,cropOverlayFill:W,cropGridStyle:B,transformerStyle:O,innerImageCropTransformerStyle:z,outerImageCropTransformerStyle:j,highlighterStyle:N,mediaLoadingStyle:H,mediaErrorStyle:G,textOverflowIndicatorStyle:_,distanceGuideStroke:I,distanceLabelFill:Y,distanceLabelTextFill:D,rulerBackgroundColor:X,rulerTextColor:A,rulerBorderColor:K,rulerBorderSize:q,rulerTickColor:V,rulerTickSize:J,components:Q,onKeyDown:U,onPaste:Z,paddingX:$,paddingY:ee,pageGap:te,altCloneEnabled:re=!0,groupSelectionMode:oe="drill",visiblePagesOffset:ne,renderOnlyActivePage:le,scrollToPageThreshold:ie=.5,tooltipSafeArea:se})=>{var ae;const ce="horizontal"===d,ue=null!=$?$:20,de=null!=ee?ee:55,[he,ge]=r.useState({width:100,height:100}),pe=r.useRef(he),fe=r.useRef(null),me=r.useRef(null),ve=r.useRef(0);let we=0,xe=0,ye=0,ke=0;if(o.bleedVisible){for(const e of o.pages){const t=e.computedBleed;we=Math.max(we,t.left),xe=Math.max(xe,t.right),ye=Math.max(ye,t.top),ke=Math.max(ke,t.bottom)}}const Le=Math.max(...o.pages.map(e=>e.computedWidth)),Te=Math.max(...o.pages.map(e=>e.computedHeight)),be=(null===(ae=o.activePage)||void 0===ae?void 0:ae.computedHeight)||0,Se=Le+we+xe,Me=(le?be:Te)+ye+ke,Ee=async({skipTimeout:e}={skipTimeout:!1})=>{if(e||await new Promise(e=>setTimeout(e,50)),null===fe.current){return}if(!Number.isFinite(Se)||!Number.isFinite(Me)){return}const t=fe.current.getBoundingClientRect();0!==t.width&&0!==t.height||(console.warn("Polotno warning: <Workspace /> component can not automatically detect its size.\nWidth or height of parent elements is equal 0.\nPlease make sure it has non-zero size. You may need to adjust it with your styles. <Workspace /> will automatically fit into parent container.\nFor simpler debugging here is the log of the parent element:"),console.log(fe.current));const r=me.current.clientWidth||t.width,n={width:r,height:t.height};(pe.current.width!==n.width||pe.current.height!==n.height)&&(ge(n),pe.current=n);const l=(r-2*ue)/Se,i=o.pages.length>1?3.1:2,s=(t.height-de*i)/Me,a=o.pages.length>1?3.1:2,c=(r-ue*a)/Se,u=(t.height-2*de)/Me,d=o.pages.length?Math.max(Math.min(ce?c:l,ce?u:s),.01):1;o.scaleToFit!==d&&(o.setScale(d),o._setScaleToFit(d))};r.useLayoutEffect(()=>{Ee({skipTimeout:!0})},[]),r.useEffect(()=>(o._setWorkspaceMounted(!0),()=>o._setWorkspaceMounted(!1)),[o]),r.useEffect(()=>{Ee()},[Se,Me,ee,$]),r.useLayoutEffect(()=>{Ee({skipTimeout:!0})},[o.openedSidePanel]),r.useEffect(()=>{o.__()},[]),r.useEffect(()=>{const e=fe.current;if(window.ResizeObserver){const t=new ResizeObserver(()=>{Ee({skipTimeout:!0})});return t.observe(e),()=>t.unobserve(e)}{const e=setInterval(()=>{Ee({skipTimeout:!0})},100);return()=>clearInterval(e)}},[Se,Me]);const Ce=le?1:o.pages.length;let Pe,Re;if(ce){const e=Se*o.scale*Ce;Pe=Math.max(ue,(he.width-e)/Ce/2),Re=Math.max(de,(he.height-Me*o.scale)/2)}else{Pe=Math.max(ue,(he.width-Se*o.scale)/2);const e=Me*o.scale*Ce;Re=Math.max(de,(he.height-e)/Ce/2)}Number.isNaN(Pe)&&(Pe=ue),Number.isNaN(Re)&&(Re=de),r.useEffect(()=>{const e=e=>{U?U(e,o):s(e,o,fe.current)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[]),r.useEffect(()=>{const e=e=>a(e,o,fe.current),t=e=>c(e,o,fe.current),r=e=>{Z?Z(e,o):u(e,o,fe.current)};return window.addEventListener("copy",e),window.addEventListener("cut",t),window.addEventListener("paste",r),()=>{window.removeEventListener("copy",e),window.removeEventListener("cut",t),window.removeEventListener("paste",r)}},[Z]),r.useEffect(()=>{const e=e=>{if(e.ctrlKey||e.metaKey){e.preventDefault();const t=Math.max(5,o.scaleToFit);let r=Math.min(.1,o.scaleToFit);ce&&Se>0&&Number.isFinite(Se)&&(r=Math.max(r,300/Se)),r=Math.max(r,.01);const n=.03,l=p(e.deltaY<0?o.scale*(1+n):o.scale/(1+n),r,t);return void o.setScale(l)}},t=me.current;return null==t||t.addEventListener("wheel",e),()=>null==t?void 0:t.removeEventListener("wheel",e)},[ce,Se,o]),r.useEffect(()=>{const e=me.current;if(!e){return}const t=e=>{2===e.touches.length&&(ve.current=f(e.touches[0],e.touches[1]))},r=t=>{if(2===t.touches.length&&ve.current>0){t.preventDefault();const r=f(t.touches[0],t.touches[1]),n=r/ve.current,l=Math.max(5,o.scaleToFit);let i=Math.min(.1,o.scaleToFit);ce&&Se>0&&Number.isFinite(Se)&&(i=Math.max(i,300/Se)),i=Math.max(i,.01);const s=o.scale,a=p(s*n,i,l),c=a/s,u=e.getBoundingClientRect(),d=(t.touches[0].clientX+t.touches[1].clientX)/2-u.left,h=(t.touches[0].clientY+t.touches[1].clientY)/2-u.top,g=e.scrollLeft+d,m=e.scrollTop+h;Ne.current=!0,o.setScale(a),e.scrollLeft=g*c-d,e.scrollTop=m*c-h,ve.current=r}},n=()=>{ve.current=0};return e.addEventListener("touchstart",t,{passive:!0}),e.addEventListener("touchmove",r,{passive:!1}),e.addEventListener("touchend",n,{passive:!0}),()=>{e.removeEventListener("touchstart",t),e.removeEventListener("touchmove",r),e.removeEventListener("touchend",n)}},[ce,Se,o]);const Fe=void 0!==te,We=o.pages.map(e=>{if(ce){const t=(e.computedWidth+we+xe)*o.scale;return Fe?t+te:t+2*Pe}{const t=(e.computedHeight+ye+ke)*o.scale;return Fe?t+te:t+2*Re}}),Be=[];let Oe=Fe?ce?Pe:Re:0;for(let e=0;e<We.length;e++){Be.push(Oe),Oe+=We[e]}const ze=We.reduce((e,t)=>e+t,0),je=Fe?ze+(ce?2*Pe:2*Re):ze,Ne=r.useRef(!1),[,He]=r.useReducer(e=>e+1,0);((e,t,o,n,l)=>{const i=r.useRef(0),s=r.useRef(0),a=r.useRef(null),c=r.useRef(null),u=r.useRef(!1),d=r.useRef(n.pages.length);u.current=d.current!==n.pages.length,d.current=n.pages.length,r.useEffect(()=>{const t=e.current,r=()=>{i.current=t.scrollLeft,s.current=t.scrollTop,a.current=t.scrollWidth,c.current=t.scrollHeight};return t.addEventListener("scroll",r),r(),()=>{t.removeEventListener("scroll",r)}},[]),r.useLayoutEffect(()=>{if(!e.current){return}if(u.current){const t=e.current;return a.current=t.scrollWidth,c.current=t.scrollHeight,i.current=t.scrollLeft,void(s.current=t.scrollTop)}const t=e.current,r=a.current,o=c.current;if(null===r||null===o){return a.current=t.scrollWidth,c.current=t.scrollHeight,i.current=t.scrollLeft,void(s.current=t.scrollTop)}l.current=!0;const n=t.offsetWidth,d=t.offsetHeight,h=(i.current+n/2)/r,g=(s.current+d/2)/o,f=Math.max(0,t.scrollWidth-n),m=Math.max(0,t.scrollHeight-d);t.scrollLeft=p(h*t.scrollWidth-n/2,0,f),t.scrollTop=p(g*t.scrollHeight-d/2,0,m),a.current=t.scrollWidth,c.current=t.scrollHeight,i.current=t.scrollLeft,s.current=t.scrollTop},[o,t])})(me,je,o.scale,o,Ne);const{handleScroll:Ge}=((e,t,o,n,l,i,s,a,c,u)=>{const d=r.useRef(!1),h=r.useRef(null),g=r.useRef(!1),p="horizontal"===c;r.useEffect(()=>{const t=e.current,r=()=>{s.current};return t.addEventListener("scroll",r),()=>{t.removeEventListener("scroll",r)}},[]);const f=n.pages.indexOf(n.activePage);return r.useLayoutEffect(()=>{if(a){return}if(!n.activePage){return}if(!e.current){return}if(d.current){return}const r=e.current,i=n.pages.indexOf(n.activePage),s=t[i]||0,c=p?r.scrollLeft:r.scrollTop,h=p?r.scrollWidth-r.clientWidth:r.scrollHeight-r.clientHeight,f=Math.min(s,Math.max(0,h)),m=o[i]||o[0]||0;let v=()=>{};return(Math.abs(f-c)>m*l||g.current)&&(g.current=!0,v=(({element:e,scrollTop:t,scrollLeft:r,duration:o=300,onFinish:n=()=>{}})=>{const l=void 0!==t,i=l?e.scrollTop:e.scrollLeft,s=l?t:r,a=s-i;let c=0,u=!1;if(0===o){return l?e.scrollTop=s:e.scrollLeft=s,()=>{}}const d=()=>{if(u){return}c+=20;const t=h(c,i,a,o);l?e.scrollTop=t:e.scrollLeft=t,c<o?setTimeout(d,20):n()},h=(e,t,r,o)=>(e/=o/2)<1?r/2*e*e+t:-r/2*(--e*(e-2)-1)+t;return d(),()=>{u=!0}})(Object.assign(Object.assign({element:r},p?{scrollLeft:f}:{scrollTop:f}),{onFinish:()=>{g.current=!1,null==u||u()},duration:n.isPlaying?0:300}))),v},[n.activePage,f,n.isPlaying,a,c]),{handleScroll:e=>{if(a){return}if(g.current){return}d.current=!0,clearTimeout(h.current),h.current=setTimeout(()=>{d.current=!1},300);const r=(p?e.currentTarget.scrollLeft:e.currentTarget.scrollTop)+(p?i.width:i.height)/3;let o=0;for(let n=t.length-1;n>=0;n--){if(r>=t[n]){o=n;break}}const l=n.pages[o];l&&n.activePage!==l&&l.select()}}})(me,Be,We,o,ie,he,Ne,le,d,He),_e=he.width>=Se*o.scale+2*Pe,Ie=he.height>=Me*o.scale+2*Re,Ye=x||"rgba(232, 232, 232, 0.9)",De=(null==Q?void 0:Q.NoPages)||m,Xe=ce?he.width:he.height,Ae=me.current?ce?me.current.scrollLeft:me.current.scrollTop:0,Ke=e=>{for(let t=Be.length-1;t>=0;t--){if(e>=Be[t]){return t}}return 0},qe=Math.max(0,Ke(Ae)),Ve=Math.min(o.pages.length-1,Ke(Ae+Xe)),Je=null!=ne?ne:1,Qe=Math.max(0,qe-Je),Ue=Math.min(o.pages.length-1,Ve+Je),Ze=g({cropOverlayFill:W,cropGridStyle:B,workspaceBackgroundColor:x,pageBorderColor:k,activePageBorderColor:L,bleedColor:T,transparencyBackgroundColor:y,transformerStyle:O,innerImageCropTransformerStyle:z,outerImageCropTransformerStyle:j,highlighterStyle:N,snapGuideStroke:b,snapGuideStrokeWidth:S,snapGuideDash:M,selectionRectFill:E,selectionRectStroke:C,selectionRectStrokeWidth:P,transformLabelFill:R,transformLabelTextFill:F,distanceGuideStroke:I,distanceLabelFill:Y,distanceLabelTextFill:D,mediaLoadingStyle:H,mediaErrorStyle:G,textOverflowIndicatorStyle:_,rulerBackgroundColor:X,rulerTextColor:A,rulerBorderColor:K,rulerBorderSize:q,rulerTickColor:V,rulerTickSize:J});return e(h,{value:Ze,children:e("div",{ref:fe,style:{width:"100%",height:"100%",position:"relative",outline:"none",flex:1,backgroundColor:Ye,overflow:"hidden"},tabIndex:0,className:"polotno-workspace-container",children:t("div",{ref:me,onScroll:Ge,style:Object.assign({position:"absolute",top:0,left:0,width:"100%",height:"100%",display:"flex",flexDirection:ce?"row":"column",overflow:"auto",overflowX:ce?"auto":_e?"hidden":"auto",overflowY:ce&&Ie?"hidden":"auto"},Fe&&{paddingTop:ce?0:Re,paddingBottom:ce?0:Re,paddingLeft:ce?Pe:0,paddingRight:ce?Pe:0,boxSizing:"border-box"}),className:"polotno-workspace-inner",children:[o.pages.map((t,r)=>{const l=t===o.activePage;if(le&&!l&&!t._exportingOrRendering&&!t._forceMount){return null}const i=l||r>=Qe&&r<=Ue||t._exportingOrRendering||t._forceMount,s=ce?We[r]:Se*o.scale+2*Pe,a=ce?Me*o.scale+2*Re:We[r];if(!i){return e("div",{style:{flexShrink:0},children:e(v,{width:s,height:a,backgroundColor:Ye,xPadding:Pe,yPadding:Re})},t.id)}const c=e(n,{page:t,xPadding:Pe,yPadding:Re,width:s,height:a,store:o,pageControlsEnabled:w,altCloneEnabled:re,groupSelectionMode:oe,components:Q,viewportSize:he,layout:d,tooltipSafeArea:se},t.id);return(t._exportingOrRendering||t._forceMount)&&!l&&le?e("div",{style:{display:"none",flexShrink:0},children:c},t.id):c}),o.rulesVisible&&e(l,{store:o,xPadding:Pe,yPadding:Re,width:Se*o.scale+2*Pe,height:Me*o.scale+2*Re,pageSizes:We,layout:d,renderOnlyActivePage:le}),0===o.pages.length&&e(De,{store:o}),o.audios.map(t=>e(i,{audio:t,store:o},t.id))]})})})});export default WorkspaceCanvas;
|
package/model/group-model.d.ts
CHANGED
|
@@ -15,6 +15,7 @@ export declare function zIndexOps<T extends {
|
|
|
15
15
|
}>(self: {
|
|
16
16
|
children: ReadonlyArray<T> & {
|
|
17
17
|
replace(items: T[]): unknown;
|
|
18
|
+
splice(start: number, deleteCount: number, ...items: T[]): unknown;
|
|
18
19
|
};
|
|
19
20
|
}): {
|
|
20
21
|
canMoveElementsUp(ids: Array<string>): boolean;
|
|
@@ -26,6 +27,9 @@ export declare function zIndexOps<T extends {
|
|
|
26
27
|
moveElementsTop(ids: Array<string>): void;
|
|
27
28
|
moveElementsBottom(ids: Array<string>): void;
|
|
28
29
|
setElementZIndex(id: string, zIndex: number): void;
|
|
30
|
+
_reconcileChildren(items: ReadonlyArray<{
|
|
31
|
+
id: string;
|
|
32
|
+
}>): void;
|
|
29
33
|
};
|
|
30
34
|
export declare const ElementTypes: any;
|
|
31
35
|
type ElementUnion = (SVGElementType & {
|
|
@@ -1989,6 +1993,9 @@ export declare const TYPES_MAP: {
|
|
|
1989
1993
|
} & {
|
|
1990
1994
|
getCell(row: number, col: number): import("./table-model.js").TableCellType | undefined;
|
|
1991
1995
|
readonly minWidth: number;
|
|
1996
|
+
readonly basePixelRowHeights: number[];
|
|
1997
|
+
contentFloors(divider?: number): number[];
|
|
1998
|
+
readonly rowContentFloors: number[];
|
|
1992
1999
|
getRowContentOuterHeight(row: number): number;
|
|
1993
2000
|
readonly minHeight: number;
|
|
1994
2001
|
readonly actualHeight: number;
|