polotno 4.0.3 → 4.1.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.
@@ -82,6 +82,7 @@ export declare const selectVideo: ({ src, droppedPos, targetElement, store, attr
82
82
  startTime: import("mobx-state-tree").IType<number | undefined, number, number>;
83
83
  endTime: import("mobx-state-tree").IType<number | undefined, number, number>;
84
84
  volume: import("mobx-state-tree").IType<number | undefined, number, number>;
85
+ speed: import("mobx-state-tree").IType<number | undefined, number, number>;
85
86
  }> & {
86
87
  readonly page: any;
87
88
  readonly store: any;
@@ -242,6 +243,7 @@ export declare const selectVideo: ({ src, droppedPos, targetElement, store, attr
242
243
  startTime: import("mobx-state-tree").IType<number | undefined, number, number>;
243
244
  endTime: import("mobx-state-tree").IType<number | undefined, number, number>;
244
245
  volume: import("mobx-state-tree").IType<number | undefined, number, number>;
246
+ speed: import("mobx-state-tree").IType<number | undefined, number, number>;
245
247
  }, {
246
248
  readonly page: any;
247
249
  readonly store: any;
package/canvas/audio.js CHANGED
@@ -1 +1 @@
1
- import e from"react";import{observer as t}from"mobx-react-lite";import{autorun as n}from"mobx";export const AudioElement=t(({audio:t,store:r})=>{const[i,o]=function(t){const[n,r]=e.useState(null),[i,o]=e.useState("loading");return e.useEffect(()=>{const e=new Audio(t),n=()=>{o("loaded"),r(e)},i=()=>{o("failed"),r(null)};return e.addEventListener("canplay",n),e.addEventListener("error",i),()=>{e.removeEventListener("canplay",n),e.removeEventListener("error",i)}},[t]),[n,i]}(t.src);return e.useEffect(()=>{i&&r.history.ignore(()=>{t.set({duration:1e3*i.duration})})},[i,t,r.history]),e.useEffect(()=>{if(!i){return}const e=()=>{i.currentTime=t.startTime*t.duration/1e3},o=()=>{const e=t.endTime*t.duration/1e3;i.currentTime>=e&&(i.pause(),i.currentTime=t.startTime*t.duration/1e3)};i.addEventListener("ended",e),i.addEventListener("timeupdate",o);const s=n(()=>{const e=r.animatedElementsIds;if(e.length&&!e.includes(t.id)){return}const n=r.currentTime-t.delay,o=t.duration*(t.endTime-t.startTime),s=n>=0&&n<o;if(!r.isPlaying||0!==r.animatedElementsIds.length||!s){return void i.pause()}i.volume=t.volume,i.paused&&i.play();const a=n%o/1e3+t.startTime*t.duration/1e3,u=i.currentTime;Math.abs(u-a)>.5&&a!==u&&(i.currentTime=a)});return()=>{i.pause(),i.removeEventListener("ended",e),i.removeEventListener("timeupdate",o),s()}},[r.isPlaying,t.startTime,t.endTime,t.volume,i]),null});
1
+ import e from"react";import{observer as t}from"mobx-react-lite";import{autorun as r}from"mobx";export const AudioElement=t(({audio:t,store:n})=>{const[i,s]=function(t){const[r,n]=e.useState(null),[i,s]=e.useState("loading");return e.useEffect(()=>{const e=new Audio(t),r=()=>{s("loaded"),n(e)},i=()=>{s("failed"),n(null)};return e.addEventListener("canplay",r),e.addEventListener("error",i),()=>{e.removeEventListener("canplay",r),e.removeEventListener("error",i)}},[t]),[r,i]}(t.src);return e.useEffect(()=>{i&&n.history.ignore(()=>{t.set({duration:1e3*i.duration})})},[i,t,n.history]),e.useEffect(()=>{if(!i){return}const e=()=>{i.currentTime=t.startTime*t.duration/1e3},s=()=>{const e=t.endTime*t.duration/1e3;i.currentTime>=e&&(i.pause(),i.currentTime=t.startTime*t.duration/1e3)};i.addEventListener("ended",e),i.addEventListener("timeupdate",s);const a=r(()=>{const e=n.animatedElementsIds;if(e.length&&!e.includes(t.id)){return}const r=n.currentTime-t.delay,s=t.speed,a=t.duration*(t.endTime-t.startTime),o=r>=0&&r<t.visibleDuration;if(!n.isPlaying||0!==n.animatedElementsIds.length||!o){return void i.pause()}i.volume=t.volume,i.playbackRate=s,i.preservesPitch=!1,i.paused&&i.play();const u=r*s%a/1e3+t.startTime*t.duration/1e3,d=i.currentTime;Math.abs(d-u)>.5&&u!==d&&(i.currentTime=u)});return()=>{i.pause(),i.removeEventListener("ended",e),i.removeEventListener("timeupdate",s),a()}},[n.isPlaying,t.startTime,t.endTime,t.volume,t.speed,i]),null});
@@ -1 +1 @@
1
- import{jsx as e,jsxs as n,Fragment as o}from"react/jsx-runtime";import{observer as t}from"mobx-react-lite";import{PolotnoIcon as l}from"../../icons/registry.js";import{t as r}from"../../utils/l10n.js";import{useDuplicateElement as i}from"../../toolbar/use-duplicate-element.js";import{useRemoveElement as a}from"../../toolbar/use-remove-element.js";import{useLock as s}from"../../toolbar/use-lock.js";import{DropdownMenu as d,DropdownMenuContent as c,DropdownMenuItem as m,DropdownMenuSeparator as h,DropdownMenuSub as u,DropdownMenuSubContent as p,DropdownMenuSubTrigger as v,DropdownMenuTrigger as b}from"../../primitives/dropdown-menu.js";export const ContextMenu=t(({store:t,isOpen:w,offset:y,setIsOpen:f})=>{var E;const{disabled:x,duplicate:g}=i({store:t}),{disabled:C,remove:R}=a({store:t}),{disabled:S,lock:j,locked:M}=s({store:t}),k=e(l,M?{name:"action.lock"}:{name:"action.unlock"});if(0===t.selectedElements.length){return null}const D={getBoundingClientRect:()=>({x:y.x,y:y.y,width:0,height:0,top:y.y,left:y.x,right:y.x,bottom:y.y,toJSON(){}})};return n(d,{open:w,onOpenChange:e=>{e||f(!1)},children:[e(b,{nativeButton:!1,render:e("span",{"aria-hidden":!0,style:{position:"fixed",width:0,height:0,pointerEvents:"none"}})}),n(c,{align:"start",anchor:D,className:"polotno-context-menu",children:[n(m,{onSelect:e=>{e.preventDefault(),j()},disabled:S,children:[k,e("span",{children:r(M?"contextMenu.unlock":"contextMenu.lock")})]}),n(m,{onSelect:()=>{g()},disabled:x,children:[e(l,{name:"action.duplicate"}),e("span",{children:r("contextMenu.duplicate")})]}),n(m,{onSelect:()=>{R()},disabled:C,children:[e(l,{name:"action.remove"}),e("span",{children:r("contextMenu.remove")})]}),e(h,{}),n(u,{children:[n(v,{children:[e(l,{name:"layering.menu"}),e("span",{children:r("toolbar.layering")})]}),n(p,{className:"polotno-context-menu",children:[n(m,{onSelect:e=>{e.preventDefault(),t.selectedElements.forEach(e=>e.moveTop())},disabled:!t.selectedElements.some(e=>{var n;return null===(n=e.parent)||void 0===n?void 0:n.canMoveElementsTop([e.id])}),children:[e(l,{name:"layering.top"}),e("span",{children:r("toolbar.toForward")})]}),n(m,{onSelect:e=>{e.preventDefault(),t.selectedElements.forEach(e=>e.moveUp())},disabled:!t.selectedElements.some(e=>{var n;return null===(n=e.parent)||void 0===n?void 0:n.canMoveElementsUp([e.id])}),children:[e(l,{name:"layering.up"}),e("span",{children:r("toolbar.up")})]}),n(m,{onSelect:e=>{e.preventDefault(),t.selectedElements.forEach(e=>e.moveDown())},disabled:!t.selectedElements.some(e=>{var n;return null===(n=e.parent)||void 0===n?void 0:n.canMoveElementsDown([e.id])}),children:[e(l,{name:"layering.down"}),e("span",{children:r("toolbar.down")})]}),n(m,{onSelect:e=>{e.preventDefault(),t.selectedElements.forEach(e=>e.moveBottom())},disabled:!t.selectedElements.some(e=>{var n;return null===(n=e.parent)||void 0===n?void 0:n.canMoveElementsBottom([e.id])}),children:[e(l,{name:"layering.bottom"}),e("span",{children:r("toolbar.toBottom")})]})]})]}),"table"===(null===(E=t.selectedElements[0])||void 0===E?void 0:E.type)&&(()=>{var l;const i=t.selectedElements[0],a=i.focusedCells[0],s=null!=a,d=null!==(l=i.getFocusedCellRange())&&void 0!==l?l:a?{minRow:a.row,maxRow:a.row,minCol:a.col,maxCol:a.col}:{minRow:0,maxRow:0,minCol:0,maxCol:0},{minRow:c,maxRow:u,minCol:p,maxCol:v}=d,b=u>c,w=v>p;return n(o,{children:[s&&n(o,{children:[e(h,{}),e(m,{onSelect:()=>{t.history.transaction(()=>{i.addRow(c)})},children:e("span",{children:r("toolbar.insertRowAbove")})}),e(m,{onSelect:()=>{t.history.transaction(()=>{i.addRow(u+1)})},children:e("span",{children:r("toolbar.insertRowBelow")})}),e(m,{disabled:i.rows<=u-c+1,onSelect:()=>{t.history.transaction(()=>{i.removeRowRange(c,u)})},children:e("span",{children:r(b?"toolbar.deleteRows":"toolbar.deleteRow")})}),e(h,{}),e(m,{onSelect:()=>{t.history.transaction(()=>{i.addColumn(p)})},children:e("span",{children:r("toolbar.insertColumnLeft")})}),e(m,{onSelect:()=>{t.history.transaction(()=>{i.addColumn(v+1)})},children:e("span",{children:r("toolbar.insertColumnRight")})}),e(m,{disabled:i.cols<=v-p+1,onSelect:()=>{t.history.transaction(()=>{i.removeColumnRange(p,v)})},children:e("span",{children:r(w?"toolbar.deleteColumns":"toolbar.deleteColumn")})})]}),e(h,{}),e(m,{onSelect:()=>{t.history.transaction(()=>{i.distributeRowsEvenly()})},children:e("span",{children:r("toolbar.distributeRowsEvenly")})}),e(m,{onSelect:()=>{t.history.transaction(()=>{i.distributeColumnsEvenly()})},children:e("span",{children:r("toolbar.distributeColumnsEvenly")})})]})})()]})]})});
1
+ import{jsx as e,jsxs as o,Fragment as n}from"react/jsx-runtime";import{observer as t}from"mobx-react-lite";import{PolotnoIcon as l}from"../../icons/registry.js";import{t as r}from"../../utils/l10n.js";import{useDuplicateElement as a}from"../../toolbar/use-duplicate-element.js";import{useRemoveElement as i}from"../../toolbar/use-remove-element.js";import{useLock as s}from"../../toolbar/use-lock.js";import{ContextMenu as c}from"@base-ui/react/context-menu";import{DropdownMenuContent as d,DropdownMenuItem as m,DropdownMenuSeparator as u,DropdownMenuSub as h,DropdownMenuSubContent as p,DropdownMenuSubTrigger as v}from"../../primitives/dropdown-menu.js";export const ContextMenu=t(({store:t,isOpen:b,offset:w,setIsOpen:f})=>{var x;const{disabled:y,duplicate:E}=a({store:t}),{disabled:C,remove:R}=i({store:t}),{disabled:g,lock:S,locked:M}=s({store:t}),j=e(l,M?{name:"action.lock"}:{name:"action.unlock"});if(0===t.selectedElements.length){return null}const k={getBoundingClientRect:()=>({x:w.x,y:w.y,width:0,height:0,top:w.y,left:w.x,right:w.x,bottom:w.y,toJSON(){}})};return e(c.Root,{open:b,onOpenChange:e=>{e||f(!1)},children:o(d,{align:"start",anchor:k,className:"polotno-context-menu",children:[o(m,{onSelect:e=>{e.preventDefault(),S()},disabled:g,children:[j,e("span",{children:r(M?"contextMenu.unlock":"contextMenu.lock")})]}),o(m,{onSelect:()=>{E()},disabled:y,children:[e(l,{name:"action.duplicate"}),e("span",{children:r("contextMenu.duplicate")})]}),o(m,{onSelect:()=>{R()},disabled:C,children:[e(l,{name:"action.remove"}),e("span",{children:r("contextMenu.remove")})]}),e(u,{}),o(h,{children:[o(v,{children:[e(l,{name:"layering.menu"}),e("span",{children:r("toolbar.layering")})]}),o(p,{className:"polotno-context-menu",children:[o(m,{onSelect:e=>{e.preventDefault(),t.selectedElements.forEach(e=>e.moveTop())},disabled:!t.selectedElements.some(e=>{var o;return null===(o=e.parent)||void 0===o?void 0:o.canMoveElementsTop([e.id])}),children:[e(l,{name:"layering.top"}),e("span",{children:r("toolbar.toForward")})]}),o(m,{onSelect:e=>{e.preventDefault(),t.selectedElements.forEach(e=>e.moveUp())},disabled:!t.selectedElements.some(e=>{var o;return null===(o=e.parent)||void 0===o?void 0:o.canMoveElementsUp([e.id])}),children:[e(l,{name:"layering.up"}),e("span",{children:r("toolbar.up")})]}),o(m,{onSelect:e=>{e.preventDefault(),t.selectedElements.forEach(e=>e.moveDown())},disabled:!t.selectedElements.some(e=>{var o;return null===(o=e.parent)||void 0===o?void 0:o.canMoveElementsDown([e.id])}),children:[e(l,{name:"layering.down"}),e("span",{children:r("toolbar.down")})]}),o(m,{onSelect:e=>{e.preventDefault(),t.selectedElements.forEach(e=>e.moveBottom())},disabled:!t.selectedElements.some(e=>{var o;return null===(o=e.parent)||void 0===o?void 0:o.canMoveElementsBottom([e.id])}),children:[e(l,{name:"layering.bottom"}),e("span",{children:r("toolbar.toBottom")})]})]})]}),"table"===(null===(x=t.selectedElements[0])||void 0===x?void 0:x.type)&&(()=>{var l;const a=t.selectedElements[0],i=a.focusedCells[0],s=null!=i,c=null!==(l=a.getFocusedCellRange())&&void 0!==l?l:i?{minRow:i.row,maxRow:i.row,minCol:i.col,maxCol:i.col}:{minRow:0,maxRow:0,minCol:0,maxCol:0},{minRow:d,maxRow:h,minCol:p,maxCol:v}=c,b=h>d,w=v>p;return o(n,{children:[s&&o(n,{children:[e(u,{}),e(m,{onSelect:()=>{t.history.transaction(()=>{a.addRow(d)})},children:e("span",{children:r("toolbar.insertRowAbove")})}),e(m,{onSelect:()=>{t.history.transaction(()=>{a.addRow(h+1)})},children:e("span",{children:r("toolbar.insertRowBelow")})}),e(m,{disabled:a.rows<=h-d+1,onSelect:()=>{t.history.transaction(()=>{a.removeRowRange(d,h)})},children:e("span",{children:r(b?"toolbar.deleteRows":"toolbar.deleteRow")})}),e(u,{}),e(m,{onSelect:()=>{t.history.transaction(()=>{a.addColumn(p)})},children:e("span",{children:r("toolbar.insertColumnLeft")})}),e(m,{onSelect:()=>{t.history.transaction(()=>{a.addColumn(v+1)})},children:e("span",{children:r("toolbar.insertColumnRight")})}),e(m,{disabled:a.cols<=v-p+1,onSelect:()=>{t.history.transaction(()=>{a.removeColumnRange(p,v)})},children:e("span",{children:r(w?"toolbar.deleteColumns":"toolbar.deleteColumn")})})]}),e(u,{}),e(m,{onSelect:()=>{t.history.transaction(()=>{a.distributeRowsEvenly()})},children:e("span",{children:r("toolbar.distributeRowsEvenly")})}),e(m,{onSelect:()=>{t.history.transaction(()=>{a.distributeColumnsEvenly()})},children:e("span",{children:r("toolbar.distributeColumnsEvenly")})})]})})()]})})});
@@ -1 +1 @@
1
- import e from"react";import{autorun as r}from"mobx";import{Input as t,UrlSource as n,BufferSource as u,CanvasSink as a,ALL_FORMATS as i}from"mediabunny";import{incrementLoader as c,triggerLoadError as s}from"../utils/loader.js";const o=.05;export const useMediabunnyVideo=(l,d,f)=>{const[m,h]=e.useState({input:null,videoSink:null,duration:0,isReady:!1,error:null});e.useRef(m).current=m;const g=e.useRef(0),p=e.useRef(null),w=e.useRef(null),v=e.useRef(null),b=e.useRef(null),y=e.useRef(null),T=e.useRef(null),R=e.useRef(!1),k=e.useRef(null),S=e.useRef([]),$=e.useRef(null),x=e.useRef(!1),[,E]=e.useReducer(e=>e+1,0);return e.useEffect(()=>{if(!f){return}let e=!0;const r=++g.current;let o=null;return(async()=>{try{if(!e||r!==g.current){return}o=c(`mediabunny init ${l.id}`);const s=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")}const t=e.slice(r+1),n=atob(t),u=new Uint8Array(n.length);for(let a=0;a<n.length;a++){u[a]=n.charCodeAt(a)}return u.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)}(l.src);if(!e||r!==g.current){return void(o&&(o(),o=null))}const d=new t({source:s,formats:i}),f=await d.computeDuration(),m=await d.getPrimaryVideoTrack();if(!m){throw new Error("No video track found")}if(null===m.codec){throw new Error("Unsupported video codec")}if(!await m.canDecode()){throw new Error("Unable to decode the video track")}const p=await m.canBeTransparent(),w=new a(m,{poolSize:5,fit:"contain",alpha:p});if(!e||r!==g.current){return d.dispose(),void(o&&(o(),o=null))}o&&(o(),o=null),h(e=>Object.assign(Object.assign({},e),{input:d,videoSink:w,duration:f,isReady:!0,error:null}))}catch(d){if(console.error("Failed to initialize mediabunny:",d),o&&(o(),o=null),e&&r===g.current){const e=`Failed to initialize mediabunny for video ${l.id}: ${d}`;s(e),h(e=>Object.assign(Object.assign({},e),{error:String(d),isReady:!1}))}}})(),()=>{e=!1,o&&(o(),o=null)}},[l.src,f]),e.useEffect(()=>()=>{w.current&&(w.current.return(),w.current=null),p.current&&(p.current(),p.current=null),v.current=null,b.current=null,y.current=null,R.current=!1,k.current=null,S.current=[],$.current=null,x.current=!1,h({input:null,videoSink:null,duration:0,isReady:!1,error:null})},[f]),e.useEffect(()=>{if(!f||!m.isReady||!m.videoSink){return}const e=++g.current,t="string"==typeof l.src?l.src.slice(0,120):String(l.src),n=(e,r={},n="debug")=>{let u="";try{u=JSON.stringify(Object.assign(Object.assign({},r),{timeCalc:T.current}))}catch(i){u=`[unserializable extras: ${String(i)}]`}const a=`mediabunny event=${e} elementId=${l.id} targetTime=${y.current} duration=${m.duration} lastFrameTimestamp=${b.current} hasIterator=${Boolean(w.current)} prefetchSize=${S.current.length} srcHint=${t} extras=${u}`;"error"===n?console.error(a):"warn"===n?console.warn(a):console.debug(a)},u=e=>{const r=m.duration||0;if(!r||!Number.isFinite(r)){return e}const t=r>o?r-o:r;return Math.max(0,Math.min(e,t))},a=e=>{const r=m.duration||0;return!(!r||!Number.isFinite(r))&&r-e<=.050001000000000004},i=e=>{let r=v.current;r&&r.width===e.canvas.width&&r.height===e.canvas.height||(r||(r=document.createElement("canvas"),v.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)),b.current=e.timestamp},s=e=>{const r=w.current;r&&(x.current||(x.current=!0,$.current=(async()=>{try{for(;S.current.length<4&&e===g.current;){const t=await r.next();if(e!==g.current){return}if(t.done||!t.value){break}S.current.push({timestamp:t.value.timestamp,frame:t.value})}}catch(t){}finally{x.current=!1,$.current=null}})()))},h=e=>{const r=S.current;for(let t=0;t<r.length;t++){if(Math.abs(r[t].timestamp-e)<o){const e=r[t];return S.current=r.slice(t+1),e}}return null},M=()=>{S.current=[]},O=async(e,r,t=0)=>{const c=u(e),l=(e=>{const r=b.current;return null===r||e<r-o||e>r+.5})(c)?"seek":"iterate";try{const t=m.videoSink,u=b.current;if(null!==u&&Math.abs(u-c)<o){return void(y.current=e)}const f=h(c);if(f){return i(f.frame),y.current=e,s(r),void E()}if($.current){await $.current;const t=h(c);if(t){return i(t.frame),y.current=e,s(r),void E()}}if(M(),"seek"===l){w.current&&(await w.current.return(),w.current=null);const u=t.canvases(c);w.current=u;const o=await u.next();if(r!==g.current){return void(w.current&&(await w.current.return(),w.current=null))}if(o.done||!o.value){if(a(c)||n("iterator_exhausted",{mode:l,requestedTargetTime:e,clampedTargetTime:c},"warn"),r===g.current&&!a(c)){try{w.current&&(await w.current.return(),w.current=null),M();const n=t.canvases(c);w.current=n;const u=await n.next();!u.done&&u.value&&(i(u.value),s(r),y.current=e,E())}catch(d){}}return}i(o.value),s(r)}else{const u=w.current;if(!u){return}let f=!1;for(;r===g.current;){const m=await u.next();if(r!==g.current){break}if(m.done||!m.value){if(a(c)||n("iterator_exhausted",{mode:l,requestedTargetTime:e,clampedTargetTime:c},"warn"),!f&&!a(c)){f=!0;try{w.current&&(await w.current.return(),w.current=null),M();const e=t.canvases(c);w.current=e;const n=await e.next();if(r!==g.current){break}if(n.done||!n.value){break}i(n.value),s(r);break}catch(d){break}}break}const h=m.value;if(i(h),Math.abs(h.timestamp-c)<o){s(r);break}if(h.timestamp>c){s(r);break}}}y.current=e,E()}catch(f){const u=f instanceof Error?{name:f.name,message:f.message,stack:f.stack}:{message:String(f)},a=f instanceof Error?`${f.name}: ${f.message}`:String(f),i=a.includes("Unsupported configuration")||a.includes("isConfigSupported")||a.includes("OperationError");if(n("frame_process_failed",{mode:l,requestedTargetTime:e,clampedTargetTime:c,unsupportedConfigAttempt:t,isUnsupportedConfig:i,error:u},"error"),i&&t<1){try{w.current&&(await w.current.return(),w.current=null),M(),$.current=null,x.current=!1,b.current=null,await O(e,r,t+1)}catch(d){}}}},U=r(()=>{const r=m.videoSink,t=m.duration;if(!r||!t){return}const n=l.startTime*t*1e3,a=t*(l.endTime-l.startTime)*1e3,i=((d.currentTime||l.page.startTime)-l.page.startTime)%a+n,s=i/1e3,o=u(s);T.current={pageStartTime:l.page.startTime,storeCurrentTime:d.currentTime,offsetMs:n,durationMs:a,restMs:i,targetTime:s,clampedTargetTime:o,startTime:l.startTime,endTime:l.endTime,videoDuration:t},((e,r)=>{R.current?k.current=e:(R.current=!0,p.current||(p.current=c(`mediabunny video frame ${l.id}`)),(async()=>{let t=e;for(;null!==t&&r===g.current;){await O(t,r),t=k.current,k.current=null}p.current&&(p.current(),p.current=null),R.current=!1})())})(o,e)});return()=>{U(),g.current++,p.current&&(p.current(),p.current=null)}},[f,m.isReady,m.videoSink,m.duration,d,l]),f&&m.isReady?v.current:null};
1
+ import e from"react";import{autorun as r}from"mobx";import{Input as t,UrlSource as n,BufferSource as u,CanvasSink as a,ALL_FORMATS as i}from"mediabunny";import{incrementLoader as c,triggerLoadError as s}from"../utils/loader.js";import{getElementTimeRange as o,getVideoRestMs as l}from"../utils/timeline.js";const d=.05;export const useMediabunnyVideo=(f,m,h)=>{const[g,p]=e.useState({input:null,videoSink:null,duration:0,isReady:!1,error:null});e.useRef(g).current=g;const w=e.useRef(0),v=e.useRef(null),b=e.useRef(null),y=e.useRef(null),T=e.useRef(null),R=e.useRef(null),k=e.useRef(null),S=e.useRef(!1),$=e.useRef(null),x=e.useRef([]),E=e.useRef(null),M=e.useRef(!1),[,O]=e.useReducer(e=>e+1,0);return e.useEffect(()=>{if(!h){return}let e=!0;const r=++w.current;let o=null;return(async()=>{try{if(!e||r!==w.current){return}o=c(`mediabunny init ${f.id}`);const s=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")}const t=e.slice(r+1),n=atob(t),u=new Uint8Array(n.length);for(let a=0;a<n.length;a++){u[a]=n.charCodeAt(a)}return u.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)}(f.src);if(!e||r!==w.current){return void(o&&(o(),o=null))}const l=new t({source:s,formats:i}),d=await l.computeDuration(),m=await l.getPrimaryVideoTrack();if(!m){throw new Error("No video track found")}if(null===m.codec){throw new Error("Unsupported video codec")}if(!await m.canDecode()){throw new Error("Unable to decode the video track")}const h=await m.canBeTransparent(),g=new a(m,{poolSize:5,fit:"contain",alpha:h});if(!e||r!==w.current){return l.dispose(),void(o&&(o(),o=null))}o&&(o(),o=null),p(e=>Object.assign(Object.assign({},e),{input:l,videoSink:g,duration:d,isReady:!0,error:null}))}catch(l){if(console.error("Failed to initialize mediabunny:",l),o&&(o(),o=null),e&&r===w.current){const e=`Failed to initialize mediabunny for video ${f.id}: ${l}`;s(e),p(e=>Object.assign(Object.assign({},e),{error:String(l),isReady:!1}))}}})(),()=>{e=!1,o&&(o(),o=null)}},[f.src,h]),e.useEffect(()=>()=>{b.current&&(b.current.return(),b.current=null),v.current&&(v.current(),v.current=null),y.current=null,T.current=null,R.current=null,S.current=!1,$.current=null,x.current=[],E.current=null,M.current=!1,p({input:null,videoSink:null,duration:0,isReady:!1,error:null})},[h]),e.useEffect(()=>{if(!h||!g.isReady||!g.videoSink){return}const e=++w.current,t="string"==typeof f.src?f.src.slice(0,120):String(f.src),n=(e,r={},n="debug")=>{let u="";try{u=JSON.stringify(Object.assign(Object.assign({},r),{timeCalc:k.current}))}catch(i){u=`[unserializable extras: ${String(i)}]`}const a=`mediabunny event=${e} elementId=${f.id} targetTime=${R.current} duration=${g.duration} lastFrameTimestamp=${T.current} hasIterator=${Boolean(b.current)} prefetchSize=${x.current.length} srcHint=${t} extras=${u}`;"error"===n?console.error(a):"warn"===n?console.warn(a):console.debug(a)},u=e=>{const r=g.duration||0;if(!r||!Number.isFinite(r)){return e}const t=r>d?r-d:r;return Math.max(0,Math.min(e,t))},a=e=>{const r=g.duration||0;return!(!r||!Number.isFinite(r))&&r-e<=.050001000000000004},i=e=>{let r=y.current;r&&r.width===e.canvas.width&&r.height===e.canvas.height||(r||(r=document.createElement("canvas"),y.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)),T.current=e.timestamp},s=e=>{const r=b.current;r&&(M.current||(M.current=!0,E.current=(async()=>{try{for(;x.current.length<4&&e===w.current;){const t=await r.next();if(e!==w.current){return}if(t.done||!t.value){break}x.current.push({timestamp:t.value.timestamp,frame:t.value})}}catch(t){}finally{M.current=!1,E.current=null}})()))},p=e=>{const r=x.current;for(let t=0;t<r.length;t++){if(Math.abs(r[t].timestamp-e)<d){const e=r[t];return x.current=r.slice(t+1),e}}return null},j=()=>{x.current=[]},U=async(e,r,t=0)=>{const c=u(e),o=(e=>{const r=T.current;return null===r||e<r-d||e>r+.5})(c)?"seek":"iterate";try{const t=g.videoSink,u=T.current;if(null!==u&&Math.abs(u-c)<d){return void(R.current=e)}const f=p(c);if(f){return i(f.frame),R.current=e,s(r),void O()}if(E.current){await E.current;const t=p(c);if(t){return i(t.frame),R.current=e,s(r),void O()}}if(j(),"seek"===o){b.current&&(await b.current.return(),b.current=null);const u=t.canvases(c);b.current=u;const d=await u.next();if(r!==w.current){return void(b.current&&(await b.current.return(),b.current=null))}if(d.done||!d.value){if(a(c)||n("iterator_exhausted",{mode:o,requestedTargetTime:e,clampedTargetTime:c},"warn"),r===w.current&&!a(c)){try{b.current&&(await b.current.return(),b.current=null),j();const n=t.canvases(c);b.current=n;const u=await n.next();!u.done&&u.value&&(i(u.value),s(r),R.current=e,O())}catch(l){}}return}i(d.value),s(r)}else{const u=b.current;if(!u){return}let f=!1;for(;r===w.current;){const m=await u.next();if(r!==w.current){break}if(m.done||!m.value){if(a(c)||n("iterator_exhausted",{mode:o,requestedTargetTime:e,clampedTargetTime:c},"warn"),!f&&!a(c)){f=!0;try{b.current&&(await b.current.return(),b.current=null),j();const e=t.canvases(c);b.current=e;const n=await e.next();if(r!==w.current){break}if(n.done||!n.value){break}i(n.value),s(r);break}catch(l){break}}break}const h=m.value;if(i(h),Math.abs(h.timestamp-c)<d){s(r);break}if(h.timestamp>c){s(r);break}}}R.current=e,O()}catch(f){const u=f instanceof Error?{name:f.name,message:f.message,stack:f.stack}:{message:String(f)},a=f instanceof Error?`${f.name}: ${f.message}`:String(f),i=a.includes("Unsupported configuration")||a.includes("isConfigSupported")||a.includes("OperationError");if(n("frame_process_failed",{mode:o,requestedTargetTime:e,clampedTargetTime:c,unsupportedConfigAttempt:t,isUnsupportedConfig:i,error:u},"error"),i&&t<1){try{b.current&&(await b.current.return(),b.current=null),j(),E.current=null,M.current=!1,T.current=null,await U(e,r,t+1)}catch(l){}}}},C=r(()=>{const r=g.videoSink,t=g.duration;if(!r||!t){return}const n=f.startTime*t*1e3,a=t*(f.endTime-f.startTime)*1e3,{start:i}=o(f.animations,f.page.duration),s=l(m.currentTime,f.page.startTime,i,a,n,f.speed),d=s/1e3,h=u(d);k.current={pageStartTime:f.page.startTime,storeCurrentTime:m.currentTime,offsetMs:n,durationMs:a,restMs:s,targetTime:d,clampedTargetTime:h,startTime:f.startTime,endTime:f.endTime,videoDuration:t},((e,r)=>{S.current?$.current=e:(S.current=!0,v.current||(v.current=c(`mediabunny video frame ${f.id}`)),(async()=>{let t=e;for(;null!==t&&r===w.current;){await U(t,r),t=$.current,$.current=null}v.current&&(v.current(),v.current=null),S.current=!1})())})(h,e)});return()=>{C(),w.current++,v.current&&(v.current(),v.current=null)}},[h,g.isReady,g.videoSink,g.duration,m,f]),h&&g.isReady?y.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 i(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 i=[];const s=n.sort((e,t)=>e.diff-t.diff),a=o.sort((e,t)=>e.diff-t.diff);var d=s[0],c=a[0];return d&&s.filter(e=>Math.abs(e.diff-d.diff)<.1).forEach(e=>{i.push(Object.assign({orientation:"V"},e))}),c&&a.filter(e=>Math.abs(e.diff-c.diff)<.1).forEach(e=>{i.push(Object.assign({orientation:"H"},e))}),i}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)}))};export function useSnap(r,d){const c=e.useRef(null),{snapGuideStyle:f}=o(),u=e.useRef(f);u.current=f;const l=e=>e.hasName("element")||e.hasName("page-background")||!c.current&&e.hasName("elements-area");function h(e){var t;const n=null===(t=r.current)||void 0===t?void 0:t.getStage(),o=[],i=[];return n.find(l).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"}),i.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:i}}function g(e){var n;const o=null===(n=r.current)||void 0===n?void 0:n.getLayer(),i=null==o?void 0:o.children.find(e=>"line-guides"===e.name());e.forEach(e=>{if("H"===e.orientation){var n=new t.Line({x:-o.getStage().x(),y:-o.getStage().y(),points:[-6e3,e.lineGuide,6e3,e.lineGuide],stroke:u.current.stroke,strokeWidth:u.current.strokeWidth,name:"guid-line",dash:u.current.dash});null==i||i.add(n),o.batchDraw()}else{"V"===e.orientation&&(n=new t.Line({x:-o.getStage().x(),y:-o.getStage().y(),points:[e.lineGuide,-6e3,e.lineGuide,6e3],stroke:u.current.stroke,strokeWidth:u.current.strokeWidth,name:"guid-line",dash:u.current.dash}),null==i||i.add(n))}})}const y=e=>{const o=e.target.getLayer().children.find(e=>"line-guides"===e.name());null==o||o.destroyChildren();var r=h(e.target.nodes()),s=function(e){const o=e.__getNodeRect(),r=n(Object.assign(Object.assign({},o),{rotation:t.Util.radToDeg(o.rotation)})),i=e.getAbsolutePosition();return{vertical:[{guide:r.x,offset:i.x-r.x,snap:"start",nodes:e.nodes()},{guide:r.x+r.width/2,offset:i.x-r.x-r.width/2,snap:"center",nodes:e.nodes()},{guide:r.x+r.width,offset:i.x-r.x-r.width,snap:"end",nodes:e.nodes()}],horizontal:[{guide:r.y,offset:i.y-r.y,snap:"start",nodes:e.nodes()},{guide:r.y+r.height/2,offset:i.y-r.y-r.height/2,snap:"center",nodes:e.nodes()},{guide:r.y+r.height,offset:i.y-r.y-r.height,snap:"end",nodes:e.nodes()}]}}(e.target),a=i(r,s);if(!a.length){return}g(a);const d=e.target.getAbsolutePosition(),c=(e.target.nodes().map(e=>e.getAbsolutePosition()),Object.assign({},d));a.forEach(e=>{switch(e.snap){case"start":case"center":case"end":switch(e.orientation){case"V":c.x=e.lineGuide+e.offset;break;case"H":c.y=e.lineGuide+e.offset}}});const f=c.x-d.x,u=c.y-d.y;e.evt.ctrlKey||e.evt.metaKey||e.target.nodes().forEach(e=>{const t=e.getAbsolutePosition();e.setAbsolutePosition({x:t.x+f,y:t.y+u})})},p=(e,t,n)=>{var o;const d=r.current,c=d.getLayer().children.find(e=>"line-guides"===e.name());if(null==c||c.destroyChildren(),"rotater"===d.getActiveAnchor()){return t}const f=d.getActiveAnchor(),u=a[f],l=null===(o=d.findOne(`.${u}`))||void 0===o?void 0:o.getAbsolutePosition();if(!l){return t}const y={x:e.x-l.x,y:e.y-l.y},p=function(e,t){const n=s(e,t)/s(t,t);return{x:n*t.x,y:n*t.y}}({x:t.x-e.x,y:t.y-e.y},y);if(Math.sqrt(Math.pow(p.x,2)+Math.pow(p.y,2))>5){return t}const x={x:e.x+p.x,y:e.y+p.y};var m=i(h(d.nodes()),{vertical:[{guide:x.x,offset:0,snap:"start",nodes:d.nodes()}],horizontal:[{guide:x.y,offset:0,snap:"start",nodes:d.nodes()}]});if(!m.length){return t}if(g(m),n.ctrlKey||n.metaKey){return t}const v=[];if(m.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}}}(x,l,{orientation:e.orientation,lineGuide:e.lineGuide});t&&v.push(t)}),v.length>0){let e=v[0],t=Math.sqrt(Math.pow(x.x-e.x,2)+Math.pow(x.y-e.y,2));if(v.forEach(n=>{const o=Math.sqrt(Math.pow(x.x-n.x,2)+Math.pow(x.y-n.y,2));o<t&&(t=o,e=n)}),t<10){return e}}return x},x=e=>{if(!e.target){return}const t=e.target.getLayer(),n=t.children.find(e=>"line-guides"===e.name());null==n||n.destroyChildren(),t.batchDraw()};e.useEffect(()=>{r.current&&(r.current.anchorDragBoundFunc(p),r.current.on("dragstart",e=>{setTimeout(()=>{ensureDragOrder()})}),r.current.on("dragmove",y),r.current.on("dragend",x),r.current.on("transformend",x),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(n,r,s){const{snapGuideStyle:a}=o(),d=e.useRef(a);d.current=a;const c=e=>e.hasName("element")||e.hasName("line-anchor")||e.hasName("page-background")||e.hasName("elements-area"),f=e=>{const o=e.target.getLayer().children.find(e=>"line-guides"===e.name());null==o||o.destroyChildren();var s,a=i(function(e){var t;const o=null===(t=n.current)||void 0===t?void 0:t.getStage();var r=[],i=[];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"}),i.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:i}}([e.target,...r.map(e=>e.current)]),{vertical:[{guide:(s=e.target).absolutePosition().x,offset:0,snap:"center",nodes:[s]}],horizontal:[{guide:s.absolutePosition().y,offset:0,snap:"center",nodes:[s]}]});if(!a.length){return}!function(e){var o;const r=null===(o=n.current)||void 0===o?void 0:o.getLayer(),i=null==r?void 0:r.children.find(e=>"line-guides"===e.name());e.forEach(e=>{if("H"===e.orientation){var n=new t.Line({x:-r.getStage().x(),y:-r.getStage().y(),points:[-6e3,e.lineGuide,6e3,e.lineGuide],stroke:d.current.stroke,strokeWidth:d.current.strokeWidth,name:"guid-line",dash:d.current.dash});null==i||i.add(n),r.batchDraw()}else{"V"===e.orientation&&(n=new t.Line({x:-r.getStage().x(),y:-r.getStage().y(),points:[e.lineGuide,-6e3,e.lineGuide,6e3],stroke:d.current.stroke,strokeWidth:d.current.strokeWidth,name:"guid-line",dash:d.current.dash}),null==i||i.add(n))}})}(a);const f=e.target.getAbsolutePosition(),u=Object.assign({},f);a.forEach(e=>{switch(e.snap){case"start":case"center":case"end":switch(e.orientation){case"V":u.x=e.lineGuide+e.offset;break;case"H":u.y=e.lineGuide+e.offset}}});const l=u.x-f.x,h=u.y-f.y;if(!e.evt.ctrlKey&&!e.evt.metaKey){const t=e.target.getAbsolutePosition();e.target.absolutePosition({x:t.x+l,y:t.y+h})}},u=e=>{if(!e.target){return}const t=e.target.getLayer(),n=t.children.find(e=>"line-guides"===e.name());null==n||n.destroyChildren(),t.batchDraw()};e.useEffect(()=>{n.current&&(n.current.on("dragmove",f),n.current.on("dragend",u))},s)}function s(e,t){return e.x*t.x+e.y*t.y}const a={"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;const r=e.target.getLayer(),a=r.children.find(e=>"line-guides"===e.name());null==a||a.destroyChildren();const d=l.current;if((null===(o=e.evt)||void 0===o?void 0:o.shiftKey)&&d){const t=e.target.getAbsolutePosition();let n=t.x-d.x,o=t.y-d.y;const s=Math.abs(n),c=Math.abs(o);if(s>2.414*c){o=0}else if(c>2.414*s){n=0}else{const e=(s+c)/2;n=Math.sign(n)*e,o=Math.sign(o)*e}e.target.nodes().forEach(e=>{const t=h.current.get(e);t&&e.setAbsolutePosition({x:t.x+n,y:t.y+o})});const f=g.current;if(f&&(s>0||c>0)){const e=Math.sign(n),t=Math.sign(o);null==a||a.add(i(r.getStage(),p.current,[f.x-6e3*e,f.y-6e3*t,f.x+6e3*e,f.y+6e3*t]))}return}var c=v(e.target.nodes()),f=function(e){const o=e.__getNodeRect(),r=n(Object.assign(Object.assign({},o),{rotation:t.Util.radToDeg(o.rotation)})),s=e.getAbsolutePosition();return{vertical:[{guide:r.x,offset:s.x-r.x,snap:"start",nodes:e.nodes()},{guide:r.x+r.width/2,offset:s.x-r.x-r.width/2,snap:"center",nodes:e.nodes()},{guide:r.x+r.width,offset:s.x-r.x-r.width,snap:"end",nodes:e.nodes()}],horizontal:[{guide:r.y,offset:s.y-r.y,snap:"start",nodes:e.nodes()},{guide:r.y+r.height/2,offset:s.y-r.y-r.height/2,snap:"center",nodes:e.nodes()},{guide:r.y+r.height,offset:s.y-r.y-r.height,snap:"end",nodes:e.nodes()}]}}(e.target),u=s(c,f);if(!u.length){return}m(u);const y=e.target.getAbsolutePosition(),x=(e.target.nodes().map(e=>e.getAbsolutePosition()),Object.assign({},y));u.forEach(e=>{switch(e.snap){case"start":case"center":case"end":switch(e.orientation){case"V":x.x=e.lineGuide+e.offset;break;case"H":x.y=e.lineGuide+e.offset}}});const b=x.x-y.x,w=x.y-y.y;e.evt.ctrlKey||e.evt.metaKey||e.target.nodes().forEach(e=>{const t=e.getAbsolutePosition();e.setAbsolutePosition({x:t.x+b,y:t.y+w})})},w=(e,t,n)=>{var o;const i=r.current,a=i.getLayer().children.find(e=>"line-guides"===e.name());if(null==a||a.destroyChildren(),"rotater"===i.getActiveAnchor()){return t}const f=i.getActiveAnchor(),u=c[f],l=null===(o=i.findOne(`.${u}`))||void 0===o?void 0:o.getAbsolutePosition();if(!l){return t}const h={x:e.x-l.x,y:e.y-l.y},g=function(e,t){const n=d(e,t)/d(t,t);return{x:n*t.x,y:n*t.y}}({x:t.x-e.x,y:t.y-e.y},h);if(Math.sqrt(Math.pow(g.x,2)+Math.pow(g.y,2))>5){return t}const y={x:e.x+g.x,y:e.y+g.y};var p=s(v(i.nodes()),{vertical:[{guide:y.x,offset:0,snap:"start",nodes:i.nodes()}],horizontal:[{guide:y.y,offset:0,snap:"start",nodes:i.nodes()}]});if(!p.length){return t}if(m(p),n.ctrlKey||n.metaKey){return t}const x=[];if(p.forEach(e=>{const t=function(e,t,n){if("V"===n.orientation){const o=n.lineGuide;if(Math.abs(t.x-e.x)<1e-4){return null}const r=(t.y-e.y)/(t.x-e.x);return{x:o,y:r*o+(e.y-r*e.x)}}{const o=n.lineGuide;if(Math.abs(t.y-e.y)<1e-4){return null}const r=(t.y-e.y)/(t.x-e.x);return{x:(o-e.y)/r+e.x,y:o}}}(y,l,{orientation:e.orientation,lineGuide:e.lineGuide});t&&x.push(t)}),x.length>0){let e=x[0],t=Math.sqrt(Math.pow(y.x-e.x,2)+Math.pow(y.y-e.y,2));if(x.forEach(n=>{const o=Math.sqrt(Math.pow(y.x-n.x,2)+Math.pow(y.y-n.y,2));o<t&&(t=o,e=n)}),t<10){return e}}return y},M=e=>{if(l.current=null,h.current=new Map,g.current=null,!e.target){return}const t=e.target.getLayer(),n=t.children.find(e=>"line-guides"===e.name());null==n||n.destroyChildren(),t.batchDraw()};e.useEffect(()=>{r.current&&(r.current.anchorDragBoundFunc(w),r.current.on("dragstart",e=>{const t=r.current;if(t){l.current=t.getAbsolutePosition(),h.current=new Map(t.nodes().map(e=>[e,e.getAbsolutePosition()]));const e=t.getClientRect();g.current={x:e.x+e.width/2,y:e.y+e.height/2}}setTimeout(()=>{ensureDragOrder()})}),r.current.on("dragmove",b),r.current.on("dragend",M),r.current.on("transformend",M),r.current.on("transform",e=>{var t,n;e.evt.ctrlKey||e.evt.metaKey?null===(t=r.current)||void 0===t||t.rotationSnapTolerance(0):null===(n=r.current)||void 0===n||n.rotationSnapTolerance(5)}))},[])}export function useAnchorSnap(t,n,r){const{snapGuideStyle:i}=o(),d=e.useRef(i);d.current=i;const c=e=>e.hasName("element")||e.hasName("line-anchor")||e.hasName("page-background")||e.hasName("elements-area"),f=e=>{const o=e.target.getLayer().children.find(e=>"line-guides"===e.name());null==o||o.destroyChildren();var r,i=s(function(e){var n;const o=null===(n=t.current)||void 0===n?void 0:n.getStage();var r=[],s=[];return o.find(c).forEach(t=>{if(!(e.indexOf(t)>=0)){var n=t.getClientRect({skipShadow:!0,skipStroke:!0});t.hasName("line-anchor")&&(n={x:t.absolutePosition().x,y:t.absolutePosition().y,width:0,height:0}),r.push({offset:n.x,node:t,snap:"start"},{offset:n.x+n.width,node:t,snap:"end"},{offset:n.x+n.width/2,node:t,snap:"center"}),s.push({offset:n.y,node:t,snap:"start"},{offset:n.y+n.height,node:t,snap:"end"},{offset:n.y+n.height/2,node:t,snap:"center"})}}),{vertical:r,horizontal:s}}([e.target,...n.map(e=>e.current)]),{vertical:[{guide:(r=e.target).absolutePosition().x,offset:0,snap:"center",nodes:[r]}],horizontal:[{guide:r.absolutePosition().y,offset:0,snap:"center",nodes:[r]}]});if(!i.length){return}!function(e){var n;a(null===(n=t.current)||void 0===n?void 0:n.getLayer(),d.current,e)}(i);const f=e.target.getAbsolutePosition(),u=Object.assign({},f);i.forEach(e=>{switch(e.snap){case"start":case"center":case"end":switch(e.orientation){case"V":u.x=e.lineGuide+e.offset;break;case"H":u.y=e.lineGuide+e.offset}}});const l=u.x-f.x,h=u.y-f.y;if(!e.evt.ctrlKey&&!e.evt.metaKey){const t=e.target.getAbsolutePosition();e.target.absolutePosition({x:t.x+l,y:t.y+h})}},u=e=>{if(!e.target){return}const t=e.target.getLayer(),n=t.children.find(e=>"line-guides"===e.name());null==n||n.destroyChildren(),t.batchDraw()};e.useEffect(()=>{t.current&&(t.current.on("dragmove",f),t.current.on("dragend",u))},r)}function d(e,t){return e.x*t.x+e.y*t.y}const c={"top-left":"bottom-right","top-center":"bottom-center","top-right":"bottom-left","middle-right":"middle-left","bottom-right":"top-left","bottom-center":"top-center","bottom-left":"top-right","middle-left":"middle-right"};
@@ -1 +1 @@
1
- import{jsx as e,jsxs as t,Fragment as r}from"react/jsx-runtime";import o from"react";import{observer as i}from"mobx-react-lite";import{autorun as n}from"mobx";import{Arc as a,Group as d,Image as h,Rect as l,Text as s,Transformer as c}from"react-konva";import{ROLES as u}from"../model/store.js";import g from"use-image";import f from"konva";import{Portal as m}from"react-konva-utils";import{useWorkspaceStyle as p}from"./workspace-style.js";import{incrementLoader as v,triggerLoadError as w}from"../utils/loader.js";import*as x from"../utils/svg.js";import{flags as M}from"../utils/flags.js";import{applyFilter as y}from"./apply-filters.js";import{useFadeIn as E}from"./use-fadein.js";import{isTouchDevice as b}from"../utils/screen.js";import{useMediabunnyVideo as L}from"./use-mediabunny-video.js";function T(){return document.createElement("canvas")}const C=new window.Image;C.src=x.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 R=new window.Image;R.src=x.svgToURL('\n <svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path opacity="0.6" d="M14 19L14 5C14 3.89543 14.8954 3 16 3L17 3C18.1046 3 19 3.89543 19 5L19 19C19 20.1046 18.1046 21 17 21L16 21C14.8954 21 14 20.1046 14 19Z" fill="white"/>\n <path opacity="0.6" d="M10 19L10 5C10 3.89543 9.10457 3 8 3L7 3C5.89543 3 5 3.89543 5 5L5 19C5 20.1046 5.89543 21 7 21L8 21C9.10457 21 10 20.1046 10 19Z" fill="white"/>\n <path d="M14 19L14 5C14 3.89543 14.8954 3 16 3L17 3C18.1046 3 19 3.89543 19 5L19 19C19 20.1046 18.1046 21 17 21L16 21C14.8954 21 14 20.1046 14 19Z" stroke="#323232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n <path d="M10 19L10 5C10 3.89543 9.10457 3 8 3L7 3C5.89543 3 5 3.89543 5 5L5 19C5 20.1046 5.89543 21 7 21L8 21C9.10457 21 10 20.1046 10 19Z" stroke="#323232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n');export const useCornerRadiusAndCrop=(e,t,r,i,n=0,a=!1)=>{var d,h;const l=Math.floor(Math.max(e.width*i,1)),s=Math.floor(Math.max(e.height*i,1)),c=Math.min(n*i,l/2,s/2),u=Math.max(e.width/r.width,e.height/r.height)*i,g=(null===(d=e.page)||void 0===d?void 0:d._exportingOrRendering)&&M.imageDownScalingEnabled&&u<1&&!a,m=t instanceof HTMLVideoElement?t.videoWidth:null==t?void 0:t.width,p=t instanceof HTMLVideoElement?t.videoHeight:null==t?void 0:t.height,v=0===r.x&&0===r.y&&r.width===m&&r.height===p,w=o.useMemo(()=>{if(t&&m&&p){return v&&0===c&&!g?void 0:T()}},[t,c,g,v,m,p]),x=()=>{if(!w||!t){return}w.width=l,w.height=s;const e=w.getContext("2d");if(!e){return}c&&(e.beginPath(),e.moveTo(c,0),e.lineTo(l-c,0),e.arc(l-c,c,c,3*Math.PI/2,0,!1),e.lineTo(l,s-c),e.arc(l-c,s-c,c,0,Math.PI/2,!1),e.lineTo(c,s),e.arc(c,s-c,c,Math.PI/2,Math.PI,!1),e.lineTo(0,c),e.arc(c,c,c,Math.PI,3*Math.PI/2,!1),e.clip());const o=g?function(e,t){var r,o;const i=T(),n=e instanceof HTMLVideoElement?e.videoWidth:e.width,a=e instanceof HTMLVideoElement?e.videoHeight:e.height;i.width=n,i.height=a,null===(r=i.getContext("2d"))||void 0===r||r.drawImage(e,0,0,i.width,i.height);const d=function(e,t,r,o,i,n,a){for(var d=new ImageData(t,r),h=new Int32Array(e.data.buffer),l=e.width,s=new Int32Array(d.data.buffer),c=d.width,u=t/n,g=r/a,f=Math.round(1/u),m=Math.round(1/g),p=f*m,v=0;v<d.height;v++){for(var w=0;w<c;w++){for(var x=0+Math.round(w/u)+(0+Math.round(v/g))*l,M=0,y=0,E=0,b=0,L=0;L<m;L++){for(var T=0;T<f;T++){var C=h[x+T+L*l];M+=C<<24>>>24,y+=C<<16>>>24,E+=C<<8>>>24,b+=C>>>24}}M=Math.round(M/p),y=Math.round(y/p),E=Math.round(E/p),b=Math.round(b/p),s[w+v*c]=b<<24|E<<16|y<<8|M}}return d}(i.getContext("2d").getImageData(0,0,i.width,i.height),Math.floor(i.width*t),Math.floor(i.height*t),0,0,i.width,i.height);return i.width=Math.floor(i.width*t),i.height=Math.floor(i.height*t),null===(o=i.getContext("2d"))||void 0===o||o.putImageData(d,0,0),i}(t,u):t,i=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(o,i.x,i.y,i.width,i.height,0,0,w.width,w.height)};return o.useLayoutEffect(()=>{x()},[w,e.width,e.height,r.x,r.y,r.width,r.height,n,i,a,null===(h=e.page)||void 0===h?void 0:h._exportingOrRendering,g]),o.useEffect(()=>()=>{w&&"CANVAS"===w.nodeName&&f.Util.releaseCanvas(w)},[w]),[w||t,x]};const S=T(),I=i(({element:r})=>{const i=Math.min(30,r.width/4,r.height/4),n=o.useRef(null);o.useEffect(()=>{const e=n.current;if(!e){return}const t=new f.Animation(t=>{e.rotate(((null==t?void 0:t.timeDiff)||0)/2)},e.getLayer());return t.start(),()=>{t.stop()}});const{mediaLoadingStyle:h}=p();return t(d,{x:r.a.x,y:r.a.y,rotation:r.a.rotation,listening:!1,opacity:r.a.opacity,hideInExport:!r.showInExport,children:[e(l,{width:r.width,height:r.height,fill:h.fill}),e(a,{ref:n,x:r.width/2,y:r.height/2,fill:h.textFill,outerRadius:Math.abs(i),innerRadius:Math.max(1,i-5),angle:270})]})}),k=i(({element:r})=>{const{mediaErrorStyle:o}=p(),i=Math.max(10,Math.min(30,r.width/25));return t(d,{x:r.a.x,y:r.a.y,rotation:r.a.rotation,listening:!1,opacity:r.a.opacity,hideInExport:!r.showInExport,children:[e(l,{width:r.width,height:r.height,fill:o.fill}),e(s,{text:"Can not load the video...",fontSize:i,width:r.width,height:r.height,align:"center",fill:o.textFill,verticalAlign:"middle",padding:5})]})});let H=function(e,t,r){const i=o.useRef("loading"),n=o.useRef(void 0),[a,d]=o.useState(0),h=o.useRef(void 0),l=o.useRef(void 0),s=o.useRef(void 0);return h.current===e&&l.current===t&&s.current===r||(i.current="loading",n.current=void 0,h.current=e,l.current=t,s.current=r),o.useLayoutEffect(function(){if(e){var o=document.createElement("video");return o.addEventListener("canplay",a),o.addEventListener("error",h),t&&(o.crossOrigin=t),r&&(o.referrerPolicy=r),o.src=e,o.load(),function(){o.removeEventListener("canplay",a),o.removeEventListener("error",h)}}function a(){i.current="loaded",n.current=o,n.current.currentTime=0,d(Math.random()),n.current.removeEventListener("canplay",a)}function h(e){var t;const r=4===o.readyState,a=o.buffered&&o.buffered.length>0&&o.buffered.end(o.buffered.length-1)/o.duration*100>=100;if(r&&a){return}const h=e.message||(null===(t=o.error)||void 0===t?void 0:t.message)||"Unknown error",l=new Error("Video failed to load: "+h);console.error(l),i.current="failed",n.current=void 0,d(Math.random())}},[e,t,r]),[n.current,i.current]};export const setVideoLoaderHook=e=>{H=e};function X(e){return e.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA}export const useLoader=(e,t,r)=>{const i=o.useRef(void 0),n=()=>{var e;null===(e=i.current)||void 0===e||e.call(i),i.current=void 0};o.useEffect(()=>n,[]),o.useLayoutEffect(()=>{const o=t.slice(0,200),a=`video with id ${r} url: ${o}`;"loading"!==e||i.current||(i.current=v(a)),"loading"!==e&&n(),"failed"===e&&w(a)},[e])};export const VideoElement=i(({element:i,store:a})=>{var s,p,w;const[M,Y]=o.useState(!1),W=o.useRef(null),O=o.useRef(null),_=i.isSelected,[A,P]=o.useState(!1),[V,D]=H(i.src,"anonymous"),[j,z]=o.useState(!1),B=a.activePage===i.page,U=(null===(s=i.page)||void 0===s?void 0:s._exportingOrRendering)&&"loaded"===D,N=L(i,a,U);useLoader(D,i.src,i.id),V&&(V.playsInline=!0);const F=((e,t,r)=>{const i=o.useMemo(()=>{var o,i;const{flipX:n,flipY:a}=e,d="svg"===e.type||e.src.indexOf("data:image/svg+xml")>=0||e.src.indexOf(".svg")>=0,h=navigator.userAgent.toLowerCase().indexOf("firefox")>-1;if(!(n||a||h&&d)){return t}if(!t){return null}const l=t instanceof HTMLVideoElement?t.videoWidth:null==t?void 0:t.width,s=t instanceof HTMLVideoElement?t.videoHeight:null==t?void 0:t.height;if(!l||!s){return null}const c=T();let u=1;"svg"===e.type&&(u=Math.max(e.width/l*r,e.height/s*r)),c.width=Math.max(l*u,1),c.height=Math.max(s*u,1);let g=n?-c.width:0,f=a?-c.height:0;return null===(o=c.getContext("2d"))||void 0===o||o.scale(n?-1:1,a?-1:1),null===(i=c.getContext("2d"))||void 0===i||i.drawImage(t,g,f,c.width,c.height),c},[e.flipX,e.flipY,t,e.width,e.height,r]);return o.useEffect(()=>()=>{i&&"CANVAS"===i.nodeName&&f.Util.releaseCanvas(i)},[i]),i})(i,V,a._elementsPixelRatio),Z=U&&N||F||S;o.useEffect(()=>{V&&a.history.ignore(()=>{i.set({duration:1e3*V.duration})})},[V]),o.useEffect(()=>{var e;if(!V){return}const t=a.animatedElementsIds,r=(!t.length||t.includes(i.id))&&a.isPlaying,o=B&&(r||A);if(!o){return void V.pause()}o&&(V.currentTime=i.startTime*V.duration,V.play());const n=new f.Animation(()=>{pe.current()},null===(e=W.current)||void 0===e?void 0:e.getLayer());n.start();const d=()=>{P(!1),V.currentTime=i.startTime*V.duration},h=()=>{V.currentTime>=i.endTime*V.duration&&(V.pause(),V.currentTime=i.startTime*V.duration,P(!1))};return V.addEventListener("ended",d),V.addEventListener("timeupdate",h),()=>{V.pause(),n.stop(),V.removeEventListener("ended",d),V.removeEventListener("timeupdate",h)}},[V,A,a.isPlaying,B]),o.useEffect(()=>{V&&(V.volume=i.volume)},[V,i.volume]);const $=o.useRef(null);o.useEffect(()=>{const e=n(()=>{var e,t;if(V){if(U&&N){return me(),void a.currentTime}const r=a.animatedElementsIds;if(r.length&&!r.includes(i.id)){return}const o=a.currentTime>=i.page.startTime&&a.currentTime<i.page.startTime+i.page.duration,n=i.startTime*V.duration*1e3,d=V.duration*(i.endTime-i.startTime)*1e3;let h=((a.currentTime||i.page.startTime)-i.page.startTime)%d+n;if(o||(h=0),Math.abs(1e3*V.currentTime-h)>500||!a.isPlaying){const e=h/1e3;e!==V.currentTime&&(V.currentTime=e),!X(V)&&!a.isPlaying&&!$.current&&($.current=v(`video ${i.id}`))}pe.current(),null===(t=null===(e=W.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()}});return()=>{e(),$.current&&($.current(),$.current=null)}},[a,V,U,N]),o.useEffect(()=>{var e,t;if(!V){return}if(U){return null===(e=$.current)||void 0===e||e.call($),void($.current=null)}const r=()=>{var e,t,r;!X(V)&&(null===(e=i.page)||void 0===e?void 0:e._exportingOrRendering)||$.current&&(pe.current(),null===(r=null===(t=W.current)||void 0===t?void 0:t.getLayer())||void 0===r||r.batchDraw(),$.current(),$.current=null)};let o;return(null===(t=i.page)||void 0===t?void 0:t._exportingOrRendering)&&(o=setInterval(r,20)),V.addEventListener("timeupdate",r),V.addEventListener("canplay",r),()=>{clearInterval(o),V.removeEventListener("timeupdate",r),V.removeEventListener("canplay",r)}},[null===(p=i.page)||void 0===p?void 0:p._exportingOrRendering,V,i.id,v,U]);let{cropX:q,cropY:G,cropWidth:J,cropHeight:K}=i;"loaded"!==D&&(q=G=0,J=K=1);const Q=(ee=Z)instanceof HTMLVideoElement?ee.videoWidth:(null==ee?void 0:ee.width)||0;var ee;const te=(e=>e instanceof HTMLVideoElement?e.videoHeight:(null==e?void 0:e.height)||0)(Z),re=Q*J,oe=te*K,ie=i.width/i.height;let ne,ae;const de=re/oe,he="svg"===i.type;he?(ne=re,ae=oe):ie>=de?(ne=re,ae=re/ie):(ne=oe*ie,ae=oe);const le={x:Q*q,y:te*G,width:ne,height:ae},se=null!==(w=i.cornerRadius)&&void 0!==w?w:0,[ce,ue]=useCornerRadiusAndCrop(i,Z,le,a._elementsPixelRatio,se,!0);let[ge,fe]=((e,t,r,i)=>{const n=(e=>{const[t,r]=o.useState(e);return o.useEffect(()=>{(async()=>{const o=await async function(e){if(!(e.indexOf("data:image/svg+xml")>=0||e.indexOf(".svg")>=0)){return e}const t=await x.urlToString(e),r=x.fixSize(t);return x.svgToURL(r)}(e);o!==t&&r(o)})()},[e]),t})(e.clipSrc||""),[a,d]=g(n,"anonymous"),h=e.clipSrc?d:"loaded";useLoader(h,e.clipSrc,e.id);const l=o.useMemo(()=>{if(t&&a){return T()}},[t,a]);function s(){var o;if(!a){return}const i=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||!i||!n){return}if(!a||!a.width||!a.height){return}if(!l){return}const d=T(),h=Math.max(e.width/a.width*r,e.height/a.height*r);d.width=a.width*h,d.height=a.height*h,null===(o=d.getContext("2d"))||void 0===o||o.drawImage(a,0,0,d.width,d.height),l.width=Math.max(i,1),l.height=Math.max(n,1);const s=l.getContext("2d");s&&(s.save(),s.drawImage(d,0,0,i,n),f.Util.releaseCanvas(d),s.globalCompositeOperation="source-in",s.drawImage(t,0,0,l.width,l.height),s.restore())}return o.useLayoutEffect(()=>{s()},[l,t,a,e.width,e.height,r,...i]),[e.clipSrc&&a?l:t,s]})(i,ce,a._elementsPixelRatio,[le,se,a._elementsPixelRatio]);function me(){var e,t;ue(),fe(),null===(t=null===(e=W.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()}o.useEffect(()=>{me()});const pe=o.useRef(me);pe.current=me;const ve=Math.max(i.width/ne,i.height/ae);o.useEffect(()=>{var e;if(!i._cropModeEnabled){return}const t=null===(e=W.current)||void 0===e?void 0:e.getStage();function r(e){i._cropModeEnabled&&e.target!==O.current&&i.toggleCropMode(!1)}function o(e){i._cropModeEnabled&&e.target.parentNode!==(null==t?void 0:t.content)&&i.toggleCropMode(!1)}return document.body.addEventListener("click",o),null==t||t.on("click",r),null==t||t.on("tap",r),()=>{document.body.removeEventListener("click",o),document.body.removeEventListener("touchstart",o),null==t||t.off("click",r),null==t||t.off("click",r)}},[i._cropModeEnabled]),o.useLayoutEffect(()=>{if(!M&&!i._cropModeEnabled){return y(W.current,i),n(()=>{y(W.current,i)},{delay:100})}},[Z,M,J,K,i._cropModeEnabled]),o.useLayoutEffect(()=>{var e;M||i._cropModeEnabled?null===(e=W.current)||void 0===e||e.clearCache():y(W.current,i)},[M,i.width,i.height,i._cropModeEnabled]),o.useEffect(()=>{y(W.current,i)},[i.shadowEnabled,i.shadowBlur,i.cornerRadius,i.shadowColor,i.shadowOffsetX,i.shadowOffsetY,i.shadowOpacity]);const we=o.useRef(null),xe=o.useRef(null),Me=o.useRef(null);o.useLayoutEffect(()=>{i._cropModeEnabled&&(xe.current.nodes([we.current]),Me.current.nodes([O.current]))},[i._cropModeEnabled]);const ye=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(),o=Math.min(1,ne/t),n=Math.min(1,ae/r),a=1-o,d=Math.min(a,Math.max(0,Math.round(-e.target.x())/t)),h=1-n,l=Math.min(h,Math.max(0,Math.round(-e.target.y())/r));e.target.setAttrs({x:-d*Q,y:-l*te,scaleX:1,scaleY:1}),i.set({cropX:d,cropY:l,cropWidth:o,cropHeight:n})},Ee=()=>{"svg"!==i.type&&i.contentEditable&&setTimeout(()=>{i.toggleCropMode(!0)})},be="loading"===D,Le="failed"===D,Te=!be&&!Le,Ce=o.useRef({cropX:0,cropY:0,cropWidth:0,cropHeight:0}),Re=Te?i.a.opacity:0;E(W,Re);const Se=i.selectable||a.role===u.ADMIN,Ie=b();return e(r,{children:t(d,{onMouseEnter:()=>z(!0),onMouseLeave:()=>z(!1),children:[be&&e(I,{element:i}),Le&&e(k,{element:i}),e(h,{ref:W,name:"element",id:i.id,image:ge,x:i.a.x,y:i.a.y,width:i.a.width||1,height:i.a.height||1,rotation:i.a.rotation,opacity:Re,shadowEnabled:i.shadowEnabled,shadowBlur:i.shadowBlur,shadowOffsetX:i.shadowOffsetX,shadowOffsetY:i.shadowOffsetY,shadowColor:i.shadowColor,shadowOpacity:i.shadowOpacity,customCrop:le,listening:Se,draggable:Ie?i.draggable&&_:i.draggable,preventDefault:!Ie||_,hideInExport:!i.showInExport,onDragMove:e=>{i.set({x:e.target.x(),y:e.target.y()})},onDragEnd:e=>{i.set({x:e.target.x(),y:e.target.y()})},onDblClick:Ee,onDblTap:Ee,onTransformStart:()=>{Y(!0),Ce.current={cropX:i.cropX,cropY:i.cropY,cropWidth:i.cropWidth,cropHeight:i.cropHeight}},onTransform:e=>{var t;const r=e.currentTarget,o=Math.abs(r.scaleX()-1)<1e-7?1:r.scaleX(),n=Math.abs(r.scaleY()-1)<1e-7?1:r.scaleY();r.scaleX(1),r.scaleY(1);const a=null===(t=e.target.getStage())||void 0===t?void 0:t.findOne("Transformer"),d=1-ne/Q,h=Math.min(d,Math.max(0,i.cropX)),l=1-ae/te,s=Math.min(l,Math.max(0,i.cropY)),c=a.getActiveAnchor(),u=!(c.indexOf("middle")>=0||c.indexOf("center")>=0),g=!u&&o<1&&Ce.current.cropHeight>ae/te;let f=u?i.cropWidth:i.cropWidth*o;g&&(f=i.cropWidth);const m=!u&&n<1&&Ce.current.cropWidth>ne/Q;let p=u?i.cropHeight:i.cropHeight*n;m&&(p=i.cropHeight),he&&(f=i.cropWidth,p=i.cropHeight),i.set({cropX:h,cropY:s,x:r.x(),y:r.y(),width:r.width()*o,height:r.height()*n,rotation:e.target.rotation(),cropWidth:Math.min(f,1-h),cropHeight:Math.min(p,1-s)})},onTransformEnd:e=>{const t=e.currentTarget;i.set({width:t.width(),height:t.height(),x:t.x(),y:t.y(),rotation:e.target.rotation(),cropWidth:ne/Q,cropHeight:ae/te}),Y(!1)}}),e(l,{x:i.a.x,y:i.a.y,width:Math.max(i.a.width-i.borderSize,0),height:Math.max(i.a.height-i.borderSize,0),opacity:Re,offsetX:-i.borderSize/2,offsetY:-i.borderSize/2,stroke:i.borderColor,strokeWidth:i.borderSize,listening:!1,visible:!!i.borderSize,rotation:i.rotation,cornerRadius:Math.max(0,se-i.borderSize),hideInExport:!i.showInExport}),!a.isPlaying&&e(h,{image:A?j||Ie?R:void 0:C,x:i.a.x,y:i.a.y,offsetX:-i.a.width/2+15/a.scale,offsetY:-i.a.height/2+15/a.scale,rotation:i.a.rotation,width:30/a.scale,height:30/a.scale,hideInExport:!0,onClick:()=>P(!A),onTap:()=>P(!A)}),i._cropModeEnabled&&t(m,{selector:".page-abs-container",enabled:!0,children:[e(l,{x:-window.innerWidth/a.scale,y:-window.innerWidth/a.scale,width:window.innerWidth/a.scale*3,height:window.innerWidth/a.scale*3,fill:"rgba(0,0,0,0.3)"}),e(h,{listening:!1,image:ge,x:i.a.x,y:i.a.y,width:i.a.width,height:i.a.height,rotation:i.a.rotation,shadowEnabled:i.shadowEnabled,shadowBlur:i.shadowBlur}),t(d,{x:i.a.x,y:i.a.y,rotation:i.a.rotation,scaleX:ve,scaleY:ve,children:[e(h,{image:Z,ref:O,width:Q,height:te,opacity:.4,draggable:!0,x:-i.cropX*Q,y:-i.cropY*te,onDragMove:ye,onTransform:ye}),e(c,{ref:Me,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(l,{width:ne,height:ae,ref:we,listening:!1,onTransform:e=>{e.target.x()<-i.cropX*Q-1e-9&&(e.target.x(-i.cropX*Q),e.target.scaleX(1)),e.target.y()<-i.cropY*te-1e-9&&(e.target.y(-i.cropY*te),e.target.scaleY(1));const t=Math.min(1,Math.max(0,i.cropX+e.target.x()/Q)),r=Math.min(1,Math.max(0,e.target.y()/te+i.cropY)),o=e.target.width()*e.target.scaleX(),n=e.target.height()*e.target.scaleY(),a=Math.min(1-t,o/Q),d=Math.min(1-r,n/te),h=e.target.getAbsolutePosition(e.target.getParent().getParent());e.target.scale({x:1,y:1}),e.target.position({x:0,y:0}),i.set({x:h.x,y:h.y,cropX:t,cropY:r,cropWidth:a,cropHeight:d,width:Math.min(o*ve,Q*(1-t)*ve),height:Math.min(n*ve,te*(1-r)*ve)})}}),e(c,{ref:xe,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:i.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{autorun as n}from"mobx";import{Arc as a,Group as d,Image as h,Rect as s,Text as l,Transformer as c}from"react-konva";import{ROLES as u}from"../model/store.js";import g from"use-image";import f from"konva";import{Portal as m}from"react-konva-utils";import{useWorkspaceStyle as p}from"./workspace-style.js";import{incrementLoader as v,triggerLoadError as w}from"../utils/loader.js";import*as x from"../utils/svg.js";import{flags as M}from"../utils/flags.js";import{applyFilter as y}from"./apply-filters.js";import{useFadeIn as E}from"./use-fadein.js";import{isTouchDevice as b}from"../utils/screen.js";import{useMediabunnyVideo as L}from"./use-mediabunny-video.js";import{getElementTimeRange as T,getVideoRestMs as C}from"../utils/timeline.js";function R(){return document.createElement("canvas")}const S=new window.Image;S.src=x.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 I=new window.Image;I.src=x.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,h;const s=Math.floor(Math.max(e.width*o,1)),l=Math.floor(Math.max(e.height*o,1)),c=Math.min(n*o,s/2,l/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)&&M.imageDownScalingEnabled&&u<1&&!a,m=t instanceof HTMLVideoElement?t.videoWidth:null==t?void 0:t.width,p=t instanceof HTMLVideoElement?t.videoHeight:null==t?void 0:t.height,v=0===r.x&&0===r.y&&r.width===m&&r.height===p,w=i.useMemo(()=>{if(t&&m&&p){return v&&0===c&&!g?void 0:R()}},[t,c,g,v,m,p]),x=()=>{if(!w||!t){return}w.width=s,w.height=l;const e=w.getContext("2d");if(!e){return}c&&(e.beginPath(),e.moveTo(c,0),e.lineTo(s-c,0),e.arc(s-c,c,c,3*Math.PI/2,0,!1),e.lineTo(s,l-c),e.arc(s-c,l-c,c,0,Math.PI/2,!1),e.lineTo(c,l),e.arc(c,l-c,c,Math.PI/2,Math.PI,!1),e.lineTo(0,c),e.arc(c,c,c,Math.PI,3*Math.PI/2,!1),e.clip());const i=g?function(e,t){var r,i;const o=R(),n=e instanceof HTMLVideoElement?e.videoWidth:e.width,a=e instanceof HTMLVideoElement?e.videoHeight:e.height;o.width=n,o.height=a,null===(r=o.getContext("2d"))||void 0===r||r.drawImage(e,0,0,o.width,o.height);const d=function(e,t,r,i,o,n,a){for(var d=new ImageData(t,r),h=new Int32Array(e.data.buffer),s=e.width,l=new Int32Array(d.data.buffer),c=d.width,u=t/n,g=r/a,f=Math.round(1/u),m=Math.round(1/g),p=f*m,v=0;v<d.height;v++){for(var w=0;w<c;w++){for(var x=0+Math.round(w/u)+(0+Math.round(v/g))*s,M=0,y=0,E=0,b=0,L=0;L<m;L++){for(var T=0;T<f;T++){var C=h[x+T+L*s];M+=C<<24>>>24,y+=C<<16>>>24,E+=C<<8>>>24,b+=C>>>24}}M=Math.round(M/p),y=Math.round(y/p),E=Math.round(E/p),b=Math.round(b/p),l[w+v*c]=b<<24|E<<16|y<<8|M}}return d}(o.getContext("2d").getImageData(0,0,o.width,o.height),Math.floor(o.width*t),Math.floor(o.height*t),0,0,o.width,o.height);return o.width=Math.floor(o.width*t),o.height=Math.floor(o.height*t),null===(i=o.getContext("2d"))||void 0===i||i.putImageData(d,0,0),o}(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===(h=e.page)||void 0===h?void 0:h._exportingOrRendering,g]),i.useEffect(()=>()=>{w&&"CANVAS"===w.nodeName&&f.Util.releaseCanvas(w)},[w]),[w||t,x]};const k=R(),H=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 f.Animation(t=>{e.rotate(((null==t?void 0:t.timeDiff)||0)/2)},e.getLayer());return t.start(),()=>{t.stop()}});const{mediaLoadingStyle:h}=p();return t(d,{x:r.a.x,y:r.a.y,rotation:r.a.rotation,listening:!1,opacity:r.a.opacity,hideInExport:!r.showInExport,children:[e(s,{width:r.width,height:r.height,fill:h.fill}),e(a,{ref:n,x:r.width/2,y:r.height/2,fill:h.textFill,outerRadius:Math.abs(o),innerRadius:Math.max(1,o-5),angle:270})]})}),X=o(({element:r})=>{const{mediaErrorStyle:i}=p(),o=Math.max(10,Math.min(30,r.width/25));return t(d,{x:r.a.x,y:r.a.y,rotation:r.a.rotation,listening:!1,opacity:r.a.opacity,hideInExport:!r.showInExport,children:[e(s,{width:r.width,height:r.height,fill:i.fill}),e(l,{text:"Can not load the video...",fontSize:o,width:r.width,height:r.height,align:"center",fill:i.textFill,verticalAlign:"middle",padding:5})]})});let Y=function(e,t,r){const o=i.useRef("loading"),n=i.useRef(void 0),[a,d]=i.useState(0),h=i.useRef(void 0),s=i.useRef(void 0),l=i.useRef(void 0);return h.current===e&&s.current===t&&l.current===r||(o.current="loading",n.current=void 0,h.current=e,s.current=t,l.current=r),i.useLayoutEffect(function(){if(e){var i=document.createElement("video");return i.addEventListener("canplay",a),i.addEventListener("error",h),t&&(i.crossOrigin=t),r&&(i.referrerPolicy=r),i.src=e,i.load(),function(){i.removeEventListener("canplay",a),i.removeEventListener("error",h)}}function a(){o.current="loaded",n.current=i,n.current.currentTime=0,d(Math.random()),n.current.removeEventListener("canplay",a)}function h(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 h=e.message||(null===(t=i.error)||void 0===t?void 0:t.message)||"Unknown error",s=new Error("Video failed to load: "+h);console.error(s),o.current="failed",n.current=void 0,d(Math.random())}},[e,t,r]),[n.current,o.current]};export const setVideoLoaderHook=e=>{Y=e};function W(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=v(a)),"loading"!==e&&n(),"failed"===e&&w(a)},[e])};export const VideoElement=o(({element:o,store:a})=>{var l,p,w;const[M,O]=i.useState(!1),P=i.useRef(null),_=i.useRef(null),A=o.isSelected,[V,j]=i.useState(!1),[D,z]=Y(o.src,"anonymous"),[B,U]=i.useState(!1),N=a.activePage===o.page,F=(null===(l=o.page)||void 0===l?void 0:l._exportingOrRendering)&&"loaded"===z,Z=L(o,a,F);useLoader(z,o.src,o.id),D&&(D.playsInline=!0);const $=((e,t,r)=>{const o=i.useMemo(()=>{var i,o;const{flipX:n,flipY:a}=e,d="svg"===e.type||e.src.indexOf("data:image/svg+xml")>=0||e.src.indexOf(".svg")>=0,h=navigator.userAgent.toLowerCase().indexOf("firefox")>-1;if(!(n||a||h&&d)){return t}if(!t){return null}const s=t instanceof HTMLVideoElement?t.videoWidth:null==t?void 0:t.width,l=t instanceof HTMLVideoElement?t.videoHeight:null==t?void 0:t.height;if(!s||!l){return null}const c=R();let u=1;"svg"===e.type&&(u=Math.max(e.width/s*r,e.height/l*r)),c.width=Math.max(s*u,1),c.height=Math.max(l*u,1);let g=n?-c.width:0,f=a?-c.height:0;return null===(i=c.getContext("2d"))||void 0===i||i.scale(n?-1:1,a?-1:1),null===(o=c.getContext("2d"))||void 0===o||o.drawImage(t,g,f,c.width,c.height),c},[e.flipX,e.flipY,t,e.width,e.height,r]);return i.useEffect(()=>()=>{o&&"CANVAS"===o.nodeName&&f.Util.releaseCanvas(o)},[o]),o})(o,D,a._elementsPixelRatio),q=F&&Z||$||k;i.useEffect(()=>{D&&a.history.ignore(()=>{o.set({duration:1e3*D.duration})})},[D]),i.useEffect(()=>{var e;if(!D){return}const t=a.animatedElementsIds,r=(!t.length||t.includes(o.id))&&a.isPlaying;if(!N||!r&&!V){return void D.pause()}V&&(D.muted=!1,D.currentTime=o.startTime*D.duration,D.play());const i=new f.Animation(()=>{we.current()},null===(e=P.current)||void 0===e?void 0:e.getLayer());i.start();const n=()=>{j(!1),D.currentTime=o.startTime*D.duration},d=()=>{D.currentTime>=o.endTime*D.duration&&(D.pause(),D.currentTime=o.startTime*D.duration,j(!1))};return D.addEventListener("ended",n),D.addEventListener("timeupdate",d),()=>{D.pause(),i.stop(),D.removeEventListener("ended",n),D.removeEventListener("timeupdate",d)}},[D,V,a.isPlaying,N]),i.useEffect(()=>{D&&(D.volume=o.volume)},[D,o.volume]),i.useEffect(()=>{D&&(D.playbackRate=o.speed,D.preservesPitch=!1)},[D,o.speed]);const G=i.useRef(null);i.useEffect(()=>{const e=n(()=>{var e,t;if(D){if(F&&Z){return ve(),void a.currentTime}const r=a.animatedElementsIds;if(r.length&&!r.includes(o.id)){return}const i=a.activePage===o.page,n=a.currentTime>=o.page.startTime&&a.currentTime<o.page.startTime+o.page.duration,d=o.startTime*D.duration*1e3,h=D.duration*(o.endTime-o.startTime)*1e3,{start:s,end:l}=T(o.animations,o.page.duration),c=(a.currentTime||o.page.startTime)-o.page.startTime,u=n?C(a.currentTime,o.page.startTime,s,h,d,o.speed):0,g=u/1e3,f=n&&c>=s&&c<l;V||(D.muted=!f,f&&a.isPlaying&&i?D.paused?(D.currentTime=g,D.play()):Math.abs(1e3*D.currentTime-u)>500&&(D.currentTime=g):(D.paused||D.pause(),g!==D.currentTime&&(D.currentTime=g),!W(D)&&!a.isPlaying&&!G.current&&(G.current=v(`video ${o.id}`)))),we.current(),null===(t=null===(e=P.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()}});return()=>{e(),G.current&&(G.current(),G.current=null)}},[a,D,F,Z,V]),i.useEffect(()=>{var e,t;if(!D){return}if(F){return null===(e=G.current)||void 0===e||e.call(G),void(G.current=null)}const r=()=>{var e,t,r;!W(D)&&(null===(e=o.page)||void 0===e?void 0:e._exportingOrRendering)||G.current&&(we.current(),null===(r=null===(t=P.current)||void 0===t?void 0:t.getLayer())||void 0===r||r.batchDraw(),G.current(),G.current=null)};let i;return(null===(t=o.page)||void 0===t?void 0:t._exportingOrRendering)&&(i=setInterval(r,20)),D.addEventListener("timeupdate",r),D.addEventListener("canplay",r),()=>{clearInterval(i),D.removeEventListener("timeupdate",r),D.removeEventListener("canplay",r)}},[null===(p=o.page)||void 0===p?void 0:p._exportingOrRendering,D,o.id,v,F]);let{cropX:J,cropY:K,cropWidth:Q,cropHeight:ee}=o;"loaded"!==z&&(J=K=0,Q=ee=1);const te=(re=q)instanceof HTMLVideoElement?re.videoWidth:(null==re?void 0:re.width)||0;var re;const ie=(e=>e instanceof HTMLVideoElement?e.videoHeight:(null==e?void 0:e.height)||0)(q),oe=te*Q,ne=ie*ee,ae=o.width/o.height;let de,he;const se=oe/ne,le="svg"===o.type;le?(de=oe,he=ne):ae>=se?(de=oe,he=oe/ae):(de=ne*ae,he=ne);const ce={x:te*J,y:ie*K,width:de,height:he},ue=null!==(w=o.cornerRadius)&&void 0!==w?w:0,[ge,fe]=useCornerRadiusAndCrop(o,q,ce,a._elementsPixelRatio,ue,!0);let[me,pe]=((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.indexOf("data:image/svg+xml")>=0||e.indexOf(".svg")>=0)){return e}const t=await x.urlToString(e),r=x.fixSize(t);return x.svgToURL(r)}(e);i!==t&&r(i)})()},[e]),t})(e.clipSrc||""),[a,d]=g(n,"anonymous"),h=e.clipSrc?d:"loaded";useLoader(h,e.clipSrc,e.id);const s=i.useMemo(()=>{if(t&&a){return R()}},[t,a]);function l(){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(!s){return}const d=R(),h=Math.max(e.width/a.width*r,e.height/a.height*r);d.width=a.width*h,d.height=a.height*h,null===(i=d.getContext("2d"))||void 0===i||i.drawImage(a,0,0,d.width,d.height),s.width=Math.max(o,1),s.height=Math.max(n,1);const l=s.getContext("2d");l&&(l.save(),l.drawImage(d,0,0,o,n),f.Util.releaseCanvas(d),l.globalCompositeOperation="source-in",l.drawImage(t,0,0,s.width,s.height),l.restore())}return i.useLayoutEffect(()=>{l()},[s,t,a,e.width,e.height,r,...o]),[e.clipSrc&&a?s:t,l]})(o,ge,a._elementsPixelRatio,[ce,ue,a._elementsPixelRatio]);function ve(){var e,t;fe(),pe(),null===(t=null===(e=P.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()}i.useEffect(()=>{ve()});const we=i.useRef(ve);we.current=ve;const xe=Math.max(o.width/de,o.height/he);i.useEffect(()=>{var e;if(!o._cropModeEnabled){return}const t=null===(e=P.current)||void 0===e?void 0:e.getStage();function r(e){o._cropModeEnabled&&e.target!==_.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]),i.useLayoutEffect(()=>{if(!M&&!o._cropModeEnabled){return y(P.current,o),n(()=>{y(P.current,o)},{delay:100})}},[q,M,Q,ee,o._cropModeEnabled]),i.useLayoutEffect(()=>{var e;M||o._cropModeEnabled?null===(e=P.current)||void 0===e||e.clearCache():y(P.current,o)},[M,o.width,o.height,o._cropModeEnabled]),i.useEffect(()=>{y(P.current,o)},[o.shadowEnabled,o.shadowBlur,o.cornerRadius,o.shadowColor,o.shadowOffsetX,o.shadowOffsetY,o.shadowOpacity]);const Me=i.useRef(null),ye=i.useRef(null),Ee=i.useRef(null);i.useLayoutEffect(()=>{o._cropModeEnabled&&(ye.current.nodes([Me.current]),Ee.current.nodes([_.current]))},[o._cropModeEnabled]);const be=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,de/t),n=Math.min(1,he/r),a=1-i,d=Math.min(a,Math.max(0,Math.round(-e.target.x())/t)),h=1-n,s=Math.min(h,Math.max(0,Math.round(-e.target.y())/r));e.target.setAttrs({x:-d*te,y:-s*ie,scaleX:1,scaleY:1}),o.set({cropX:d,cropY:s,cropWidth:i,cropHeight:n})},Le=()=>{"svg"!==o.type&&o.contentEditable&&setTimeout(()=>{o.toggleCropMode(!0)})},Te="loading"===z,Ce="failed"===z,Re=!Te&&!Ce,Se=i.useRef({cropX:0,cropY:0,cropWidth:0,cropHeight:0}),Ie=Re?o.a.opacity:0;E(P,Ie);const ke=o.selectable||a.role===u.ADMIN,He=b();return e(r,{children:t(d,{onMouseEnter:()=>U(!0),onMouseLeave:()=>U(!1),children:[Te&&e(H,{element:o}),Ce&&e(X,{element:o}),e(h,{ref:P,name:"element",id:o.id,image:me,x:o.a.x,y:o.a.y,width:o.a.width||1,height:o.a.height||1,rotation:o.a.rotation,opacity:Ie,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity,customCrop:ce,listening:ke,draggable:He?o.draggable&&A:o.draggable,preventDefault:!He||A,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:Le,onDblTap:Le,onTransformStart:()=>{O(!0),Se.current={cropX:o.cropX,cropY:o.cropY,cropWidth:o.cropWidth,cropHeight:o.cropHeight}},onTransform:e=>{var t;const r=e.currentTarget,i=Math.abs(r.scaleX()-1)<1e-7?1:r.scaleX(),n=Math.abs(r.scaleY()-1)<1e-7?1:r.scaleY();r.scaleX(1),r.scaleY(1);const a=null===(t=e.target.getStage())||void 0===t?void 0:t.findOne("Transformer"),d=1-de/te,h=Math.min(d,Math.max(0,o.cropX)),s=1-he/ie,l=Math.min(s,Math.max(0,o.cropY)),c=a.getActiveAnchor(),u=!(c.indexOf("middle")>=0||c.indexOf("center")>=0),g=!u&&i<1&&Se.current.cropHeight>he/ie;let f=u?o.cropWidth:o.cropWidth*i;g&&(f=o.cropWidth);const m=!u&&n<1&&Se.current.cropWidth>de/te;let p=u?o.cropHeight:o.cropHeight*n;m&&(p=o.cropHeight),le&&(f=o.cropWidth,p=o.cropHeight),o.set({cropX:h,cropY:l,x:r.x(),y:r.y(),width:r.width()*i,height:r.height()*n,rotation:e.target.rotation(),cropWidth:Math.min(f,1-h),cropHeight:Math.min(p,1-l)})},onTransformEnd:e=>{const t=e.currentTarget;o.set({width:t.width(),height:t.height(),x:t.x(),y:t.y(),rotation:e.target.rotation(),cropWidth:de/te,cropHeight:he/ie}),O(!1)}}),e(s,{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:Ie,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,ue-o.borderSize),hideInExport:!o.showInExport}),!a.isPlaying&&e(h,{image:V?B||He?I:void 0:S,x:o.a.x,y:o.a.y,offsetX:-o.a.width/2+15/a.scale,offsetY:-o.a.height/2+15/a.scale,rotation:o.a.rotation,width:30/a.scale,height:30/a.scale,hideInExport:!0,onClick:()=>j(!V),onTap:()=>j(!V)}),o._cropModeEnabled&&t(m,{selector:".page-abs-container",enabled:!0,children:[e(s,{x:-window.innerWidth/a.scale,y:-window.innerWidth/a.scale,width:window.innerWidth/a.scale*3,height:window.innerWidth/a.scale*3,fill:"rgba(0,0,0,0.3)"}),e(h,{listening:!1,image:me,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(d,{x:o.a.x,y:o.a.y,rotation:o.a.rotation,scaleX:xe,scaleY:xe,children:[e(h,{image:q,ref:_,width:te,height:ie,opacity:.4,draggable:!0,x:-o.cropX*te,y:-o.cropY*ie,onDragMove:be,onTransform:be}),e(c,{ref:Ee,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(s,{width:de,height:he,ref:Me,listening:!1,onTransform:e=>{e.target.x()<-o.cropX*te-1e-9&&(e.target.x(-o.cropX*te),e.target.scaleX(1)),e.target.y()<-o.cropY*ie-1e-9&&(e.target.y(-o.cropY*ie),e.target.scaleY(1));const t=Math.min(1,Math.max(0,o.cropX+e.target.x()/te)),r=Math.min(1,Math.max(0,e.target.y()/ie+o.cropY)),i=e.target.width()*e.target.scaleX(),n=e.target.height()*e.target.scaleY(),a=Math.min(1-t,i/te),d=Math.min(1-r,n/ie),h=e.target.getAbsolutePosition(e.target.getParent().getParent());e.target.scale({x:1,y:1}),e.target.position({x:0,y:0}),o.set({x:h.x,y:h.y,cropX:t,cropY:r,cropWidth:a,cropHeight:d,width:Math.min(i*xe,te*(1-t)*xe),height:Math.min(n*xe,ie*(1-r)*xe)})}}),e(c,{ref:ye,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})]})]})]})})});
@@ -7,6 +7,7 @@ export declare const Audio: import("mobx-state-tree").IModelType<{
7
7
  endTime: import("mobx-state-tree").IType<number | undefined, number, number>;
8
8
  volume: import("mobx-state-tree").IType<number | undefined, number, number>;
9
9
  delay: import("mobx-state-tree").IType<number | undefined, number, number>;
10
+ speed: import("mobx-state-tree").IType<number | undefined, number, number>;
10
11
  custom: import("mobx-state-tree").IType<any, any, any>;
11
12
  }, {
12
13
  readonly visibleDuration: number;
@@ -19,6 +20,7 @@ export declare const Audio: import("mobx-state-tree").IModelType<{
19
20
  endTime: number;
20
21
  volume: number;
21
22
  delay: number;
23
+ speed: number;
22
24
  custom: any;
23
25
  };
24
26
  } & {
@@ -1 +1 @@
1
- import{types as e,getSnapshot as t}from"mobx-state-tree";export const Audio=e.model("Audio",{id:e.identifier,src:"",duration:0,startTime:0,endTime:1,volume:1,delay:0,custom:e.frozen()}).views(e=>({get visibleDuration(){return(e.endTime-e.startTime)*e.duration}})).actions(e=>({toJSON:()=>Object.assign({},t(e))})).actions(e=>({set(t){Object.assign(e,t)}}));
1
+ import{types as e,getSnapshot as t}from"mobx-state-tree";export const Audio=e.model("Audio",{id:e.identifier,src:"",duration:0,startTime:0,endTime:1,volume:1,delay:0,speed:1,custom:e.frozen()}).views(e=>({get visibleDuration(){return(e.endTime-e.startTime)*e.duration/e.speed}})).actions(e=>({toJSON:()=>Object.assign({},t(e))})).actions(e=>({set(t){Object.assign(e,t)}}));
@@ -813,6 +813,7 @@ export declare const TYPES_MAP: {
813
813
  startTime: import("mobx-state-tree").IType<number | undefined, number, number>;
814
814
  endTime: import("mobx-state-tree").IType<number | undefined, number, number>;
815
815
  volume: import("mobx-state-tree").IType<number | undefined, number, number>;
816
+ speed: import("mobx-state-tree").IType<number | undefined, number, number>;
816
817
  }, {
817
818
  readonly page: any;
818
819
  readonly store: any;
@@ -752,6 +752,7 @@ export declare const Page: import("mobx-state-tree").IModelType<{
752
752
  startTime: import("mobx-state-tree").IType<number | undefined, number, number>;
753
753
  endTime: import("mobx-state-tree").IType<number | undefined, number, number>;
754
754
  volume: import("mobx-state-tree").IType<number | undefined, number, number>;
755
+ speed: import("mobx-state-tree").IType<number | undefined, number, number>;
755
756
  }, {
756
757
  readonly page: any;
757
758
  readonly store: any;
package/model/schema.d.ts CHANGED
@@ -1,253 +1,20 @@
1
- export interface Store {
2
- schemaVersion: number;
3
- width: number;
4
- height: number;
5
- unit: 'px' | 'pt' | 'mm' | 'cm' | 'in';
6
- dpi: number;
7
- custom?: unknown;
8
- fonts: Font[];
9
- pages: Page[];
10
- audios: Audio[];
11
- }
12
- export interface FontStyleVariant {
13
- src: string;
14
- fontStyle?: string;
15
- fontWeight?: string;
16
- }
17
- export interface Font {
18
- fontFamily: string;
19
- url?: string;
20
- styles?: FontStyleVariant[];
21
- }
22
- export interface Audio {
23
- id: string;
24
- src: string;
25
- duration: number;
26
- startTime: number;
27
- endTime: number;
28
- volume: number;
29
- delay: number;
30
- }
31
- export interface Page {
32
- id: string;
33
- width: number | 'auto';
34
- height: number | 'auto';
35
- background: string;
36
- bleed: number;
37
- custom?: unknown;
38
- duration: number;
39
- children: Element[];
40
- }
41
- export type Element = TextElement | ImageElement | SVGElement | LineElement | VideoElement | FigureElement | GifElement | GroupElement | TableElement;
42
- export interface Animation {
43
- delay: number;
44
- duration: number;
45
- enabled: boolean;
46
- type: 'enter' | 'exit' | 'loop';
47
- name: string;
48
- data: unknown;
49
- }
50
- interface ShapeAttributes {
51
- id: string;
52
- type: string;
53
- name?: string;
54
- custom?: unknown;
55
- x: number;
56
- y: number;
57
- width: number;
58
- height: number;
59
- rotation: number;
60
- opacity: number;
61
- animations: Animation[];
62
- blurEnabled: boolean;
63
- blurRadius: number;
64
- brightnessEnabled: boolean;
65
- brightness: number;
66
- sepiaEnabled: boolean;
67
- grayscaleEnabled: boolean;
68
- filters: Record<string, {
69
- intensity: number;
70
- }>;
71
- shadowEnabled: boolean;
72
- shadowBlur: number;
73
- shadowOffsetX: number;
74
- shadowOffsetY: number;
75
- shadowColor: string;
76
- shadowOpacity: number;
77
- visible: boolean;
78
- draggable: boolean;
79
- resizable: boolean;
80
- selectable: boolean;
81
- contentEditable: boolean;
82
- styleEditable: boolean;
83
- alwaysOnTop: boolean;
84
- showInExport: boolean;
85
- }
86
- export interface GroupElement {
87
- id: string;
88
- type: 'group';
89
- name?: string;
90
- custom?: unknown;
91
- opacity?: number;
92
- visible?: boolean;
93
- selectable?: boolean;
94
- removable?: boolean;
95
- alwaysOnTop?: boolean;
96
- showInExport?: boolean;
97
- animations?: Animation[];
98
- children: Element[];
99
- }
100
- export interface TextElement extends ShapeAttributes {
101
- type: 'text';
102
- text: string;
103
- placeholder: string;
104
- fontSize: number;
105
- fontFamily: string;
106
- fontStyle: string;
107
- fontWeight: string;
108
- textDecoration: string;
109
- textTransform: string;
110
- fill: string;
111
- align: 'left' | 'center' | 'right' | 'justify';
112
- height: number;
113
- verticalAlign: string;
114
- strokeWidth: number;
115
- stroke: string;
116
- lineHeight: number | string;
117
- letterSpacing: number;
118
- backgroundEnabled: boolean;
119
- backgroundColor: string;
120
- backgroundOpacity: number;
121
- backgroundCornerRadius: number;
122
- backgroundPadding: number;
123
- curveEnabled: boolean;
124
- curvePower: number;
125
- }
126
- interface BaseImageProps {
127
- src: string;
128
- cropX: number;
129
- cropY: number;
130
- cropWidth: number;
131
- cropHeight: number;
132
- cornerRadius: number;
133
- flipX: boolean;
134
- flipY: boolean;
135
- clipSrc: string;
136
- borderColor: string;
137
- borderSize: number;
138
- keepRatio: boolean;
139
- stretchEnabled: boolean;
140
- }
141
- export interface ImageElement extends ShapeAttributes, BaseImageProps {
142
- type: 'image';
143
- }
144
- export interface SVGElement extends ShapeAttributes {
145
- type: 'svg';
146
- src: string;
147
- maskSrc: string;
148
- cropX: number;
149
- cropY: number;
150
- cropWidth: number;
151
- cropHeight: number;
152
- keepRatio: boolean;
153
- stretchEnabled: boolean;
154
- flipX: boolean;
155
- flipY: boolean;
156
- borderColor: string;
157
- borderSize: number;
158
- cornerRadius: number;
159
- colorsReplace: Record<string, string>;
160
- }
161
- export interface LineElement extends ShapeAttributes {
162
- type: 'line';
163
- color: string;
164
- dash: number[];
165
- startHead: string;
166
- endHead: string;
167
- }
168
- export interface FigureElement extends ShapeAttributes {
169
- type: 'figure';
170
- subType: string;
171
- fill: string;
172
- dash: number[];
173
- strokeWidth: number;
174
- stroke: string;
175
- cornerRadius: number;
176
- }
177
- export interface GifElement extends ShapeAttributes, BaseImageProps {
178
- type: 'gif';
179
- duration: number;
180
- keepRatio: boolean;
181
- }
182
- export interface VideoElement extends ShapeAttributes, BaseImageProps {
183
- type: 'video';
184
- duration: number;
185
- startTime: number;
186
- endTime: number;
187
- volume: number;
188
- }
189
- export interface BorderSide {
190
- color?: string;
191
- width?: number;
192
- style?: 'solid' | 'dashed' | 'dotted' | 'none';
193
- }
194
- export interface CellBorders {
195
- top?: BorderSide;
196
- right?: BorderSide;
197
- bottom?: BorderSide;
198
- left?: BorderSide;
199
- }
200
- export interface TableCell {
201
- id: string;
202
- type: 'tablecell';
203
- text?: string;
204
- opacity?: number;
205
- rowSpan?: number;
206
- colSpan?: number;
207
- mergedInto?: string;
208
- name?: string;
209
- custom?: unknown;
210
- borders?: CellBorders;
211
- fontSize?: number;
212
- fontFamily?: string;
213
- fontWeight?: string;
214
- fontStyle?: string;
215
- textDecoration?: string;
216
- textTransform?: string;
217
- fill?: string;
218
- align?: string;
219
- verticalAlign?: string;
220
- lineHeight?: number | string;
221
- letterSpacing?: number;
222
- strokeWidth?: number;
223
- stroke?: string;
224
- cellBackground?: string;
225
- cellPadding?: number;
226
- }
227
- export interface TableElement extends Omit<ShapeAttributes, 'blurEnabled' | 'blurRadius' | 'brightnessEnabled' | 'brightness' | 'sepiaEnabled' | 'grayscaleEnabled' | 'filters' | 'shadowEnabled' | 'shadowBlur' | 'shadowOffsetX' | 'shadowOffsetY' | 'shadowColor' | 'shadowOpacity'> {
228
- type: 'table';
229
- rows: number;
230
- cols: number;
231
- colWidths: number[];
232
- rowHeights: number[];
233
- cells: TableCell[];
234
- borderColor: string;
235
- borderWidth: number;
236
- borderStyle: 'solid' | 'dashed' | 'dotted' | 'none';
237
- fontSize: number;
238
- fontFamily: string;
239
- fontWeight: string;
240
- fontStyle: string;
241
- textDecoration: string;
242
- textTransform: string;
243
- fill: string;
244
- align: string;
245
- verticalAlign: string;
246
- lineHeight: number | string;
247
- letterSpacing: number;
248
- strokeWidth: number;
249
- stroke: string;
250
- cellBackground: string;
251
- cellPadding: number;
252
- }
253
- export {};
1
+ import type * as Schema from '@polotno/schema';
2
+ export type Store = Schema.Design;
3
+ export type FontStyleVariant = Schema.FontStyleVariant;
4
+ export type Font = Schema.Font;
5
+ export type Audio = Schema.Audio;
6
+ export type Page = Schema.Page;
7
+ export type Element = Schema.Element;
8
+ export type Animation = Schema.Animation;
9
+ export type GroupElement = Schema.GroupElement;
10
+ export type TextElement = Schema.TextElement;
11
+ export type ImageElement = Schema.ImageElement;
12
+ export type SVGElement = Schema.SVGElement;
13
+ export type LineElement = Schema.LineElement;
14
+ export type FigureElement = Schema.FigureElement;
15
+ export type GifElement = Schema.GifElement;
16
+ export type VideoElement = Schema.VideoElement;
17
+ export type BorderSide = Schema.BorderSide;
18
+ export type CellBorders = Schema.CellBorders;
19
+ export type TableCell = Schema.TableCell;
20
+ export type TableElement = Schema.TableElement;