polotno 3.10.0 → 3.11.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.
@@ -1 +1 @@
1
- import{jsx as t,Fragment as e,jsxs as r}from"react/jsx-runtime";import n from"react";import{observer as o}from"mobx-react-lite";import{Group as i,Path as a,Text as s,TextPath as l}from"react-konva";import{Html as c}from"react-konva-utils";import{nodeAutorun as u}from"../utils/mobx.js";import d from"konva";import{parsePath as f,roundCommands as h}from"svg-round-corners/lib/index.js";import{generateBackgroundShapeFromRects as g,textLinesToRects as p}from"@polotno/core/background-shape";import{useColor as m}from"./use-color.js";import{useWorkspaceStyle as x}from"./workspace-style.js";import{ROLES as w}from"../model/store.js";import{incrementLoader as v}from"../utils/loader.js";import{activeAnchorOf as y,scaledFontSizeAttrs as b,roundedFontSizeAttrs as S,roundedTextDecorationAttrs as E,textMinResizeWidth as z}from"../utils/px.js";import{isFontLoaded as k}from"../utils/fonts.js";import{flags as O}from"../utils/flags.js";import{removeTags as R}from"@polotno/core/text";import{getDir as F,getCurvePath as A,resolveLineHeight as M,normalizeStrokeLineJoin as j}from"@polotno/core/text-html";import{cssFontFamily as L}from"@polotno/core/fonts";import{FIT_FONT_SIZE_STEP as C,FIT_HEIGHT_EPSILON as T}from"@polotno/core/fit-text";import{applyFilter as H}from"./apply-filters.js";import{useFadeIn as P}from"./use-fadein.js";import{isTouchDevice as X}from"../utils/screen.js";import{isAlive as Y,getParent as W}from"mobx-state-tree";import{getLimitedFontSize as D}from"./text-element/max-font-size.js";import{getOptimalCaretColor as $}from"./text-element/caret-color.js";import{visiblePlaceholder as B}from"./text-element/placeholder.js";import{hasMeasuredHeight as I,resolveTextBoxHeight as N}from"@polotno/core/text-types";let J;function _(){return J||(J=document.getElementById("polotno-text-style"),J||(J=document.createElement("style"),J.id="polotno-text-style",document.head.appendChild(J)),J)}d._fixTextRendering=!0;const V={border:"none",padding:"0px",overflow:"hidden",background:"none",outline:"none",resize:"none",overflowWrap:"break-word",whiteSpace:"pre-wrap",userSelect:"text",wordBreak:"normal",textTransform:"none"};export{getDir}from"@polotno/core/text-html";const q=o(({textNodeRef:e,element:r,onBlur:o,selectAll:i,cursorPosition:a})=>{const[s,l]=n.useState(V),c=e.current;n.useLayoutEffect(()=>{if(!c){return}const t={};t.width=c.width()-2*c.padding()+"px",t.height=c.height()-2*c.padding()+c.fontSize()*c.lineHeight()+"px",t.fontSize=c.fontSize()+"px",t.lineHeight=c.lineHeight()+.01,t.fontFamily=c.fontFamily(),t.textAlign=c.align(),t.color=c.fill(),t.fontWeight=r.fontWeight,t.fontStyle=r.fontStyle,t.letterSpacing=r.letterSpacing+"em",t.opacity=Math.max(r.a.opacity,.2),t.textTransform=r.textTransform,t.caretColor=$(r);const e=`\n .polotno-input::placeholder {\n color: ${s.color};\n opacity: 0.6;\n }\n `,n=_();n.innerHTML="",n.appendChild(document.createTextNode(e)),JSON.stringify(t)!==JSON.stringify(s)&&l(t)});const u=n.useRef(null);if(n.useLayoutEffect(()=>{var t;const e=u.current;if(!e){return}null===(t=u.current)||void 0===t||t.focus({preventScroll:!0});const r=a||e.value.length;e.selectionStart=e.selectionEnd=r,i&&(null==e||e.select(),document.execCommand("selectAll",!1,void 0))},[]),n.useEffect(()=>{window.addEventListener("blur",o);const t=t=>{var e;(null===(e=u.current)||void 0===e?void 0:e.contains(t.target))||o()};return window.addEventListener("touchstart",t),()=>{window.removeEventListener("blur",o),window.removeEventListener("touchstart",t)}},[]),!c){return null}let d=0;const f=c.textArr.length*c.lineHeight()*c.fontSize(),h=N(r.a,f);"middle"===r.verticalAlign&&(d=(h-f)/2),"bottom"===r.verticalAlign&&(d=h-f);const g=R(r.text);return t("textarea",{className:"polotno-input",ref:u,dir:F(g),style:Object.assign(Object.assign(Object.assign({},V),s),{paddingTop:d+"px"}),value:g,onChange:t=>{const e=D({oldText:r.text,newText:t.target.value,element:r});r.set(Object.assign({text:t.target.value},b(r,e)))},placeholder:B(r.placeholder),onBlur:o})}),U=e=>t(c,{children:t(q,Object.assign({},e))});export const useFontLoader=(t,e,r,o,i)=>{const[a,s]=n.useReducer(t=>t+1,0),l=n.useRef(k(e,r,o)),c=n.useRef(null);return n.useLayoutEffect(()=>{if(l.current=k(e,r,o),l.current){return}let n=!0;return(async()=>{l.current=!1,s();const a=v(`text ${e}`);await t.loadFont(e,r,o,i),n?(c.current=a,l.current=!0,s()):a()})(),()=>{c.current&&(c.current(),c.current=null),n=!1}},[e,r,o]),n.useEffect(()=>{l.current&&setTimeout(()=>{c.current&&(c.current(),c.current=null)})},[l.current]),[l.current]};export const useFontFamiliesLoader=(t,e,r,o,i)=>{const[a,s]=n.useReducer(t=>t+1,0),l=e.join("\0"),c=n.useRef(e.every(t=>k(t,r,o))),u=n.useRef(null);return n.useLayoutEffect(()=>{if(c.current=e.every(t=>k(t,r,o)),c.current){return}let n=!0;return(async()=>{c.current=!1,s();const a=v(`text fonts ${l}`);await Promise.all(e.map(e=>t.loadFont(e,r,o,i))),n?(u.current=a,c.current=!0,s()):a()})(),()=>{u.current&&(u.current(),u.current=null),n=!1}},[l,r,o]),n.useEffect(()=>{c.current&&setTimeout(()=>{u.current&&(u.current(),u.current=null)})},[c.current]),[c.current]};export const getLineHeight=({fontLoaded:t,fontFamily:e,fontSize:r,lineHeight:o})=>n.useMemo(()=>M({fontFamily:e,fontSize:r,lineHeight:o}),[t,e,r,o]);export function usePrevious(t){const e=n.useRef(t),r=n.useRef(t);return n.useMemo(()=>{r.current=e.current,e.current=t},[t]),r.current}function Z(t,e,r=!1){const n=t.fontSize(),o=t.height(),i=R(e.text);let a=e.a.fontSize;t.height(void 0);const s=Math.round(2*e.a.fontSize)-1;for(let l=1;l<s;l++){const n=I(e.a)&&t.height()>e.a.height+T;let o=i.split("\n").join(" ").split(/[\s-]+/).reduce((t,e)=>(e=e.toLowerCase(),/[\u3000-\u303F\u3040-\u309F\u30A0-\u30FF\uFF00-\uFFEF\u4E00-\u9FAF\uAC00-\uD7AF]/.test(e)?t.concat(e.split("")):t.concat(e)),[]),s=t.textArr.map(t=>t.text.toLowerCase()).join(";");const l=o.find(t=>!s.includes(t)||(s=s.replace(t,""),!1));if(!(n||l&&!r)){break}a-=C,t.fontSize(a)}return t.fontSize(n),t.height(o),a}export{getCurvePath}from"@polotno/core/text-html";export const TextElement=o(({element:o,store:c})=>{const{textOverflowIndicatorStyle:d}=x(),k=n.useRef(null),M=n.useRef(null),C=n.useRef(null),T=n.useRef([]),D=n.useRef(!0),[,$]=n.useReducer(t=>t+1,0),{editorEnabled:J,selectAll:_}=(t=>{const[e,r]=n.useState(!1),o=n.useRef(!1);return n.useEffect(()=>{var e=!0;return setTimeout(()=>{e&&(t._editModeEnabled&&(o.current=!0),r(!0),setTimeout(()=>{o.current=!1},50))},50),()=>{e=!1}},[]),{editorEnabled:e&&t._editModeEnabled,selectAll:o.current}})(o),[V,q]=n.useState(!1),[G,K]=n.useState(!1),Q=n.useRef(o.a.height),tt=n.useRef(0),et=n.useRef(""),rt=n.useRef(0),nt=o.isSelected,ot=usePrevious(nt),{textVerticalResizeEnabled:it}=O,at=O.autoDeleteEmptyText,st=usePrevious(o.fontFamily),[lt,ct]=n.useState([]);n.useEffect(()=>{var t,e;const r=null!==(e=null===(t=k.current)||void 0===t?void 0:t.textArr)&&void 0!==e?e:[];JSON.stringify(r)!==JSON.stringify(lt)&&ct(r)}),n.useEffect(()=>{if(o.a.width||"tablecell"===o.type){return}const t=k.current;t.width(600),o.set({width:1.4*t.getTextWidth()})},[]),n.useEffect(()=>{ot&&!nt&&at&&""===o.text&&o.removable&&!B(o.placeholder)&&c.deleteElements([o.id])},[at,o.placeholder,o.removable,o.text,nt,ot]);const ut=()=>{if(o.curveEnabled){const t=k.current;null==t||t.clearCache(),null==t||t.setAttrs({filters:[]});const e=M.current;e&&H(e,o)}else{const t=k.current;t&&H(t,o)}};n.useLayoutEffect(()=>{if(!G){return u(o,()=>{ut()})}}),n.useEffect(()=>{const t=T.current;t.length>0&&(T.current=[],t.forEach(t=>t()))}),n.useEffect(()=>()=>{D.current=!1;const t=T.current;t.length>0&&(T.current=[],t.forEach(t=>t()))},[]);let dt=R(o.text);"uppercase"===o.textTransform&&(dt=dt.toUpperCase());const[ft]=useFontLoader(c,o.fontFamily,o.fontStyle,o.fontWeight,o.text||o.placeholder),ht=()=>{if(o.curveEnabled){const t=M.current;return t.getSelfRect().height||t.fontSize()}const t=k.current.clone({height:void 0}),e=Math.ceil(t.fontSize()*t.lineHeight()*t.textArr.length+1);return t.destroy(),e};n.useLayoutEffect(()=>{if(!ft){return}if("tablecell"===o.type){const{textOverflow:t}=O;if("resize"===t){const t=ht(),e=Y(o)?W(o,2):null;(null==e?void 0:e.setCellContentHeight)&&e.setCellContentHeight(o.id,t)}else if("change-font-size"===t){const t=k.current;if(t){const e=Z(t,o,O.textSplitAllowed);e!==o.fontSize&&c.history.ignore(()=>{o.set({fontSize:e})})}}return}const{textOverflow:t,textSplitAllowed:e}=O,r=(t,e,r,n)=>{const i=v(`text ${o.id}`),a=()=>{c.history.ignore(t,e,r).then(()=>{D.current?(T.current.push(i),$()):i()})};n?queueMicrotask(a):a()};if(!I(o)){const t=ht();return void r(()=>{I(o)||o.set({height:t})},void 0,void 0,!0)}if(!c.isPlaying){if("change-font-size"!==t||V){if("resize"===t){const t=ht();it&&o.height<t&&!V&&r(()=>{var e;Y(o)&&o.set({height:t}),null===(e=k.current)||void 0===e||e.height(t)},!1,!0),it||o.height===t||V||r(()=>{var e;Y(o)&&o.set({height:t}),null===(e=k.current)||void 0===e||e.height(t)},!1,!0)}}else{const t=k.current,n=o.curveEnabled?o.fontSize:Z(t,o,e);if(n!==o.fontSize){return void r(()=>{o.set(b(o,n))},!1,!0)}const i=ht();o.height===i||it||r(()=>{o.set({height:i})},!1,!0)}}}),n.useLayoutEffect(()=>{var t;if(ft&&o.curveEnabled){const e=null===(t=M.current)||void 0===t?void 0:t.getSelfRect().width;if(e){const t=e-o.a.width,r=o.a.rotation*Math.PI/180,n=-t/2*Math.cos(r),i=-t/2*Math.sin(r);o.set({width:e,x:o.a.x+n,y:o.a.y+i})}}},[ft,o.curveEnabled,o.curvePower,o.text,o.fontSize,o.fontFamily,o.fontWeight,o.fontStyle,o.letterSpacing]),n.useLayoutEffect(()=>{const t=k.current;t&&(t.width(t.width()+1e-8),t.width(t.width()-1e-8),t._setTextData(),ut())},[ft]);const gt=n.useRef(null),pt=n.useRef(o.width),mt=n.useRef(0),xt=t=>{t.evt.preventDefault();const e=c.selectedShapes.find(t=>t===o);e&&o.contentEditable&&(mt.current=function(t){var e;const r=t.target,n=function(t){var e=t.getAbsoluteTransform().copy();e.invert();var r=t.getStage().getPointerPosition();return e.point(r)}(r),o=r.textArr,i=Math.floor(n.y/(r.fontSize()*r.lineHeight())),a=o.slice(0,i).reduce((t,e)=>t+e.text.length,i),s=null!==(e=o[i])&&void 0!==e?e:o[0];let l=0;return"right"===r.align()?l=r.width()-s.width:"center"===r.align()&&(l=r.width()/2-s.width/2),a+Math.round((n.x-l)/s.width*s.text.length)}(t),o.toggleEditMode())},wt=B(o.placeholder),vt=!dt&&wt?.6:o.a.opacity;P(k,vt);const yt=getLineHeight({fontLoaded:ft,fontFamily:o.fontFamily,fontSize:o.a.fontSize,lineHeight:o.lineHeight}),bt=o.selectable||c.role===w.ADMIN,St=m(o),Et=m(o,o.stroke,"stroke"),zt=n.useMemo(()=>o.backgroundEnabled?o.curveEnabled?function({width:t,height:e,padding:r=0,cornerRadius:n=0}){const o=-r,i=-r,a=t+r,s=e+r,l=f(`M ${o} ${i} L ${a} ${i} L ${a} ${s} L ${o} ${s} Z`);return h(l,n).path}({width:o.a.width,height:o.a.height,cornerRadius:o.backgroundCornerRadius*(o.a.fontSize*yt*.5),padding:o.backgroundPadding*(o.a.fontSize*yt*.5)}):function({lines:t,lineHeight:e,width:r,align:n="left",padding:o=0,cornerRadius:i=0}){const a=p({lines:t,lineHeight:e,width:r,align:n});return g({rects:a,padding:o,cornerRadius:i})}({lines:JSON.parse(JSON.stringify(lt)),cornerRadius:o.backgroundCornerRadius*(o.a.fontSize*yt*.5),lineHeight:yt*o.a.fontSize,padding:o.backgroundPadding*(o.a.fontSize*yt*.5),width:o.a.width,align:o.align}):"",[o.backgroundEnabled,o.curveEnabled,o.backgroundCornerRadius,o.a.fontSize,o.a.height,yt,o.backgroundPadding,o.a.width,o.align,lt]),kt=X();let Ot=0;if(!o.curveEnabled){const t=lt.length*yt*o.a.fontSize,e=N(o.a,t);"middle"===o.verticalAlign?Ot=(e-t)/2:"bottom"===o.verticalAlign&&(Ot=e-t)}const Rt=o.curveEnabled?A(o.a.width,o.a.height,o.curvePower,o.a.fontSize):"",Ft=ft?L(o.fontFamily):st===o.fontFamily?"Arial":L(st),At=F(dt);return r(e,{children:[t(a,{ref:C,x:o.a.x,y:o.a.y,rotation:o.a.rotation,hideInExport:!o.showInExport,listening:!1,visible:o.backgroundEnabled,opacity:o.backgroundOpacity*vt,data:zt,fill:o.backgroundColor,offsetY:-Ot}),t(a,{data:Rt,stroke:d.stroke,strokeWidth:1,x:o.a.x,y:o.a.y,rotation:o.a.rotation,visible:!1}),t(l,Object.assign({ref:M,visible:o.curveEnabled,data:Rt,text:dt||wt,listening:!1,align:"center",textBaseline:"middle",direction:At},St,Et,{strokeWidth:o.strokeWidth,lineJoin:j(o.strokeLineJoin),fillAfterStrokeEnabled:!0,fontSize:o.a.fontSize,fontFamily:`${L(o.fontFamily)}, ${L(st)}`,fontStyle:o.fontStyle+" "+o.fontWeight,textDecoration:o.textDecoration.trim(),letterSpacing:o.letterSpacing*o.a.fontSize,x:o.a.x,y:o.a.y,rotation:o.a.rotation,opacity:o._editModeEnabled?.3:vt,hideInExport:!o.showInExport,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity})),t(s,Object.assign({ref:k,id:o.selectable?o.id:void 0,name:o.selectable?"element":"",hideInExport:!o.showInExport,editModeEnabled:o._editModeEnabled,x:o.a.x,y:o.a.y,rotation:o.a.rotation,width:o.a.width,height:I(o.a)?o.a.height:void 0,text:dt||wt,direction:At},St,Et,{lineJoin:j(o.strokeLineJoin),strokeWidth:o.strokeWidth,fillAfterStrokeEnabled:!0,fontSize:o.a.fontSize,fontFamily:Ft,fontStyle:o.fontStyle+" "+o.fontWeight,textDecoration:o.textDecoration,align:o.align,verticalAlign:o.verticalAlign,draggable:kt?o.draggable&&nt:o.draggable,preventDefault:!kt||nt,opacity:o.curveEnabled?0:vt,visible:!o._editModeEnabled,ellipsis:"ellipsis"===O.textOverflow,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity,lineHeight:yt,letterSpacing:o.letterSpacing*o.a.fontSize,listening:!!o.selectable&&bt,onDragStart:()=>{K(!0)},onDragMove:t=>{o.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{K(!1),o.set({x:t.target.x(),y:t.target.y()})},onClick:xt,onTap:xt,onTransformStart:()=>{q(!0);const t=k.current;Q.current=t.height(),pt.current=o.a.width,gt.current=t.position(),tt.current=t.rotation(),rt.current=t.height(),et.current=y(t)},onTransform:t=>{var e,r;const n=t.target;null===(e=C.current)||void 0===e||e.setAttrs({x:n.x(),y:n.y(),rotation:n.rotation(),scale:n.scale()});const i=et.current;if("middle-left"===i||"middle-right"===i){const t=n.scaleX(),e=n.width()*t,r=z(pt.current,o.a.fontSize);let i=e;e<r&&(i=r,gt.current&&n.position(gt.current)),n.width(i),n.scaleX(1),n.scaleY(1);let a=ht();if("ellipsis"===O.textOverflow){a=Q.current}else{const t=Math.max(a,Q.current);n.height(t),o.set({height:n.height()})}const s=O.textVerticalResizeEnabled?Math.max(a,Q.current):ht();o.set({x:n.x(),width:n.width(),rotation:n.rotation(),height:s}),n.skewX(0),n.skewY(0),ut()}if("top-center"===i||"bottom-center"===i){const e="resize"===O.textOverflow?ht():yt*o.a.fontSize,r=t.target.height()*t.target.scaleY();if(r<e){if(t.target.height(e),gt.current){if("top-center"===et.current){const r=tt.current*Math.PI/180,n=rt.current-e;t.target.x(gt.current.x-n*Math.sin(r)),t.target.y(gt.current.y+n*Math.cos(r))}else{t.target.position(gt.current)}}}else{t.target.height(r)}t.target.scaleY(1),t.target.scaleX(1),t.target.rotation(tt.current),t.target.skewX(0),t.target.skewY(0),rt.current=Math.max(e,r)}gt.current=t.target.position();const a=t.target.scaleX();null===(r=C.current)||void 0===r||r.setAttrs({scaleX:1,scaleY:1}),t.target.scaleX(1),t.target.scaleY(1),o.set({fontSize:o.a.fontSize*a,width:t.target.width()*a,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),height:t.target.height()*a,shadowBlur:o.shadowBlur*a,shadowOffsetX:o.shadowOffsetX*a,shadowOffsetY:o.shadowOffsetY*a,strokeWidth:o.strokeWidth*a})},onTransformEnd:t=>{var e;const r=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),o.set(Object.assign(Object.assign({},S(o,o.fontSize*r)),{width:Math.ceil(t.target.width()*r),x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),height:t.target.height()*r})),null===(e=C.current)||void 0===e||e.setAttrs({scaleX:1,scaleY:1}),q(!1)}})),J&&o.contentEditable&&t(i,{x:o.a.x,y:o.a.y,rotation:o.a.rotation,children:t(U,{textNodeRef:k,element:o,selectAll:_,cursorPosition:mt.current,onBlur:()=>{o.set(E(o)),o.toggleEditMode(!1)}})})]})});
1
+ import{jsx as t,Fragment as e,jsxs as r}from"react/jsx-runtime";import n from"react";import{observer as o}from"mobx-react-lite";import{Group as i,Path as a,Text as s,TextPath as l}from"react-konva";import{Html as c}from"react-konva-utils";import{nodeAutorun as u}from"../utils/mobx.js";import d from"konva";import{parsePath as f,roundCommands as h}from"svg-round-corners/lib/index.js";import{generateBackgroundShapeFromRects as g,textLinesToRects as p}from"@polotno/core/background-shape";import{useColor as m}from"./use-color.js";import{useWorkspaceStyle as x}from"./workspace-style.js";import{ROLES as w}from"../model/store.js";import{incrementLoader as v}from"../utils/loader.js";import{activeAnchorOf as y,scaledFontSizeAttrs as b,roundedFontSizeAttrs as S,roundedTextDecorationAttrs as E,roundedGeometryPx as z,roundedPosition as k,textMinResizeWidth as O}from"../utils/px.js";import{isFontLoaded as R}from"../utils/fonts.js";import{flags as F}from"../utils/flags.js";import{removeTags as A}from"@polotno/core/text";import{getDir as M,getCurvePath as j,resolveLineHeight as L,normalizeStrokeLineJoin as C}from"@polotno/core/text-html";import{cssFontFamily as T}from"@polotno/core/fonts";import{FIT_FONT_SIZE_STEP as H,FIT_HEIGHT_EPSILON as P}from"@polotno/core/fit-text";import{applyFilter as X}from"./apply-filters.js";import{useFadeIn as Y}from"./use-fadein.js";import{isTouchDevice as W}from"../utils/screen.js";import{isAlive as D,getParent as $}from"mobx-state-tree";import{getLimitedFontSize as B}from"./text-element/max-font-size.js";import{getOptimalCaretColor as I}from"./text-element/caret-color.js";import{visiblePlaceholder as N}from"./text-element/placeholder.js";import{hasMeasuredHeight as J,resolveTextBoxHeight as _}from"@polotno/core/text-types";let V;function q(){return V||(V=document.getElementById("polotno-text-style"),V||(V=document.createElement("style"),V.id="polotno-text-style",document.head.appendChild(V)),V)}d._fixTextRendering=!0;const U={border:"none",padding:"0px",overflow:"hidden",background:"none",outline:"none",resize:"none",overflowWrap:"break-word",whiteSpace:"pre-wrap",userSelect:"text",wordBreak:"normal",textTransform:"none"};export{getDir}from"@polotno/core/text-html";const Z=o(({textNodeRef:e,element:r,onBlur:o,selectAll:i,cursorPosition:a})=>{const[s,l]=n.useState(U),c=e.current;n.useLayoutEffect(()=>{if(!c){return}const t={};t.width=c.width()-2*c.padding()+"px",t.height=c.height()-2*c.padding()+c.fontSize()*c.lineHeight()+"px",t.fontSize=c.fontSize()+"px",t.lineHeight=c.lineHeight()+.01,t.fontFamily=c.fontFamily(),t.textAlign=c.align(),t.color=c.fill(),t.fontWeight=r.fontWeight,t.fontStyle=r.fontStyle,t.letterSpacing=r.letterSpacing+"em",t.opacity=Math.max(r.a.opacity,.2),t.textTransform=r.textTransform,t.caretColor=I(r);const e=`\n .polotno-input::placeholder {\n color: ${s.color};\n opacity: 0.6;\n }\n `,n=q();n.innerHTML="",n.appendChild(document.createTextNode(e)),JSON.stringify(t)!==JSON.stringify(s)&&l(t)});const u=n.useRef(null);if(n.useLayoutEffect(()=>{var t;const e=u.current;if(!e){return}null===(t=u.current)||void 0===t||t.focus({preventScroll:!0});const r=a||e.value.length;e.selectionStart=e.selectionEnd=r,i&&(null==e||e.select(),document.execCommand("selectAll",!1,void 0))},[]),n.useEffect(()=>{window.addEventListener("blur",o);const t=t=>{var e;(null===(e=u.current)||void 0===e?void 0:e.contains(t.target))||o()};return window.addEventListener("touchstart",t),()=>{window.removeEventListener("blur",o),window.removeEventListener("touchstart",t)}},[]),!c){return null}let d=0;const f=c.textArr.length*c.lineHeight()*c.fontSize(),h=_(r.a,f);"middle"===r.verticalAlign&&(d=(h-f)/2),"bottom"===r.verticalAlign&&(d=h-f);const g=A(r.text);return t("textarea",{className:"polotno-input",ref:u,dir:M(g),style:Object.assign(Object.assign(Object.assign({},U),s),{paddingTop:d+"px"}),value:g,onChange:t=>{const e=B({oldText:r.text,newText:t.target.value,element:r});r.set(Object.assign({text:t.target.value},b(r,e)))},placeholder:N(r.placeholder),onBlur:o})}),G=e=>t(c,{children:t(Z,Object.assign({},e))});export const useFontLoader=(t,e,r,o,i)=>{const[a,s]=n.useReducer(t=>t+1,0),l=n.useRef(R(e,r,o)),c=n.useRef(null);return n.useLayoutEffect(()=>{if(l.current=R(e,r,o),l.current){return}let n=!0;return(async()=>{l.current=!1,s();const a=v(`text ${e}`);await t.loadFont(e,r,o,i),n?(c.current=a,l.current=!0,s()):a()})(),()=>{c.current&&(c.current(),c.current=null),n=!1}},[e,r,o]),n.useEffect(()=>{l.current&&setTimeout(()=>{c.current&&(c.current(),c.current=null)})},[l.current]),[l.current]};export const useFontFamiliesLoader=(t,e,r,o,i)=>{const[a,s]=n.useReducer(t=>t+1,0),l=e.join("\0"),c=n.useRef(e.every(t=>R(t,r,o))),u=n.useRef(null);return n.useLayoutEffect(()=>{if(c.current=e.every(t=>R(t,r,o)),c.current){return}let n=!0;return(async()=>{c.current=!1,s();const a=v(`text fonts ${l}`);await Promise.all(e.map(e=>t.loadFont(e,r,o,i))),n?(u.current=a,c.current=!0,s()):a()})(),()=>{u.current&&(u.current(),u.current=null),n=!1}},[l,r,o]),n.useEffect(()=>{c.current&&setTimeout(()=>{u.current&&(u.current(),u.current=null)})},[c.current]),[c.current]};export const getLineHeight=({fontLoaded:t,fontFamily:e,fontSize:r,lineHeight:o})=>n.useMemo(()=>L({fontFamily:e,fontSize:r,lineHeight:o}),[t,e,r,o]);export function usePrevious(t){const e=n.useRef(t),r=n.useRef(t);return n.useMemo(()=>{r.current=e.current,e.current=t},[t]),r.current}function K(t,e,r=!1){const n=t.fontSize(),o=t.height(),i=A(e.text);let a=e.a.fontSize;t.height(void 0);const s=Math.round(2*e.a.fontSize)-1;for(let l=1;l<s;l++){const n=J(e.a)&&t.height()>e.a.height+P;let o=i.split("\n").join(" ").split(/[\s-]+/).reduce((t,e)=>(e=e.toLowerCase(),/[\u3000-\u303F\u3040-\u309F\u30A0-\u30FF\uFF00-\uFFEF\u4E00-\u9FAF\uAC00-\uD7AF]/.test(e)?t.concat(e.split("")):t.concat(e)),[]),s=t.textArr.map(t=>t.text.toLowerCase()).join(";");const l=o.find(t=>!s.includes(t)||(s=s.replace(t,""),!1));if(!(n||l&&!r)){break}a-=H,t.fontSize(a)}return t.fontSize(n),t.height(o),a}export{getCurvePath}from"@polotno/core/text-html";export const TextElement=o(({element:o,store:c})=>{const{textOverflowIndicatorStyle:d}=x(),R=n.useRef(null),L=n.useRef(null),H=n.useRef(null),P=n.useRef([]),B=n.useRef(!0),[,I]=n.useReducer(t=>t+1,0),{editorEnabled:V,selectAll:q}=(t=>{const[e,r]=n.useState(!1),o=n.useRef(!1);return n.useEffect(()=>{var e=!0;return setTimeout(()=>{e&&(t._editModeEnabled&&(o.current=!0),r(!0),setTimeout(()=>{o.current=!1},50))},50),()=>{e=!1}},[]),{editorEnabled:e&&t._editModeEnabled,selectAll:o.current}})(o),[U,Z]=n.useState(!1),[Q,tt]=n.useState(!1),et=n.useRef(o.a.height),rt=n.useRef(0),nt=n.useRef(""),ot=n.useRef(0),it=o.isSelected,at=usePrevious(it),{textVerticalResizeEnabled:st}=F,lt=F.autoDeleteEmptyText,ct=usePrevious(o.fontFamily),[ut,dt]=n.useState([]);n.useEffect(()=>{var t,e;const r=null!==(e=null===(t=R.current)||void 0===t?void 0:t.textArr)&&void 0!==e?e:[];JSON.stringify(r)!==JSON.stringify(ut)&&dt(r)}),n.useEffect(()=>{if(o.a.width||"tablecell"===o.type){return}const t=R.current;t.width(600),o.set({width:1.4*t.getTextWidth()})},[]),n.useEffect(()=>{at&&!it&&lt&&""===o.text&&o.removable&&!N(o.placeholder)&&c.deleteElements([o.id])},[lt,o.placeholder,o.removable,o.text,it,at]);const ft=()=>{if(o.curveEnabled){const t=R.current;null==t||t.clearCache(),null==t||t.setAttrs({filters:[]});const e=L.current;e&&X(e,o)}else{const t=R.current;t&&X(t,o)}};n.useLayoutEffect(()=>{if(!Q){return u(o,()=>{ft()})}}),n.useEffect(()=>{const t=P.current;t.length>0&&(P.current=[],t.forEach(t=>t()))}),n.useEffect(()=>()=>{B.current=!1;const t=P.current;t.length>0&&(P.current=[],t.forEach(t=>t()))},[]);let ht=A(o.text);"uppercase"===o.textTransform&&(ht=ht.toUpperCase());const[gt]=useFontLoader(c,o.fontFamily,o.fontStyle,o.fontWeight,o.text||o.placeholder),pt=()=>{if(o.curveEnabled){const t=L.current;return t.getSelfRect().height||t.fontSize()}const t=R.current.clone({height:void 0}),e=Math.ceil(t.fontSize()*t.lineHeight()*t.textArr.length+1);return t.destroy(),e};n.useLayoutEffect(()=>{if(!gt){return}if("tablecell"===o.type){const{textOverflow:t}=F;if("resize"===t){const t=pt(),e=D(o)?$(o,2):null;(null==e?void 0:e.setCellContentHeight)&&e.setCellContentHeight(o.id,t)}else if("change-font-size"===t){const t=R.current;if(t){const e=K(t,o,F.textSplitAllowed);e!==o.fontSize&&c.history.ignore(()=>{o.set({fontSize:e})})}}return}const{textOverflow:t,textSplitAllowed:e}=F,r=(t,e,r,n)=>{const i=v(`text ${o.id}`),a=()=>{c.history.ignore(t,e,r).then(()=>{B.current?(P.current.push(i),I()):i()})};n?queueMicrotask(a):a()};if(!J(o)){const t=pt();return void r(()=>{J(o)||o.set({height:t})},void 0,void 0,!0)}if(!c.isPlaying){if("change-font-size"!==t||U){if("resize"===t){const t=pt();st&&o.height<t&&!U&&r(()=>{var e;D(o)&&o.set({height:t}),null===(e=R.current)||void 0===e||e.height(t)},!1,!0),st||o.height===t||U||r(()=>{var e;D(o)&&o.set({height:t}),null===(e=R.current)||void 0===e||e.height(t)},!1,!0)}}else{const t=R.current,n=o.curveEnabled?o.fontSize:K(t,o,e);if(n!==o.fontSize){return void r(()=>{o.set(b(o,n))},!1,!0)}const i=pt();o.height===i||st||r(()=>{o.set({height:i})},!1,!0)}}}),n.useLayoutEffect(()=>{var t;if(gt&&o.curveEnabled){const e=null===(t=L.current)||void 0===t?void 0:t.getSelfRect().width;if(e){const t=e-o.a.width,r=o.a.rotation*Math.PI/180,n=-t/2*Math.cos(r),i=-t/2*Math.sin(r);o.set({width:e,x:o.a.x+n,y:o.a.y+i})}}},[gt,o.curveEnabled,o.curvePower,o.text,o.fontSize,o.fontFamily,o.fontWeight,o.fontStyle,o.letterSpacing]),n.useLayoutEffect(()=>{const t=R.current;t&&(t.width(t.width()+1e-8),t.width(t.width()-1e-8),t._setTextData(),ft())},[gt]);const mt=n.useRef(null),xt=n.useRef(o.width),wt=n.useRef(0),vt=t=>{t.evt.preventDefault();const e=c.selectedShapes.find(t=>t===o);e&&o.contentEditable&&(wt.current=function(t){var e;const r=t.target,n=function(t){var e=t.getAbsoluteTransform().copy();e.invert();var r=t.getStage().getPointerPosition();return e.point(r)}(r),o=r.textArr,i=Math.floor(n.y/(r.fontSize()*r.lineHeight())),a=o.slice(0,i).reduce((t,e)=>t+e.text.length,i),s=null!==(e=o[i])&&void 0!==e?e:o[0];let l=0;return"right"===r.align()?l=r.width()-s.width:"center"===r.align()&&(l=r.width()/2-s.width/2),a+Math.round((n.x-l)/s.width*s.text.length)}(t),o.toggleEditMode())},yt=N(o.placeholder),bt=!ht&&yt?.6:o.a.opacity;Y(R,bt);const St=getLineHeight({fontLoaded:gt,fontFamily:o.fontFamily,fontSize:o.a.fontSize,lineHeight:o.lineHeight}),Et=o.selectable||c.role===w.ADMIN,zt=m(o),kt=m(o,o.stroke,"stroke"),Ot=n.useMemo(()=>o.backgroundEnabled?o.curveEnabled?function({width:t,height:e,padding:r=0,cornerRadius:n=0}){const o=-r,i=-r,a=t+r,s=e+r,l=f(`M ${o} ${i} L ${a} ${i} L ${a} ${s} L ${o} ${s} Z`);return h(l,n).path}({width:o.a.width,height:o.a.height,cornerRadius:o.backgroundCornerRadius*(o.a.fontSize*St*.5),padding:o.backgroundPadding*(o.a.fontSize*St*.5)}):function({lines:t,lineHeight:e,width:r,align:n="left",padding:o=0,cornerRadius:i=0}){const a=p({lines:t,lineHeight:e,width:r,align:n});return g({rects:a,padding:o,cornerRadius:i})}({lines:JSON.parse(JSON.stringify(ut)),cornerRadius:o.backgroundCornerRadius*(o.a.fontSize*St*.5),lineHeight:St*o.a.fontSize,padding:o.backgroundPadding*(o.a.fontSize*St*.5),width:o.a.width,align:o.align}):"",[o.backgroundEnabled,o.curveEnabled,o.backgroundCornerRadius,o.a.fontSize,o.a.height,St,o.backgroundPadding,o.a.width,o.align,ut]),Rt=W();let Ft=0;if(!o.curveEnabled){const t=ut.length*St*o.a.fontSize,e=_(o.a,t);"middle"===o.verticalAlign?Ft=(e-t)/2:"bottom"===o.verticalAlign&&(Ft=e-t)}const At=o.curveEnabled?j(o.a.width,o.a.height,o.curvePower,o.a.fontSize):"",Mt=gt?T(o.fontFamily):ct===o.fontFamily?"Arial":T(ct),jt=M(ht);return r(e,{children:[t(a,{ref:H,x:o.a.x,y:o.a.y,rotation:o.a.rotation,hideInExport:!o.showInExport,listening:!1,visible:o.backgroundEnabled,opacity:o.backgroundOpacity*bt,data:Ot,fill:o.backgroundColor,offsetY:-Ft}),t(a,{data:At,stroke:d.stroke,strokeWidth:1,x:o.a.x,y:o.a.y,rotation:o.a.rotation,visible:!1}),t(l,Object.assign({ref:L,visible:o.curveEnabled,data:At,text:ht||yt,listening:!1,align:"center",textBaseline:"middle",direction:jt},zt,kt,{strokeWidth:o.strokeWidth,lineJoin:C(o.strokeLineJoin),fillAfterStrokeEnabled:!0,fontSize:o.a.fontSize,fontFamily:`${T(o.fontFamily)}, ${T(ct)}`,fontStyle:o.fontStyle+" "+o.fontWeight,textDecoration:o.textDecoration.trim(),letterSpacing:o.letterSpacing*o.a.fontSize,x:o.a.x,y:o.a.y,rotation:o.a.rotation,opacity:o._editModeEnabled?.3:bt,hideInExport:!o.showInExport,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity})),t(s,Object.assign({ref:R,id:o.selectable?o.id:void 0,name:o.selectable?"element":"",hideInExport:!o.showInExport,editModeEnabled:o._editModeEnabled,x:o.a.x,y:o.a.y,rotation:o.a.rotation,width:o.a.width,height:J(o.a)?o.a.height:void 0,text:ht||yt,direction:jt},zt,kt,{lineJoin:C(o.strokeLineJoin),strokeWidth:o.strokeWidth,fillAfterStrokeEnabled:!0,fontSize:o.a.fontSize,fontFamily:Mt,fontStyle:o.fontStyle+" "+o.fontWeight,textDecoration:o.textDecoration,align:o.align,verticalAlign:o.verticalAlign,draggable:Rt?o.draggable&&it:o.draggable,preventDefault:!Rt||it,opacity:o.curveEnabled?0:bt,visible:!o._editModeEnabled,ellipsis:"ellipsis"===F.textOverflow,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity,lineHeight:St,letterSpacing:o.letterSpacing*o.a.fontSize,listening:!!o.selectable&&Et,onDragStart:()=>{tt(!0)},onDragMove:t=>{o.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{tt(!1),o.set(k(t.target))},onClick:vt,onTap:vt,onTransformStart:()=>{Z(!0);const t=R.current;et.current=t.height(),xt.current=o.a.width,mt.current=t.position(),rt.current=t.rotation(),ot.current=t.height(),nt.current=y(t)},onTransform:t=>{var e,r;const n=t.target;null===(e=H.current)||void 0===e||e.setAttrs({x:n.x(),y:n.y(),rotation:n.rotation(),scale:n.scale()});const i=nt.current;if("middle-left"===i||"middle-right"===i){const t=n.scaleX(),e=n.width()*t,r=O(xt.current,o.a.fontSize);let i=e;e<r&&(i=r,mt.current&&n.position(mt.current)),n.width(i),n.scaleX(1),n.scaleY(1);let a=pt();if("ellipsis"===F.textOverflow){a=et.current}else{const t=Math.max(a,et.current);n.height(t),o.set({height:n.height()})}const s=F.textVerticalResizeEnabled?Math.max(a,et.current):pt();o.set({x:n.x(),width:n.width(),rotation:n.rotation(),height:s}),n.skewX(0),n.skewY(0),ft()}if("top-center"===i||"bottom-center"===i){const e="resize"===F.textOverflow?pt():St*o.a.fontSize,r=t.target.height()*t.target.scaleY();if(r<e){if(t.target.height(e),mt.current){if("top-center"===nt.current){const r=rt.current*Math.PI/180,n=ot.current-e;t.target.x(mt.current.x-n*Math.sin(r)),t.target.y(mt.current.y+n*Math.cos(r))}else{t.target.position(mt.current)}}}else{t.target.height(r)}t.target.scaleY(1),t.target.scaleX(1),t.target.rotation(rt.current),t.target.skewX(0),t.target.skewY(0),ot.current=Math.max(e,r)}mt.current=t.target.position();const a=t.target.scaleX();null===(r=H.current)||void 0===r||r.setAttrs({scaleX:1,scaleY:1}),t.target.scaleX(1),t.target.scaleY(1),o.set({fontSize:o.a.fontSize*a,width:t.target.width()*a,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),height:t.target.height()*a,shadowBlur:o.shadowBlur*a,shadowOffsetX:o.shadowOffsetX*a,shadowOffsetY:o.shadowOffsetY*a,strokeWidth:o.strokeWidth*a})},onTransformEnd:t=>{var e;const r=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),o.set(Object.assign(Object.assign({},S(o,o.fontSize*r)),{width:Math.ceil(t.target.width()*r),x:z(t.target.x()),y:z(t.target.y()),rotation:z(t.target.rotation()),height:z(t.target.height()*r)})),null===(e=H.current)||void 0===e||e.setAttrs({scaleX:1,scaleY:1}),Z(!1)}})),V&&o.contentEditable&&t(i,{x:o.a.x,y:o.a.y,rotation:o.a.rotation,children:t(G,{textNodeRef:R,element:o,selectAll:q,cursorPosition:wt.current,onBlur:()=>{o.set(E(o)),o.toggleEditMode(!1)}})})]})});
@@ -1 +1 @@
1
- import e from"react";import{nodeAutorun as r}from"../utils/mobx.js";import{Input as t,UrlSource as n,BufferSource as u,CanvasSink as i,ALL_FORMATS as a}from"mediabunny";import{incrementLoader as c,triggerLoadError as o}from"../utils/loader.js";import{polotnoError as s}from"@polotno/core/errors";import{getElementTimeRange as l,getVideoRestMs as d}from"../utils/timeline.js";import{decodeBase64 as m}from"../utils/base64.js";function f(e,r){const t=p(e);return t>0&&r>=e.timestamp&&r<e.timestamp+t}function p(e){var r;const t=null!==(r=e.duration)&&void 0!==r?r:0;return Number.isFinite(t)&&t>0?t:0}export const useMediabunnyVideo=(g,v,h)=>{const[w,y]=e.useState({input:null,videoSink:null,duration:0,isReady:!1,error:null});e.useRef(w).current=w;const b=e.useRef(0),T=e.useRef(null),R=e.useRef(null),k=e.useRef(null),E=e.useRef(null),S=e.useRef(null),$=e.useRef(null),O=e.useRef(!1),I=e.useRef(null),j=e.useRef([]),x=e.useRef(null),D=e.useRef(!1),[,F]=e.useReducer(e=>e+1,0);return e.useEffect(()=>{if(!h){return}let e=!0;const r=++b.current;let l=null;return(async()=>{try{if(!e||r!==b.current){return}l=c(`mediabunny init ${g.id}`);const o=await async function(e){if(function(e){return e.startsWith("data:")}(e)){const r=function(e){const r=e.indexOf(",");if(-1===r){throw new Error("Invalid data URL format")}return m(e.slice(r+1)).buffer}(e);return new u(r)}if(function(e){return e.startsWith("file://")}(e)){try{const r=await fetch(e),t=await r.arrayBuffer();return new u(t)}catch(r){throw new Error(`Failed to load file URL: ${e}. File URLs may not be supported in this environment. Error: ${r}`)}}return new n(e)}(g.src);if(!e||r!==b.current){return void(l&&(l(),l=null))}const d=new t({source:o,formats:a}),f=await d.computeDuration(),p=await d.getPrimaryVideoTrack();if(!p){throw s("VIDEO_FAILED","No video track found",{reason:"no-video-track"})}if(null===p.codec){throw s("VIDEO_FAILED","Unsupported video codec",{reason:"unsupported-codec"})}if(!await p.canDecode()){throw s("VIDEO_FAILED","Unable to decode the video track",{reason:"cannot-decode"})}const v=await p.canBeTransparent(),h=new i(p,{poolSize:5,fit:"contain",alpha:v});if(!e||r!==b.current){return d.dispose(),void(l&&(l(),l=null))}l&&(l(),l=null),y(e=>Object.assign(Object.assign({},e),{input:d,videoSink:h,duration:f,isReady:!0,error:null}))}catch(d){if(console.error("Failed to initialize mediabunny:",d),l&&(l(),l=null),e&&r===b.current){const e=`Failed to initialize mediabunny for video ${g.id}: ${d}`;o(s("VIDEO_FAILED",e,Object.assign({reason:"load"},null==d?void 0:d.details),d)),y(e=>Object.assign(Object.assign({},e),{error:String(d),isReady:!1}))}}})(),()=>{e=!1,l&&(l(),l=null)}},[g.src,h]),e.useEffect(()=>()=>{R.current&&(R.current.return(),R.current=null),T.current&&(T.current(),T.current=null),k.current=null,E.current=null,S.current=null,O.current=!1,I.current=null,j.current=[],x.current=null,D.current=!1,y({input:null,videoSink:null,duration:0,isReady:!1,error:null})},[h]),e.useEffect(()=>{if(!h||!w.isReady||!w.videoSink){return}const e=++b.current,t="string"==typeof g.src?g.src.slice(0,120):String(g.src),n=(e,r={},n="debug")=>{var u;let i="";try{i=JSON.stringify(Object.assign(Object.assign({},r),{timeCalc:$.current}))}catch(c){i=`[unserializable extras: ${String(c)}]`}const a=`mediabunny event=${e} elementId=${g.id} targetTime=${S.current} duration=${w.duration} lastFrameTimestamp=${null===(u=E.current)||void 0===u?void 0:u.timestamp} hasIterator=${Boolean(R.current)} prefetchSize=${j.current.length} srcHint=${t} extras=${i}`;"error"===n?console.error(a):"warn"===n?console.warn(a):console.debug(a)},u=e=>{const r=w.duration||0;return r&&Number.isFinite(r)?Math.max(0,Math.min(e,r)):e},i=e=>{let r=k.current;r&&r.width===e.canvas.width&&r.height===e.canvas.height||(r||(r=document.createElement("canvas"),k.current=r),r.width=e.canvas.width,r.height=e.canvas.height);const t=r.getContext("2d");t&&(t.clearRect(0,0,r.width,r.height),t.drawImage(e.canvas,0,0)),E.current={timestamp:e.timestamp,duration:p(e)}},a=e=>{const r=R.current;r&&(D.current||(D.current=!0,x.current=(async()=>{try{for(;j.current.length<4&&e===b.current;){const t=await r.next();if(e!==b.current){return}if(t.done||!t.value){break}j.current.push({timestamp:t.value.timestamp,frame:t.value})}}catch(t){}finally{D.current=!1,x.current=null}})()))},o=e=>{const r=j.current;let t=-1;for(let u=0;u<r.length&&!(r[u].timestamp>e);u++){t=u}if(-1===t){return null}const n=r[t];return t<r.length-1||f(n.frame,e)?(j.current=r.slice(t+1),n):null},s=()=>{j.current=[]},m=async(e,r,t=0)=>{const c=u(e),l=(e=>{const r=E.current;return!r||e<r.timestamp||e>r.timestamp+.5})(c)?"seek":"iterate";try{const t=w.videoSink,u=E.current;if(u&&f(u,c)){return void(S.current=e)}const d=o(c);if(d){return i(d.frame),S.current=e,a(r),void F()}if(x.current){await x.current;const t=o(c);if(t){return i(t.frame),S.current=e,a(r),void F()}}s();const m=()=>n("iterator_exhausted",{mode:l,requestedTargetTime:e,clampedTargetTime:c},"warn"),p=async e=>{R.current&&(await R.current.return(),R.current=null),s();const n=t.canvases(e);R.current=n;const u=await n.next();return r!==b.current?(await n.return(),R.current===n&&(R.current=null),"cancelled"):u.done||!u.value?"empty":(i(u.value),a(r),"drawn")};if("seek"===l){const e=await p(c);if("cancelled"===e){return}if("empty"===e){return void m()}}else{const e=R.current;if(!e){return}for(;r===b.current;){const t=await e.next();if(r!==b.current){break}if(t.done||!t.value){"empty"===await p(c)&&m();break}const n=t.value;if(i(n),f(n,c)||n.timestamp>=c){a(r);break}}}S.current=e,F()}catch(d){const u=d instanceof Error?{name:d.name,message:d.message,stack:d.stack}:{message:String(d)},i=d instanceof Error?`${d.name}: ${d.message}`:String(d),a=i.includes("Unsupported configuration")||i.includes("isConfigSupported")||i.includes("OperationError");if(n("frame_process_failed",{mode:l,requestedTargetTime:e,clampedTargetTime:c,unsupportedConfigAttempt:t,isUnsupportedConfig:a,error:u},"error"),a&&t<1){try{R.current&&(await R.current.return(),R.current=null),s(),x.current=null,D.current=!1,E.current=null,await m(e,r,t+1)}catch(p){}}}},y=r(g,()=>{const r=w.videoSink,t=w.duration;if(!r||!t){return}const n=g.startTime*t*1e3,i=t*(g.endTime-g.startTime)*1e3,{start:a}=l(g.animations,g.page.duration),o=d(v.currentTime,g.page.startTime,a,i,n,g.speed),s=o/1e3+1e-6,f=u(s);$.current={pageStartTime:g.page.startTime,storeCurrentTime:v.currentTime,offsetMs:n,durationMs:i,restMs:o,targetTime:s,clampedTargetTime:f,startTime:g.startTime,endTime:g.endTime,videoDuration:t},((e,r)=>{O.current?I.current=e:(O.current=!0,T.current||(T.current=c(`mediabunny video frame ${g.id}`)),(async()=>{let t=e;for(;null!==t&&r===b.current;){await m(t,r),t=I.current,I.current=null}T.current&&(T.current(),T.current=null),O.current=!1})())})(s,e)});return()=>{y(),b.current++,T.current&&(T.current(),T.current=null)}},[h,w.isReady,w.videoSink,w.duration,v,g]),h&&w.isReady?k.current:null};
1
+ import e from"react";import{nodeAutorun as r}from"../utils/mobx.js";import{Input as t,UrlSource as n,BufferSource as u,VideoSampleSink as i,ALL_FORMATS as a}from"mediabunny";import{incrementLoader as c,triggerLoadError as o}from"../utils/loader.js";import{polotnoError as s}from"@polotno/core/errors";import{getElementTimeRange as l,getVideoRestMs as d}from"../utils/timeline.js";import{decodeBase64 as m}from"../utils/base64.js";function f(e,r){const t=p(e);return t>0&&r>=e.timestamp&&r<e.timestamp+t}function p(e){var r;const t=null!==(r=e.duration)&&void 0!==r?r:0;return Number.isFinite(t)&&t>0?t:0}function h(e){var r;null===(r=null==e?void 0:e.close)||void 0===r||r.call(e)}function v(e){for(const r of e.current){h(r.frame)}e.current=[]}export const useMediabunnyVideo=(g,y,w)=>{const[b,T]=e.useState({input:null,videoSink:null,duration:0,isReady:!1,error:null,hasAlpha:!1});e.useRef(b).current=b;const R=e.useRef(0),k=e.useRef(null),E=e.useRef(null),$=e.useRef(null),S=e.useRef(null),O=e.useRef(null),F=e.useRef(null),j=e.useRef(null),x=e.useRef(!1),D=e.useRef(null),I=e.useRef([]),A=e.useRef(null),L=e.useRef(!1),[,U]=e.useReducer(e=>e+1,0);return e.useEffect(()=>{if(!w){return}let e=!0;const r=++R.current;let l=null;return(async()=>{try{if(!e||r!==R.current){return}l=c(`mediabunny init ${g.id}`);const o=await async function(e){if(function(e){return e.startsWith("data:")}(e)){const r=function(e){const r=e.indexOf(",");if(-1===r){throw new Error("Invalid data URL format")}return m(e.slice(r+1)).buffer}(e);return new u(r)}if(function(e){return e.startsWith("file://")}(e)){try{const r=await fetch(e),t=await r.arrayBuffer();return new u(t)}catch(r){throw new Error(`Failed to load file URL: ${e}. File URLs may not be supported in this environment. Error: ${r}`)}}return new n(e)}(g.src);if(!e||r!==R.current){return void(l&&(l(),l=null))}const d=new t({source:o,formats:a}),f=await d.computeDuration(),p=await d.getPrimaryVideoTrack();if(!p){throw s("VIDEO_FAILED","No video track found",{reason:"no-video-track"})}if(null===p.codec){throw s("VIDEO_FAILED","Unsupported video codec",{reason:"unsupported-codec"})}if(!await p.canDecode()){throw s("VIDEO_FAILED","Unable to decode the video track",{reason:"cannot-decode"})}const h=await p.canBeTransparent(),v=new i(p);if(!e||r!==R.current){return d.dispose(),void(l&&(l(),l=null))}l&&(l(),l=null),T(e=>Object.assign(Object.assign({},e),{input:d,videoSink:v,duration:f,isReady:!0,error:null,hasAlpha:h}))}catch(d){if(console.error("Failed to initialize mediabunny:",d),l&&(l(),l=null),e&&r===R.current){const e=`Failed to initialize mediabunny for video ${g.id}: ${d}`;o(s("VIDEO_FAILED",e,Object.assign({reason:"load"},null==d?void 0:d.details),d)),T(e=>Object.assign(Object.assign({},e),{error:String(d),isReady:!1}))}}})(),()=>{e=!1,l&&(l(),l=null)}},[g.src,w]),e.useEffect(()=>()=>{E.current&&(E.current.return(),E.current=null),k.current&&(k.current(),k.current=null),$.current=null,S.current=null,O.current=null,F.current=null,x.current=!1,D.current=null,v(I),A.current=null,L.current=!1,T({input:null,videoSink:null,duration:0,isReady:!1,error:null,hasAlpha:!1})},[w]),e.useEffect(()=>{if(!w||!b.isReady||!b.videoSink){return}const e=++R.current,t="string"==typeof g.src?g.src.slice(0,120):String(g.src),n=(e,r={},n="debug")=>{var u;let i="";try{i=JSON.stringify(Object.assign(Object.assign({},r),{timeCalc:j.current}))}catch(c){i=`[unserializable extras: ${String(c)}]`}const a=`mediabunny event=${e} elementId=${g.id} targetTime=${F.current} duration=${b.duration} lastFrameTimestamp=${null===(u=O.current)||void 0===u?void 0:u.timestamp} hasIterator=${Boolean(E.current)} prefetchSize=${I.current.length} srcHint=${t} extras=${i}`;"error"===n?console.error(a):"warn"===n?console.warn(a):console.debug(a)},u=e=>{const r=b.duration||0;return r&&Number.isFinite(r)?Math.max(0,Math.min(e,r)):e},i=e=>{const r=e.displayWidth,t=e.displayHeight;let n=$.current;n&&n.width===r&&n.height===t||(n||(n=document.createElement("canvas"),$.current=n,S.current=n.getContext("2d",{alpha:b.hasAlpha})),n.width=r,n.height=t);const u=S.current,i=e.timestamp,a=p(e);try{u&&(b.hasAlpha&&u.clearRect(0,0,n.width,n.height),e.drawWithFit(u,{fit:"contain"}))}finally{h(e)}O.current={timestamp:i,duration:a}},a=e=>{const r=E.current;r&&(L.current||(L.current=!0,A.current=(async()=>{try{for(;I.current.length<4&&e===R.current;){const t=await r.next();if(e!==R.current){return void h(t.value)}if(t.done||!t.value){break}I.current.push({timestamp:t.value.timestamp,frame:t.value})}}catch(t){}finally{L.current=!1,A.current=null}})()))},o=e=>{const r=I.current;let t=-1;for(let u=0;u<r.length&&!(r[u].timestamp>e);u++){t=u}if(-1===t){return null}const n=r[t];if(!(t<r.length-1||f(n.frame,e))){return null}for(let u=0;u<t;u++){h(r[u].frame)}return I.current=r.slice(t+1),n},s=()=>v(I),m=async(e,r,t=0)=>{const c=u(e),l=(e=>{const r=O.current;return!r||e<r.timestamp||e>r.timestamp+.5})(c)?"seek":"iterate";try{const t=b.videoSink,u=O.current;if(u&&f(u,c)){return void(F.current=e)}const d=o(c);if(d){return i(d.frame),F.current=e,a(r),void U()}if(A.current){await A.current;const t=o(c);if(t){return i(t.frame),F.current=e,a(r),void U()}}s();const m=()=>n("iterator_exhausted",{mode:l,requestedTargetTime:e,clampedTargetTime:c},"warn"),p=async e=>{E.current&&(await E.current.return(),E.current=null),s();const n=t.samples(e);E.current=n;const u=await n.next();return r!==R.current?(u.value&&h(u.value),await n.return(),E.current===n&&(E.current=null),"cancelled"):u.done||!u.value?"empty":(i(u.value),a(r),"drawn")};if("seek"===l){const e=await p(c);if("cancelled"===e){return}if("empty"===e){return void m()}}else{const e=E.current;if(!e){return}for(;r===R.current;){const t=await e.next();if(r!==R.current){t.value&&h(t.value);break}if(t.done||!t.value){"empty"===await p(c)&&m();break}const n=t.value;if(f(n,c)||n.timestamp>=c){i(n),a(r);break}h(n)}}F.current=e,U()}catch(d){const u=d instanceof Error?{name:d.name,message:d.message,stack:d.stack}:{message:String(d)},i=d instanceof Error?`${d.name}: ${d.message}`:String(d),a=i.includes("Unsupported configuration")||i.includes("isConfigSupported")||i.includes("OperationError");if(n("frame_process_failed",{mode:l,requestedTargetTime:e,clampedTargetTime:c,unsupportedConfigAttempt:t,isUnsupportedConfig:a,error:u},"error"),a&&t<1){try{E.current&&(await E.current.return(),E.current=null),s(),A.current=null,L.current=!1,O.current=null,await m(e,r,t+1)}catch(p){}}}},T=r(g,()=>{const r=b.videoSink,t=b.duration;if(!r||!t){return}const n=g.startTime*t*1e3,i=t*(g.endTime-g.startTime)*1e3,{start:a}=l(g.animations,g.page.duration),o=d(y.currentTime,g.page.startTime,a,i,n,g.speed),s=o/1e3+1e-6,f=u(s);j.current={pageStartTime:g.page.startTime,storeCurrentTime:y.currentTime,offsetMs:n,durationMs:i,restMs:o,targetTime:s,clampedTargetTime:f,startTime:g.startTime,endTime:g.endTime,videoDuration:t},((e,r)=>{x.current?D.current=e:(x.current=!0,k.current||(k.current=c(`mediabunny video frame ${g.id}`)),(async()=>{let t=e;for(;null!==t&&r===R.current;){await m(t,r),t=D.current,D.current=null}k.current&&(k.current(),k.current=null),x.current=!1})())})(s,e)});return()=>{T(),R.current++,k.current&&(k.current(),k.current=null)}},[w,b.isReady,b.videoSink,b.duration,y,g]),w&&b.isReady?$.current:null};
@@ -1 +1 @@
1
- import e from"react";import t from"konva";import{getClientRect as n}from"../utils/math.js";import{useWorkspaceStyle as o}from"./workspace-style.js";let r=({targetKonvaNodes:e,guideKonvaNode:t,distance:n,snapDirection:o})=>n<5;export const setSnapFilterFunc=e=>{r=e};function s(e,t){var n=[],o=[];e.vertical.forEach(e=>{t.vertical.forEach(t=>{var o=Math.abs(e.offset-t.guide);r({targetKonvaNodes:t.nodes,guideKonvaNode:e.node,distance:o,snapDirection:e.snap})&&n.push({lineGuide:e.offset,diff:o,snap:t.snap,offset:t.offset})})}),e.horizontal.forEach(e=>{t.horizontal.forEach(t=>{var n=Math.abs(e.offset-t.guide);r({targetKonvaNodes:t.nodes,guideKonvaNode:e.node,distance:n,snapDirection:e.snap})&&o.push({lineGuide:e.offset,diff:n,snap:t.snap,offset:t.offset})})});var s=[];const i=n.sort((e,t)=>e.diff-t.diff),a=o.sort((e,t)=>e.diff-t.diff);var d=i[0],c=a[0];return d&&i.filter(e=>Math.abs(e.diff-d.diff)<.1).forEach(e=>{s.push(Object.assign({orientation:"V"},e))}),c&&a.filter(e=>Math.abs(e.diff-c.diff)<.1).forEach(e=>{s.push(Object.assign({orientation:"H"},e))}),s}export const ensureDragOrder=()=>{if(0===t.DD._dragElements.size){return}const e=[...t.DD._dragElements.entries()],n=e.find(([e,n])=>n.node instanceof t.Transformer);n&&(e.splice(e.indexOf(n),1),e.unshift(n),t.DD._dragElements.clear(),e.forEach(([e,n])=>{t.DD._dragElements.set(e,n)}))};function i(e,n,o){return new t.Line({x:-e.x(),y:-e.y(),points:o,stroke:n.stroke,strokeWidth:n.strokeWidth,name:"guid-line",dash:n.dash})}function a(e,t,n){const o=null==e?void 0:e.children.find(e=>"line-guides"===e.name()),r=e.getStage();n.forEach(e=>{"H"===e.orientation?null==o||o.add(i(r,t,[-6e3,e.lineGuide,6e3,e.lineGuide])):"V"===e.orientation&&(null==o||o.add(i(r,t,[e.lineGuide,-6e3,e.lineGuide,6e3])))})}export function useSnap(r,f){const u=e.useRef(null),l=e.useRef(null),h=e.useRef(new Map),g=e.useRef(null),{snapGuideStyle:y}=o(),p=e.useRef(y);p.current=y;const x=e=>e.hasName("element")||e.hasName("page-background")||!u.current&&e.hasName("elements-area");function v(e){var t;const n=null===(t=r.current)||void 0===t?void 0:t.getStage(),o=[],s=[];return n.find(x).forEach(t=>{if(!(e.indexOf(t)>=0)){var n=t.getClientRect({skipShadow:!0,skipStroke:!0});o.push({offset:n.x,node:t,snap:"start"},{offset:n.x+n.width,node:t,snap:"end"},{offset:n.x+n.width/2,node:t,snap:"center"}),s.push({offset:n.y,node:t,snap:"start"},{offset:n.y+n.height,node:t,snap:"end"},{offset:n.y+n.height/2,node:t,snap:"center"})}}),{vertical:o,horizontal:s}}function m(e){var t;a(null===(t=r.current)||void 0===t?void 0:t.getLayer(),p.current,e)}const b=e=>{var o,r;const a=null===(o=e.target)||void 0===o?void 0:o.getLayer();if(!a){return}const d=a.children.find(e=>"line-guides"===e.name());null==d||d.destroyChildren();const c=l.current;if((null===(r=e.evt)||void 0===r?void 0:r.shiftKey)&&c){const t=e.target.getAbsolutePosition();let n=t.x-c.x,o=t.y-c.y;const r=Math.abs(n),s=Math.abs(o);if(r>2.414*s){o=0}else if(s>2.414*r){n=0}else{const e=(r+s)/2;n=Math.sign(n)*e,o=Math.sign(o)*e}e.target.nodes().forEach(e=>{const t=h.current.get(e);t&&e.setAbsolutePosition({x:t.x+n,y:t.y+o})});const f=g.current;if(f&&(r>0||s>0)){const e=Math.sign(n),t=Math.sign(o);null==d||d.add(i(a.getStage(),p.current,[f.x-6e3*e,f.y-6e3*t,f.x+6e3*e,f.y+6e3*t]))}return}var f=v(e.target.nodes()),u=function(e){const o=e.__getNodeRect(),r=n(Object.assign(Object.assign({},o),{rotation:t.Util.radToDeg(o.rotation)})),s=e.getAbsolutePosition();return{vertical:[{guide:r.x,offset:s.x-r.x,snap:"start",nodes:e.nodes()},{guide:r.x+r.width/2,offset:s.x-r.x-r.width/2,snap:"center",nodes:e.nodes()},{guide:r.x+r.width,offset:s.x-r.x-r.width,snap:"end",nodes:e.nodes()}],horizontal:[{guide:r.y,offset:s.y-r.y,snap:"start",nodes:e.nodes()},{guide:r.y+r.height/2,offset:s.y-r.y-r.height/2,snap:"center",nodes:e.nodes()},{guide:r.y+r.height,offset:s.y-r.y-r.height,snap:"end",nodes:e.nodes()}]}}(e.target),y=s(f,u);if(!y.length){return}m(y);const x=e.target.getAbsolutePosition(),b=(e.target.nodes().map(e=>e.getAbsolutePosition()),Object.assign({},x));y.forEach(e=>{switch(e.snap){case"start":case"center":case"end":switch(e.orientation){case"V":b.x=e.lineGuide+e.offset;break;case"H":b.y=e.lineGuide+e.offset}}});const w=b.x-x.x,M=b.y-x.y;e.evt.ctrlKey||e.evt.metaKey||e.target.nodes().forEach(e=>{const t=e.getAbsolutePosition();e.setAbsolutePosition({x:t.x+w,y:t.y+M})})},w=(e,t,n)=>{var o;const i=r.current;if(!i){return t}const a=i.getLayer();if(!a){return t}const f=a.children.find(e=>"line-guides"===e.name());if(null==f||f.destroyChildren(),"rotater"===i.getActiveAnchor()){return t}const u=i.getActiveAnchor(),l=c[u],h=null===(o=i.findOne(`.${l}`))||void 0===o?void 0:o.getAbsolutePosition();if(!h){return t}const g={x:e.x-h.x,y:e.y-h.y},y=function(e,t){const n=d(e,t)/d(t,t);return{x:n*t.x,y:n*t.y}}({x:t.x-e.x,y:t.y-e.y},g);if(Math.sqrt(Math.pow(y.x,2)+Math.pow(y.y,2))>5){return t}const p={x:e.x+y.x,y:e.y+y.y};var x=s(v(i.nodes()),{vertical:[{guide:p.x,offset:0,snap:"start",nodes:i.nodes()}],horizontal:[{guide:p.y,offset:0,snap:"start",nodes:i.nodes()}]});if(!x.length){return t}if(m(x),n.ctrlKey||n.metaKey){return t}const b=[];if(x.forEach(e=>{const t=function(e,t,n){if("V"===n.orientation){const o=n.lineGuide;if(Math.abs(t.x-e.x)<1e-4){return null}const r=(t.y-e.y)/(t.x-e.x);return{x:o,y:r*o+(e.y-r*e.x)}}{const o=n.lineGuide;if(Math.abs(t.y-e.y)<1e-4){return null}const r=(t.y-e.y)/(t.x-e.x);return{x:(o-e.y)/r+e.x,y:o}}}(p,h,{orientation:e.orientation,lineGuide:e.lineGuide});t&&b.push(t)}),b.length>0){let e=b[0],t=Math.sqrt(Math.pow(p.x-e.x,2)+Math.pow(p.y-e.y,2));if(b.forEach(n=>{const o=Math.sqrt(Math.pow(p.x-n.x,2)+Math.pow(p.y-n.y,2));o<t&&(t=o,e=n)}),t<10){return e}}return p},M=e=>{if(l.current=null,h.current=new Map,g.current=null,!e.target){return}const t=e.target.getLayer();if(!t){return}const n=t.children.find(e=>"line-guides"===e.name());null==n||n.destroyChildren(),t.batchDraw()};e.useEffect(()=>{r.current&&(r.current.anchorDragBoundFunc(w),r.current.on("dragstart",e=>{const t=r.current;if(t){l.current=t.getAbsolutePosition(),h.current=new Map(t.nodes().map(e=>[e,e.getAbsolutePosition()]));const e=t.getClientRect();g.current={x:e.x+e.width/2,y:e.y+e.height/2}}setTimeout(()=>{ensureDragOrder()})}),r.current.on("dragmove",b),r.current.on("dragend",M),r.current.on("transformend",M),r.current.on("transform",e=>{var t,n;e.evt.ctrlKey||e.evt.metaKey?null===(t=r.current)||void 0===t||t.rotationSnapTolerance(0):null===(n=r.current)||void 0===n||n.rotationSnapTolerance(5)}))},[])}export function useAnchorSnap(t,n,r){const{snapGuideStyle:i}=o(),d=e.useRef(i);d.current=i;const c=e=>e.hasName("element")||e.hasName("line-anchor")||e.hasName("page-background")||e.hasName("elements-area"),f=e=>{var o;const r=null===(o=e.target)||void 0===o?void 0:o.getLayer();if(!r){return}const i=r.children.find(e=>"line-guides"===e.name());null==i||i.destroyChildren();var f,u=function(e){var n;const o=null===(n=t.current)||void 0===n?void 0:n.getStage();var r=[],s=[];return o.find(c).forEach(t=>{if(!(e.indexOf(t)>=0)){var n=t.getClientRect({skipShadow:!0,skipStroke:!0});t.hasName("line-anchor")&&(n={x:t.absolutePosition().x,y:t.absolutePosition().y,width:0,height:0}),r.push({offset:n.x,node:t,snap:"start"},{offset:n.x+n.width,node:t,snap:"end"},{offset:n.x+n.width/2,node:t,snap:"center"}),s.push({offset:n.y,node:t,snap:"start"},{offset:n.y+n.height,node:t,snap:"end"},{offset:n.y+n.height/2,node:t,snap:"center"})}}),{vertical:r,horizontal:s}}([e.target,...n.map(e=>e.current)]),l=s(u,{vertical:[{guide:(f=e.target).absolutePosition().x,offset:0,snap:"center",nodes:[f]}],horizontal:[{guide:f.absolutePosition().y,offset:0,snap:"center",nodes:[f]}]});if(!l.length){return}!function(e){var n;a(null===(n=t.current)||void 0===n?void 0:n.getLayer(),d.current,e)}(l);const h=e.target.getAbsolutePosition(),g=Object.assign({},h);l.forEach(e=>{switch(e.snap){case"start":case"center":case"end":switch(e.orientation){case"V":g.x=e.lineGuide+e.offset;break;case"H":g.y=e.lineGuide+e.offset}}});const y=g.x-h.x,p=g.y-h.y;if(!e.evt.ctrlKey&&!e.evt.metaKey){const t=e.target.getAbsolutePosition();e.target.absolutePosition({x:t.x+y,y:t.y+p})}},u=e=>{if(!e.target){return}const t=e.target.getLayer();if(!t){return}const n=t.children.find(e=>"line-guides"===e.name());null==n||n.destroyChildren(),t.batchDraw()};e.useEffect(()=>{t.current&&(t.current.on("dragmove",f),t.current.on("dragend",u))},r)}function d(e,t){return e.x*t.x+e.y*t.y}const c={"top-left":"bottom-right","top-center":"bottom-center","top-right":"bottom-left","middle-right":"middle-left","bottom-right":"top-left","bottom-center":"top-center","bottom-left":"top-right","middle-left":"middle-right"};
1
+ import e from"react";import t from"konva";import{getClientRect as n}from"../utils/math.js";import{useWorkspaceStyle as o}from"./workspace-style.js";let r=({targetKonvaNodes:e,guideKonvaNode:t,distance:n,snapDirection:o})=>n<5;export const setSnapFilterFunc=e=>{r=e};function s(e,t){var n=[],o=[];e.vertical.forEach(e=>{t.vertical.forEach(t=>{var o=Math.abs(e.offset-t.guide);r({targetKonvaNodes:t.nodes,guideKonvaNode:e.node,distance:o,snapDirection:e.snap})&&n.push({lineGuide:e.offset,diff:o,snap:t.snap,offset:t.offset})})}),e.horizontal.forEach(e=>{t.horizontal.forEach(t=>{var n=Math.abs(e.offset-t.guide);r({targetKonvaNodes:t.nodes,guideKonvaNode:e.node,distance:n,snapDirection:e.snap})&&o.push({lineGuide:e.offset,diff:n,snap:t.snap,offset:t.offset})})});var s=[];const i=n.sort((e,t)=>e.diff-t.diff),a=o.sort((e,t)=>e.diff-t.diff);var d=i[0],c=a[0];return d&&i.filter(e=>Math.abs(e.diff-d.diff)<.1).forEach(e=>{s.push(Object.assign({orientation:"V"},e))}),c&&a.filter(e=>Math.abs(e.diff-c.diff)<.1).forEach(e=>{s.push(Object.assign({orientation:"H"},e))}),s}export const ensureDragOrder=()=>{if(0===t.DD._dragElements.size){return}const e=[...t.DD._dragElements.entries()],n=e.find(([e,n])=>n.node instanceof t.Transformer);n&&(e.splice(e.indexOf(n),1),e.unshift(n),t.DD._dragElements.clear(),e.forEach(([e,n])=>{t.DD._dragElements.set(e,n)}))};function i(e,n,o){return new t.Line({x:-e.x(),y:-e.y(),points:o,stroke:n.stroke,strokeWidth:n.strokeWidth,name:"guid-line",dash:n.dash})}function a(e,t,n){const o=null==e?void 0:e.children.find(e=>"line-guides"===e.name()),r=e.getStage();n.forEach(e=>{"H"===e.orientation?null==o||o.add(i(r,t,[-6e3,e.lineGuide,6e3,e.lineGuide])):"V"===e.orientation&&(null==o||o.add(i(r,t,[e.lineGuide,-6e3,e.lineGuide,6e3])))})}export function useSnap(r,f){const u=e.useRef(null),l=e.useRef(null),h=e.useRef(new Map),g=e.useRef(null),{snapGuideStyle:y}=o(),p=e.useRef(y);p.current=y;const x=e=>e.hasName("element")||e.hasName("page-background")||!u.current&&e.hasName("elements-area");function v(e){var t;const n=null===(t=r.current)||void 0===t?void 0:t.getStage(),o=[],s=[];return n.find(x).forEach(t=>{if(!(e.indexOf(t)>=0)){var n=t.getClientRect({skipShadow:!0,skipStroke:!0});o.push({offset:n.x,node:t,snap:"start"},{offset:n.x+n.width,node:t,snap:"end"},{offset:n.x+n.width/2,node:t,snap:"center"}),s.push({offset:n.y,node:t,snap:"start"},{offset:n.y+n.height,node:t,snap:"end"},{offset:n.y+n.height/2,node:t,snap:"center"})}}),{vertical:o,horizontal:s}}function m(e){var t;a(null===(t=r.current)||void 0===t?void 0:t.getLayer(),p.current,e)}const b=e=>{var o,r;const a=null===(o=e.target)||void 0===o?void 0:o.getLayer();if(!a){return}const d=a.children.find(e=>"line-guides"===e.name());null==d||d.destroyChildren();const c=l.current;if((null===(r=e.evt)||void 0===r?void 0:r.shiftKey)&&c){const t=e.target.getAbsolutePosition();let n=t.x-c.x,o=t.y-c.y;const r=Math.abs(n),s=Math.abs(o);if(r>2.414*s){o=0}else if(s>2.414*r){n=0}else{const e=(r+s)/2;n=Math.sign(n)*e,o=Math.sign(o)*e}e.target.nodes().forEach(e=>{const t=h.current.get(e);t&&e.setAbsolutePosition({x:t.x+n,y:t.y+o})});const f=g.current;if(f&&(r>0||s>0)){const e=Math.sign(n),t=Math.sign(o);null==d||d.add(i(a.getStage(),p.current,[f.x-6e3*e,f.y-6e3*t,f.x+6e3*e,f.y+6e3*t]))}return}var f=v(e.target.nodes()),u=function(e){const o=e.__getNodeRect(),r=n(Object.assign(Object.assign({},o),{rotation:t.Util.radToDeg(o.rotation)})),s=e.getAbsolutePosition();return{vertical:[{guide:r.x,offset:s.x-r.x,snap:"start",nodes:e.nodes()},{guide:r.x+r.width/2,offset:s.x-r.x-r.width/2,snap:"center",nodes:e.nodes()},{guide:r.x+r.width,offset:s.x-r.x-r.width,snap:"end",nodes:e.nodes()}],horizontal:[{guide:r.y,offset:s.y-r.y,snap:"start",nodes:e.nodes()},{guide:r.y+r.height/2,offset:s.y-r.y-r.height/2,snap:"center",nodes:e.nodes()},{guide:r.y+r.height,offset:s.y-r.y-r.height,snap:"end",nodes:e.nodes()}]}}(e.target),y=s(f,u);if(!y.length){return}m(y);const x=e.target.getAbsolutePosition(),b=Object.assign({},x);y.forEach(e=>{switch(e.snap){case"start":case"center":case"end":switch(e.orientation){case"V":b.x=e.lineGuide+e.offset;break;case"H":b.y=e.lineGuide+e.offset}}});const w=b.x-x.x,M=b.y-x.y;e.evt.ctrlKey||e.evt.metaKey||e.target.nodes().forEach(e=>{const t=e.getAbsolutePosition();e.setAbsolutePosition({x:t.x+w,y:t.y+M})})},w=(e,t,n)=>{var o;const i=r.current;if(!i){return t}const a=i.getLayer();if(!a){return t}const f=a.children.find(e=>"line-guides"===e.name());if(null==f||f.destroyChildren(),"rotater"===i.getActiveAnchor()){return t}const u=i.getActiveAnchor(),l=c[u],h=null===(o=i.findOne(`.${l}`))||void 0===o?void 0:o.getAbsolutePosition();if(!h){return t}const g={x:e.x-h.x,y:e.y-h.y},y=function(e,t){const n=d(e,t)/d(t,t);return{x:n*t.x,y:n*t.y}}({x:t.x-e.x,y:t.y-e.y},g);if(Math.sqrt(Math.pow(y.x,2)+Math.pow(y.y,2))>5){return t}const p={x:e.x+y.x,y:e.y+y.y};var x=s(v(i.nodes()),{vertical:[{guide:p.x,offset:0,snap:"start",nodes:i.nodes()}],horizontal:[{guide:p.y,offset:0,snap:"start",nodes:i.nodes()}]});if(!x.length){return t}if(m(x),n.ctrlKey||n.metaKey){return t}const b=[];if(x.forEach(e=>{const t=function(e,t,n){if("V"===n.orientation){const o=n.lineGuide;if(Math.abs(t.x-e.x)<1e-4){return null}const r=(t.y-e.y)/(t.x-e.x);return{x:o,y:r*o+(e.y-r*e.x)}}{const o=n.lineGuide;if(Math.abs(t.y-e.y)<1e-4){return null}const r=(t.y-e.y)/(t.x-e.x);return{x:(o-e.y)/r+e.x,y:o}}}(p,h,{orientation:e.orientation,lineGuide:e.lineGuide});t&&b.push(t)}),b.length>0){let e=b[0],t=Math.sqrt(Math.pow(p.x-e.x,2)+Math.pow(p.y-e.y,2));if(b.forEach(n=>{const o=Math.sqrt(Math.pow(p.x-n.x,2)+Math.pow(p.y-n.y,2));o<t&&(t=o,e=n)}),t<10){return e}}return p},M=e=>{if(l.current=null,h.current=new Map,g.current=null,!e.target){return}const t=e.target.getLayer();if(!t){return}const n=t.children.find(e=>"line-guides"===e.name());null==n||n.destroyChildren(),t.batchDraw()};e.useEffect(()=>{r.current&&(r.current.anchorDragBoundFunc(w),r.current.on("dragstart",e=>{const t=r.current;if(t){l.current=t.getAbsolutePosition(),h.current=new Map(t.nodes().map(e=>[e,e.getAbsolutePosition()]));const e=t.getClientRect();g.current={x:e.x+e.width/2,y:e.y+e.height/2}}setTimeout(()=>{ensureDragOrder()})}),r.current.on("dragmove",b),r.current.on("dragend",M),r.current.on("transformend",M),r.current.on("transform",e=>{var t,n;e.evt.ctrlKey||e.evt.metaKey?null===(t=r.current)||void 0===t||t.rotationSnapTolerance(0):null===(n=r.current)||void 0===n||n.rotationSnapTolerance(5)}))},[])}export function useAnchorSnap(t,n,r){const{snapGuideStyle:i}=o(),d=e.useRef(i);d.current=i;const c=e=>e.hasName("element")||e.hasName("line-anchor")||e.hasName("page-background")||e.hasName("elements-area"),f=e=>{var o;const r=null===(o=e.target)||void 0===o?void 0:o.getLayer();if(!r){return}const i=r.children.find(e=>"line-guides"===e.name());null==i||i.destroyChildren();var f,u=function(e){var n;const o=null===(n=t.current)||void 0===n?void 0:n.getStage();var r=[],s=[];return o.find(c).forEach(t=>{if(!(e.indexOf(t)>=0)){var n=t.getClientRect({skipShadow:!0,skipStroke:!0});t.hasName("line-anchor")&&(n={x:t.absolutePosition().x,y:t.absolutePosition().y,width:0,height:0}),r.push({offset:n.x,node:t,snap:"start"},{offset:n.x+n.width,node:t,snap:"end"},{offset:n.x+n.width/2,node:t,snap:"center"}),s.push({offset:n.y,node:t,snap:"start"},{offset:n.y+n.height,node:t,snap:"end"},{offset:n.y+n.height/2,node:t,snap:"center"})}}),{vertical:r,horizontal:s}}([e.target,...n.map(e=>e.current)]),l=s(u,{vertical:[{guide:(f=e.target).absolutePosition().x,offset:0,snap:"center",nodes:[f]}],horizontal:[{guide:f.absolutePosition().y,offset:0,snap:"center",nodes:[f]}]});if(!l.length){return}!function(e){var n;a(null===(n=t.current)||void 0===n?void 0:n.getLayer(),d.current,e)}(l);const h=e.target.getAbsolutePosition(),g=Object.assign({},h);l.forEach(e=>{switch(e.snap){case"start":case"center":case"end":switch(e.orientation){case"V":g.x=e.lineGuide+e.offset;break;case"H":g.y=e.lineGuide+e.offset}}}),e.evt.ctrlKey||e.evt.metaKey||e.target.absolutePosition(g)},u=e=>{if(!e.target){return}const t=e.target.getLayer();if(!t){return}const n=t.children.find(e=>"line-guides"===e.name());null==n||n.destroyChildren(),t.batchDraw()};e.useEffect(()=>{t.current&&(t.current.on("dragmove",f),t.current.on("dragend",u))},r)}function d(e,t){return e.x*t.x+e.y*t.y}const c={"top-left":"bottom-right","top-center":"bottom-center","top-right":"bottom-left","middle-right":"middle-left","bottom-right":"top-left","bottom-center":"top-center","bottom-left":"top-right","middle-left":"middle-right"};
@@ -1 +1 @@
1
- import{jsx as e,jsxs as t,Fragment as r}from"react/jsx-runtime";import i from"react";import{observer as o}from"mobx-react-lite";import{isAlive as n}from"mobx-state-tree";import{nodeAutorun as a}from"../utils/mobx.js";import{Arc as d,Group as s,Image as l,Rect as c,Text as h,Transformer as u}from"react-konva";import{ROLES as g}from"../model/store.js";import m from"use-image";import p from"konva";import{Portal as f}from"react-konva-utils";import{useWorkspaceStyle as v}from"./workspace-style.js";import{incrementLoader as w,triggerLoadError as x}from"../utils/loader.js";import{polotnoError as y}from"@polotno/core/errors";import{getCropRect as M}from"@polotno/core/image";import*as E from"@polotno/core/svg";import{flags as b}from"../utils/flags.js";import{roundEnabledPx as L,activeAnchorOf as T,isCornerAnchor as C,scaledBoxStyleAttrs as S,roundedBoxStyleAttrs as R}from"../utils/px.js";import{useFilteredSource as k}from"./use-filtered-source.js";import{useEvent as I}from"../hooks/use-event.js";import{useFadeIn as H}from"./use-fadein.js";import{isTouchDevice as X}from"../utils/screen.js";import{createPlayGate as Y,playMedia as W}from"../utils/media.js";import{useMediabunnyVideo as j}from"./use-mediabunny-video.js";import{getElementTimeRange as P,getVideoRestMs as O}from"../utils/timeline.js";import{downScaleCanvas as _}from"./downscale.js";function A(){return document.createElement("canvas")}const V=new window.Image;V.src=E.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 z=new window.Image;z.src=E.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,o,n=0,a=!1)=>{var d,s;const l=Math.floor(Math.max(e.width*o,1)),c=Math.floor(Math.max(e.height*o,1)),h=Math.min(n*o,l/2,c/2),u=Math.max(e.width/r.width,e.height/r.height)*o,g=(null===(d=e.page)||void 0===d?void 0:d._exportingOrRendering)&&b.imageDownScalingEnabled&&u<1&&!a,m=t instanceof HTMLVideoElement?t.videoWidth:null==t?void 0:t.width,f=t instanceof HTMLVideoElement?t.videoHeight:null==t?void 0:t.height,v=0===r.x&&0===r.y&&r.width===m&&r.height===f,w=i.useMemo(()=>{if(t&&m&&f){return v&&0===h&&!g?void 0:A()}},[t,h,g,v,m,f]),x=()=>{if(!w||!t){return}w.width=l,w.height=c;const e=w.getContext("2d");if(!e){return}h&&(e.beginPath(),e.moveTo(h,0),e.lineTo(l-h,0),e.arc(l-h,h,h,3*Math.PI/2,0,!1),e.lineTo(l,c-h),e.arc(l-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());const i=g?_(t,u):t,o=g?{x:Math.floor(r.x*u),y:Math.floor(r.y*u),width:Math.floor(r.width*u),height:Math.floor(r.height*u)}:r;e.drawImage(i,o.x,o.y,o.width,o.height,0,0,w.width,w.height)};return i.useLayoutEffect(()=>{x()},[w,e.width,e.height,r.x,r.y,r.width,r.height,n,o,a,null===(s=e.page)||void 0===s?void 0:s._exportingOrRendering,g]),i.useEffect(()=>()=>{w&&"CANVAS"===w.nodeName&&p.Util.releaseCanvas(w)},[w]),[w||t,x]};const D=A(),U=o(({element:r})=>{const o=Math.min(30,r.width/4,r.height/4),n=i.useRef(null);i.useEffect(()=>{const e=n.current;if(!e){return}const t=new p.Animation(t=>{e.rotate(((null==t?void 0:t.timeDiff)||0)/2)},e.getLayer());return t.start(),()=>{t.stop()}});const{mediaLoadingStyle:a}=v();return t(s,{x:r.a.x,y:r.a.y,rotation:r.a.rotation,listening:!1,opacity:r.a.opacity,hideInExport:!r.showInExport,children:[e(c,{width:r.width,height:r.height,fill:a.fill}),e(d,{ref:n,x:r.width/2,y:r.height/2,fill:a.textFill,outerRadius:Math.abs(o),innerRadius:Math.max(1,o-5),angle:270})]})}),B=o(({element:r})=>{const{mediaErrorStyle:i}=v(),o=Math.max(10,Math.min(30,r.width/25));return t(s,{x:r.a.x,y:r.a.y,rotation:r.a.rotation,listening:!1,opacity:r.a.opacity,hideInExport:!r.showInExport,children:[e(c,{width:r.width,height:r.height,fill:i.fill}),e(h,{text:"Can not load the video...",fontSize:o,width:r.width,height:r.height,align:"center",fill:i.textFill,verticalAlign:"middle",padding:5})]})});let F=function(e,t,r){const o=i.useRef("loading"),n=i.useRef(void 0),[a,d]=i.useState(0),s=i.useRef(void 0),l=i.useRef(void 0),c=i.useRef(void 0);return s.current===e&&l.current===t&&c.current===r||(o.current="loading",n.current=void 0,s.current=e,l.current=t,c.current=r),i.useLayoutEffect(function(){if(e){var i=document.createElement("video");return i.addEventListener("canplay",a),i.addEventListener("error",s),t&&(i.crossOrigin=t),r&&(i.referrerPolicy=r),i.src=e,i.load(),function(){i.removeEventListener("canplay",a),i.removeEventListener("error",s)}}function a(){o.current="loaded",n.current=i,n.current.currentTime=0,d(Math.random()),n.current.removeEventListener("canplay",a)}function s(e){var t;const r=4===i.readyState,a=i.buffered&&i.buffered.length>0&&i.buffered.end(i.buffered.length-1)/i.duration*100>=100;if(r&&a){return}const s=e.message||(null===(t=i.error)||void 0===t?void 0:t.message)||"Unknown error",l=new Error("Video failed to load: "+s);console.error(l),o.current="failed",n.current=void 0,d(Math.random())}},[e,t,r]),[n.current,o.current]};export const setVideoLoaderHook=e=>{F=e};function N(e){return e.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA}export const useLoader=(e,t,r)=>{const o=i.useRef(void 0),n=()=>{var e;null===(e=o.current)||void 0===e||e.call(o),o.current=void 0};i.useEffect(()=>n,[]),i.useLayoutEffect(()=>{const i=t.slice(0,200),a=`video with id ${r} url: ${i}`;"loading"!==e||o.current||(o.current=w(a)),"loading"!==e&&n(),"failed"===e&&x(y("VIDEO_FAILED",a,{src:i,elementId:r,reason:"load"}))},[e])};export const VideoElement=o(({element:o,store:d})=>{var h,v,x;const[y,b]=i.useState(!1),_=i.useRef(null),Z=i.useRef(null),$=o.isSelected,[q,G]=i.useState(!1),[J,K]=F(o.src,"anonymous"),[Q,ee]=i.useState(!1),te=d.activePage===o.page,re=(null===(h=o.page)||void 0===h?void 0:h._exportingOrRendering)&&"loaded"===K,ie=j(o,d,re);useLoader(K,o.src,o.id),J&&(J.playsInline=!0);const oe=((e,t,r)=>{const o=i.useMemo(()=>{var i,o;const{flipX:n,flipY:a}=e,d="svg"===e.type||E.isSvgUrl(e.src),s=navigator.userAgent.toLowerCase().indexOf("firefox")>-1;if(!(n||a||s&&d)){return t}if(!t){return null}const l=t instanceof HTMLVideoElement?t.videoWidth:null==t?void 0:t.width,c=t instanceof HTMLVideoElement?t.videoHeight:null==t?void 0:t.height;if(!l||!c){return null}const h=A();let u=1;"svg"===e.type&&(u=Math.max(e.width/l*r,e.height/c*r)),h.width=Math.max(l*u,1),h.height=Math.max(c*u,1);let g=n?-h.width:0,m=a?-h.height:0;return null===(i=h.getContext("2d"))||void 0===i||i.scale(n?-1:1,a?-1:1),null===(o=h.getContext("2d"))||void 0===o||o.drawImage(t,g,m,h.width,h.height),h},[e.flipX,e.flipY,t,e.width,e.height,r]);return i.useEffect(()=>()=>{o&&"CANVAS"===o.nodeName&&p.Util.releaseCanvas(o)},[o]),o})(o,J,d._elementsPixelRatio),ne=re&&ie||oe||D,[ae=D,de]=k(o,ne);i.useEffect(()=>{J&&d.history.ignore(()=>{o.set({duration:1e3*J.duration})})},[J]);const se=i.useMemo(Y,[J]);i.useEffect(()=>{var e;if(!J){return}const t=d.animatedElementsIds,r=(!t.length||t.includes(o.id))&&d.isPlaying;if(!te||!r&&!q){return void J.pause()}q&&(J.muted=!1,J.currentTime=o.startTime*J.duration,W(J).then(e=>{"refused"===e&&G(!1)}));const i=new p.Animation(()=>{Ce()},null===(e=_.current)||void 0===e?void 0:e.getLayer());i.start();const n=()=>{G(!1),J.currentTime=o.startTime*J.duration},a=()=>{J.currentTime>=o.endTime*J.duration&&(J.pause(),J.currentTime=o.startTime*J.duration,G(!1))};return J.addEventListener("ended",n),J.addEventListener("timeupdate",a),()=>{J.pause(),i.stop(),J.removeEventListener("ended",n),J.removeEventListener("timeupdate",a)}},[J,q,d.isPlaying,te]),i.useEffect(()=>{J&&(J.volume=o.volume)},[J,o.volume]),i.useEffect(()=>{J&&(J.playbackRate=o.speed,J.preservesPitch=!1)},[J,o.speed]);const le=i.useRef(null);i.useEffect(()=>{const e=a(o,()=>{var e,t;if(J){if(re&&ie){return Ce(),void d.currentTime}const r=d.animatedElementsIds;if(r.length&&!r.includes(o.id)){return}const i=d.activePage===o.page,n=d.currentTime>=o.page.startTime&&d.currentTime<o.page.startTime+o.page.duration,a=o.startTime*J.duration*1e3,s=J.duration*(o.endTime-o.startTime)*1e3,{start:l,end:c}=P(o.animations,o.page.duration),h=(d.currentTime||o.page.startTime)-o.page.startTime,u=n?O(d.currentTime,o.page.startTime,l,s,a,o.speed):0,g=u/1e3,m=n&&h>=l&&h<c;q||(J.muted=!m,m&&d.isPlaying&&i?J.paused?(J.currentTime=g,se.play(J)):Math.abs(1e3*J.currentTime-u)>500&&(J.currentTime=g):(se.reset(),J.paused||J.pause(),g!==J.currentTime&&(J.currentTime=g),!N(J)&&!d.isPlaying&&!le.current&&(le.current=w(`video ${o.id}`)))),Ce(),null===(t=null===(e=_.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()}});return()=>{e(),le.current&&(le.current(),le.current=null)}},[d,J,re,ie,q]),i.useEffect(()=>{var e,t;if(!J){return}if(re){return null===(e=le.current)||void 0===e||e.call(le),void(le.current=null)}const r=()=>{var e,t,r;!N(J)&&(null===(e=o.page)||void 0===e?void 0:e._exportingOrRendering)||le.current&&(Ce(),null===(r=null===(t=_.current)||void 0===t?void 0:t.getLayer())||void 0===r||r.batchDraw(),le.current(),le.current=null)};let i;return(null===(t=o.page)||void 0===t?void 0:t._exportingOrRendering)&&(i=setInterval(r,20)),J.addEventListener("timeupdate",r),J.addEventListener("canplay",r),()=>{clearInterval(i),J.removeEventListener("timeupdate",r),J.removeEventListener("canplay",r)}},[null===(v=o.page)||void 0===v?void 0:v._exportingOrRendering,J,o.id,w,re]);let{cropX:ce,cropY:he,cropWidth:ue,cropHeight:ge}=o;"loaded"!==K&&(ce=he=0,ue=ge=1);const me=(pe=ae)instanceof HTMLVideoElement?pe.videoWidth:(null==pe?void 0:pe.width)||0;var pe;const fe=(e=>e instanceof HTMLVideoElement?e.videoHeight:(null==e?void 0:e.height)||0)(ae),ve=M({cropX:ce,cropY:he,cropWidth:ue,cropHeight:ge,width:o.width,height:o.height},{width:me,height:fe}),we=ve.width,xe=ve.height,ye="svg"===o.type,Me=null!==(x=o.cornerRadius)&&void 0!==x?x:0,[Ee,be]=useCornerRadiusAndCrop(o,ae,ve,d._elementsPixelRatio,Me,!0);let[Le,Te]=((e,t,r,o)=>{const n=(e=>{const[t,r]=i.useState(e);return i.useEffect(()=>{(async()=>{const i=await async function(e){if(!E.isSvgUrl(e)){return e}const t=await E.urlToString(e),r=E.fixSize(t);return E.svgToURL(r)}(e);i!==t&&r(i)})()},[e]),t})(e.clipSrc||""),[a,d]=m(n,"anonymous"),s=e.clipSrc?d:"loaded";useLoader(s,e.clipSrc,e.id);const l=i.useMemo(()=>{if(t&&a){return A()}},[t,a]);function c(){var i;if(!a){return}const o=t instanceof HTMLVideoElement?t.videoWidth:null==t?void 0:t.width,n=t instanceof HTMLVideoElement?t.videoHeight:null==t?void 0:t.height;if(!t||!o||!n){return}if(!a||!a.width||!a.height){return}if(!l){return}const d=A(),s=Math.max(e.width/a.width*r,e.height/a.height*r);d.width=a.width*s,d.height=a.height*s,null===(i=d.getContext("2d"))||void 0===i||i.drawImage(a,0,0,d.width,d.height),l.width=Math.max(o,1),l.height=Math.max(n,1);const c=l.getContext("2d");c&&(c.save(),c.drawImage(d,0,0,o,n),p.Util.releaseCanvas(d),c.globalCompositeOperation="source-in",c.drawImage(t,0,0,l.width,l.height),c.restore())}return i.useLayoutEffect(()=>{c()},[l,t,a,e.width,e.height,r,...o]),[e.clipSrc&&a?l:t,c]})(o,Ee,d._elementsPixelRatio,[ve,Me,d._elementsPixelRatio]);const Ce=I(()=>{var e,t;de(),be(),Te(),null===(t=null===(e=_.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()});i.useEffect(()=>{Ce()});const Se=Math.max(o.width/we,o.height/xe);i.useEffect(()=>{var e;if(!o._cropModeEnabled){return}const t=null===(e=_.current)||void 0===e?void 0:e.getStage();function r(e){o._cropModeEnabled&&e.target!==Z.current&&o.toggleCropMode(!1)}function i(e){o._cropModeEnabled&&e.target.parentNode!==(null==t?void 0:t.content)&&o.toggleCropMode(!1)}return document.body.addEventListener("click",i),null==t||t.on("click",r),null==t||t.on("tap",r),()=>{document.body.removeEventListener("click",i),document.body.removeEventListener("touchstart",i),null==t||t.off("click",r),null==t||t.off("click",r)}},[o._cropModeEnabled]);const Re=i.useRef(null),ke=i.useRef(null),Ie=i.useRef(null);i.useLayoutEffect(()=>{o._cropModeEnabled&&(ke.current.nodes([Re.current]),Ie.current.nodes([Z.current]))},[o._cropModeEnabled]);const He=e=>{Math.round(e.target.x())>0&&(e.target.x(0),e.target.scaleX(1)),Math.round(e.target.y())>0&&(e.target.y(0),e.target.scaleY(1));const t=e.target.width()*e.target.scaleX(),r=e.target.height()*e.target.scaleY(),i=Math.min(1,we/t),n=Math.min(1,xe/r),a=1-i,d=Math.min(a,Math.max(0,Math.round(-e.target.x())/t)),s=1-n,l=Math.min(s,Math.max(0,Math.round(-e.target.y())/r));e.target.setAttrs({x:-d*me,y:-l*fe,scaleX:1,scaleY:1}),o.set({cropX:d,cropY:l,cropWidth:i,cropHeight:n})},Xe=()=>{"svg"!==o.type&&o.contentEditable&&setTimeout(()=>{n(o)&&o.toggleCropMode(!0)})},Ye="loading"===K,We="failed"===K,je=!Ye&&!We,Pe=i.useRef({cropX:0,cropY:0,cropWidth:0,cropHeight:0}),Oe=i.useRef(!1),_e=je?o.a.opacity:0;H(_,_e);const Ae=o.selectable||d.role===g.ADMIN,Ve=X();return e(r,{children:t(s,{onMouseEnter:()=>ee(!0),onMouseLeave:()=>ee(!1),children:[Ye&&e(U,{element:o}),We&&e(B,{element:o}),e(l,{ref:_,name:"element",id:o.id,image:Le,x:o.a.x,y:o.a.y,width:o.a.width||1,height:o.a.height||1,rotation:o.a.rotation,opacity:_e,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity,customCrop:ve,listening:Ae,draggable:Ve?o.draggable&&$:o.draggable,preventDefault:!Ve||$,hideInExport:!o.showInExport,onDragMove:e=>{o.set({x:e.target.x(),y:e.target.y()})},onDragEnd:e=>{o.set({x:e.target.x(),y:e.target.y()})},onDblClick:Xe,onDblTap:Xe,onTransformStart:e=>{b(!0),Oe.current=C(T(e.target)),Pe.current={cropX:o.cropX,cropY:o.cropY,cropWidth:o.cropWidth,cropHeight:o.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 n=1-we/me,a=Math.min(n,Math.max(0,o.cropX)),d=1-xe/fe,s=Math.min(d,Math.max(0,o.cropY)),l=Oe.current,c=!l&&r<1&&Pe.current.cropHeight>xe/fe;let h=l?o.cropWidth:o.cropWidth*r;c&&(h=o.cropWidth);const u=!l&&i<1&&Pe.current.cropWidth>we/me;let g=l?o.cropHeight:o.cropHeight*i;u&&(g=o.cropHeight),ye&&(h=o.cropWidth,g=o.cropHeight);const m=l?Math.min(r,i):1;o.set(Object.assign({cropX:a,cropY:s,x:t.x(),y:t.y(),width:t.width()*r,height:t.height()*i,rotation:e.target.rotation(),cropWidth:Math.min(h,1-a),cropHeight:Math.min(g,1-s)},1!==m&&Object.assign(Object.assign({},S(o,m)),{borderSize:o.borderSize*m})))},onTransformEnd:e=>{const t=e.currentTarget;o.set(Object.assign(Object.assign({width:t.width(),height:t.height(),x:t.x(),y:t.y(),rotation:e.target.rotation(),cropWidth:we/me,cropHeight:xe/fe},R(o)),{borderSize:L(o.borderSize)})),b(!1)}}),e(c,{x:o.a.x,y:o.a.y,width:Math.max(o.a.width-o.borderSize,0),height:Math.max(o.a.height-o.borderSize,0),opacity:_e,offsetX:-o.borderSize/2,offsetY:-o.borderSize/2,stroke:o.borderColor,strokeWidth:o.borderSize,listening:!1,visible:!!o.borderSize,rotation:o.rotation,cornerRadius:Math.max(0,Me-o.borderSize),hideInExport:!o.showInExport}),!d.isPlaying&&e(l,{image:q?Q||Ve?z:void 0:V,x:o.a.x,y:o.a.y,offsetX:-o.a.width/2+15/d.scale,offsetY:-o.a.height/2+15/d.scale,rotation:o.a.rotation,width:30/d.scale,height:30/d.scale,hideInExport:!0,onClick:()=>G(!q),onTap:()=>G(!q)}),o._cropModeEnabled&&t(f,{selector:".page-abs-container",enabled:!0,children:[e(c,{x:-window.innerWidth/d.scale,y:-window.innerWidth/d.scale,width:window.innerWidth/d.scale*3,height:window.innerWidth/d.scale*3,fill:"rgba(0,0,0,0.3)"}),e(l,{listening:!1,image:Le,x:o.a.x,y:o.a.y,width:o.a.width,height:o.a.height,rotation:o.a.rotation,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur}),t(s,{x:o.a.x,y:o.a.y,rotation:o.a.rotation,scaleX:Se,scaleY:Se,children:[e(l,{image:ae,ref:Z,width:me,height:fe,opacity:.4,draggable:!0,x:-o.cropX*me,y:-o.cropY*fe,onDragMove:He,onTransform:He}),e(u,{ref:Ie,anchorSize:20,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],boundBoxFunc:(e,t)=>t.width<5||t.height<5?e:t,rotateEnabled:!1,borderEnabled:!1,anchorCornerRadius:10,anchorStrokeWidth:2,borderStrokeWidth:2}),e(c,{width:we,height:xe,ref:Re,listening:!1,onTransform:e=>{e.target.x()<-o.cropX*me-1e-9&&(e.target.x(-o.cropX*me),e.target.scaleX(1)),e.target.y()<-o.cropY*fe-1e-9&&(e.target.y(-o.cropY*fe),e.target.scaleY(1));const t=Math.min(1,Math.max(0,o.cropX+e.target.x()/me)),r=Math.min(1,Math.max(0,e.target.y()/fe+o.cropY)),i=e.target.width()*e.target.scaleX(),n=e.target.height()*e.target.scaleY(),a=Math.min(1-t,i/me),d=Math.min(1-r,n/fe),s=e.target.getAbsolutePosition(e.target.getParent().getParent());e.target.scale({x:1,y:1}),e.target.position({x:0,y:0}),o.set({x:s.x,y:s.y,cropX:t,cropY:r,cropWidth:a,cropHeight:d,width:Math.min(i*Se,me*(1-t)*Se),height:Math.min(n*Se,fe*(1-r)*Se)})}}),e(u,{ref:ke,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],boundBoxFunc:(e,t)=>t.width<5||t.height<5?e:t,keepRatio:!1,rotateEnabled:!1,anchorFill:"rgb(240, 240, 240)",anchorStrokeWidth:2,borderStrokeWidth:2,visible:o.resizable})]})]})]})})});
1
+ import{jsx as e,jsxs as t,Fragment as r}from"react/jsx-runtime";import i from"react";import{observer as o}from"mobx-react-lite";import{isAlive as n}from"mobx-state-tree";import{nodeAutorun as a}from"../utils/mobx.js";import{Arc as d,Group as s,Image as l,Rect as c,Text as h,Transformer as u}from"react-konva";import{ROLES as g}from"../model/store.js";import m from"use-image";import p from"konva";import{Portal as f}from"react-konva-utils";import{useWorkspaceStyle as v}from"./workspace-style.js";import{incrementLoader as w,triggerLoadError as x}from"../utils/loader.js";import{polotnoError as M}from"@polotno/core/errors";import{getCropRect as y}from"@polotno/core/image";import*as E from"@polotno/core/svg";import{flags as b}from"../utils/flags.js";import{roundEnabledPx as L,activeAnchorOf as T,roundedCropFraction as C,roundedGeometryPx as R,roundedPosition as S,isCornerAnchor as k,scaledBoxStyleAttrs as I,roundedBoxStyleAttrs as X}from"../utils/px.js";import{useFilteredSource as Y}from"./use-filtered-source.js";import{useEvent as H}from"../hooks/use-event.js";import{useFadeIn as W}from"./use-fadein.js";import{isTouchDevice as j}from"../utils/screen.js";import{createPlayGate as P,playMedia as O}from"../utils/media.js";import{useMediabunnyVideo as _}from"./use-mediabunny-video.js";import{getElementTimeRange as A,getVideoRestMs as V}from"../utils/timeline.js";import{resampleCanvas as D,RESAMPLE_SKIP_THRESHOLD as z}from"./downscale.js";import{useSizeFixer as U}from"./image-element.js";function B(){return document.createElement("canvas")}const F=new window.Image;F.src=E.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 N=new window.Image;N.src=E.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,o,n=0,a=!1)=>{var d,s;const l=Math.floor(Math.max(e.width*o,1)),c=Math.floor(Math.max(e.height*o,1)),h=Math.min(n*o,l/2,c/2),u=Math.max(e.width/r.width,e.height/r.height)*o,g=(null===(d=e.page)||void 0===d?void 0:d._exportingOrRendering)&&b.imageDownScalingEnabled&&u<z&&!a,m=t instanceof HTMLVideoElement?t.videoWidth:null==t?void 0:t.width,f=t instanceof HTMLVideoElement?t.videoHeight:null==t?void 0:t.height,v=0===r.x&&0===r.y&&r.width===m&&r.height===f,w=i.useMemo(()=>{if(t&&m&&f){return v&&0===h&&!g?void 0:B()}},[t,h,g,v,m,f]),x=()=>{if(!w||!t){return}w.width=l,w.height=c;const e=w.getContext("2d");if(e){if(h&&(e.beginPath(),e.moveTo(h,0),e.lineTo(l-h,0),e.arc(l-h,h,h,3*Math.PI/2,0,!1),e.lineTo(l,c-h),e.arc(l-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()),g){const i=D(t,r,w.width,w.height);return e.drawImage(i,0,0),void p.Util.releaseCanvas(i)}e.drawImage(t,r.x,r.y,r.width,r.height,0,0,w.width,w.height)}};return i.useLayoutEffect(()=>{x()},[w,e.width,e.height,r.x,r.y,r.width,r.height,n,o,a,null===(s=e.page)||void 0===s?void 0:s._exportingOrRendering,g]),i.useEffect(()=>()=>{w&&"CANVAS"===w.nodeName&&p.Util.releaseCanvas(w)},[w]),[w||t,x]};const Z=B(),$=o(({element:r})=>{const o=Math.min(30,r.width/4,r.height/4),n=i.useRef(null);i.useEffect(()=>{const e=n.current;if(!e){return}const t=new p.Animation(t=>{e.rotate(((null==t?void 0:t.timeDiff)||0)/2)},e.getLayer());return t.start(),()=>{t.stop()}});const{mediaLoadingStyle:a}=v();return t(s,{x:r.a.x,y:r.a.y,rotation:r.a.rotation,listening:!1,opacity:r.a.opacity,hideInExport:!r.showInExport,children:[e(c,{width:r.width,height:r.height,fill:a.fill}),e(d,{ref:n,x:r.width/2,y:r.height/2,fill:a.textFill,outerRadius:Math.abs(o),innerRadius:Math.max(1,o-5),angle:270})]})}),q=o(({element:r})=>{const{mediaErrorStyle:i}=v(),o=Math.max(10,Math.min(30,r.width/25));return t(s,{x:r.a.x,y:r.a.y,rotation:r.a.rotation,listening:!1,opacity:r.a.opacity,hideInExport:!r.showInExport,children:[e(c,{width:r.width,height:r.height,fill:i.fill}),e(h,{text:"Can not load the video...",fontSize:o,width:r.width,height:r.height,align:"center",fill:i.textFill,verticalAlign:"middle",padding:5})]})});let G=function(e,t,r){const o=i.useRef("loading"),n=i.useRef(void 0),[a,d]=i.useState(0),s=i.useRef(void 0),l=i.useRef(void 0),c=i.useRef(void 0);return s.current===e&&l.current===t&&c.current===r||(o.current="loading",n.current=void 0,s.current=e,l.current=t,c.current=r),i.useLayoutEffect(function(){if(e){var i=document.createElement("video");return i.addEventListener("canplay",a),i.addEventListener("error",s),t&&(i.crossOrigin=t),r&&(i.referrerPolicy=r),i.src=e,i.load(),function(){i.removeEventListener("canplay",a),i.removeEventListener("error",s)}}function a(){o.current="loaded",n.current=i,n.current.currentTime=0,d(Math.random()),n.current.removeEventListener("canplay",a)}function s(e){var t;const r=4===i.readyState,a=i.buffered&&i.buffered.length>0&&i.buffered.end(i.buffered.length-1)/i.duration*100>=100;if(r&&a){return}const s=e.message||(null===(t=i.error)||void 0===t?void 0:t.message)||"Unknown error",l=new Error("Video failed to load: "+s);console.error(l),o.current="failed",n.current=void 0,d(Math.random())}},[e,t,r]),[n.current,o.current]};export const setVideoLoaderHook=e=>{G=e};function J(e){return e.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA}export const useLoader=(e,t,r)=>{const o=i.useRef(void 0),n=()=>{var e;null===(e=o.current)||void 0===e||e.call(o),o.current=void 0};i.useEffect(()=>n,[]),i.useLayoutEffect(()=>{const i=t.slice(0,200),a=`video with id ${r} url: ${i}`;"loading"!==e||o.current||(o.current=w(a)),"loading"!==e&&n(),"failed"===e&&x(M("VIDEO_FAILED",a,{src:i,elementId:r,reason:"load"}))},[e])};export const VideoElement=o(({element:o,store:d})=>{var h,v,x;const[M,b]=i.useState(!1),D=i.useRef(null),z=i.useRef(null),K=o.isSelected,[Q,ee]=i.useState(!1),[te,re]=G(o.src,"anonymous"),[ie,oe]=i.useState(!1),ne=d.activePage===o.page,ae=(null===(h=o.page)||void 0===h?void 0:h._exportingOrRendering)&&"loaded"===re,de=_(o,d,ae);useLoader(re,o.src,o.id),te&&(te.playsInline=!0);const se=((e,t,r)=>{const o=i.useMemo(()=>{var i,o;const{flipX:n,flipY:a}=e,d="svg"===e.type||E.isSvgUrl(e.src),s=navigator.userAgent.toLowerCase().indexOf("firefox")>-1;if(!(n||a||s&&d)){return t}if(!t){return null}const l=t instanceof HTMLVideoElement?t.videoWidth:null==t?void 0:t.width,c=t instanceof HTMLVideoElement?t.videoHeight:null==t?void 0:t.height;if(!l||!c){return null}const h=B();let u=1;"svg"===e.type&&(u=Math.max(e.width/l*r,e.height/c*r)),h.width=Math.max(l*u,1),h.height=Math.max(c*u,1);let g=n?-h.width:0,m=a?-h.height:0;return null===(i=h.getContext("2d"))||void 0===i||i.scale(n?-1:1,a?-1:1),null===(o=h.getContext("2d"))||void 0===o||o.drawImage(t,g,m,h.width,h.height),h},[e.flipX,e.flipY,t,e.width,e.height,r]);return i.useEffect(()=>()=>{o&&"CANVAS"===o.nodeName&&p.Util.releaseCanvas(o)},[o]),o})(o,te,d._elementsPixelRatio),le=ae&&de||se||Z,[ce=Z,he]=Y(o,le);i.useEffect(()=>{te&&d.history.ignore(()=>{o.set({duration:1e3*te.duration})})},[te]);const ue=i.useMemo(P,[te]);i.useEffect(()=>{var e;if(!te){return}const t=d.animatedElementsIds,r=(!t.length||t.includes(o.id))&&d.isPlaying;if(!ne||!r&&!Q){return void te.pause()}Q&&(te.muted=!1,te.currentTime=o.startTime*te.duration,O(te).then(e=>{"refused"===e&&ee(!1)}));const i=new p.Animation(()=>{Ie()},null===(e=D.current)||void 0===e?void 0:e.getLayer());i.start();const n=()=>{ee(!1),te.currentTime=o.startTime*te.duration},a=()=>{te.currentTime>=o.endTime*te.duration&&(te.pause(),te.currentTime=o.startTime*te.duration,ee(!1))};return te.addEventListener("ended",n),te.addEventListener("timeupdate",a),()=>{te.pause(),i.stop(),te.removeEventListener("ended",n),te.removeEventListener("timeupdate",a)}},[te,Q,d.isPlaying,ne]),i.useEffect(()=>{te&&(te.volume=o.volume)},[te,o.volume]),i.useEffect(()=>{te&&(te.playbackRate=o.speed,te.preservesPitch=!1)},[te,o.speed]);const ge=i.useRef(null);i.useEffect(()=>{const e=a(o,()=>{var e,t;if(te){if(ae&&de){return Ie(),void d.currentTime}const r=d.animatedElementsIds;if(r.length&&!r.includes(o.id)){return}const i=d.activePage===o.page,n=d.currentTime>=o.page.startTime&&d.currentTime<o.page.startTime+o.page.duration,a=o.startTime*te.duration*1e3,s=te.duration*(o.endTime-o.startTime)*1e3,{start:l,end:c}=A(o.animations,o.page.duration),h=(d.currentTime||o.page.startTime)-o.page.startTime,u=n?V(d.currentTime,o.page.startTime,l,s,a,o.speed):0,g=u/1e3,m=n&&h>=l&&h<c;Q||(te.muted=!m,m&&d.isPlaying&&i?te.paused?(te.currentTime=g,ue.play(te)):Math.abs(1e3*te.currentTime-u)>500&&(te.currentTime=g):(ue.reset(),te.paused||te.pause(),g!==te.currentTime&&(te.currentTime=g),!J(te)&&!d.isPlaying&&!ge.current&&(ge.current=w(`video ${o.id}`)))),Ie(),null===(t=null===(e=D.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()}});return()=>{e(),ge.current&&(ge.current(),ge.current=null)}},[d,te,ae,de,Q]),i.useEffect(()=>{var e,t;if(!te){return}if(ae){return null===(e=ge.current)||void 0===e||e.call(ge),void(ge.current=null)}const r=()=>{var e,t,r;!J(te)&&(null===(e=o.page)||void 0===e?void 0:e._exportingOrRendering)||ge.current&&(Ie(),null===(r=null===(t=D.current)||void 0===t?void 0:t.getLayer())||void 0===r||r.batchDraw(),ge.current(),ge.current=null)};let i;return(null===(t=o.page)||void 0===t?void 0:t._exportingOrRendering)&&(i=setInterval(r,20)),te.addEventListener("timeupdate",r),te.addEventListener("canplay",r),()=>{clearInterval(i),te.removeEventListener("timeupdate",r),te.removeEventListener("canplay",r)}},[null===(v=o.page)||void 0===v?void 0:v._exportingOrRendering,te,o.id,w,ae]);let{cropX:me,cropY:pe,cropWidth:fe,cropHeight:ve}=o;"loaded"!==re&&(me=pe=0,fe=ve=1);const we=(xe=ce)instanceof HTMLVideoElement?xe.videoWidth:(null==xe?void 0:xe.width)||0;var xe;const Me=(e=>e instanceof HTMLVideoElement?e.videoHeight:(null==e?void 0:e.height)||0)(ce),ye=y({cropX:me,cropY:pe,cropWidth:fe,cropHeight:ve,width:o.width,height:o.height},{width:we,height:Me}),Ee=ye.width,be=ye.height,Le="svg"===o.type,Te=null!==(x=o.cornerRadius)&&void 0!==x?x:0,[Ce,Re]=useCornerRadiusAndCrop(o,ce,ye,d._elementsPixelRatio,Te,!0);let[Se,ke]=((e,t,r,o)=>{const n=U(e.clipSrc||""),[a,d]=m(n,"anonymous"),s=e.clipSrc?d:"loaded";useLoader(s,e.clipSrc,e.id);const l=i.useMemo(()=>{if(t&&a){return B()}},[t,a]);function c(){var i;if(!a){return}const o=t instanceof HTMLVideoElement?t.videoWidth:null==t?void 0:t.width,n=t instanceof HTMLVideoElement?t.videoHeight:null==t?void 0:t.height;if(!t||!o||!n){return}if(!a||!a.width||!a.height){return}if(!l){return}const d=B(),s=Math.max(e.width/a.width*r,e.height/a.height*r);d.width=a.width*s,d.height=a.height*s,null===(i=d.getContext("2d"))||void 0===i||i.drawImage(a,0,0,d.width,d.height),l.width=Math.max(o,1),l.height=Math.max(n,1);const c=l.getContext("2d");c&&(c.save(),c.drawImage(d,0,0,o,n),p.Util.releaseCanvas(d),c.globalCompositeOperation="source-in",c.drawImage(t,0,0,l.width,l.height),c.restore())}return i.useLayoutEffect(()=>{c()},[l,t,a,e.width,e.height,r,...o]),[e.clipSrc&&a?l:t,c]})(o,Ce,d._elementsPixelRatio,[ye,Te,d._elementsPixelRatio]);const Ie=H(()=>{var e,t;he(),Re(),ke(),null===(t=null===(e=D.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()});i.useEffect(()=>{Ie()});const Xe=Math.max(o.width/Ee,o.height/be);i.useEffect(()=>{var e;if(!o._cropModeEnabled){return}const t=null===(e=D.current)||void 0===e?void 0:e.getStage();function r(e){o._cropModeEnabled&&e.target!==z.current&&o.toggleCropMode(!1)}function i(e){o._cropModeEnabled&&e.target.parentNode!==(null==t?void 0:t.content)&&o.toggleCropMode(!1)}return document.body.addEventListener("click",i),null==t||t.on("click",r),null==t||t.on("tap",r),()=>{document.body.removeEventListener("click",i),document.body.removeEventListener("touchstart",i),null==t||t.off("click",r),null==t||t.off("click",r)}},[o._cropModeEnabled]);const Ye=i.useRef(null),He=i.useRef(null),We=i.useRef(null);i.useLayoutEffect(()=>{o._cropModeEnabled&&(He.current.nodes([Ye.current]),We.current.nodes([z.current]))},[o._cropModeEnabled]);const je=e=>{Math.round(e.target.x())>0&&(e.target.x(0),e.target.scaleX(1)),Math.round(e.target.y())>0&&(e.target.y(0),e.target.scaleY(1));const t=e.target.width()*e.target.scaleX(),r=e.target.height()*e.target.scaleY(),i=Math.min(1,Ee/t),n=Math.min(1,be/r),a=1-i,d=Math.min(a,Math.max(0,Math.round(-e.target.x())/t)),s=1-n,l=Math.min(s,Math.max(0,Math.round(-e.target.y())/r));e.target.setAttrs({x:-d*we,y:-l*Me,scaleX:1,scaleY:1}),o.set({cropX:d,cropY:l,cropWidth:i,cropHeight:n})},Pe=()=>{"svg"!==o.type&&o.contentEditable&&setTimeout(()=>{n(o)&&o.toggleCropMode(!0)})},Oe="loading"===re,_e="failed"===re,Ae=!Oe&&!_e,Ve=i.useRef({cropX:0,cropY:0,cropWidth:0,cropHeight:0}),De=i.useRef(!1),ze=Ae?o.a.opacity:0;W(D,ze);const Ue=o.selectable||d.role===g.ADMIN,Be=j();return e(r,{children:t(s,{onMouseEnter:()=>oe(!0),onMouseLeave:()=>oe(!1),children:[Oe&&e($,{element:o}),_e&&e(q,{element:o}),e(l,{ref:D,name:"element",id:o.id,image:Se,x:o.a.x,y:o.a.y,width:o.a.width||1,height:o.a.height||1,rotation:o.a.rotation,opacity:ze,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity,customCrop:ye,listening:Ue,draggable:Be?o.draggable&&K:o.draggable,preventDefault:!Be||K,hideInExport:!o.showInExport,onDragMove:e=>{o.set({x:e.target.x(),y:e.target.y()})},onDragEnd:e=>{o.set(S(e.target))},onDblClick:Pe,onDblTap:Pe,onTransformStart:e=>{b(!0),De.current=k(T(e.target)),Ve.current={cropX:o.cropX,cropY:o.cropY,cropWidth:o.cropWidth,cropHeight:o.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 n=1-Ee/we,a=Math.min(n,Math.max(0,o.cropX)),d=1-be/Me,s=Math.min(d,Math.max(0,o.cropY)),l=De.current,c=!l&&r<1&&Ve.current.cropHeight>be/Me;let h=l?o.cropWidth:o.cropWidth*r;c&&(h=o.cropWidth);const u=!l&&i<1&&Ve.current.cropWidth>Ee/we;let g=l?o.cropHeight:o.cropHeight*i;u&&(g=o.cropHeight),Le&&(h=o.cropWidth,g=o.cropHeight);const m=l?Math.min(r,i):1;o.set(Object.assign({cropX:a,cropY:s,x:t.x(),y:t.y(),width:t.width()*r,height:t.height()*i,rotation:e.target.rotation(),cropWidth:Math.min(h,1-a),cropHeight:Math.min(g,1-s)},1!==m&&Object.assign(Object.assign({},I(o,m)),{borderSize:o.borderSize*m})))},onTransformEnd:e=>{const t=e.currentTarget;o.set(Object.assign(Object.assign({width:R(t.width()),height:R(t.height()),x:R(t.x()),y:R(t.y()),rotation:R(e.target.rotation()),cropX:C(o.cropX),cropY:C(o.cropY),cropWidth:C(Ee/we),cropHeight:C(be/Me)},X(o)),{borderSize:L(o.borderSize)})),b(!1)}}),e(c,{x:o.a.x,y:o.a.y,width:Math.max(o.a.width-o.borderSize,0),height:Math.max(o.a.height-o.borderSize,0),opacity:ze,offsetX:-o.borderSize/2,offsetY:-o.borderSize/2,stroke:o.borderColor,strokeWidth:o.borderSize,listening:!1,visible:!!o.borderSize,rotation:o.rotation,cornerRadius:Math.max(0,Te-o.borderSize),hideInExport:!o.showInExport}),!d.isPlaying&&e(l,{image:Q?ie||Be?N:void 0:F,x:o.a.x,y:o.a.y,offsetX:-o.a.width/2+15/d.scale,offsetY:-o.a.height/2+15/d.scale,rotation:o.a.rotation,width:30/d.scale,height:30/d.scale,hideInExport:!0,onClick:()=>ee(!Q),onTap:()=>ee(!Q)}),o._cropModeEnabled&&t(f,{selector:".page-abs-container",enabled:!0,children:[e(c,{x:-window.innerWidth/d.scale,y:-window.innerWidth/d.scale,width:window.innerWidth/d.scale*3,height:window.innerWidth/d.scale*3,fill:"rgba(0,0,0,0.3)"}),e(l,{listening:!1,image:Se,x:o.a.x,y:o.a.y,width:o.a.width,height:o.a.height,rotation:o.a.rotation,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur}),t(s,{x:o.a.x,y:o.a.y,rotation:o.a.rotation,scaleX:Xe,scaleY:Xe,children:[e(l,{image:ce,ref:z,width:we,height:Me,opacity:.4,draggable:!0,x:-o.cropX*we,y:-o.cropY*Me,onDragMove:je,onTransform:je}),e(u,{ref:We,anchorSize:20,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],boundBoxFunc:(e,t)=>t.width<5||t.height<5?e:t,rotateEnabled:!1,borderEnabled:!1,anchorCornerRadius:10,anchorStrokeWidth:2,borderStrokeWidth:2}),e(c,{width:Ee,height:be,ref:Ye,listening:!1,onTransform:e=>{e.target.x()<-o.cropX*we-1e-9&&(e.target.x(-o.cropX*we),e.target.scaleX(1)),e.target.y()<-o.cropY*Me-1e-9&&(e.target.y(-o.cropY*Me),e.target.scaleY(1));const t=Math.min(1,Math.max(0,o.cropX+e.target.x()/we)),r=Math.min(1,Math.max(0,e.target.y()/Me+o.cropY)),i=e.target.width()*e.target.scaleX(),n=e.target.height()*e.target.scaleY(),a=Math.min(1-t,i/we),d=Math.min(1-r,n/Me),s=e.target.getAbsolutePosition(e.target.getParent().getParent());e.target.scale({x:1,y:1}),e.target.position({x:0,y:0}),o.set({x:s.x,y:s.y,cropX:t,cropY:r,cropWidth:a,cropHeight:d,width:Math.min(i*Xe,we*(1-t)*Xe),height:Math.min(n*Xe,Me*(1-r)*Xe)})}}),e(u,{ref:He,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],boundBoxFunc:(e,t)=>t.width<5||t.height<5?e:t,keepRatio:!1,rotateEnabled:!1,anchorFill:"rgb(240, 240, 240)",anchorStrokeWidth:2,borderStrokeWidth:2,visible:o.resizable})]})]})]})})});
package/model/store.js CHANGED
@@ -1 +1 @@
1
- var e=this&&this.__rest||function(e,t){var o={};for(var i in e){Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(o[i]=e[i])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++){t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(o[i[n]]=e[i[n]])}}return o};import{applySnapshot as t,cast as o,destroy as i,detach as n,getSnapshot as a,onSnapshot as s,setLivelinessChecking as r,types as l}from"mobx-state-tree";import{UndoManager as d}from"./history.js";import{nanoid as p}from"nanoid";import c from"konva";import{computed as g}from"mobx";import{ZERO_BLEED as m,migrateDesign as u,CURRENT_SCHEMA_VERSION as f}from"@polotno/schema";import{downloadFile as h}from"../utils/download.js";import{getJsPDF as v}from"../utils/pdf.js";import{createGIF as b}from"../utils/gif-lib.js";import{validateKey as y,setKey as P}from"../utils/validate-key.js";import*as w from"../utils/fonts.js";import{flags as x}from"../utils/flags.js";import{addDpiMetadataToImage as E}from"../utils/image-dpi.js";import{nodeToCanvas as I}from"../utils/canvas.js";import{whenLoaded as T}from"../utils/loader.js";import{polotnoError as _}from"@polotno/core/errors";import{pxToUnit as O}from"../utils/unit.js";import{deepEqual as S}from"../utils/deep-equal.js";import{waitTillAvailable as k}from"../utils/wait.js";import{jsonToHTML as j}from"@polotno/html-export";import{jsonToSVG as R}from"@polotno/svg-export";import{warnOnceDeprecated as F}from"../utils/deprecation.js";import{Page as A}from"./page-model.js";import{forEveryChild as V,forEveryNode as C}from"./group-model.js";import{Audio as L}from"./audio-model.js";r("ignore");export const Font=l.model("Font",{fontFamily:l.string,url:l.optional(l.string,""),styles:l.frozen()}).preProcessSnapshot(e=>Object.assign(Object.assign({},e),{fontFamily:e.fontFamily||e.name}));export const ROLES={ADMIN:"admin",VIEWER:"viewer"};export const Store=l.model("Store",{role:"",pages:l.array(A),fonts:l.array(Font),audios:l.array(L),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:l.optional(l.enumeration("UnitType",["pt","mm","cm","in","px"]),"px"),dpi:72,schemaVersion:f,bleedVisible:!1,rulesVisible:!1,distanceGuidesVisible:!1,timingPreview:l.optional(l.enumeration("TimingPreview",["all","playhead"]),"all"),openedSidePanel:"",previousOpenedSidePanel:"",custom:l.frozen(),tool:l.optional(l.enumeration("Tool",["selection","draw","pan","text","eraser"]),"selection"),toolOptions:l.optional(l.model({brushType:l.optional(l.enumeration("BrushType",["brush","highlighter"]),"brush"),strokeWidth:l.optional(l.number,5),stroke:l.optional(l.string,"#000000"),opacity:l.optional(l.number,1)}),{}),selectedElementsIds:l.array(l.string),animatedElementsIds:l.array(l.string),history:l.optional(d,{targetPath:"../pages"}),_elementsPixelRatio:Math.min(2,"undefined"!=typeof window&&window.devicePixelRatio||1),_activePageId:"",_selectedPagesIds:l.array(l.string),_forceShowCredit:!1,_validated:!1}).views(e=>{const t=g(()=>{const t={};return C({children:e.pages},e=>(t[e.id]=e,!1)),t},{keepAlive:!0});return{get _idsMap(){return t.get()}}}).views(e=>({get _bleedVisible(){return console.warn("store._bleedVisible is deprecated. Please use store.bleedVisible instead."),e.bleedVisible},get selectedElements(){return e.selectedElementsIds.map(t=>e._idsMap[t]).filter(e=>!!e)},get children(){return e.pages},get selectedShapes(){const e=[];return V({children:this.selectedElements},t=>{"group"!==t.type&&e.push(t)}),e},get activePage(){return e.pages.slice().find(t=>t.id===e._activePageId)||(e.pages.length?e.pages[0]:null)},get selectedPages(){return e._selectedPagesIds.map(t=>e.pages.find(e=>e.id===t))},get duration(){let t=0;return e.pages.forEach(e=>{t+=e.duration}),t},pageAtTime(t){for(const o of e.pages){if(t>=o.startTime&&t<o.startTime+o.duration){return o}}return e.pages.length&&t>=this.duration?e.pages[e.pages.length-1]:null},get effectiveTime(){if(e.isPlaying){return e.currentTime}const t=this.activePage;return t&&this.pageAtTime(e.currentTime)!==t?t.startTime:e.currentTime},get playheadAccurate(){return e.isPlaying||"playhead"===e.timingPreview},get isEditingPaused(){var t;return!e.isPlaying&&!(null===(t=this.activePage)||void 0===t?void 0:t._exportingOrRendering)},get _hasCroppedImages(){return this.find(e=>"image"===e.type&&e._cropModeEnabled)},find(t){let o;return C({children:e.pages},e=>{if(!o&&t(e)){return o=e,!0}}),o},getElementById:t=>e._idsMap[t]})).actions(r=>{let l=0,d=null,g=!1;const f={afterCreate(){r.history.canUndo},setCurrentTime(e){r.currentTime=e},_togglePlaying(e=!r.isPlaying){r.isPlaying=e},play({animatedElementsIds:e=[],startTime:t=0,currentTime:i=0,endTime:n=r.duration,repeat:a=!1}={}){i&&(console.warn("currentTime property of store.play() is deprecated. Please use startTime instead."),t=i),r.animatedElementsIds=o(e),r.currentTime=t,r.isPlaying=!0,l=Date.now(),d=n,g=a,requestAnimationFrame(()=>f.seek())},checkActivePage(){const e=r.pageAtTime(r.currentTime);e&&f.selectPage(e.id)},seek(){if(!r.isPlaying){return}const e=Date.now(),t=e-l;l=e,r.currentTime+=t;const o=d||r.duration;r.currentTime>=o&&!g&&(r.currentTime=o),f.checkActivePage(),r.isPlaying&&r.currentTime<o?requestAnimationFrame(()=>f.seek()):r.isPlaying&&g?(r.currentTime=0,requestAnimationFrame(()=>f.seek())):f.pause()},pause(){r.isPlaying=!1,r.animatedElementsIds=o([])},stop(){f.pause(),r.currentTime=0,f.checkActivePage()},__(){r._validated||(y(r._forceShowCredit),r._validated=!0)},set(e){Object.assign(r,e)},setUnit({unit:e,dpi:t}){r.unit=e||r.unit,r.dpi=t||r.dpi},setRole(e){r.role=e},setTool(e){r.tool=e},setToolOptions(e){Object.assign(r.toolOptions,e)},addPage(e){const t=A.create(Object.assign({id:p(10)},e));return r.pages.push(t),r._activePageId=t.id,r._selectedPagesIds=o([]),t},selectPage(e){r._activePageId=e,1===r._selectedPagesIds.length&&(r._selectedPagesIds=o([e]))},selectPages(e){r._selectedPagesIds=o(e),1===r._selectedPagesIds.length&&(r._activePageId=r._selectedPagesIds[0])},selectElements(e){const t=e.map(e=>r.getElementById(e)).filter(e=>!!e);t.sort((e,t)=>{var o,i,n,a;return(null!==(i=null===(o=e.parent)||void 0===o?void 0:o.children.indexOf(e))&&void 0!==i?i:0)-(null!==(a=null===(n=t.parent)||void 0===n?void 0:n.children.indexOf(t))&&void 0!==a?a:0)}),r.selectedElementsIds=o(t.map(e=>e.id))},toggleBleed(e){r.bleedVisible=null!=e?e:!r.bleedVisible},toggleRulers(e){r.rulesVisible=null!=e?e:!r.rulesVisible},setTimingPreview(e){r.timingPreview=e},toggleDistanceGuides(e){r.distanceGuidesVisible=null!=e?e:!r.distanceGuidesVisible},openSidePanel(e){r.openedSidePanel!==e&&(r.previousOpenedSidePanel=r.openedSidePanel,r.openedSidePanel=e)},restoreSidePanel(){const e=r.previousOpenedSidePanel;e&&e!==r.openedSidePanel?r.openedSidePanel=e:r.openedSidePanel="photos"},setScale(e){r.scale=e},_setScaleToFit(e){r.scaleToFit=e},setElementsPixelRatio(e){r._elementsPixelRatio=e},setSize(e,t,o){r.pages.forEach(i=>{i.setSize({width:e,height:t,useMagic:o,softChange:!0})}),r.width=e,r.height=t},setPageZIndex(e,t){const o=r.pages.find(t=>t.id===e);o&&(n(o),r.pages.remove(o),r.pages.splice(t,0,o))},deletePages(e){const t=r.pages.indexOf(r.activePage);e.forEach(e=>{const t=r.pages.find(t=>t.id===e);i(t)});const n=r._selectedPagesIds.filter(e=>r.pages.some(t=>t.id===e)),a=Math.min(r.pages.length-1,t),s=r.pages[a];s&&(r._activePageId=s.id),f.selectPages(n),r.selectedElementsIds=o(r.selectedElementsIds.filter(e=>r.getElementById(e)))},groupElements(e,t={}){const i=e.map(e=>r.getElementById(e)).filter(e=>!!e);if(!i.length){return}const a=i[0].parent;if(!a){return}if(!i.every(e=>e.parent===a)){return void console.warn("store.groupElements: refusing to group elements that do not share a parent. Pass ids whose elements all live under the same page or the same group.")}i.forEach(e=>n(e));const s=a.children.reduce((e,t)=>{var o;if("group"===t.type){const i=null===(o=t.name)||void 0===o?void 0:o.match(/group-(\d+)/);if(i){const t=parseInt(i[1],10);return Math.max(e,t)}}return e},0),l=Object.assign({id:p(10),name:`group-${s+1}`,children:i,type:"group"},t);return a.children.push(l),r.selectedElementsIds=o([l.id]),a.children.find(e=>e.id===l.id)},ungroupElements(e){const t=e.map(e=>r.getElementById(e)),i=[];t.forEach(e=>{if(e&&"group"===e.type){const t=e.parent;if(!t){return}const o=t.children.indexOf(e);e.children.forEach(e=>{i.push(e.id)}),e.children.slice().forEach(e=>{n(e),t.children.push(e)}),t.children.splice(o,1)}}),r.selectedElementsIds=o(i)},deleteElements(e){const t=[];r.find(o=>(e.includes(o.id)&&t.push(o),!1)),t.forEach(e=>{i(e)}),r.selectedElementsIds=o(r.selectedElementsIds.filter(e=>r.getElementById(e)))},on(e,t){if("change"===e){let e=f.toJSON();return s(r,o=>{const i=f.toJSON();!S(e,i)&&(e=i,t(i))})}},async _toCanvas({pixelRatio:e,ignoreBackground:t,pageId:o,mimeType:i,includeBleed:n,_skipTimeout:a,quickMode:s=!1,_exportCanvases:l}={}){var d;const p=e||1;o=o||(null===(d=r.pages[0])||void 0===d?void 0:d.id);const g=r.pages.find(e=>e.id===o);if(!g){throw _("EXPORT_FAILED",`No page for export with id ${o}`,{reason:"page-not-found",pageId:o,availablePageIds:r.pages.map(e=>e.id)})}const u=r._elementsPixelRatio;p>r._elementsPixelRatio&&f.setElementsPixelRatio(p),s?null==g||g.set({_forceMount:!0}):null==g||g.set({_exporting:!0});const h=await k(()=>{const e=c.stages.filter(e=>e.getAttr("pageId")===o);return 0===e.length?null:e});if(!h){throw null==g||g.set({_forceMount:!1,_exporting:!1}),f.setElementsPixelRatio(u),_("EXPORT_FAILED",`Export is failed. Can not find stage for page ${o}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`,{reason:"workspace-not-mounted",pageId:o})}h.length>1&&console.error(`Polotno error: Detected several canvas elements for page "${o}" in the document. This is not supported and will lead to incorrect export. Make sure to use unique ids for all pages and make sure you unmount <Workspace /> when it is not needed.`);const v=h[0];await f.waitLoading({_skipTimeout:a});const b=v.findOne(".page-container");if(!b){throw f.setElementsPixelRatio(u),null==g||g.set({_forceMount:!1,_exporting:!1}),_("EXPORT_FAILED","Export is failed. Canvas was unmounted.",{reason:"unmounted-during-export",pageId:o})}const y=v.position();v.position({x:0,y:0}),v.find("Transformer").forEach(e=>{e.setAttr("oldVisible",e.visible()),e.visible(!1)}),b.find(".page-background").forEach(e=>e.shadowEnabled(!1)),b.find(".page-background").forEach(e=>e.strokeEnabled(!1)),b.find(".highlighter").forEach(e=>e.visible(!1));const P=b.findOne(".page-background-group"),w=P.clip();P.clip({x:null,y:null,width:null,height:null});const x=b.findOne(".elements-container"),E=x.clip();x.clip({x:null,y:null,width:null,height:null});const T=b.find(e=>!e.visible()&&e.getAttr("editModeEnabled")&&!e.getAttr("hideInExport"));T.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.show()});const O=b.find(e=>e.getAttr("hideInExport"));O.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.hide()}),t&&b.find(".page-background").forEach(e=>e.hide());const S=n?g.computedBleed:m;let j=S.left,R=S.top;!r.bleedVisible&&n||(r.bleedVisible||n?r.bleedVisible&&n?(j=0,R=0):r.bleedVisible&&!n&&(j=-g.computedBleed.left,R=-g.computedBleed.top):(j=0,R=0));const F=g.computedWidth+S.left+S.right,A=g.computedHeight+S.top+S.bottom,V=b.scale();b.scale({x:1,y:1});const C=I(b,{x:b.x()-j,y:b.y()-R,width:F,height:A,pixelRatio:p,sceneCanvas:null==l?void 0:l.sceneCanvas,bufferCanvas:null==l?void 0:l.bufferCanvas});b.scale(V);const L=C._canvas;if("image/jpeg"===i){const e=L.getContext("2d");e.save(),e.globalCompositeOperation="destination-over",e.fillStyle="white",e.fillRect(0,0,L.width,L.height),e.restore()}return t&&b.find(".page-background").forEach(e=>e.show()),O.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),T.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),b.find(".page-background").forEach(e=>e.shadowEnabled(!0)),b.find(".page-background").forEach(e=>e.strokeEnabled(!0)),v.find("Transformer").forEach(e=>{e.visible(e.getAttr("oldVisible"))}),b.find(".highlighter").forEach(e=>e.visible(!0)),P.clip(w),x.clip(E),v.position(y),null==g||g.set({_exporting:!1,_forceMount:!1}),await Promise.resolve(),f.setElementsPixelRatio(u),L},async toDataURL(t={}){var{mimeType:o,quality:i,dpi:n,dpiMetadata:a="auto"}=t,s=e(t,["mimeType","quality","dpi","dpiMetadata"]);const l=await f._toCanvas(Object.assign({mimeType:o},s)),d=o||"image/png",p=l.toDataURL(d,i);c.Util.releaseCanvas(l);const g=null!=n?n:r.dpi;return"image/png"!==d&&"image/jpeg"!==d||"never"===a||"auto"===a&&72===g?p:E(p,d,g)},async toBlob(t={}){var{mimeType:o,quality:i}=t,n=e(t,["mimeType","quality"]);const a=await f._toCanvas(Object.assign({mimeType:o},n)),s=await new Promise(e=>{a.toBlob(e,o,i)});return c.Util.releaseCanvas(a),s},async saveAsImage(t={}){var{fileName:o}=t,i=e(t,["fileName"]);const n=(i.mimeType||"image/png").split("/")[1];h(await f.toDataURL(i),o||"polotno."+n)},async _toPDF(e){const t=e.dpi||r.dpi,o=e.parallel||1,i=e.unit||("px"===r.unit?"mm":r.unit),n=e.pixelRatio||1,a=e.pageIds||(e.pageId?[e.pageId]:r.pages.map(e=>e.id)),s=r.pages.filter(e=>a.includes(e.id)),l=await v(),d=e=>O({px:e,unit:i,dpi:t}),p=e.cropMarkSize||0,c=d(p),g=s[0]||{},u=e.includeBleed&&g.computedBleed||m,h=d(g.computedWidth+u.left+u.right+2*c),b=d(g.computedHeight+u.top+u.bottom+2*c);var y=new l({unit:i,orientation:h>b?"landscape":"portrait",format:[h,b],compress:!0,putOnlyUsedFonts:!0});y.deletePage(1);const P=((e,t)=>{const o=[];for(let i=0;i<e.length;i+=t){o.push(e.slice(i,i+t))}return o})(s,o);let w=0;for(const r of P){const t=r.map(async t=>{const o=e.includeBleed?t.computedBleed:m,i=t.computedWidth+o.left+o.right+2*p,s=t.computedHeight+o.top+o.bottom+2*p,r=d(i),l=d(s);let c=0,g=n;for(;c<10;){c+=1;const d=await f.toDataURL(Object.assign(Object.assign({},e),{pageId:t.id,pixelRatio:g,dpiMetadata:"never"}));if(d.length>20){return g!==n&&console.error(`Polotno can not export PDF with current settings. Quality is automatically reduced. pixelRatio was reduced to ${parseFloat(g.toFixed(3))}.`),e.onProgress&&e.onProgress(++w/a.length*.9),{url:d,width:r,height:l,widthPx:i,heightPx:s,cb:o}}g*=.8}});(await Promise.all(t)).filter(e=>void 0!==e).forEach(({url:e,width:t,height:o,widthPx:n,heightPx:a,cb:s})=>{y.addPage([t,o],t>o?"landscape":"portrait");const r=y.getCurrentPageInfo();var l;switch(i){case"pt":l=1;break;case"mm":l=72/25.4;break;case"cm":l=72/2.54;break;case"in":l=72;break;case"px":l=.75;break;default:throw _("EXPORT_FAILED","Invalid unit: "+i,{reason:"invalid-options",option:"unit",value:i})}if(r.pageContext.cropBox={bottomLeftX:0,bottomLeftY:0,topRightX:t*l,topRightY:o*l},r.pageContext.artBox={bottomLeftX:d(p+s.left)*l,bottomLeftY:d(p+s.bottom)*l,topRightX:d(n-p-s.right)*l,topRightY:d(a-p-s.top)*l},r.pageContext.bleedBox={bottomLeftX:d(p+s.left)*l,bottomLeftY:d(p+s.bottom)*l,topRightX:d(n-p-s.right)*l,topRightY:d(a-p-s.top)*l},c){y.setLineWidth(d(1));const e=c+d(s.left),i=c+d(s.right),n=c+d(s.top),a=c+d(s.bottom);y.line(e,0,e,c),y.line(0,n,c,n),y.line(t-i,0,t-i,c),y.line(t,n,t-c,n),y.line(0,o-a,c,o-a),y.line(e,o,e,o-c),y.line(t,o-a,t-c,o-a),y.line(t-i,o,t-i,o-c)}y.addImage(e,c,c,t-2*c,o-2*c,void 0,"FAST")})}return y},toPDFDataURL:async e=>(await f._toPDF(Object.assign({mimeType:"image/jpeg"},e))).output("datauristring"),async toGIFDataURL(e={}){const t=e.pixelRatio||1,o=e.pageIds||(e.pageId?[e.pageId]:r.pages.map(e=>e.id)),i=r.pages.filter(e=>o.includes(e.id));if(!i.length){throw _("EXPORT_FAILED","No pages found for GIF export",{reason:"page-not-found",pageId:e.pageId,availablePageIds:r.pages.map(e=>e.id)})}const n=i[0],a=await b({width:n.computedWidth*t,height:n.computedHeight*t}),s=1e3/(e.fps||10);for(const l of i){const e=Math.max(1,Math.floor(l.duration/s));for(let o=0;o<e;o++){const e=l.startTime+o*s||1;f.setCurrentTime(e);for(const t of r.pages){t.set({_rendering:t.id===l.id})}const i=await f._toCanvas({pixelRatio:t,pageId:l.id,_skipTimeout:!0});a.addFrame(i.getContext("2d"),{delay:s,copy:!0})}}for(const l of r.pages){l.set({_rendering:!1})}return f.stop(),a.render(),new Promise(e=>{a.on("finished",function(t){!function(e,t){var o=new FileReader;o.onload=function(e){t(e.target.result)},o.readAsDataURL(e)}(t,e)})})},async saveAsGIF(t={}){var{fileName:o}=t,i=e(t,["fileName"]);const n=await f.toGIFDataURL(i);h(n,o||"polotno.gif")},async toHTML({elementHook:e}={}){F("store.toHTML","store.toHTML()/saveAsHTML() are deprecated: install @polotno/html-export and call jsonToHTML(store.toJSON()) instead");const t=f.toJSON();return j(t,{elementHook:e,textOverflow:x.textOverflow,textSplitAllowed:x.textSplitAllowed})},async saveAsHTML({fileName:e,elementHook:t}={}){const o=await f.toHTML({elementHook:t}),i="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(o)));h(i,e||"polotno.html")},async toSVG({elementHook:e,pageId:t,fontEmbedding:o="inline"}={fontEmbedding:"inline"}){var i;F("store.toSVG","store.toSVG()/saveAsSVG() are deprecated: install @polotno/svg-export and call jsonToSVG(store.toJSON()) instead");const n=f.toJSON();t=t||(null===(i=n.pages[0])||void 0===i?void 0:i.id);const a=n.pages.find(e=>e.id===t);return R(Object.assign(Object.assign({},n),{pages:a?[a]:[]}),{elementHook:e,fontEmbedding:o})},async saveAsSVG({fileName:e,elementHook:t,pageId:o,fontEmbedding:i="inline"}={}){const n=await f.toSVG({elementHook:t,pageId:o,fontEmbedding:i}),a="data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(n)));h(a,e||"polotno.svg")},async saveAsPDF(t={}){var{fileName:o}=t,i=e(t,["fileName"]);(await f._toPDF(Object.assign({mimeType:"image/jpeg"},i))).save(o||"polotno.pdf")},async waitLoading({_skipTimeout:e=!1}={}){e||await new Promise(e=>setTimeout(e,50)),await T()},toJSON:()=>({width:r.width,height:r.height,fonts:a(r.fonts),pages:a(r.pages),audios:a(r.audios),unit:r.unit,dpi:r.dpi,custom:r.custom,schemaVersion:r.schemaVersion}),loadJSON(e,o=!1){var i,n;const s="boolean"==typeof o?o:null!==(i=null==o?void 0:o.keepHistory)&&void 0!==i&&i,l="boolean"==typeof o||null==o?void 0:o.modernizeTextBackground,d=u(e,{modernTextRenderer:x.htmlRenderEnabled||x.renderTagTextEnabled,modernizeTextBackground:l});delete d.schemaVersion;const p=r.activePage?r.pages.indexOf(r.activePage):0;let c=null===(n=d.pages[p]||d.pages[0])||void 0===n?void 0:n.id;d._activePageId=c,d._selectedPagesIds=[];const g=Object.assign({},a(r));Object.assign(g,d),g.history=s?a(r.history):{history:[],undoIdx:-1,targetPath:""},t(r,g)},clear({keepHistory:e=!1}={}){const t=r.pages.map(e=>e.id);f.deletePages(t),r.custom=null,e||r.history.clear()},addFont(e){f.removeFont(e.fontFamily),r.fonts.push(e)},removeFont(e){r.fonts.filter(t=>t.fontFamily===e).forEach(e=>i(e))},addAudio(e){const t=L.create(Object.assign({id:p(10)},e));r.audios.push(t)},removeAudio(e){const t=r.audios.find(t=>t.id===e);t&&r.audios.remove(t)},async loadFont(e,t,o,i){const n=r.fonts.find(t=>t.fontFamily===e)||w.globalFonts.find(t=>t.fontFamily===e);let a=[{fontStyle:"normal",fontWeight:"normal"},{fontStyle:"normal",fontWeight:"bold"}];return n?(n.styles&&(a=n.styles.map(e=>({fontStyle:e.fontStyle||"normal",fontWeight:e.fontWeight||"normal"}))),w.injectCustomFont(n)):w.injectGoogleFont(e),t&&o&&!a.some(e=>e.fontStyle===t&&e.fontWeight===o)&&a.push({fontStyle:t,fontWeight:o}),Promise.all(a.map(t=>w.loadFont(e,t.fontStyle,t.fontWeight,i)))},validate:e=>Store.validate(e,[{path:"",type:Store}]).map(e=>({path:"store"+e.context.map(e=>e.path).join("."),message:e.message}))};return f});export function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){return P(e),Store.create({_forceShowCredit:t})}export default createStore;
1
+ var e=this&&this.__rest||function(e,t){var i={};for(var o in e){Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(i[o]=e[o])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(e);n<o.length;n++){t.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(e,o[n])&&(i[o[n]]=e[o[n]])}}return i};import{applySnapshot as t,cast as i,destroy as o,detach as n,getSnapshot as a,onSnapshot as s,setLivelinessChecking as r,types as l}from"mobx-state-tree";import{UndoManager as d}from"./history.js";import{nanoid as p}from"nanoid";import c from"konva";import{computed as g}from"mobx";import{ZERO_BLEED as m,migrateDesign as u,CURRENT_SCHEMA_VERSION as f}from"@polotno/schema";import{downloadFile as h}from"../utils/download.js";import{getJsPDF as v}from"../utils/pdf.js";import{createGIF as b}from"../utils/gif-lib.js";import{validateKey as y,setKey as P}from"../utils/validate-key.js";import*as w from"../utils/fonts.js";import{flags as x}from"../utils/flags.js";import{addDpiMetadataToImage as E}from"../utils/image-dpi.js";import{nodeToCanvas as I,createExportCanvases as T,releaseExportCanvases as _}from"../utils/canvas.js";import{whenLoaded as S}from"../utils/loader.js";import{polotnoError as O}from"@polotno/core/errors";import{pxToUnit as k}from"../utils/unit.js";import{deepEqual as R}from"../utils/deep-equal.js";import{waitTillAvailable as j}from"../utils/wait.js";import{jsonToHTML as F}from"@polotno/html-export";import{jsonToSVG as A}from"@polotno/svg-export";import{warnOnceDeprecated as V}from"../utils/deprecation.js";import{Page as C}from"./page-model.js";import{forEveryChild as L,forEveryNode as M}from"./group-model.js";import{Audio as D}from"./audio-model.js";r("ignore");export const Font=l.model("Font",{fontFamily:l.string,url:l.optional(l.string,""),styles:l.frozen()}).preProcessSnapshot(e=>Object.assign(Object.assign({},e),{fontFamily:e.fontFamily||e.name}));export const ROLES={ADMIN:"admin",VIEWER:"viewer"};export const Store=l.model("Store",{role:"",pages:l.array(C),fonts:l.array(Font),audios:l.array(D),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:l.optional(l.enumeration("UnitType",["pt","mm","cm","in","px"]),"px"),dpi:72,schemaVersion:f,bleedVisible:!1,rulesVisible:!1,distanceGuidesVisible:!1,timingPreview:l.optional(l.enumeration("TimingPreview",["all","playhead"]),"all"),openedSidePanel:"",previousOpenedSidePanel:"",custom:l.frozen(),tool:l.optional(l.enumeration("Tool",["selection","draw","pan","text","eraser"]),"selection"),toolOptions:l.optional(l.model({brushType:l.optional(l.enumeration("BrushType",["brush","highlighter"]),"brush"),strokeWidth:l.optional(l.number,5),stroke:l.optional(l.string,"#000000"),opacity:l.optional(l.number,1)}),{}),selectedElementsIds:l.array(l.string),animatedElementsIds:l.array(l.string),history:l.optional(d,{targetPath:"../pages"}),_elementsPixelRatio:Math.min(2,"undefined"!=typeof window&&window.devicePixelRatio||1),_activePageId:"",_selectedPagesIds:l.array(l.string),_forceShowCredit:!1,_validated:!1}).views(e=>{const t=g(()=>{const t={};return M({children:e.pages},e=>(t[e.id]=e,!1)),t},{keepAlive:!0});return{get _idsMap(){return t.get()}}}).views(e=>({get _bleedVisible(){return console.warn("store._bleedVisible is deprecated. Please use store.bleedVisible instead."),e.bleedVisible},get selectedElements(){return e.selectedElementsIds.map(t=>e._idsMap[t]).filter(e=>!!e)},get children(){return e.pages},get selectedShapes(){const e=[];return L({children:this.selectedElements},t=>{"group"!==t.type&&e.push(t)}),e},get activePage(){return e.pages.slice().find(t=>t.id===e._activePageId)||(e.pages.length?e.pages[0]:null)},get selectedPages(){return e._selectedPagesIds.map(t=>e.pages.find(e=>e.id===t))},get duration(){let t=0;return e.pages.forEach(e=>{t+=e.duration}),t},pageAtTime(t){for(const i of e.pages){if(t>=i.startTime&&t<i.startTime+i.duration){return i}}return e.pages.length&&t>=this.duration?e.pages[e.pages.length-1]:null},get effectiveTime(){if(e.isPlaying){return e.currentTime}const t=this.activePage;return t&&this.pageAtTime(e.currentTime)!==t?t.startTime:e.currentTime},get playheadAccurate(){return e.isPlaying||"playhead"===e.timingPreview},get isEditingPaused(){var t;return!e.isPlaying&&!(null===(t=this.activePage)||void 0===t?void 0:t._exportingOrRendering)},get _hasCroppedImages(){return this.find(e=>"image"===e.type&&e._cropModeEnabled)},find(t){let i;return M({children:e.pages},e=>{if(!i&&t(e)){return i=e,!0}}),i},getElementById:t=>e._idsMap[t]})).actions(r=>{let l=0,d=null,g=!1;const f={afterCreate(){r.history.canUndo},setCurrentTime(e){r.currentTime=e},_togglePlaying(e=!r.isPlaying){r.isPlaying=e},play({animatedElementsIds:e=[],startTime:t=0,currentTime:o=0,endTime:n=r.duration,repeat:a=!1}={}){o&&(console.warn("currentTime property of store.play() is deprecated. Please use startTime instead."),t=o),r.animatedElementsIds=i(e),r.currentTime=t,r.isPlaying=!0,l=Date.now(),d=n,g=a,requestAnimationFrame(()=>f.seek())},checkActivePage(){const e=r.pageAtTime(r.currentTime);e&&f.selectPage(e.id)},seek(){if(!r.isPlaying){return}const e=Date.now(),t=e-l;l=e,r.currentTime+=t;const i=d||r.duration;r.currentTime>=i&&!g&&(r.currentTime=i),f.checkActivePage(),r.isPlaying&&r.currentTime<i?requestAnimationFrame(()=>f.seek()):r.isPlaying&&g?(r.currentTime=0,requestAnimationFrame(()=>f.seek())):f.pause()},pause(){r.isPlaying=!1,r.animatedElementsIds=i([])},stop(){f.pause(),r.currentTime=0,f.checkActivePage()},__(){r._validated||(y(r._forceShowCredit),r._validated=!0)},set(e){Object.assign(r,e)},setUnit({unit:e,dpi:t}){r.unit=e||r.unit,r.dpi=t||r.dpi},setRole(e){r.role=e},setTool(e){r.tool=e},setToolOptions(e){Object.assign(r.toolOptions,e)},addPage(e){const t=C.create(Object.assign({id:p(10)},e));return r.pages.push(t),r._activePageId=t.id,r._selectedPagesIds=i([]),t},selectPage(e){r._activePageId=e,1===r._selectedPagesIds.length&&(r._selectedPagesIds=i([e]))},selectPages(e){r._selectedPagesIds=i(e),1===r._selectedPagesIds.length&&(r._activePageId=r._selectedPagesIds[0])},selectElements(e){const t=e.map(e=>r.getElementById(e)).filter(e=>!!e);t.sort((e,t)=>{var i,o,n,a;return(null!==(o=null===(i=e.parent)||void 0===i?void 0:i.children.indexOf(e))&&void 0!==o?o:0)-(null!==(a=null===(n=t.parent)||void 0===n?void 0:n.children.indexOf(t))&&void 0!==a?a:0)}),r.selectedElementsIds=i(t.map(e=>e.id))},toggleBleed(e){r.bleedVisible=null!=e?e:!r.bleedVisible},toggleRulers(e){r.rulesVisible=null!=e?e:!r.rulesVisible},setTimingPreview(e){r.timingPreview=e},toggleDistanceGuides(e){r.distanceGuidesVisible=null!=e?e:!r.distanceGuidesVisible},openSidePanel(e){r.openedSidePanel!==e&&(r.previousOpenedSidePanel=r.openedSidePanel,r.openedSidePanel=e)},restoreSidePanel(){const e=r.previousOpenedSidePanel;e&&e!==r.openedSidePanel?r.openedSidePanel=e:r.openedSidePanel="photos"},setScale(e){r.scale=e},_setScaleToFit(e){r.scaleToFit=e},setElementsPixelRatio(e){r._elementsPixelRatio=e},setSize(e,t,i){r.pages.forEach(o=>{o.setSize({width:e,height:t,useMagic:i,softChange:!0})}),r.width=e,r.height=t},setPageZIndex(e,t){const i=r.pages.find(t=>t.id===e);i&&(n(i),r.pages.remove(i),r.pages.splice(t,0,i))},deletePages(e){const t=r.pages.indexOf(r.activePage);e.forEach(e=>{const t=r.pages.find(t=>t.id===e);o(t)});const n=r._selectedPagesIds.filter(e=>r.pages.some(t=>t.id===e)),a=Math.min(r.pages.length-1,t),s=r.pages[a];s&&(r._activePageId=s.id),f.selectPages(n),r.selectedElementsIds=i(r.selectedElementsIds.filter(e=>r.getElementById(e)))},groupElements(e,t={}){const o=e.map(e=>r.getElementById(e)).filter(e=>!!e);if(!o.length){return}const a=o[0].parent;if(!a){return}if(!o.every(e=>e.parent===a)){return void console.warn("store.groupElements: refusing to group elements that do not share a parent. Pass ids whose elements all live under the same page or the same group.")}o.forEach(e=>n(e));const s=a.children.reduce((e,t)=>{var i;if("group"===t.type){const o=null===(i=t.name)||void 0===i?void 0:i.match(/group-(\d+)/);if(o){const t=parseInt(o[1],10);return Math.max(e,t)}}return e},0),l=Object.assign({id:p(10),name:`group-${s+1}`,children:o,type:"group"},t);return a.children.push(l),r.selectedElementsIds=i([l.id]),a.children.find(e=>e.id===l.id)},ungroupElements(e){const t=e.map(e=>r.getElementById(e)),o=[];t.forEach(e=>{if(e&&"group"===e.type){const t=e.parent;if(!t){return}const i=t.children.indexOf(e);e.children.forEach(e=>{o.push(e.id)}),e.children.slice().forEach(e=>{n(e),t.children.push(e)}),t.children.splice(i,1)}}),r.selectedElementsIds=i(o)},deleteElements(e){const t=[];r.find(i=>(e.includes(i.id)&&t.push(i),!1)),t.forEach(e=>{o(e)}),r.selectedElementsIds=i(r.selectedElementsIds.filter(e=>r.getElementById(e)))},on(e,t){if("change"===e){let e=f.toJSON();return s(r,i=>{const o=f.toJSON();!R(e,o)&&(e=o,t(o))})}},async _toCanvas({pixelRatio:e,ignoreBackground:t,pageId:i,mimeType:o,includeBleed:n,_skipTimeout:a,quickMode:s=!1,_exportCanvases:l}={}){var d;const p=e||1;i=i||(null===(d=r.pages[0])||void 0===d?void 0:d.id);const g=r.pages.find(e=>e.id===i);if(!g){throw O("EXPORT_FAILED",`No page for export with id ${i}`,{reason:"page-not-found",pageId:i,availablePageIds:r.pages.map(e=>e.id)})}const u=r._elementsPixelRatio;try{(s?p>r._elementsPixelRatio:p!==r._elementsPixelRatio)&&f.setElementsPixelRatio(p),s?null==g||g.set({_forceMount:!0}):null==g||g.set({_exporting:!0});const e=await j(()=>{const e=c.stages.filter(e=>e.getAttr("pageId")===i);return 0===e.length?null:e});if(!e){throw O("EXPORT_FAILED",`Export is failed. Can not find stage for page ${i}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`,{reason:"workspace-not-mounted",pageId:i})}e.length>1&&console.error(`Polotno error: Detected several canvas elements for page "${i}" in the document. This is not supported and will lead to incorrect export. Make sure to use unique ids for all pages and make sure you unmount <Workspace /> when it is not needed.`);const d=e[0];await f.waitLoading({_skipTimeout:a});const u=d.findOne(".page-container");if(!u){throw O("EXPORT_FAILED","Export is failed. Canvas was unmounted.",{reason:"unmounted-during-export",pageId:i})}const h=d.position();d.position({x:0,y:0}),d.find("Transformer").forEach(e=>{e.setAttr("oldVisible",e.visible()),e.visible(!1)}),u.find(".page-background").forEach(e=>e.shadowEnabled(!1)),u.find(".page-background").forEach(e=>e.strokeEnabled(!1)),u.find(".highlighter").forEach(e=>e.visible(!1));const v=u.findOne(".page-background-group"),b=v.clip();v.clip({x:null,y:null,width:null,height:null});const y=u.findOne(".elements-container"),P=y.clip();y.clip({x:null,y:null,width:null,height:null});const w=u.find(e=>!e.visible()&&e.getAttr("editModeEnabled")&&!e.getAttr("hideInExport"));w.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.show()});const E=u.find(e=>e.getAttr("hideInExport"));E.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.hide()}),t&&u.find(".page-background").forEach(e=>e.hide());const T=n?g.computedBleed:m;let _=T.left,S=T.top;!r.bleedVisible&&n||(r.bleedVisible||n?r.bleedVisible&&n?(_=0,S=0):r.bleedVisible&&!n&&(_=-g.computedBleed.left,S=-g.computedBleed.top):(_=0,S=0));const k=g.computedWidth+T.left+T.right,R=g.computedHeight+T.top+T.bottom,F=u.scale();u.scale({x:1,y:1});const A=I(u,{x:u.x()-_,y:u.y()-S,width:k,height:R,pixelRatio:p,imageSmoothingQuality:x.imageDownScalingEnabled&&!s?"high":void 0,sceneCanvas:null==l?void 0:l.sceneCanvas,bufferCanvas:null==l?void 0:l.bufferCanvas});u.scale(F);const V=A._canvas;if("image/jpeg"===o){const e=V.getContext("2d");e.save(),e.globalCompositeOperation="destination-over",e.fillStyle="white",e.fillRect(0,0,V.width,V.height),e.restore()}return t&&u.find(".page-background").forEach(e=>e.show()),E.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),w.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),u.find(".page-background").forEach(e=>e.shadowEnabled(!0)),u.find(".page-background").forEach(e=>e.strokeEnabled(!0)),d.find("Transformer").forEach(e=>{e.visible(e.getAttr("oldVisible"))}),u.find(".highlighter").forEach(e=>e.visible(!0)),v.clip(b),y.clip(P),d.position(h),null==g||g.set({_exporting:!1,_forceMount:!1}),await Promise.resolve(),V}finally{f.setElementsPixelRatio(u),null==g||g.set({_forceMount:!1,_exporting:!1})}},async toDataURL(t={}){var{mimeType:i,quality:o,dpi:n,dpiMetadata:a="auto"}=t,s=e(t,["mimeType","quality","dpi","dpiMetadata"]);const l=await f._toCanvas(Object.assign({mimeType:i},s)),d=i||"image/png",p=l.toDataURL(d,o);c.Util.releaseCanvas(l);const g=null!=n?n:r.dpi;return"image/png"!==d&&"image/jpeg"!==d||"never"===a||"auto"===a&&72===g?p:E(p,d,g)},async toBlob(t={}){var{mimeType:i,quality:o}=t,n=e(t,["mimeType","quality"]);const a=await f._toCanvas(Object.assign({mimeType:i},n)),s=await new Promise(e=>{a.toBlob(e,i,o)});return c.Util.releaseCanvas(a),s},async saveAsImage(t={}){var{fileName:i}=t,o=e(t,["fileName"]);const n=(o.mimeType||"image/png").split("/")[1];h(await f.toDataURL(o),i||"polotno."+n)},async _toPDF(e){const t=e.dpi||r.dpi,i=e.parallel||1,o=e.unit||("px"===r.unit?"mm":r.unit),n=e.pixelRatio||1,a=e.pageIds||(e.pageId?[e.pageId]:r.pages.map(e=>e.id)),s=r.pages.filter(e=>a.includes(e.id)),l=await v(),d=e=>k({px:e,unit:o,dpi:t}),p=e.cropMarkSize||0,c=d(p),g=s[0]||{},u=e.includeBleed&&g.computedBleed||m,h=d(g.computedWidth+u.left+u.right+2*c),b=d(g.computedHeight+u.top+u.bottom+2*c);var y=new l({unit:o,orientation:h>b?"landscape":"portrait",format:[h,b],compress:!0,putOnlyUsedFonts:!0});y.deletePage(1);const P=((e,t)=>{const i=[];for(let o=0;o<e.length;o+=t){i.push(e.slice(o,o+t))}return i})(s,i);let w=0;for(const r of P){const t=r.map(async t=>{const i=e.includeBleed?t.computedBleed:m,o=t.computedWidth+i.left+i.right+2*p,s=t.computedHeight+i.top+i.bottom+2*p,r=d(o),l=d(s);let c=0,g=n;for(;c<10;){c+=1;const d=await f.toDataURL(Object.assign(Object.assign({},e),{pageId:t.id,pixelRatio:g,dpiMetadata:"never"}));if(d.length>20){return g!==n&&console.error(`Polotno can not export PDF with current settings. Quality is automatically reduced. pixelRatio was reduced to ${parseFloat(g.toFixed(3))}.`),e.onProgress&&e.onProgress(++w/a.length*.9),{url:d,width:r,height:l,widthPx:o,heightPx:s,cb:i}}g*=.8}});(await Promise.all(t)).filter(e=>void 0!==e).forEach(({url:e,width:t,height:i,widthPx:n,heightPx:a,cb:s})=>{y.addPage([t,i],t>i?"landscape":"portrait");const r=y.getCurrentPageInfo();var l;switch(o){case"pt":l=1;break;case"mm":l=72/25.4;break;case"cm":l=72/2.54;break;case"in":l=72;break;case"px":l=.75;break;default:throw O("EXPORT_FAILED","Invalid unit: "+o,{reason:"invalid-options",option:"unit",value:o})}if(r.pageContext.cropBox={bottomLeftX:0,bottomLeftY:0,topRightX:t*l,topRightY:i*l},r.pageContext.artBox={bottomLeftX:d(p+s.left)*l,bottomLeftY:d(p+s.bottom)*l,topRightX:d(n-p-s.right)*l,topRightY:d(a-p-s.top)*l},r.pageContext.bleedBox={bottomLeftX:d(p+s.left)*l,bottomLeftY:d(p+s.bottom)*l,topRightX:d(n-p-s.right)*l,topRightY:d(a-p-s.top)*l},c){y.setLineWidth(d(1));const e=c+d(s.left),o=c+d(s.right),n=c+d(s.top),a=c+d(s.bottom);y.line(e,0,e,c),y.line(0,n,c,n),y.line(t-o,0,t-o,c),y.line(t,n,t-c,n),y.line(0,i-a,c,i-a),y.line(e,i,e,i-c),y.line(t,i-a,t-c,i-a),y.line(t-o,i,t-o,i-c)}y.addImage(e,c,c,t-2*c,i-2*c,void 0,"FAST")})}return y},toPDFDataURL:async e=>(await f._toPDF(Object.assign({mimeType:"image/jpeg"},e))).output("datauristring"),async toGIFDataURL(e={}){const t=e.pixelRatio||1,i=e.pageIds||(e.pageId?[e.pageId]:r.pages.map(e=>e.id)),o=r.pages.filter(e=>i.includes(e.id));if(!o.length){throw O("EXPORT_FAILED","No pages found for GIF export",{reason:"page-not-found",pageId:e.pageId,availablePageIds:r.pages.map(e=>e.id)})}const n=o[0],a=await b({width:n.computedWidth*t,height:n.computedHeight*t}),s=1e3/(e.fps||10),l=T(),d=r._elementsPixelRatio;f.setElementsPixelRatio(t);try{for(const e of o){const i=Math.max(1,Math.floor(e.duration/s));for(let o=0;o<i;o++){const i=e.startTime+o*s||1;f.setCurrentTime(i);for(const t of r.pages){t.set({_rendering:t.id===e.id})}const n=await f._toCanvas({pixelRatio:t,pageId:e.id,_skipTimeout:!0,_exportCanvases:l});a.addFrame(n.getContext("2d"),{delay:s,copy:!0})}}}finally{_(l),f.setElementsPixelRatio(d)}for(const p of r.pages){p.set({_rendering:!1})}return f.stop(),a.render(),new Promise(e=>{a.on("finished",function(t){!function(e,t){var i=new FileReader;i.onload=function(e){t(e.target.result)},i.readAsDataURL(e)}(t,e)})})},async saveAsGIF(t={}){var{fileName:i}=t,o=e(t,["fileName"]);const n=await f.toGIFDataURL(o);h(n,i||"polotno.gif")},async toHTML({elementHook:e}={}){V("store.toHTML","store.toHTML()/saveAsHTML() are deprecated: install @polotno/html-export and call jsonToHTML(store.toJSON()) instead");const t=f.toJSON();return F(t,{elementHook:e,textOverflow:x.textOverflow,textSplitAllowed:x.textSplitAllowed})},async saveAsHTML({fileName:e,elementHook:t}={}){const i=await f.toHTML({elementHook:t}),o="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(i)));h(o,e||"polotno.html")},async toSVG({elementHook:e,pageId:t,fontEmbedding:i="inline"}={fontEmbedding:"inline"}){var o;V("store.toSVG","store.toSVG()/saveAsSVG() are deprecated: install @polotno/svg-export and call jsonToSVG(store.toJSON()) instead");const n=f.toJSON();t=t||(null===(o=n.pages[0])||void 0===o?void 0:o.id);const a=n.pages.find(e=>e.id===t);return A(Object.assign(Object.assign({},n),{pages:a?[a]:[]}),{elementHook:e,fontEmbedding:i})},async saveAsSVG({fileName:e,elementHook:t,pageId:i,fontEmbedding:o="inline"}={}){const n=await f.toSVG({elementHook:t,pageId:i,fontEmbedding:o}),a="data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(n)));h(a,e||"polotno.svg")},async saveAsPDF(t={}){var{fileName:i}=t,o=e(t,["fileName"]);(await f._toPDF(Object.assign({mimeType:"image/jpeg"},o))).save(i||"polotno.pdf")},async waitLoading({_skipTimeout:e=!1}={}){e||await new Promise(e=>setTimeout(e,50)),await S()},toJSON:()=>({width:r.width,height:r.height,fonts:a(r.fonts),pages:a(r.pages),audios:a(r.audios),unit:r.unit,dpi:r.dpi,custom:r.custom,schemaVersion:r.schemaVersion}),loadJSON(e,i=!1){var o,n;const s="boolean"==typeof i?i:null!==(o=null==i?void 0:i.keepHistory)&&void 0!==o&&o,l="boolean"==typeof i||null==i?void 0:i.modernizeTextBackground,d=u(e,{modernTextRenderer:x.htmlRenderEnabled||x.renderTagTextEnabled,modernizeTextBackground:l});delete d.schemaVersion;const p=r.activePage?r.pages.indexOf(r.activePage):0;let c=null===(n=d.pages[p]||d.pages[0])||void 0===n?void 0:n.id;d._activePageId=c,d._selectedPagesIds=[];const g=Object.assign({},a(r));Object.assign(g,d),g.history=s?a(r.history):{history:[],undoIdx:-1,targetPath:""},t(r,g)},clear({keepHistory:e=!1}={}){const t=r.pages.map(e=>e.id);f.deletePages(t),r.custom=null,e||r.history.clear()},addFont(e){f.removeFont(e.fontFamily),r.fonts.push(e)},removeFont(e){r.fonts.filter(t=>t.fontFamily===e).forEach(e=>o(e))},addAudio(e){const t=D.create(Object.assign({id:p(10)},e));r.audios.push(t)},removeAudio(e){const t=r.audios.find(t=>t.id===e);t&&r.audios.remove(t)},async loadFont(e,t,i,o){const n=r.fonts.find(t=>t.fontFamily===e)||w.globalFonts.find(t=>t.fontFamily===e);let a=[{fontStyle:"normal",fontWeight:"normal"},{fontStyle:"normal",fontWeight:"bold"}];return n?(n.styles&&(a=n.styles.map(e=>({fontStyle:e.fontStyle||"normal",fontWeight:e.fontWeight||"normal"}))),w.injectCustomFont(n)):w.injectGoogleFont(e),t&&i&&!a.some(e=>e.fontStyle===t&&e.fontWeight===i)&&a.push({fontStyle:t,fontWeight:i}),Promise.all(a.map(t=>w.loadFont(e,t.fontStyle,t.fontWeight,o)))},validate:e=>Store.validate(e,[{path:"",type:Store}]).map(e=>({path:"store"+e.context.map(e=>e.path).join("."),message:e.message}))};return f});export function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){return P(e),Store.create({_forceShowCredit:t})}export default createStore;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "polotno",
3
- "version": "3.10.0",
3
+ "version": "3.11.0",
4
4
  "description": "Design Editor Framework",
5
5
  "author": "Anton Lavrenov",
6
6
  "keywords": [
@@ -96,14 +96,14 @@
96
96
  },
97
97
  "dependencies": {
98
98
  "@base-ui/react": "^1.7.0",
99
- "@polotno/core": "0.8.0",
100
- "@polotno/html-export": "0.4.1",
99
+ "@polotno/core": "0.9.0",
100
+ "@polotno/html-export": "0.5.0",
101
101
  "@polotno/schema": "0.6.1",
102
- "@polotno/svg-export": "0.5.0",
102
+ "@polotno/svg-export": "0.6.0",
103
103
  "class-variance-authority": "^0.7.1",
104
104
  "clsx": "^2.1.1",
105
105
  "gifuct-js": "^2.1.2",
106
- "konva": "^10.3.1",
106
+ "konva": "^10.3.2",
107
107
  "lodash-es": "^4.18.1",
108
108
  "lucide-react": "^1.29.0",
109
109
  "mediabunny": "^1.52.3",
@@ -116,7 +116,7 @@
116
116
  "react-konva-utils": "^2.0.0",
117
117
  "react-sortablejs": "6.1.4",
118
118
  "react-window": "^2.3.0",
119
- "render-tag": "^0.1.34",
119
+ "render-tag": "^0.1.35",
120
120
  "sortablejs": "^1.15.7",
121
121
  "svg-round-corners": "^0.4.3",
122
122
  "swr": "^2.5.0",