polotno 2.34.0 → 2.34.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/canvas/html-element.js +3 -2
- package/canvas/rules.d.ts +2 -2
- package/canvas/rules.js +6 -6
- package/canvas/use-mediabunny-video.d.ts +3 -0
- package/canvas/use-mediabunny-video.js +1 -0
- package/canvas/use-transformer-snap.js +1 -1
- package/canvas/video-element.js +1 -1
- package/canvas/workspace-canvas.js +1 -1
- package/model/store.d.ts +3 -1
- package/model/store.js +1 -1
- package/package.json +2 -1
- package/polotno.bundle.js +145 -122
- package/utils/canvas.d.ts +21 -0
- package/utils/canvas.js +1 -1
- package/utils/image-dpi.js +1 -1
- package/utils/to-html.js +1 -1
- package/utils/validate-key.js +1 -1
package/canvas/html-element.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import t from"react";import{observer as e}from"mobx-react-lite";import{Group as o,Image as n,Path as i,Rect as r}from"react-konva";import a from"quill";import l from"konva";import*as s from"mobx";import{reaction as c}from"mobx";import{flags as d}from"../utils/flags.js";import{applyFilter as f}from"./apply-filters.js";import{getLineHeight as u,useFontLoader as h,usePrevious as g}from"./text-element.js";import{getCurvePath as m,getDir as p}from"../utils/text-html.js";import{useColor as x}from"./use-color.js";import{detectSize as w,htmlToCanvas as y,isContentWrapping as v}from"../utils/html2canvas.js";import{resetStyleContent as b}from"../utils/reset-style.js";import{useFadeIn as E}from"./use-fadein.js";import{Html as S}from"react-konva-utils";import
|
|
1
|
+
import t from"react";import{observer as e}from"mobx-react-lite";import{Group as o,Image as n,Path as i,Rect as r}from"react-konva";import a from"quill";import l from"konva";import*as s from"mobx";import{reaction as c}from"mobx";import{flags as d}from"../utils/flags.js";import{applyFilter as f}from"./apply-filters.js";import{getLineHeight as u,useFontLoader as h,usePrevious as g}from"./text-element.js";import{getCurvePath as m,getDir as p}from"../utils/text-html.js";import{useColor as x}from"./use-color.js";import{detectSize as w,htmlToCanvas as y,isContentWrapping as v}from"../utils/html2canvas.js";import{resetStyleContent as b}from"../utils/reset-style.js";import{useFadeIn as E}from"./use-fadein.js";import{Html as S}from"react-konva-utils";import F from"../utils/styled.js";import{incrementLoader as k,triggerLoadError as z}from"../utils/loader.js";import{removeTags as O}from"../utils/text.js";import*as C from"../utils/fonts.js";import{isTouchDevice as R}from"../utils/screen.js";import{getLimitedFontSize as T}from"./text-element/max-font-size.js";import{useDelayer as j}from"./use-delayer.js";import{getOptimalCaretColor as M}from"./text-element/caret-color.js";import{getHtml as P}from"../utils/text-html.js";function A(t,e){if(1===e){return t}const o=l.Util.colorToRGBA(t);return o?`rgba(${o.r}, ${o.g}, ${o.b}, ${o.a*e})`:t}function Y(t){const e=(t||"").trim();if("<p><br></p>"===e||"<p></p>"===e){return""}if(e.startsWith("<p>")&&e.endsWith("</p>")){const t=e.slice(3,-4);if(!/(<\/?(p|div|h[1-6]|ul|ol|li|table|thead|tbody|tr|td|blockquote)\b)/i.test(t)){return t}}return t}export const quillRef=s.observable({enabled:!1,currentFormat:{},editor:s.observable.object({instance:null},{},{deep:!1})});const L=F("div",t.forwardRef)`
|
|
2
2
|
.ql-editor {
|
|
3
3
|
outline: none;
|
|
4
4
|
}
|
|
5
5
|
.ql-clipboard {
|
|
6
6
|
pointer-events: none;
|
|
7
|
+
opacity: 0;
|
|
7
8
|
}
|
|
8
9
|
${b}
|
|
9
10
|
strong {
|
|
@@ -12,4 +13,4 @@ import t from"react";import{observer as e}from"mobx-react-lite";import{Group as
|
|
|
12
13
|
.ql-direction-rtl {
|
|
13
14
|
direction: rtl;
|
|
14
15
|
}
|
|
15
|
-
`;let Y=["bold","color","font","italic","size","strike","underline","indent","list","direction"];export const setQuillFormats=t=>{Y=t};export const createQuill=t=>new a(t,{toolbar:!1,keyboard:!1,clipboard:{matchVisual:!1},formats:Y});export const setQuillContent=(t,e)=>{var o=t.clipboard.convert("<div class='ql-editor' style='outline: none;'>"+e+"<p><br></p></div>");t.setContents(o),t.history.clear()};const $=({html:e,onBlur:o,onChange:n,element:i,clickCoords:r})=>{var l;const d=t.useRef(null);t.useEffect(()=>{if(!d.current){return}const t=(i=d.current,new a(i,{toolbar:!1,keyboard:!1,clipboard:{matchVisual:!1},formats:Y}));var i;s.runInAction(()=>{quillRef.editor.instance=t}),window.__polotnoQuill=t,t.on("text-change",()=>{t.getSelection()&&s.runInAction(()=>{quillRef.currentFormat=t.getFormat(t.getSelection())}),setTimeout(()=>{var t;const e=null===(t=d.current)||void 0===t?void 0:t.childNodes[0];if(!e){return}const o=e.innerHTML;n(L(o))},10)}),setQuillContent(t,e),r?setCursorFromCoords(t,r):t.setSelection(0,0,"api"),t.on("selection-change",(e,o,n)=>{e&&s.runInAction(()=>{quillRef.currentFormat=t.getFormat(t.getSelection())})}),d.current.childNodes[0].addEventListener("blur",t=>{var e;if(null===(e=t.relatedTarget)||void 0===e?void 0:e.classList.contains("ql-clipboard")){return}const n=function(t){return!!t&&!!t.closest(".sketch-picker")}(t.relatedTarget);n||o()});const l=d.current.childNodes[0],c=e=>{var o,n;const i=t.getSelection();if(!i||0===i.length){return}const r=t.getText(i.index,i.length).replace(/\n$/,""),a=window.getSelection();let l="";if(a&&a.rangeCount>0){const t=a.getRangeAt(0),e=document.createElement("div");e.appendChild(t.cloneContents()),l=e.innerHTML}null===(o=e.clipboardData)||void 0===o||o.setData("text/plain",r),l&&(null===(n=e.clipboardData)||void 0===n||n.setData("text/html",l)),e.preventDefault()},f=e=>{c(e);const o=t.getSelection();o&&o.length>0&&t.deleteText(o.index,o.length)};return l.addEventListener("copy",c),l.addEventListener("cut",f),()=>{l.removeEventListener("copy",c),l.removeEventListener("cut",f),s.runInAction(()=>{quillRef.editor.instance=null,quillRef.currentFormat={}}),delete window.__polotnoQuill}},[]),t.useEffect(()=>c(()=>i.text,()=>{var t;const o=quillRef.editor.instance;if(!o){return}const n=o.getSelection();L(null===(t=d.current)||void 0===t?void 0:t.childNodes[0].innerHTML)===i.text||(setQuillContent(o,e),n&&(o.setSelection(n.index,n.length),s.runInAction(()=>{quillRef.currentFormat=o.getFormat(o.getSelection())})))},{fireImmediately:!0}),[]),t.useEffect(()=>{window.addEventListener("blur",o);const t=t=>{var e;(null===(e=d.current)||void 0===e?void 0:e.contains(t.target))||o()};return window.addEventListener("touchstart",t),()=>{window.removeEventListener("blur",o),window.removeEventListener("touchstart",t)}},[]);const f={color:i.fill};i.fill.indexOf("gradient")>=0&&(f.backgroundColor=i.fill,f.backgroundImage=i.fill,f.backgroundSize="100% 100%",f.backgroundRepeat="repeat",f.webkitBackgroundClip="text",f.MozBackgroundClip="text",f.WebkitTextFillColor="transparent",f.MozTextFillColor="transparent");const u=M(i);return t.createElement(X,{ref:d,style:Object.assign(Object.assign({},f),{fontSize:i.fontSize,fontWeight:i.fontWeight,textTransform:i.textTransform,width:i.a.width,fontFamily:'"'+i.fontFamily+'"',lineHeight:i.lineHeight,letterSpacing:i.letterSpacing*i.fontSize+"px",textAlign:i.align,opacity:Math.max(i.a.opacity,.2),textShadow:i.shadowEnabled?`${i.shadowOffsetX}px ${i.shadowOffsetY}px ${i.shadowBlur}px ${P(i.shadowColor,null!==(l=i.shadowOpacity)&&void 0!==l?l:1)}`:void 0,caretColor:u}),dir:p(O(i.text))})};function I(t){return!function(t){const e=t.getContext("2d").getImageData(0,0,t.width,t.height).data;for(let o=0;o<e.length;o+=4){if(0!==e[o+3]){return!0}}return!1}(t)}const q=/^((?!chrome|android).)*safari/i.test(navigator.userAgent);export const HTMLElement=e(({element:e,store:a})=>{var c;const p=t.useRef(null),[b,z]=t.useState(),[M,L]=t.useState(!1),[Y,B]=t.useState(!1),D=t.useRef(e.height),W=a.selectedShapes.indexOf(e)>=0&&e.selectable,H=g(W),_=e.fontSize/3,{textVerticalResizeEnabled:N}=d,Q=d.autoDeleteEmptyText,V=g(e.fontFamily),[J]=h(a,e.fontFamily),G=e._editModeEnabled;E(p);const U=J?e.fontFamily:V!==e.fontFamily?V:"Arial",K=x(e).fill,Z=A(e,{fontFamily:U,color:K}),tt=A(e,{fontFamily:U,color:K,forEditor:!0});let{width:et,height:ot}=function(e,o,n){return t.useMemo(()=>w(e),[e,o.width,n])}(Z,e,J);t.useEffect(()=>{if(!J){return}if(!e.height){return void a.history.ignore(()=>{e.set({height:ot})})}const{textOverflow:t}=d;if("change-font-size"!==t||M){"resize"===t&&(N&&e.height<ot&&!M&&a.history.ignore(()=>{e.set({height:ot})}),N||e.height===ot||a.history.ignore(()=>{e.set({height:ot})}))}else{const t=(t=>{let e=t.fontSize;for(let o=1;o<50;o++){const o=A(Object.assign(Object.assign({},t.toJSON()),{fontSize:e}),{fontFamily:t.fontFamily}),{height:n}=w(o);if(!(t.height&&n>t.height||!d.textSplitAllowed&&!t.curveEnabled&&v({html:o}))){break}e-=.5}return e})(e);t!==e.fontSize?a.history.ignore(()=>{e.set({fontSize:t})}):e.height!==ot&&(N&&e.height<ot?a.history.ignore(()=>{e.set({height:ot})}):N||a.history.ignore(()=>{e.set({height:ot})}))}});const nt=t.useMemo(()=>{const t={lastArgs:null,lastResult:null};return async function(e){return t.lastArgs&&t.lastResult&&(o=t.lastArgs,n=e,JSON.stringify(o)===JSON.stringify(n))||(t.lastResult=await y(e),t.lastArgs=Object.assign({},e)),t.lastResult;var o,n}},[]),it=t.useRef(0),rt=t.useRef(null);t.useEffect(()=>{M||G||(async()=>{it.current++;const t=it.current;let o=F(`text ${e.id} ${t}`);rt.current&&rt.current(),rt.current=o,B(!0);let n=null;const i=q?5:1;for(let l=0;l<i;l++){const o=l>0?nt:y;try{if(n=await o({skipCache:l>0,html:Z,width:e.width||1,height:e.height||ot||1,fontFamily:U,padding:_,pixelRatio:a._elementsPixelRatio,font:a.fonts.find(t=>t.fontFamily===U)||R.globalFonts.find(t=>t.fontFamily===U)}),t!==it.current){return}if(q&&I(n)){await new Promise(t=>setTimeout(t,50*(l+1)));continue}break}catch(r){console.error(r),k(`Error rendering rich text with id ${e.id}`);break}}n?z(n):o?(o(),o=null):console.error("Finish function is called twice!"),B(!1)})()},[Z,M,ot,G,U,e.height,a._elementsPixelRatio,J]);const[at,lt]=j(Y,300),[st]=j(M,300,!0),ct=st||at;t.useEffect(()=>{var t;if(!ct){return s.autorun(()=>{const t=p.current;f(t,e)})}null===(t=p.current)||void 0===t||t.clearCache()},[b,ct,e.shadowColor,e.shadowOffsetX,e.shadowOffsetY,e.shadowOpacity]),t.useEffect(()=>{b&&!Y&&rt.current&&(rt.current(),rt.current=null)},[b,Y]),t.useLayoutEffect(()=>{if(!J){return}if(!e.curveEnabled){return}const t=new l.TextPath({data:m(e.a.width,e.a.height,e.curvePower,e.a.fontSize),text:O(e.text),letterSpacing:e.letterSpacing*e.a.fontSize,fontSize:e.a.fontSize,fontFamily:e.fontFamily,fontWeight:e.fontWeight,fontStyle:e.fontStyle,align:"center",textBaseline:"middle",fill:e.fill}),o=t.getSelfRect().width;if(o){const t=o-e.a.width,n=e.a.rotation*Math.PI/180,i=-t/2*Math.cos(n),r=-t/2*Math.sin(n);e.set({width:o,x:e.a.x+i,y:e.a.y+r})}t.destroy()},[J,e.curveEnabled,e.curvePower,e.text,e.fontSize,e.fontFamily,e.fontWeight,e.fontStyle,e.letterSpacing]),t.useEffect(()=>()=>{rt.current&&rt.current()},[]),t.useEffect(()=>{H&&!W&&Q&&""===O(e.text)&&e.removable&&!e.placeholder&&a.deleteElements([e.id])},[Q,e.placeholder,e.removable,e.text,W,H]);let dt=0;"middle"===e.verticalAlign&&(dt=(e.height-ot)/2),"bottom"===e.verticalAlign&&(dt=e.height-ot);const ft=u({fontLoaded:J,fontFamily:e.fontFamily,fontSize:e.fontSize,lineHeight:e.lineHeight}),ut=C(),ht=m(e.a.width,ot,e.curvePower,e.fontSize),gt=t.useRef(null),mt=t.useRef(null),pt=G&&e.strokeWidth>0&&!e.curveEnabled;return t.createElement(t.Fragment,null,t.createElement(r,{x:e.a.x,y:e.a.y,offsetX:e.backgroundPadding*(e.fontSize*ft*.5),offsetY:e.backgroundPadding*(e.fontSize*ft*.5),rotation:e.a.rotation,hideInExport:!e.showInExport,listening:!1,visible:e.backgroundEnabled,opacity:e.backgroundOpacity*e.a.opacity,fill:e.backgroundColor,width:e.a.width+e.backgroundPadding*(e.fontSize*ft),height:e.a.height+e.backgroundPadding*(e.fontSize*ft),cornerRadius:e.backgroundCornerRadius*(e.fontSize*ft*.5)}),t.createElement(i,{x:e.a.x,y:e.a.y,rotation:e.a.rotation,data:ht,stroke:"red",strokeWidth:1,visible:!1}),t.createElement(r,{ref:p,name:"element",x:e.a.x,y:e.a.y,listening:e.selectable,rotation:e.a.rotation,width:e.a.width,height:e.a.height,visible:!ct,draggable:ut?e.draggable&&W:e.draggable,preventDefault:!ut||W,opacity:G?0:e.a.opacity,hideInExport:!e.showInExport,onDragMove:t=>{e.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{e.set({x:t.target.x(),y:t.target.y()})},id:e.id,onDblClick:t=>{e.contentEditable&&(mt.current={x:t.evt.clientX,y:t.evt.clientY},e.toggleEditMode(!0))},onDblTap:t=>{var o;if(e.contentEditable){const n=null===(o=t.evt.changedTouches)||void 0===o?void 0:o[0];mt.current=n?{x:n.clientX,y:n.clientY}:null,e.toggleEditMode(!0)}},onTransformStart:t=>{L(!0),D.current=e.height},onTransform:t=>{var o;const n=t.target,i=(null===(o=n.getStage())||void 0===o?void 0:o.findOne("Transformer")).getActiveAnchor(),r="middle-left"===i||"middle-right"===i,a="top-center"===i||"bottom-center"===i,l=n.scaleX();if(r){const t=n.scaleX(),o=n.width()*t,i=e.fontSize;let r=o;if(o<i&&(r=i,gt.current&&n.position(gt.current)),n.width(r),n.scaleX(1),d.textVerticalResizeEnabled){const t=Math.max(ot,D.current);e.set({height:t})}e.set({width:n.width(),x:n.x(),y:n.y()})}else if(a){let o="resize"===d.textOverflow?ot:e.lineHeight*e.fontSize;const i=Math.max(o,t.target.height()*t.target.scaleY());n.scaleY(1),e.set({x:n.x(),y:n.y(),height:i,rotation:n.rotation()})}else{n.scaleX(1),n.scaleY(1),e.set({fontSize:e.fontSize*l,letterSpacing:e.letterSpacing,width:n.width()*l,x:n.x(),y:n.y(),rotation:n.rotation(),height:n.height()*l})}gt.current=t.target.position()},onTransformEnd:t=>{L(!1),B(!0);const o=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),e.set({fontSize:e.fontSize*o,width:t.target.width()*o,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),shadowBlur:e.shadowBlur*o,shadowOffsetX:e.shadowOffsetX*o,shadowOffsetY:e.shadowOffsetY*o,strokeWidth:e.strokeWidth*o})}}),t.createElement(n,{ref:p,image:b,x:e.a.x,y:e.a.y,offsetX:_,offsetY:_-dt,listening:!1,rotation:e.a.rotation,width:e.a.width+2*_,height:(e.a.width+2*_)*((null==b?void 0:b.height)/(null==b?void 0:b.width)||1),visible:!ct&&!G,opacity:e.a.opacity,shadowEnabled:e.shadowEnabled,shadowBlur:e.shadowBlur,shadowOffsetX:e.shadowOffsetX,shadowOffsetY:e.shadowOffsetY,shadowColor:e.shadowColor,shadowOpacity:e.shadowOpacity,hideInExport:!e.showInExport,editModeEnabled:e._editModeEnabled||M||ct}),(ct||pt)&&t.createElement(o,{x:e.a.x,y:e.a.y,rotation:e.a.rotation,offsetY:-dt},t.createElement(S,{divProps:{style:{pointerEvents:"none"}}},t.createElement(X,{dangerouslySetInnerHTML:{__html:Z},style:{pointerEvents:"none",opacity:e.a.opacity,textShadow:e.shadowEnabled?`${e.shadowOffsetX}px ${e.shadowOffsetY}px ${e.shadowBlur}px ${P(e.shadowColor,null!==(c=e.shadowOpacity)&&void 0!==c?c:1)}`:void 0}}))),G&&t.createElement(o,{x:e.a.x,y:e.a.y,rotation:e.a.rotation,offsetY:-dt},t.createElement(S,null,t.createElement($,{html:tt,element:e,onChange:t=>{const o=T({oldText:O(e.text),newText:O(t),element:e});e.set({text:t,fontSize:o})},onBlur:t=>{e.toggleEditMode(!1),lt(!0)},clickCoords:mt.current}))))});export function setCursorFromCoords(t,e){if(!t||!e){return}const{x:o,y:n}=e;try{let e=null;if(document.caretRangeFromPoint){e=document.caretRangeFromPoint(o,n)}else if(document.caretPositionFromPoint){const t=document.caretPositionFromPoint(o,n);t&&(e=document.createRange(),e.setStart(t.offsetNode,t.offset))}if(e){const o=a.find(e.startContainer,!0);if(o){const n=o.offset(t.scroll)+e.startOffset;return void t.setSelection(n,0,"api")}}}catch(i){}t.setSelection(0,0,"api")}
|
|
16
|
+
`;let X=["bold","color","font","italic","size","strike","underline","indent","list","direction"];export const setQuillFormats=t=>{X=t};export const createQuill=t=>new a(t,{toolbar:!1,keyboard:!1,clipboard:{matchVisual:!1},formats:X});export const setQuillContent=(t,e)=>{var o=t.clipboard.convert("<div class='ql-editor' style='outline: none;'>"+e+"<p><br></p></div>");t.setContents(o),t.history.clear()};const $=({html:e,onBlur:o,onChange:n,element:i,clickCoords:r})=>{var l;const d=t.useRef(null);t.useEffect(()=>{if(!d.current){return}const t=(i=d.current,new a(i,{toolbar:!1,keyboard:!1,clipboard:{matchVisual:!1},formats:X}));var i;s.runInAction(()=>{quillRef.editor.instance=t}),window.__polotnoQuill=t,t.on("text-change",()=>{t.getSelection()&&s.runInAction(()=>{quillRef.currentFormat=t.getFormat(t.getSelection())}),setTimeout(()=>{var t;const e=null===(t=d.current)||void 0===t?void 0:t.childNodes[0];if(!e){return}const o=e.innerHTML;n(Y(o))},10)}),setQuillContent(t,e),r?setCursorFromCoords(t,r):t.setSelection(0,0,"api"),t.on("selection-change",(e,o,n)=>{e&&s.runInAction(()=>{quillRef.currentFormat=t.getFormat(t.getSelection())})}),d.current.childNodes[0].addEventListener("blur",t=>{const e=t.relatedTarget;if(null==e?void 0:e.classList.contains("ql-clipboard")){return}const n=function(t){return!!t&&!!t.closest(".sketch-picker")}(e);n||o()});const l=d.current.childNodes[0],c=e=>{var o,n;const i=t.getSelection();if(!i||0===i.length){return}const r=t.getText(i.index,i.length).replace(/\n$/,""),a=window.getSelection();let l="";if(a&&a.rangeCount>0){const t=a.getRangeAt(0),e=document.createElement("div");e.appendChild(t.cloneContents()),l=e.innerHTML}if(null===(o=e.clipboardData)||void 0===o||o.setData("text/plain",r),l){const t='<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>\x3c!--StartFragment--\x3e<div style="white-space: pre-wrap; word-wrap: break-word;">'+l+"</div>\x3c!--EndFragment--\x3e</body></html>";null===(n=e.clipboardData)||void 0===n||n.setData("text/html",t)}e.preventDefault()},f=e=>{c(e);const o=t.getSelection();o&&o.length>0&&t.deleteText(o.index,o.length)};return l.addEventListener("copy",c),l.addEventListener("cut",f),()=>{l.removeEventListener("copy",c),l.removeEventListener("cut",f),s.runInAction(()=>{quillRef.editor.instance=null,quillRef.currentFormat={}}),delete window.__polotnoQuill}},[]),t.useEffect(()=>c(()=>i.text,()=>{var t,o;const n=quillRef.editor.instance;if(!n){return}const r=n.getSelection(),a=null===(o=null===(t=d.current)||void 0===t?void 0:t.childNodes)||void 0===o?void 0:o[0];Y((null==a?void 0:a.innerHTML)||"")===i.text||(setQuillContent(n,e),r&&(n.setSelection(r.index,r.length),s.runInAction(()=>{quillRef.currentFormat=n.getFormat(n.getSelection())})))},{fireImmediately:!0}),[]),t.useEffect(()=>{window.addEventListener("blur",o);const t=t=>{var e;(null===(e=d.current)||void 0===e?void 0:e.contains(t.target))||o()};return window.addEventListener("touchstart",t),()=>{window.removeEventListener("blur",o),window.removeEventListener("touchstart",t)}},[]);const f={color:i.fill};i.fill.indexOf("gradient")>=0&&(f.backgroundColor=i.fill,f.backgroundImage=i.fill,f.backgroundSize="100% 100%",f.backgroundRepeat="repeat",f.webkitBackgroundClip="text",f.MozBackgroundClip="text",f.WebkitTextFillColor="transparent",f.MozTextFillColor="transparent");const u=M(i);return t.createElement(L,{ref:d,style:Object.assign(Object.assign({},f),{fontSize:i.fontSize,fontWeight:i.fontWeight,textTransform:i.textTransform,width:i.a.width,fontFamily:'"'+i.fontFamily+'"',lineHeight:i.lineHeight,letterSpacing:i.letterSpacing*i.fontSize+"px",textAlign:i.align,opacity:Math.max(i.a.opacity,.2),textShadow:i.shadowEnabled?`${i.shadowOffsetX}px ${i.shadowOffsetY}px ${i.shadowBlur}px ${A(i.shadowColor,null!==(l=i.shadowOpacity)&&void 0!==l?l:1)}`:void 0,caretColor:u}),dir:p(O(i.text))})};function I(t){return!function(t){const e=t.getContext("2d").getImageData(0,0,t.width,t.height).data;for(let o=0;o<e.length;o+=4){if(0!==e[o+3]){return!0}}return!1}(t)}const q=/^((?!chrome|android).)*safari/i.test(navigator.userAgent);export const HTMLElement=e(({element:e,store:a})=>{var c;const p=t.useRef(null),[b,F]=t.useState(),[M,Y]=t.useState(!1),[X,D]=t.useState(!1),B=t.useRef(e.height),W=a.selectedShapes.indexOf(e)>=0&&e.selectable,H=g(W),_=e.fontSize/3,{textVerticalResizeEnabled:N}=d,Q=d.autoDeleteEmptyText,V=g(e.fontFamily),[J]=h(a,e.fontFamily),G=e._editModeEnabled;E(p);const U=J?e.fontFamily:V!==e.fontFamily?V:"Arial",K=x(e).fill,Z=P(e,{fontFamily:U,color:K}),tt=P(e,{fontFamily:U,color:K,forEditor:!0});let{width:et,height:ot}=function(e,o,n){return t.useMemo(()=>w(e),[e,o.width,n])}(Z,e,J);t.useEffect(()=>{if(!J){return}if(!e.height){return void a.history.ignore(()=>{e.set({height:ot})})}const{textOverflow:t}=d;if("change-font-size"!==t||M){"resize"===t&&(N&&e.height<ot&&!M&&a.history.ignore(()=>{e.set({height:ot})}),N||e.height===ot||a.history.ignore(()=>{e.set({height:ot})}))}else{const t=(t=>{let e=t.fontSize;for(let o=1;o<50;o++){const o=P(Object.assign(Object.assign({},t.toJSON()),{fontSize:e}),{fontFamily:t.fontFamily}),{height:n}=w(o);if(!(t.height&&n>t.height||!d.textSplitAllowed&&!t.curveEnabled&&v({html:o}))){break}e-=.5}return e})(e);t!==e.fontSize?a.history.ignore(()=>{e.set({fontSize:t})}):e.height!==ot&&(N&&e.height<ot?a.history.ignore(()=>{e.set({height:ot})}):N||a.history.ignore(()=>{e.set({height:ot})}))}});const nt=t.useMemo(()=>{const t={lastArgs:null,lastResult:null};return async function(e){return t.lastArgs&&t.lastResult&&(o=t.lastArgs,n=e,JSON.stringify(o)===JSON.stringify(n))||(t.lastResult=await y(e),t.lastArgs=Object.assign({},e)),t.lastResult;var o,n}},[]),it=t.useRef(0),rt=t.useRef(null);t.useEffect(()=>{M||G||(async()=>{it.current++;const t=it.current;let o=k(`text ${e.id} ${t}`);rt.current&&rt.current(),rt.current=o,D(!0);let n=null;const i=q?5:1;for(let l=0;l<i;l++){const o=l>0?nt:y;try{if(n=await o({skipCache:l>0,html:Z,width:e.width||1,height:e.height||ot||1,fontFamily:U,padding:_,pixelRatio:a._elementsPixelRatio,font:a.fonts.find(t=>t.fontFamily===U)||C.globalFonts.find(t=>t.fontFamily===U)}),t!==it.current){return}if(q&&I(n)){await new Promise(t=>setTimeout(t,50*(l+1)));continue}break}catch(r){console.error(r),z(`Error rendering rich text with id ${e.id}`);break}}n?F(n):o?(o(),o=null):console.error("Finish function is called twice!"),D(!1)})()},[Z,M,ot,G,U,e.height,a._elementsPixelRatio,J]);const[at,lt]=j(X,300),[st]=j(M,300,!0),ct=st||at;t.useEffect(()=>{var t;if(!ct){return s.autorun(()=>{const t=p.current;f(t,e)})}null===(t=p.current)||void 0===t||t.clearCache()},[b,ct,e.shadowColor,e.shadowOffsetX,e.shadowOffsetY,e.shadowOpacity]),t.useEffect(()=>{b&&!X&&rt.current&&(rt.current(),rt.current=null)},[b,X]),t.useLayoutEffect(()=>{if(!J){return}if(!e.curveEnabled){return}const t=new l.TextPath({data:m(e.a.width,e.a.height,e.curvePower,e.a.fontSize),text:O(e.text),letterSpacing:e.letterSpacing*e.a.fontSize,fontSize:e.a.fontSize,fontFamily:e.fontFamily,fontWeight:e.fontWeight,fontStyle:e.fontStyle,align:"center",textBaseline:"middle",fill:e.fill}),o=t.getSelfRect().width;if(o){const t=o-e.a.width,n=e.a.rotation*Math.PI/180,i=-t/2*Math.cos(n),r=-t/2*Math.sin(n);e.set({width:o,x:e.a.x+i,y:e.a.y+r})}t.destroy()},[J,e.curveEnabled,e.curvePower,e.text,e.fontSize,e.fontFamily,e.fontWeight,e.fontStyle,e.letterSpacing]),t.useEffect(()=>()=>{rt.current&&rt.current()},[]),t.useEffect(()=>{H&&!W&&Q&&""===O(e.text)&&e.removable&&!e.placeholder&&a.deleteElements([e.id])},[Q,e.placeholder,e.removable,e.text,W,H]);let dt=0;"middle"===e.verticalAlign&&(dt=(e.height-ot)/2),"bottom"===e.verticalAlign&&(dt=e.height-ot);const ft=u({fontLoaded:J,fontFamily:e.fontFamily,fontSize:e.fontSize,lineHeight:e.lineHeight}),ut=R(),ht=m(e.a.width,ot,e.curvePower,e.fontSize),gt=t.useRef(null),mt=t.useRef(null),pt=G&&e.strokeWidth>0&&!e.curveEnabled;return t.createElement(t.Fragment,null,t.createElement(r,{x:e.a.x,y:e.a.y,offsetX:e.backgroundPadding*(e.fontSize*ft*.5),offsetY:e.backgroundPadding*(e.fontSize*ft*.5),rotation:e.a.rotation,hideInExport:!e.showInExport,listening:!1,visible:e.backgroundEnabled,opacity:e.backgroundOpacity*e.a.opacity,fill:e.backgroundColor,width:e.a.width+e.backgroundPadding*(e.fontSize*ft),height:e.a.height+e.backgroundPadding*(e.fontSize*ft),cornerRadius:e.backgroundCornerRadius*(e.fontSize*ft*.5)}),t.createElement(i,{x:e.a.x,y:e.a.y,rotation:e.a.rotation,data:ht,stroke:"red",strokeWidth:1,visible:!1}),t.createElement(r,{ref:p,name:"element",x:e.a.x,y:e.a.y,listening:e.selectable,rotation:e.a.rotation,width:e.a.width,height:e.a.height,visible:!ct,draggable:ut?e.draggable&&W:e.draggable,preventDefault:!ut||W,opacity:G?0:e.a.opacity,hideInExport:!e.showInExport,onDragMove:t=>{e.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{e.set({x:t.target.x(),y:t.target.y()})},id:e.id,onDblClick:t=>{e.contentEditable&&(mt.current={x:t.evt.clientX,y:t.evt.clientY},e.toggleEditMode(!0))},onDblTap:t=>{var o;if(e.contentEditable){const n=null===(o=t.evt.changedTouches)||void 0===o?void 0:o[0];mt.current=n?{x:n.clientX,y:n.clientY}:null,e.toggleEditMode(!0)}},onTransformStart:t=>{Y(!0),B.current=e.height},onTransform:t=>{var o;const n=t.target,i=(null===(o=n.getStage())||void 0===o?void 0:o.findOne("Transformer")).getActiveAnchor(),r="middle-left"===i||"middle-right"===i,a="top-center"===i||"bottom-center"===i,l=n.scaleX();if(r){const t=n.scaleX(),o=n.width()*t,i=e.fontSize;let r=o;if(o<i&&(r=i,gt.current&&n.position(gt.current)),n.width(r),n.scaleX(1),d.textVerticalResizeEnabled){const t=Math.max(ot,B.current);e.set({height:t})}e.set({width:n.width(),x:n.x(),y:n.y()})}else if(a){const o="resize"===d.textOverflow,i="number"==typeof e.lineHeight?e.lineHeight:1;let r=o?ot:i*e.fontSize;const a=Math.max(r,t.target.height()*t.target.scaleY());n.scaleY(1),e.set({x:n.x(),y:n.y(),height:a,rotation:n.rotation()})}else{n.scaleX(1),n.scaleY(1),e.set({fontSize:e.fontSize*l,letterSpacing:e.letterSpacing,width:n.width()*l,x:n.x(),y:n.y(),rotation:n.rotation(),height:n.height()*l})}gt.current=t.target.position()},onTransformEnd:t=>{Y(!1),D(!0);const o=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),e.set({fontSize:e.fontSize*o,width:t.target.width()*o,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),shadowBlur:e.shadowBlur*o,shadowOffsetX:e.shadowOffsetX*o,shadowOffsetY:e.shadowOffsetY*o,strokeWidth:e.strokeWidth*o})}}),t.createElement(n,{ref:p,image:b,x:e.a.x,y:e.a.y,offsetX:_,offsetY:_-dt,listening:!1,rotation:e.a.rotation,width:e.a.width+2*_,height:(e.a.width+2*_)*((null==b?void 0:b.height)/(null==b?void 0:b.width)||1),visible:!ct&&!G,opacity:e.a.opacity,shadowEnabled:e.shadowEnabled,shadowBlur:e.shadowBlur,shadowOffsetX:e.shadowOffsetX,shadowOffsetY:e.shadowOffsetY,shadowColor:e.shadowColor,shadowOpacity:e.shadowOpacity,hideInExport:!e.showInExport,editModeEnabled:e._editModeEnabled||M||ct}),(ct||pt)&&t.createElement(o,{x:e.a.x,y:e.a.y,rotation:e.a.rotation,offsetY:-dt},t.createElement(S,{divProps:{style:{pointerEvents:"none"}}},t.createElement(L,{dangerouslySetInnerHTML:{__html:Z},style:{pointerEvents:"none",opacity:e.a.opacity,textShadow:e.shadowEnabled?`${e.shadowOffsetX}px ${e.shadowOffsetY}px ${e.shadowBlur}px ${A(e.shadowColor,null!==(c=e.shadowOpacity)&&void 0!==c?c:1)}`:void 0}}))),G&&t.createElement(o,{x:e.a.x,y:e.a.y,rotation:e.a.rotation,offsetY:-dt},t.createElement(S,null,t.createElement($,{html:tt,element:e,onChange:t=>{const o=T({oldText:O(e.text),newText:O(t),element:e});e.set({text:t,fontSize:o})},onBlur:t=>{e.toggleEditMode(!1),lt(!0)},clickCoords:mt.current}))))});export function setCursorFromCoords(t,e){if(!t||!e){return}const{x:o,y:n}=e;try{let e=null;if(document.caretRangeFromPoint){e=document.caretRangeFromPoint(o,n)}else if(document.caretPositionFromPoint){const t=document.caretPositionFromPoint(o,n);t&&(e=document.createRange(),e.setStart(t.offsetNode,t.offset))}if(e){const o=a.find(e.startContainer,!0);if(o){const n=o.offset(t.scroll)+e.startOffset;return void t.setSelection(n,0,"api")}}}catch(i){}t.setSelection(0,0,"api")}
|
package/canvas/rules.d.ts
CHANGED
|
@@ -6,9 +6,9 @@ type PageProps = {
|
|
|
6
6
|
yPadding: number;
|
|
7
7
|
width: number;
|
|
8
8
|
height: number;
|
|
9
|
+
layout?: 'vertical' | 'horizontal';
|
|
9
10
|
};
|
|
10
|
-
export declare const TopRules: (({ store, width, height }: PageProps) => React.JSX.Element) & {
|
|
11
|
+
export declare const TopRules: (({ store, width, height, layout }: PageProps) => React.JSX.Element) & {
|
|
11
12
|
displayName: string;
|
|
12
13
|
};
|
|
13
|
-
export declare function LeftRules(): React.JSX.Element;
|
|
14
14
|
export {};
|
package/canvas/rules.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import e from"react";import{getTotalClientRect as t}from"../utils/math.js";import{unitToPx as o}from"../utils/unit.js";import{observer as
|
|
1
|
+
import e from"react";import{getTotalClientRect as t}from"../utils/math.js";import{unitToPx as o}from"../utils/unit.js";import{observer as i}from"mobx-react-lite";import{styled as l}from"../utils/goober.js";const r=l("div",e.forwardRef)`
|
|
2
2
|
position: absolute;
|
|
3
3
|
top: 0;
|
|
4
4
|
left: 0;
|
|
5
5
|
pointer-events: none;
|
|
6
|
-
`,
|
|
6
|
+
`,a=l("div",e.forwardRef)`
|
|
7
7
|
height: 14px;
|
|
8
8
|
position: sticky;
|
|
9
9
|
font-size: 8px;
|
|
@@ -14,7 +14,7 @@ import e from"react";import{getTotalClientRect as t}from"../utils/math.js";impor
|
|
|
14
14
|
border-bottom: 1px solid grey;
|
|
15
15
|
background-color: #e8e8e8;
|
|
16
16
|
overflow: hidden;
|
|
17
|
-
`,
|
|
17
|
+
`,s=l("div",e.forwardRef)`
|
|
18
18
|
left: 0;
|
|
19
19
|
width: 14px;
|
|
20
20
|
position: sticky;
|
|
@@ -24,11 +24,11 @@ import e from"react";import{getTotalClientRect as t}from"../utils/math.js";impor
|
|
|
24
24
|
border-right: 1px solid grey;
|
|
25
25
|
background-color: #e8e8e8;
|
|
26
26
|
overflow: hidden;
|
|
27
|
-
`,
|
|
27
|
+
`,n=l("div",e.forwardRef)`
|
|
28
28
|
position: absolute;
|
|
29
29
|
border-left: 1px solid grey;
|
|
30
30
|
padding-left: 2px;
|
|
31
|
-
`,
|
|
31
|
+
`,p=l("div",e.forwardRef)`
|
|
32
32
|
position: absolute;
|
|
33
33
|
left: 14px;
|
|
34
34
|
border-left: 1px solid grey;
|
|
@@ -36,4 +36,4 @@ import e from"react";import{getTotalClientRect as t}from"../utils/math.js";impor
|
|
|
36
36
|
transform: rotate(90deg);
|
|
37
37
|
transform-origin: left top;
|
|
38
38
|
overflow: hidden;
|
|
39
|
-
`,
|
|
39
|
+
`,d=[.1,.2,.5,1,2,5,10,20,25,50,100,200,500,1e3,2e3,5e3,1e4];export const TopRules=i(({store:i,width:l,height:c,layout:h="vertical"})=>{const x=e.useRef(null);if(!i.activePage){return null}const u="horizontal"===h,g=i.activePage,m=(i.bleedVisible&&g.bleed,g.computedWidth*i.scale),f=g.computedHeight*i.scale,y=(l-m)/2,b=(c-f)/2,v=(w=e=>o({unitVal:e,dpi:i.dpi,unit:i.unit})*i.scale,d.find(e=>w(e)>30)||1e4);var w;const k=o({unitVal:v,dpi:i.dpi,unit:i.unit})*i.scale,E=Math.round(m/k)+1,R=Math.round(f/k)+1,S=t(i.selectedShapes);return e.createElement(r,{ref:x,className:"polotno-rulers",style:{display:"flex",flexDirection:"column"}},u?e.createElement(e.Fragment,null,e.createElement("div",{style:{display:"flex",flexDirection:"row",position:"sticky",top:0,zIndex:1}},e.createElement("div",{style:{width:"14px",height:"14px",flexShrink:0,backgroundColor:"#e8e8e8",borderRight:"1px solid grey",borderBottom:"1px solid grey",position:"sticky",left:0,zIndex:2}}),i.pages.map((t,o)=>{var r;const s=t.computedWidth*i.scale,p=(l-s)/2;return e.createElement(a,{key:t.id,style:{width:l+"px",flexShrink:0,position:"relative"},className:"polotno-x-ruler"},[...Array(E)].map((t,o)=>e.createElement(n,{key:o,style:{left:p+o*k+"px",width:k+"px"}},"px"===i.unit||v>=1?Math.round(v*o):(v*o).toFixed(1))),(null===(r=i.selectedShapes[0])||void 0===r?void 0:r.page)===t&&e.createElement("div",{style:{position:"absolute",left:p+S.x*i.scale+"px",height:"14px",width:S.width*i.scale,backgroundColor:"rgba(0,0,0,0.15)"}}))})),e.createElement(s,{style:{height:c+"px",position:"sticky",left:0,marginTop:"-14px"},className:"polotno-y-ruler"},[...Array(R)].map((t,o)=>e.createElement(p,{key:o,style:{top:b+o*k+"px",width:k+"px"}},"px"===i.unit||v>=1?Math.round(v*o):(v*o).toFixed(1))),!!i.selectedShapes.length&&e.createElement("div",{style:{position:"absolute",top:b+S.y*i.scale+"px",width:"14px",height:S.height*i.scale,backgroundColor:"rgba(0,0,0,0.15)"}}))):e.createElement(e.Fragment,null,e.createElement(a,{style:{width:l+"px"},className:"polotno-x-ruler"},[...Array(E)].map((t,o)=>e.createElement(n,{key:o,style:{left:y+o*k+"px",width:k+"px"}},"px"===i.unit||v>=1?Math.round(v*o):(v*o).toFixed(1))),!!i.selectedShapes.length&&e.createElement("div",{style:{position:"absolute",left:y+S.x*i.scale+"px",height:"14px",width:S.width*i.scale,backgroundColor:"rgba(0,0,0,0.15)"}})),i.pages.map((t,o)=>{var l;const r=t.computedHeight*i.scale,a=(c-r)/2,n=0===o?14:0;return e.createElement(s,{key:t.id,style:{height:c-n+"px"},className:"polotno-y-ruler"},[...Array(R)].map((t,o)=>e.createElement(p,{key:o,style:{top:a+o*k-n+"px",width:k+"px"}},"px"===i.unit||v>=1?Math.round(v*o):(v*o).toFixed(1))),(null===(l=i.selectedShapes[0])||void 0===l?void 0:l.page)===t&&e.createElement("div",{style:{position:"absolute",top:a+S.y*i.scale-n+"px",width:"14px",height:S.height*i.scale,backgroundColor:"rgba(0,0,0,0.15)"}}))})))});
|
|
@@ -0,0 +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 +1 @@
|
|
|
1
|
-
import e from"react";import t from"konva";import{getClientRect as n}from"../utils/math.js";const o={stroke:"rgb(0, 161, 255)",strokeWidth:1,dash:[4,6]};export const setSnapGuideStyle=({stroke:e,strokeWidth:t,dash:n})=>{void 0!==e&&(o.stroke=e),void 0!==t&&(o.strokeWidth=t),void 0!==n&&(o.dash=n)};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],f=a[0];return d&&s.filter(e=>Math.abs(e.diff-d.diff)<.1).forEach(e=>{i.push(Object.assign({orientation:"V"},e))}),f&&a.filter(e=>Math.abs(e.diff-f.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,f){const c=e.useRef(null);setSnapGuideStyle(f);const u=e=>e.hasName("element")||e.hasName("page-background")||!c.current&&e.hasName("elements-area");function l(e){var t;const n=null===(t=r.current)||void 0===t?void 0:t.getStage(),o=[],i=[];return n.find(u).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 h(e){var n;const i=null===(n=r.current)||void 0===n?void 0:n.getLayer(),s=null==i?void 0:i.children.find(e=>"line-guides"===e.name());e.forEach(e=>{if("H"===e.orientation){var n=new t.Line({x:-i.getStage().x(),y:-i.getStage().y(),points:[-6e3,e.lineGuide,6e3,e.lineGuide],stroke:o.stroke,strokeWidth:o.strokeWidth,name:"guid-line",dash:o.dash});null==s||s.add(n),i.batchDraw()}else{"V"===e.orientation&&(n=new t.Line({x:-i.getStage().x(),y:-i.getStage().y(),points:[e.lineGuide,-6e3,e.lineGuide,6e3],stroke:o.stroke,strokeWidth:o.strokeWidth,name:"guid-line",dash:o.dash}),null==s||s.add(n))}})}const g=e=>{const o=e.target.getLayer().children.find(e=>"line-guides"===e.name());null==o||o.destroyChildren();var r=l(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}h(a);const d=e.target.getAbsolutePosition(),f=(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":f.x=e.lineGuide+e.offset;break;case"H":f.y=e.lineGuide+e.offset}}});const c=f.x-d.x,u=f.y-d.y;e.evt.ctrlKey||e.evt.metaKey||e.target.nodes().forEach(e=>{const t=e.getAbsolutePosition();e.setAbsolutePosition({x:t.x+c,y:t.y+u})})},y=(e,t,n)=>{var o;const d=r.current,f=d.getLayer().children.find(e=>"line-guides"===e.name());if(null==f||f.destroyChildren(),"rotater"===d.getActiveAnchor()){return t}const c=d.getActiveAnchor(),u=a[c],g=null===(o=d.findOne(`.${u}`))||void 0===o?void 0:o.getAbsolutePosition();if(!g){return t}const y={x:e.x-g.x,y:e.y-g.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 v=i(l(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(!v.length){return t}if(h(v),n.ctrlKey||n.metaKey){return t}const m=[];if(v.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,g,{orientation:e.orientation,lineGuide:e.lineGuide});t&&m.push(t)}),m.length>0){let e=m[0],t=Math.sqrt(Math.pow(x.x-e.x,2)+Math.pow(x.y-e.y,2));if(m.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},p=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(y),r.current.on("dragstart",e=>{setTimeout(()=>{ensureDragOrder()})}),r.current.on("dragmove",g),r.current.on("dragend",p),r.current.on("transformend",p),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 a=e=>e.hasName("element")||e.hasName("line-anchor")||e.hasName("page-background")||e.hasName("elements-area"),d=e=>{const s=e.target.getLayer().children.find(e=>"line-guides"===e.name());null==s||s.destroyChildren();var d,f=i(function(e){var t;const o=null===(t=n.current)||void 0===t?void 0:t.getStage();var r=[],i=[];return o.find(a).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:(d=e.target).absolutePosition().x,offset:0,snap:"center",nodes:[d]}],horizontal:[{guide:d.absolutePosition().y,offset:0,snap:"center",nodes:[d]}]});if(!f.length){return}!function(e){var r;const i=null===(r=n.current)||void 0===r?void 0:r.getLayer(),s=null==i?void 0:i.children.find(e=>"line-guides"===e.name());e.forEach(e=>{if("H"===e.orientation){var n=new t.Line({points:[-6e3,e.lineGuide,6e3,e.lineGuide],stroke:o.stroke,strokeWidth:o.strokeWidth,name:"guid-line",dash:o.dash});null==s||s.add(n),i.batchDraw()}else{"V"===e.orientation&&(n=new t.Line({points:[e.lineGuide,-6e3,e.lineGuide,6e3],stroke:o.stroke,strokeWidth:o.strokeWidth,name:"guid-line",dash:o.dash}),null==s||s.add(n))}})}(f);const c=e.target.getAbsolutePosition(),u=Object.assign({},c);f.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-c.x,h=u.y-c.y;if(!e.evt.ctrlKey&&!e.evt.metaKey){const t=e.target.getAbsolutePosition();e.target.absolutePosition({x:t.x+l,y:t.y+h})}},f=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",d),n.current.on("dragend",f))},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";const o={stroke:"rgb(0, 161, 255)",strokeWidth:1,dash:[4,6]};export const setSnapGuideStyle=({stroke:e,strokeWidth:t,dash:n})=>{void 0!==e&&(o.stroke=e),void 0!==t&&(o.strokeWidth=t),void 0!==n&&(o.dash=n)};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],f=a[0];return d&&s.filter(e=>Math.abs(e.diff-d.diff)<.1).forEach(e=>{i.push(Object.assign({orientation:"V"},e))}),f&&a.filter(e=>Math.abs(e.diff-f.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,f){const c=e.useRef(null);setSnapGuideStyle(f);const u=e=>e.hasName("element")||e.hasName("page-background")||!c.current&&e.hasName("elements-area");function l(e){var t;const n=null===(t=r.current)||void 0===t?void 0:t.getStage(),o=[],i=[];return n.find(u).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 h(e){var n;const i=null===(n=r.current)||void 0===n?void 0:n.getLayer(),s=null==i?void 0:i.children.find(e=>"line-guides"===e.name());e.forEach(e=>{if("H"===e.orientation){var n=new t.Line({x:-i.getStage().x(),y:-i.getStage().y(),points:[-6e3,e.lineGuide,6e3,e.lineGuide],stroke:o.stroke,strokeWidth:o.strokeWidth,name:"guid-line",dash:o.dash});null==s||s.add(n),i.batchDraw()}else{"V"===e.orientation&&(n=new t.Line({x:-i.getStage().x(),y:-i.getStage().y(),points:[e.lineGuide,-6e3,e.lineGuide,6e3],stroke:o.stroke,strokeWidth:o.strokeWidth,name:"guid-line",dash:o.dash}),null==s||s.add(n))}})}const g=e=>{const o=e.target.getLayer().children.find(e=>"line-guides"===e.name());null==o||o.destroyChildren();var r=l(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}h(a);const d=e.target.getAbsolutePosition(),f=(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":f.x=e.lineGuide+e.offset;break;case"H":f.y=e.lineGuide+e.offset}}});const c=f.x-d.x,u=f.y-d.y;e.evt.ctrlKey||e.evt.metaKey||e.target.nodes().forEach(e=>{const t=e.getAbsolutePosition();e.setAbsolutePosition({x:t.x+c,y:t.y+u})})},y=(e,t,n)=>{var o;const d=r.current,f=d.getLayer().children.find(e=>"line-guides"===e.name());if(null==f||f.destroyChildren(),"rotater"===d.getActiveAnchor()){return t}const c=d.getActiveAnchor(),u=a[c],g=null===(o=d.findOne(`.${u}`))||void 0===o?void 0:o.getAbsolutePosition();if(!g){return t}const y={x:e.x-g.x,y:e.y-g.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 v=i(l(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(!v.length){return t}if(h(v),n.ctrlKey||n.metaKey){return t}const m=[];if(v.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,g,{orientation:e.orientation,lineGuide:e.lineGuide});t&&m.push(t)}),m.length>0){let e=m[0],t=Math.sqrt(Math.pow(x.x-e.x,2)+Math.pow(x.y-e.y,2));if(m.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},p=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(y),r.current.on("dragstart",e=>{setTimeout(()=>{ensureDragOrder()})}),r.current.on("dragmove",g),r.current.on("dragend",p),r.current.on("transformend",p),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 a=e=>e.hasName("element")||e.hasName("line-anchor")||e.hasName("page-background")||e.hasName("elements-area"),d=e=>{const s=e.target.getLayer().children.find(e=>"line-guides"===e.name());null==s||s.destroyChildren();var d,f=i(function(e){var t;const o=null===(t=n.current)||void 0===t?void 0:t.getStage();var r=[],i=[];return o.find(a).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:(d=e.target).absolutePosition().x,offset:0,snap:"center",nodes:[d]}],horizontal:[{guide:d.absolutePosition().y,offset:0,snap:"center",nodes:[d]}]});if(!f.length){return}!function(e){var r;const i=null===(r=n.current)||void 0===r?void 0:r.getLayer(),s=null==i?void 0:i.children.find(e=>"line-guides"===e.name());e.forEach(e=>{if("H"===e.orientation){var n=new t.Line({x:-i.getStage().x(),y:-i.getStage().y(),points:[-6e3,e.lineGuide,6e3,e.lineGuide],stroke:o.stroke,strokeWidth:o.strokeWidth,name:"guid-line",dash:o.dash});null==s||s.add(n),i.batchDraw()}else{"V"===e.orientation&&(n=new t.Line({x:-i.getStage().x(),y:-i.getStage().y(),points:[e.lineGuide,-6e3,e.lineGuide,6e3],stroke:o.stroke,strokeWidth:o.strokeWidth,name:"guid-line",dash:o.dash}),null==s||s.add(n))}})}(f);const c=e.target.getAbsolutePosition(),u=Object.assign({},c);f.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-c.x,h=u.y-c.y;if(!e.evt.ctrlKey&&!e.evt.metaKey){const t=e.target.getAbsolutePosition();e.target.absolutePosition({x:t.x+l,y:t.y+h})}},f=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",d),n.current.on("dragend",f))},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"};
|
package/canvas/video-element.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"react";import{observer as t}from"mobx-react-lite";import{autorun as r}from"mobx";import{Arc as n,Group as o,Image as i,Rect as a,Text as d,Transformer as h}from"react-konva";import c from"use-image";import l from"konva";import{Portal as s}from"react-konva-utils";import{incrementLoader as u,triggerLoadError as g}from"../utils/loader.js";import*as f from"../utils/svg.js";import{flags as m}from"../utils/flags.js";import{applyFilter as p}from"./apply-filters.js";import{useFadeIn as w}from"./use-fadein.js";import{isTouchDevice as v}from"../utils/screen.js";function x(){return document.createElement("canvas")}const M=new window.Image;M.src=f.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 E=new window.Image;E.src=f.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=(t,r,n,o,i=0,a=!1)=>{const d=Math.floor(Math.max(t.width*o,1)),h=Math.floor(Math.max(t.height*o,1)),c=Math.min(i*o,d/2,h/2),s=Math.max(t.width/n.width,t.height/n.height)*o,u=t.page._exportingOrRendering&&m.imageDownScalingEnabled&&s<1&&!a,g=r instanceof HTMLVideoElement?r.videoWidth:null==r?void 0:r.width,f=r instanceof HTMLVideoElement?r.videoHeight:null==r?void 0:r.height,p=0===n.x&&0===n.y&&n.width===g&&n.height===f,w=e.useMemo(()=>{if(r&&g&&f){return p&&0===c&&!u?void 0:x()}},[r,c,u,p,g,f]),v=()=>{if(!w||!r){return}w.width=d,w.height=h;const e=w.getContext("2d");if(!e){return}c&&(e.beginPath(),e.moveTo(c,0),e.lineTo(d-c,0),e.arc(d-c,c,c,3*Math.PI/2,0,!1),e.lineTo(d,h-c),e.arc(d-c,h-c,c,0,Math.PI/2,!1),e.lineTo(c,h),e.arc(c,h-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 t=u?function(e,t){var r,n;const o=x(),i=e instanceof HTMLVideoElement?e.videoWidth:e.width,a=e instanceof HTMLVideoElement?e.videoHeight:e.height;o.width=i,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,n,o,i,a){for(var d=new ImageData(t,r),h=new Int32Array(e.data.buffer),c=e.width,l=new Int32Array(d.data.buffer),s=d.width,u=t/i,g=r/a,f=Math.round(1/u),m=Math.round(1/g),p=f*m,w=0;w<d.height;w++){for(var v=0;v<s;v++){for(var x=0+Math.round(v/u)+(0+Math.round(w/g))*c,M=0,E=0,y=0,b=0,L=0;L<m;L++){for(var C=0;C<f;C++){var T=h[x+C+L*c];M+=T<<24>>>24,E+=T<<16>>>24,y+=T<<8>>>24,b+=T>>>24}}M=Math.round(M/p),E=Math.round(E/p),y=Math.round(y/p),b=Math.round(b/p),l[v+w*s]=b<<24|y<<16|E<<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===(n=o.getContext("2d"))||void 0===n||n.putImageData(d,0,0),o}(r,s):r,o=u?{x:Math.floor(n.x*s),y:Math.floor(n.y*s),width:Math.floor(n.width*s),height:Math.floor(n.height*s)}:n;e.drawImage(t,o.x,o.y,o.width,o.height,0,0,w.width,w.height)};return e.useLayoutEffect(()=>{v()},[w,t.width,t.height,n.x,n.y,n.width,n.height,i,o,a,t.page._exportingOrRendering,u]),e.useEffect(()=>()=>{w&&"CANVAS"===w.nodeName&&l.Util.releaseCanvas(w)},[w]),[w||r,v]};const y=x(),b=t(({element:t})=>{const r=Math.min(30,t.width/4,t.height/4),i=e.useRef(null);return e.useEffect(()=>{const e=i.current;if(!e){return}const t=new l.Animation(t=>{e.rotate(((null==t?void 0:t.timeDiff)||0)/2)},e.getLayer());return t.start(),()=>{t.stop()}}),e.createElement(o,{x:t.a.x,y:t.a.y,rotation:t.a.rotation,listening:!1,opacity:t.a.opacity,hideInExport:!t.showInExport},e.createElement(a,{width:t.width,height:t.height,fill:"rgba(124, 173, 212, 0.8)"}),e.createElement(n,{ref:i,x:t.width/2,y:t.height/2,fill:"white",outerRadius:Math.abs(r),innerRadius:Math.max(1,r-5),angle:270}))}),L=t(({element:t})=>{const r=Math.max(10,Math.min(30,t.width/25));return e.createElement(o,{x:t.a.x,y:t.a.y,rotation:t.a.rotation,listening:!1,opacity:t.a.opacity,hideInExport:!t.showInExport},e.createElement(a,{width:t.width,height:t.height,fill:"rgba(223, 102, 102, 0.8)"}),e.createElement(d,{text:"Can not load the video...",fontSize:r,width:t.width,height:t.height,align:"center",fill:"white",verticalAlign:"middle",padding:5}))});let C=function(t,r,n){const o=e.useRef("loading"),i=e.useRef(null),[a,d]=e.useState(0),h=e.useRef(),c=e.useRef(),l=e.useRef();return h.current===t&&c.current===r&&l.current===n||(o.current="loading",i.current=void 0,h.current=t,c.current=r,l.current=n),e.useLayoutEffect(function(){if(t){var e=document.createElement("video");return e.addEventListener("canplay",a),e.addEventListener("error",h),r&&(e.crossOrigin=r),n&&(e.referrerPolicy=n),e.src=t,e.load(),function(){e.removeEventListener("canplay",a),e.removeEventListener("error",h)}}function a(){o.current="loaded",i.current=e,i.current.currentTime=0,d(Math.random()),i.current.removeEventListener("canplay",a)}function h(t){var r;const n=4===e.readyState,a=e.buffered&&e.buffered.length>0&&e.buffered.end(e.buffered.length-1)/e.duration*100>=100;if(n&&a){return}const h=t.message||(null===(r=e.error)||void 0===r?void 0:r.message)||"Unknown error",c=new Error("Video failed to load: "+h);console.error(c),o.current="failed",i.current=void 0,d(Math.random())}},[t,r,n]),[i.current,o.current]};export const setVideoLoaderHook=e=>{C=e};function T(e){return e.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA}export const useLoader=(t,r,n)=>{const o=e.useRef(),i=()=>{var e;null===(e=o.current)||void 0===e||e.call(o),o.current=void 0};e.useEffect(()=>i,[]),e.useLayoutEffect(()=>{const e=r.slice(0,200),a=`video with id ${n} url: ${e}`;"loading"!==t||o.current||(o.current=u(a)),"loading"!==t&&i(),"failed"===t&&g(a)},[t])};export const VideoElement=t(({element:t,store:n})=>{var d;const[g,m]=e.useState(!1),R=e.useRef(null),I=e.useRef(null),S=n.selectedShapes.indexOf(t)>=0&&t.selectable,[k,H]=e.useState(!1),[X,Y]=C(t.src,"anonymous"),[W,O]=e.useState(!1),_=n.activePage===t.page;useLoader(Y,t.src,t.id),X&&(X.playsInline=!0);const A=((t,r,n)=>{const o=e.useMemo(()=>{var e,o;const{flipX:i,flipY:a}=t,d="svg"===t.type||t.src.indexOf("data:image/svg+xml")>=0||t.src.indexOf(".svg")>=0,h=navigator.userAgent.toLowerCase().indexOf("firefox")>-1;if(!(i||a||h&&d)){return r}if(!r){return null}const c=r instanceof HTMLVideoElement?r.videoWidth:null==r?void 0:r.width,l=r instanceof HTMLVideoElement?r.videoHeight:null==r?void 0:r.height;if(!c||!l){return null}const s=x();let u=1;"svg"===t.type&&(u=Math.max(t.width/c*n,t.height/l*n)),s.width=Math.max(c*u,1),s.height=Math.max(l*u,1);let g=i?-s.width:0,f=a?-s.height:0;return null===(e=s.getContext("2d"))||void 0===e||e.scale(i?-1:1,a?-1:1),null===(o=s.getContext("2d"))||void 0===o||o.drawImage(r,g,f,s.width,s.height),s},[t.flipX,t.flipY,r,t.width,t.height,n]);return e.useEffect(()=>()=>{o&&"CANVAS"===o.nodeName&&l.Util.releaseCanvas(o)},[o]),o})(t,X,n._elementsPixelRatio),P=A||y;e.useEffect(()=>{X&&n.history.ignore(()=>{t.set({duration:1e3*X.duration})})},[X]),e.useEffect(()=>{var e;if(!X){return}const r=n.animatedElementsIds,o=(!r.length||r.includes(t.id))&&n.isPlaying,i=_&&(o||k);if(!i){return void X.pause()}i&&(X.currentTime=t.startTime*X.duration,X.play());const a=new l.Animation(()=>{de.current()},null===(e=R.current)||void 0===e?void 0:e.getLayer());a.start();const d=()=>{H(!1),X.currentTime=t.startTime*X.duration},h=()=>{X.currentTime>=t.endTime*X.duration&&(X.pause(),X.currentTime=t.startTime*X.duration,H(!1))};return X.addEventListener("ended",d),X.addEventListener("timeupdate",h),()=>{X.pause(),a.stop(),X.removeEventListener("ended",d),X.removeEventListener("timeupdate",h)}},[X,k,n.isPlaying,_]),e.useEffect(()=>{X&&(X.volume=t.volume)},[X,t.volume]);const V=e.useRef();e.useEffect(()=>{const e=r(()=>{var e,r;if(X){const o=n.animatedElementsIds;if(o.length&&!o.includes(t.id)){return}const i=t.startTime*X.duration*1e3,a=X.duration*(t.endTime-t.startTime)*1e3,d=((n.currentTime||t.page.startTime)-t.page.startTime)%a+i;if(Math.abs(1e3*X.currentTime-d)>500||!n.isPlaying){const e=d/1e3;e!==X.currentTime&&(X.currentTime=e),!T(X)&&!n.isPlaying&&!V.current&&(V.current=u(`video ${t.id}`))}de.current(),null===(r=null===(e=R.current)||void 0===e?void 0:e.getLayer())||void 0===r||r.batchDraw()}});return()=>{e(),V.current&&(V.current(),V.current=null)}},[n,X]),e.useEffect(()=>{if(!X){return}const e=()=>{var e,r;!T(X)&&t.page._exportingOrRendering||V.current&&(de.current(),null===(r=null===(e=R.current)||void 0===e?void 0:e.getLayer())||void 0===r||r.batchDraw(),V.current(),V.current=null)};let r;return t.page._exportingOrRendering&&(r=setInterval(e,20)),X.addEventListener("timeupdate",e),X.addEventListener("canplay",e),()=>{clearInterval(r),X.removeEventListener("timeupdate",e),X.removeEventListener("canplay",e)}},[t.page._exportingOrRendering,X,t.id,u]);let{cropX:D,cropY:z,cropWidth:j,cropHeight:B}=t;"loaded"!==Y&&(D=z=0,j=B=1);const U=(N=P)instanceof HTMLVideoElement?N.videoWidth:(null==N?void 0:N.width)||0;var N;const Z=(e=>e instanceof HTMLVideoElement?e.videoHeight:(null==e?void 0:e.height)||0)(P),F=U*j,$=Z*B,q=t.width/t.height;let G,J;const K=F/$,Q="svg"===t.type;Q?(G=F,J=$):q>=K?(G=F,J=F/q):(G=$*q,J=$);const ee={x:U*D,y:Z*z,width:G,height:J},te=null!==(d=t.cornerRadius)&&void 0!==d?d:0,[re,ne]=useCornerRadiusAndCrop(t,P,ee,n._elementsPixelRatio,te,!0);let[oe,ie]=((t,r,n,o)=>{const i=(t=>{const[r,n]=e.useState(t);return e.useEffect(()=>{(async()=>{const e=await async function(e){if(!(e.indexOf("data:image/svg+xml")>=0||e.indexOf(".svg")>=0)){return e}const t=await f.urlToString(e),r=f.fixSize(t);return f.svgToURL(r)}(t);e!==r&&n(e)})()},[t]),r})(t.clipSrc||""),[a,d]=c(i,"anonymous"),h=t.clipSrc?d:"loaded";useLoader(h,t.clipSrc,t.id);const s=e.useMemo(()=>{if(r&&a){return x()}},[r,a]);function u(){var e;if(!a){return}const o=r instanceof HTMLVideoElement?r.videoWidth:null==r?void 0:r.width,i=r instanceof HTMLVideoElement?r.videoHeight:null==r?void 0:r.height;if(!r||!o||!i){return}if(!a||!a.width||!a.height){return}if(!s){return}const d=x(),h=Math.max(t.width/a.width*n,t.height/a.height*n);d.width=a.width*h,d.height=a.height*h,null===(e=d.getContext("2d"))||void 0===e||e.drawImage(a,0,0,d.width,d.height),s.width=Math.max(o,1),s.height=Math.max(i,1);const c=s.getContext("2d");c&&(c.save(),c.drawImage(d,0,0,o,i),l.Util.releaseCanvas(d),c.globalCompositeOperation="source-in",c.drawImage(r,0,0,s.width,s.height),c.restore())}return e.useLayoutEffect(()=>{u()},[s,r,a,t.width,t.height,n,...o]),[t.clipSrc&&a?s:r,u]})(t,re,n._elementsPixelRatio,[ee,te,n._elementsPixelRatio]);function ae(){ne(),ie()}const de=e.useRef(ae);de.current=ae;const he=Math.max(t.width/G,t.height/J);e.useEffect(()=>{var e;if(!t._cropModeEnabled){return}const r=null===(e=R.current)||void 0===e?void 0:e.getStage();function n(e){t._cropModeEnabled&&e.target!==I.current&&t.toggleCropMode(!1)}function o(e){t._cropModeEnabled&&e.target.parentNode!==r.content&&t.toggleCropMode(!1)}return document.body.addEventListener("click",o),null==r||r.on("click",n),null==r||r.on("tap",n),()=>{document.body.removeEventListener("click",o),document.body.removeEventListener("touchstart",o),null==r||r.off("click",n),null==r||r.off("click",n)}},[t._cropModeEnabled]),e.useLayoutEffect(()=>{if(!g&&!t._cropModeEnabled){return p(R.current,t),r(()=>{p(R.current,t)},{delay:100})}},[P,g,j,B,t._cropModeEnabled]),e.useLayoutEffect(()=>{var e;g||t._cropModeEnabled?null===(e=R.current)||void 0===e||e.clearCache():p(R.current,t)},[g,t.width,t.height,t._cropModeEnabled]),e.useEffect(()=>{p(R.current,t)},[t.shadowEnabled,t.shadowBlur,t.cornerRadius,t.shadowColor,t.shadowOffsetX,t.shadowOffsetY,t.shadowOpacity]);const ce=e.useRef(null),le=e.useRef(null),se=e.useRef(null);e.useLayoutEffect(()=>{t._cropModeEnabled&&(le.current.nodes([ce.current]),se.current.nodes([I.current]))},[t._cropModeEnabled]);const ue=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 r=e.target.width()*e.target.scaleX(),n=e.target.height()*e.target.scaleY(),o=Math.min(1,G/r),i=Math.min(1,J/n),a=1-o,d=Math.min(a,Math.max(0,Math.round(-e.target.x())/r)),h=1-i,c=Math.min(h,Math.max(0,Math.round(-e.target.y())/n));e.target.setAttrs({x:-d*U,y:-c*Z,scaleX:1,scaleY:1}),t.set({cropX:d,cropY:c,cropWidth:o,cropHeight:i})},ge=()=>{"svg"!==t.type&&t.contentEditable&&setTimeout(()=>{t.toggleCropMode(!0)})},fe="loading"===Y,me="failed"===Y,pe=!fe&&!me,we=e.useRef({cropX:0,cropY:0,cropWidth:0,cropHeight:0}),ve=pe?t.a.opacity:0;w(R,ve);const xe=t.selectable||"admin"===n.role,Me=v();return e.createElement(e.Fragment,null,e.createElement(o,{onMouseEnter:()=>O(!0),onMouseLeave:()=>O(!1)},fe&&e.createElement(b,{element:t}),me&&e.createElement(L,{element:t}),e.createElement(i,{ref:R,name:"element",id:t.id,image:oe,x:t.a.x,y:t.a.y,width:t.a.width||1,height:t.a.height||1,rotation:t.a.rotation,opacity:ve,shadowEnabled:t.shadowEnabled,shadowBlur:t.shadowBlur,shadowOffsetX:t.shadowOffsetX,shadowOffsetY:t.shadowOffsetY,shadowColor:t.shadowColor,shadowOpacity:t.shadowOpacity,customCrop:ee,listening:xe,draggable:Me?t.draggable&&S:t.draggable,preventDefault:!Me||S,hideInExport:!t.showInExport,onDragMove:e=>{t.set({x:e.target.x(),y:e.target.y()})},onDragEnd:e=>{t.set({x:e.target.x(),y:e.target.y()})},onDblClick:ge,onDblTap:ge,onTransformStart:()=>{m(!0),we.current={cropX:t.cropX,cropY:t.cropY,cropWidth:t.cropWidth,cropHeight:t.cropHeight}},onTransform:e=>{var r;const n=e.currentTarget,o=Math.abs(n.scaleX()-1)<1e-7?1:n.scaleX(),i=Math.abs(n.scaleY()-1)<1e-7?1:n.scaleY();n.scaleX(1),n.scaleY(1);const a=null===(r=e.target.getStage())||void 0===r?void 0:r.findOne("Transformer"),d=1-G/U,h=Math.min(d,Math.max(0,t.cropX)),c=1-J/Z,l=Math.min(c,Math.max(0,t.cropY)),s=a.getActiveAnchor(),u=!(s.indexOf("middle")>=0||s.indexOf("center")>=0),g=!u&&o<1&&we.current.cropHeight>J/Z;let f=u?t.cropWidth:t.cropWidth*o;g&&(f=t.cropWidth);const m=!u&&i<1&&we.current.cropWidth>G/U;let p=u?t.cropHeight:t.cropHeight*i;m&&(p=t.cropHeight),Q&&(f=t.cropWidth,p=t.cropHeight),t.set({cropX:h,cropY:l,x:n.x(),y:n.y(),width:n.width()*o,height:n.height()*i,rotation:e.target.rotation(),cropWidth:Math.min(f,1-h),cropHeight:Math.min(p,1-l)})},onTransformEnd:e=>{const r=e.currentTarget;t.set({width:r.width(),height:r.height(),x:r.x(),y:r.y(),rotation:e.target.rotation(),cropWidth:G/U,cropHeight:J/Z}),m(!1)}}),e.createElement(a,{x:t.a.x,y:t.a.y,width:Math.max(t.a.width-t.borderSize,0),height:Math.max(t.a.height-t.borderSize,0),opacity:ve,offsetX:-t.borderSize/2,offsetY:-t.borderSize/2,stroke:t.borderColor,strokeWidth:t.borderSize,listening:!1,visible:!!t.borderSize,rotation:t.rotation,cornerRadius:Math.max(0,te-t.borderSize),hideInExport:!t.showInExport}),!n.isPlaying&&e.createElement(i,{image:k?(W||Me)&&E:M,x:t.a.x,y:t.a.y,offsetX:-t.a.width/2+15/n.scale,offsetY:-t.a.height/2+15/n.scale,rotation:t.a.rotation,width:30/n.scale,height:30/n.scale,hideInExport:!0,onClick:()=>H(!k),onTap:()=>H(!k)}),t._cropModeEnabled&&e.createElement(s,{selector:".page-abs-container",enabled:!0},e.createElement(a,{x:-window.innerWidth/n.scale,y:-window.innerWidth/n.scale,width:window.innerWidth/n.scale*3,height:window.innerWidth/n.scale*3,fill:"rgba(0,0,0,0.3)"}),e.createElement(i,{listening:!1,image:oe,x:t.a.x,y:t.a.y,width:t.a.width,height:t.a.height,rotation:t.a.rotation,shadowEnabled:t.shadowEnabled,shadowBlur:t.shadowBlur}),e.createElement(o,{x:t.a.x,y:t.a.y,rotation:t.a.rotation,scaleX:he,scaleY:he},e.createElement(i,{image:P,ref:I,width:U,height:Z,opacity:.4,draggable:!0,x:-t.cropX*U,y:-t.cropY*Z,onDragMove:ue,onTransform:ue}),e.createElement(h,{ref:se,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.createElement(a,{width:G,height:J,ref:ce,listening:!1,onTransform:e=>{e.target.x()<-t.cropX*U-1e-9&&(e.target.x(-t.cropX*U),e.target.scaleX(1)),e.target.y()<-t.cropY*Z-1e-9&&(e.target.y(-t.cropY*Z),e.target.scaleY(1));const r=Math.min(1,Math.max(0,t.cropX+e.target.x()/U)),n=Math.min(1,Math.max(0,e.target.y()/Z+t.cropY)),o=e.target.width()*e.target.scaleX(),i=e.target.height()*e.target.scaleY(),a=Math.min(1-r,o/U),d=Math.min(1-n,i/Z),h=e.target.getAbsolutePosition(e.target.getParent().getParent());e.target.scale({x:1,y:1}),e.target.position({x:0,y:0}),t.set({x:h.x,y:h.y,cropX:r,cropY:n,cropWidth:a,cropHeight:d,width:Math.min(o*he,U*(1-r)*he),height:Math.min(i*he,Z*(1-n)*he)})}}),e.createElement(h,{ref:le,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:t.resizable})))))});
|
|
1
|
+
import e from"react";import{observer as t}from"mobx-react-lite";import{autorun as r}from"mobx";import{Arc as n,Group as o,Image as i,Rect as a,Text as d,Transformer as h}from"react-konva";import c from"use-image";import l from"konva";import{Portal as s}from"react-konva-utils";import{incrementLoader as u,triggerLoadError as g}from"../utils/loader.js";import*as f from"../utils/svg.js";import{flags as m}from"../utils/flags.js";import{applyFilter as p}from"./apply-filters.js";import{useFadeIn as w}from"./use-fadein.js";import{isTouchDevice as v}from"../utils/screen.js";import{useMediabunnyVideo as x}from"./use-mediabunny-video.js";function M(){return document.createElement("canvas")}const E=new window.Image;E.src=f.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 y=new window.Image;y.src=f.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=(t,r,n,o,i=0,a=!1)=>{const d=Math.floor(Math.max(t.width*o,1)),h=Math.floor(Math.max(t.height*o,1)),c=Math.min(i*o,d/2,h/2),s=Math.max(t.width/n.width,t.height/n.height)*o,u=t.page._exportingOrRendering&&m.imageDownScalingEnabled&&s<1&&!a,g=r instanceof HTMLVideoElement?r.videoWidth:null==r?void 0:r.width,f=r instanceof HTMLVideoElement?r.videoHeight:null==r?void 0:r.height,p=0===n.x&&0===n.y&&n.width===g&&n.height===f,w=e.useMemo(()=>{if(r&&g&&f){return p&&0===c&&!u?void 0:M()}},[r,c,u,p,g,f]),v=()=>{if(!w||!r){return}w.width=d,w.height=h;const e=w.getContext("2d");if(!e){return}c&&(e.beginPath(),e.moveTo(c,0),e.lineTo(d-c,0),e.arc(d-c,c,c,3*Math.PI/2,0,!1),e.lineTo(d,h-c),e.arc(d-c,h-c,c,0,Math.PI/2,!1),e.lineTo(c,h),e.arc(c,h-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 t=u?function(e,t){var r,n;const o=M(),i=e instanceof HTMLVideoElement?e.videoWidth:e.width,a=e instanceof HTMLVideoElement?e.videoHeight:e.height;o.width=i,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,n,o,i,a){for(var d=new ImageData(t,r),h=new Int32Array(e.data.buffer),c=e.width,l=new Int32Array(d.data.buffer),s=d.width,u=t/i,g=r/a,f=Math.round(1/u),m=Math.round(1/g),p=f*m,w=0;w<d.height;w++){for(var v=0;v<s;v++){for(var x=0+Math.round(v/u)+(0+Math.round(w/g))*c,M=0,E=0,y=0,b=0,L=0;L<m;L++){for(var T=0;T<f;T++){var C=h[x+T+L*c];M+=C<<24>>>24,E+=C<<16>>>24,y+=C<<8>>>24,b+=C>>>24}}M=Math.round(M/p),E=Math.round(E/p),y=Math.round(y/p),b=Math.round(b/p),l[v+w*s]=b<<24|y<<16|E<<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===(n=o.getContext("2d"))||void 0===n||n.putImageData(d,0,0),o}(r,s):r,o=u?{x:Math.floor(n.x*s),y:Math.floor(n.y*s),width:Math.floor(n.width*s),height:Math.floor(n.height*s)}:n;e.drawImage(t,o.x,o.y,o.width,o.height,0,0,w.width,w.height)};return e.useLayoutEffect(()=>{v()},[w,t.width,t.height,n.x,n.y,n.width,n.height,i,o,a,t.page._exportingOrRendering,u]),e.useEffect(()=>()=>{w&&"CANVAS"===w.nodeName&&l.Util.releaseCanvas(w)},[w]),[w||r,v]};const b=M(),L=t(({element:t})=>{const r=Math.min(30,t.width/4,t.height/4),i=e.useRef(null);return e.useEffect(()=>{const e=i.current;if(!e){return}const t=new l.Animation(t=>{e.rotate(((null==t?void 0:t.timeDiff)||0)/2)},e.getLayer());return t.start(),()=>{t.stop()}}),e.createElement(o,{x:t.a.x,y:t.a.y,rotation:t.a.rotation,listening:!1,opacity:t.a.opacity,hideInExport:!t.showInExport},e.createElement(a,{width:t.width,height:t.height,fill:"rgba(124, 173, 212, 0.8)"}),e.createElement(n,{ref:i,x:t.width/2,y:t.height/2,fill:"white",outerRadius:Math.abs(r),innerRadius:Math.max(1,r-5),angle:270}))}),T=t(({element:t})=>{const r=Math.max(10,Math.min(30,t.width/25));return e.createElement(o,{x:t.a.x,y:t.a.y,rotation:t.a.rotation,listening:!1,opacity:t.a.opacity,hideInExport:!t.showInExport},e.createElement(a,{width:t.width,height:t.height,fill:"rgba(223, 102, 102, 0.8)"}),e.createElement(d,{text:"Can not load the video...",fontSize:r,width:t.width,height:t.height,align:"center",fill:"white",verticalAlign:"middle",padding:5}))});let C=function(t,r,n){const o=e.useRef("loading"),i=e.useRef(null),[a,d]=e.useState(0),h=e.useRef(),c=e.useRef(),l=e.useRef();return h.current===t&&c.current===r&&l.current===n||(o.current="loading",i.current=void 0,h.current=t,c.current=r,l.current=n),e.useLayoutEffect(function(){if(t){var e=document.createElement("video");return e.addEventListener("canplay",a),e.addEventListener("error",h),r&&(e.crossOrigin=r),n&&(e.referrerPolicy=n),e.src=t,e.load(),function(){e.removeEventListener("canplay",a),e.removeEventListener("error",h)}}function a(){o.current="loaded",i.current=e,i.current.currentTime=0,d(Math.random()),i.current.removeEventListener("canplay",a)}function h(t){var r;const n=4===e.readyState,a=e.buffered&&e.buffered.length>0&&e.buffered.end(e.buffered.length-1)/e.duration*100>=100;if(n&&a){return}const h=t.message||(null===(r=e.error)||void 0===r?void 0:r.message)||"Unknown error",c=new Error("Video failed to load: "+h);console.error(c),o.current="failed",i.current=void 0,d(Math.random())}},[t,r,n]),[i.current,o.current]};export const setVideoLoaderHook=e=>{C=e};function R(e){return e.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA}export const useLoader=(t,r,n)=>{const o=e.useRef(),i=()=>{var e;null===(e=o.current)||void 0===e||e.call(o),o.current=void 0};e.useEffect(()=>i,[]),e.useLayoutEffect(()=>{const e=r.slice(0,200),a=`video with id ${n} url: ${e}`;"loading"!==t||o.current||(o.current=u(a)),"loading"!==t&&i(),"failed"===t&&g(a)},[t])};export const VideoElement=t(({element:t,store:n})=>{var d;const[g,m]=e.useState(!1),I=e.useRef(null),S=e.useRef(null),k=n.selectedShapes.indexOf(t)>=0&&t.selectable,[H,X]=e.useState(!1),[Y,W]=C(t.src,"anonymous"),[O,_]=e.useState(!1),A=n.activePage===t.page,P=t.page._exportingOrRendering&&"loaded"===W,V=x(t,n,P);useLoader(W,t.src,t.id),Y&&(Y.playsInline=!0);const D=((t,r,n)=>{const o=e.useMemo(()=>{var e,o;const{flipX:i,flipY:a}=t,d="svg"===t.type||t.src.indexOf("data:image/svg+xml")>=0||t.src.indexOf(".svg")>=0,h=navigator.userAgent.toLowerCase().indexOf("firefox")>-1;if(!(i||a||h&&d)){return r}if(!r){return null}const c=r instanceof HTMLVideoElement?r.videoWidth:null==r?void 0:r.width,l=r instanceof HTMLVideoElement?r.videoHeight:null==r?void 0:r.height;if(!c||!l){return null}const s=M();let u=1;"svg"===t.type&&(u=Math.max(t.width/c*n,t.height/l*n)),s.width=Math.max(c*u,1),s.height=Math.max(l*u,1);let g=i?-s.width:0,f=a?-s.height:0;return null===(e=s.getContext("2d"))||void 0===e||e.scale(i?-1:1,a?-1:1),null===(o=s.getContext("2d"))||void 0===o||o.drawImage(r,g,f,s.width,s.height),s},[t.flipX,t.flipY,r,t.width,t.height,n]);return e.useEffect(()=>()=>{o&&"CANVAS"===o.nodeName&&l.Util.releaseCanvas(o)},[o]),o})(t,Y,n._elementsPixelRatio),z=P&&V||D||b;e.useEffect(()=>{Y&&n.history.ignore(()=>{t.set({duration:1e3*Y.duration})})},[Y]),e.useEffect(()=>{var e;if(!Y){return}const r=n.animatedElementsIds,o=(!r.length||r.includes(t.id))&&n.isPlaying,i=A&&(o||H);if(!i){return void Y.pause()}i&&(Y.currentTime=t.startTime*Y.duration,Y.play());const a=new l.Animation(()=>{le.current()},null===(e=I.current)||void 0===e?void 0:e.getLayer());a.start();const d=()=>{X(!1),Y.currentTime=t.startTime*Y.duration},h=()=>{Y.currentTime>=t.endTime*Y.duration&&(Y.pause(),Y.currentTime=t.startTime*Y.duration,X(!1))};return Y.addEventListener("ended",d),Y.addEventListener("timeupdate",h),()=>{Y.pause(),a.stop(),Y.removeEventListener("ended",d),Y.removeEventListener("timeupdate",h)}},[Y,H,n.isPlaying,A]),e.useEffect(()=>{Y&&(Y.volume=t.volume)},[Y,t.volume]);const j=e.useRef();e.useEffect(()=>{const e=r(()=>{var e,r;if(Y){if(P&&V){return ce(),void n.currentTime}const o=n.animatedElementsIds;if(o.length&&!o.includes(t.id)){return}const i=n.currentTime>=t.page.startTime&&n.currentTime<t.page.startTime+t.page.duration,a=t.startTime*Y.duration*1e3,d=Y.duration*(t.endTime-t.startTime)*1e3;let h=((n.currentTime||t.page.startTime)-t.page.startTime)%d+a;if(i||(h=0),Math.abs(1e3*Y.currentTime-h)>500||!n.isPlaying){const e=h/1e3;e!==Y.currentTime&&(Y.currentTime=e),!R(Y)&&!n.isPlaying&&!j.current&&(j.current=u(`video ${t.id}`))}le.current(),null===(r=null===(e=I.current)||void 0===e?void 0:e.getLayer())||void 0===r||r.batchDraw()}});return()=>{e(),j.current&&(j.current(),j.current=null)}},[n,Y,P,V]),e.useEffect(()=>{var e;if(!Y){return}if(P){return null===(e=j.current)||void 0===e||e.call(j),void(j.current=null)}const r=()=>{var e,r;!R(Y)&&t.page._exportingOrRendering||j.current&&(le.current(),null===(r=null===(e=I.current)||void 0===e?void 0:e.getLayer())||void 0===r||r.batchDraw(),j.current(),j.current=null)};let n;return t.page._exportingOrRendering&&(n=setInterval(r,20)),Y.addEventListener("timeupdate",r),Y.addEventListener("canplay",r),()=>{clearInterval(n),Y.removeEventListener("timeupdate",r),Y.removeEventListener("canplay",r)}},[t.page._exportingOrRendering,Y,t.id,u,P]);let{cropX:B,cropY:U,cropWidth:N,cropHeight:Z}=t;"loaded"!==W&&(B=U=0,N=Z=1);const F=($=z)instanceof HTMLVideoElement?$.videoWidth:(null==$?void 0:$.width)||0;var $;const q=(e=>e instanceof HTMLVideoElement?e.videoHeight:(null==e?void 0:e.height)||0)(z),G=F*N,J=q*Z,K=t.width/t.height;let Q,ee;const te=G/J,re="svg"===t.type;re?(Q=G,ee=J):K>=te?(Q=G,ee=G/K):(Q=J*K,ee=J);const ne={x:F*B,y:q*U,width:Q,height:ee},oe=null!==(d=t.cornerRadius)&&void 0!==d?d:0,[ie,ae]=useCornerRadiusAndCrop(t,z,ne,n._elementsPixelRatio,oe,!0);let[de,he]=((t,r,n,o)=>{const i=(t=>{const[r,n]=e.useState(t);return e.useEffect(()=>{(async()=>{const e=await async function(e){if(!(e.indexOf("data:image/svg+xml")>=0||e.indexOf(".svg")>=0)){return e}const t=await f.urlToString(e),r=f.fixSize(t);return f.svgToURL(r)}(t);e!==r&&n(e)})()},[t]),r})(t.clipSrc||""),[a,d]=c(i,"anonymous"),h=t.clipSrc?d:"loaded";useLoader(h,t.clipSrc,t.id);const s=e.useMemo(()=>{if(r&&a){return M()}},[r,a]);function u(){var e;if(!a){return}const o=r instanceof HTMLVideoElement?r.videoWidth:null==r?void 0:r.width,i=r instanceof HTMLVideoElement?r.videoHeight:null==r?void 0:r.height;if(!r||!o||!i){return}if(!a||!a.width||!a.height){return}if(!s){return}const d=M(),h=Math.max(t.width/a.width*n,t.height/a.height*n);d.width=a.width*h,d.height=a.height*h,null===(e=d.getContext("2d"))||void 0===e||e.drawImage(a,0,0,d.width,d.height),s.width=Math.max(o,1),s.height=Math.max(i,1);const c=s.getContext("2d");c&&(c.save(),c.drawImage(d,0,0,o,i),l.Util.releaseCanvas(d),c.globalCompositeOperation="source-in",c.drawImage(r,0,0,s.width,s.height),c.restore())}return e.useLayoutEffect(()=>{u()},[s,r,a,t.width,t.height,n,...o]),[t.clipSrc&&a?s:r,u]})(t,ie,n._elementsPixelRatio,[ne,oe,n._elementsPixelRatio]);function ce(){var e,t;ae(),he(),null===(t=null===(e=I.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()}e.useEffect(()=>{ce()});const le=e.useRef(ce);le.current=ce;const se=Math.max(t.width/Q,t.height/ee);e.useEffect(()=>{var e;if(!t._cropModeEnabled){return}const r=null===(e=I.current)||void 0===e?void 0:e.getStage();function n(e){t._cropModeEnabled&&e.target!==S.current&&t.toggleCropMode(!1)}function o(e){t._cropModeEnabled&&e.target.parentNode!==r.content&&t.toggleCropMode(!1)}return document.body.addEventListener("click",o),null==r||r.on("click",n),null==r||r.on("tap",n),()=>{document.body.removeEventListener("click",o),document.body.removeEventListener("touchstart",o),null==r||r.off("click",n),null==r||r.off("click",n)}},[t._cropModeEnabled]),e.useLayoutEffect(()=>{if(!g&&!t._cropModeEnabled){return p(I.current,t),r(()=>{p(I.current,t)},{delay:100})}},[z,g,N,Z,t._cropModeEnabled]),e.useLayoutEffect(()=>{var e;g||t._cropModeEnabled?null===(e=I.current)||void 0===e||e.clearCache():p(I.current,t)},[g,t.width,t.height,t._cropModeEnabled]),e.useEffect(()=>{p(I.current,t)},[t.shadowEnabled,t.shadowBlur,t.cornerRadius,t.shadowColor,t.shadowOffsetX,t.shadowOffsetY,t.shadowOpacity]);const ue=e.useRef(null),ge=e.useRef(null),fe=e.useRef(null);e.useLayoutEffect(()=>{t._cropModeEnabled&&(ge.current.nodes([ue.current]),fe.current.nodes([S.current]))},[t._cropModeEnabled]);const me=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 r=e.target.width()*e.target.scaleX(),n=e.target.height()*e.target.scaleY(),o=Math.min(1,Q/r),i=Math.min(1,ee/n),a=1-o,d=Math.min(a,Math.max(0,Math.round(-e.target.x())/r)),h=1-i,c=Math.min(h,Math.max(0,Math.round(-e.target.y())/n));e.target.setAttrs({x:-d*F,y:-c*q,scaleX:1,scaleY:1}),t.set({cropX:d,cropY:c,cropWidth:o,cropHeight:i})},pe=()=>{"svg"!==t.type&&t.contentEditable&&setTimeout(()=>{t.toggleCropMode(!0)})},we="loading"===W,ve="failed"===W,xe=!we&&!ve,Me=e.useRef({cropX:0,cropY:0,cropWidth:0,cropHeight:0}),Ee=xe?t.a.opacity:0;w(I,Ee);const ye=t.selectable||"admin"===n.role,be=v();return e.createElement(e.Fragment,null,e.createElement(o,{onMouseEnter:()=>_(!0),onMouseLeave:()=>_(!1)},we&&e.createElement(L,{element:t}),ve&&e.createElement(T,{element:t}),e.createElement(i,{ref:I,name:"element",id:t.id,image:de,x:t.a.x,y:t.a.y,width:t.a.width||1,height:t.a.height||1,rotation:t.a.rotation,opacity:Ee,shadowEnabled:t.shadowEnabled,shadowBlur:t.shadowBlur,shadowOffsetX:t.shadowOffsetX,shadowOffsetY:t.shadowOffsetY,shadowColor:t.shadowColor,shadowOpacity:t.shadowOpacity,customCrop:ne,listening:ye,draggable:be?t.draggable&&k:t.draggable,preventDefault:!be||k,hideInExport:!t.showInExport,onDragMove:e=>{t.set({x:e.target.x(),y:e.target.y()})},onDragEnd:e=>{t.set({x:e.target.x(),y:e.target.y()})},onDblClick:pe,onDblTap:pe,onTransformStart:()=>{m(!0),Me.current={cropX:t.cropX,cropY:t.cropY,cropWidth:t.cropWidth,cropHeight:t.cropHeight}},onTransform:e=>{var r;const n=e.currentTarget,o=Math.abs(n.scaleX()-1)<1e-7?1:n.scaleX(),i=Math.abs(n.scaleY()-1)<1e-7?1:n.scaleY();n.scaleX(1),n.scaleY(1);const a=null===(r=e.target.getStage())||void 0===r?void 0:r.findOne("Transformer"),d=1-Q/F,h=Math.min(d,Math.max(0,t.cropX)),c=1-ee/q,l=Math.min(c,Math.max(0,t.cropY)),s=a.getActiveAnchor(),u=!(s.indexOf("middle")>=0||s.indexOf("center")>=0),g=!u&&o<1&&Me.current.cropHeight>ee/q;let f=u?t.cropWidth:t.cropWidth*o;g&&(f=t.cropWidth);const m=!u&&i<1&&Me.current.cropWidth>Q/F;let p=u?t.cropHeight:t.cropHeight*i;m&&(p=t.cropHeight),re&&(f=t.cropWidth,p=t.cropHeight),t.set({cropX:h,cropY:l,x:n.x(),y:n.y(),width:n.width()*o,height:n.height()*i,rotation:e.target.rotation(),cropWidth:Math.min(f,1-h),cropHeight:Math.min(p,1-l)})},onTransformEnd:e=>{const r=e.currentTarget;t.set({width:r.width(),height:r.height(),x:r.x(),y:r.y(),rotation:e.target.rotation(),cropWidth:Q/F,cropHeight:ee/q}),m(!1)}}),e.createElement(a,{x:t.a.x,y:t.a.y,width:Math.max(t.a.width-t.borderSize,0),height:Math.max(t.a.height-t.borderSize,0),opacity:Ee,offsetX:-t.borderSize/2,offsetY:-t.borderSize/2,stroke:t.borderColor,strokeWidth:t.borderSize,listening:!1,visible:!!t.borderSize,rotation:t.rotation,cornerRadius:Math.max(0,oe-t.borderSize),hideInExport:!t.showInExport}),!n.isPlaying&&e.createElement(i,{image:H?(O||be)&&y:E,x:t.a.x,y:t.a.y,offsetX:-t.a.width/2+15/n.scale,offsetY:-t.a.height/2+15/n.scale,rotation:t.a.rotation,width:30/n.scale,height:30/n.scale,hideInExport:!0,onClick:()=>X(!H),onTap:()=>X(!H)}),t._cropModeEnabled&&e.createElement(s,{selector:".page-abs-container",enabled:!0},e.createElement(a,{x:-window.innerWidth/n.scale,y:-window.innerWidth/n.scale,width:window.innerWidth/n.scale*3,height:window.innerWidth/n.scale*3,fill:"rgba(0,0,0,0.3)"}),e.createElement(i,{listening:!1,image:de,x:t.a.x,y:t.a.y,width:t.a.width,height:t.a.height,rotation:t.a.rotation,shadowEnabled:t.shadowEnabled,shadowBlur:t.shadowBlur}),e.createElement(o,{x:t.a.x,y:t.a.y,rotation:t.a.rotation,scaleX:se,scaleY:se},e.createElement(i,{image:z,ref:S,width:F,height:q,opacity:.4,draggable:!0,x:-t.cropX*F,y:-t.cropY*q,onDragMove:me,onTransform:me}),e.createElement(h,{ref:fe,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.createElement(a,{width:Q,height:ee,ref:ue,listening:!1,onTransform:e=>{e.target.x()<-t.cropX*F-1e-9&&(e.target.x(-t.cropX*F),e.target.scaleX(1)),e.target.y()<-t.cropY*q-1e-9&&(e.target.y(-t.cropY*q),e.target.scaleY(1));const r=Math.min(1,Math.max(0,t.cropX+e.target.x()/F)),n=Math.min(1,Math.max(0,e.target.y()/q+t.cropY)),o=e.target.width()*e.target.scaleX(),i=e.target.height()*e.target.scaleY(),a=Math.min(1-r,o/F),d=Math.min(1-n,i/q),h=e.target.getAbsolutePosition(e.target.getParent().getParent());e.target.scale({x:1,y:1}),e.target.position({x:0,y:0}),t.set({x:h.x,y:h.y,cropX:r,cropY:n,cropWidth:a,cropHeight:d,width:Math.min(o*se,F*(1-r)*se),height:Math.min(i*se,q*(1-n)*se)})}}),e.createElement(h,{ref:ge,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:t.resizable})))))});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"react";import{observer as t}from"mobx-react-lite";import r from"./page.js";import{TopRules as n}from"./rules.js";import{AudioElement as o}from"./audio.js";import{handleHotkey as i}from"./hotkeys.js";import{t as a}from"../utils/l10n.js";const l=({store:t})=>e.createElement("div",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",textAlign:"center"}},e.createElement("p",null,a("workspace.noPages")),e.createElement("button",{onClick:()=>{t.addPage()}},a("workspace.addPage"))),s=({width:t,height:r,xPadding:n,yPadding:o,backgroundColor:i})=>e.createElement("div",{style:{width:t+"px",height:r+"px",backgroundColor:i,paddingLeft:n+"px",paddingRight:n+"px",paddingTop:o+"px",paddingBottom:o+"px",flexShrink:0}},e.createElement("div",{style:{width:" 100%",height:"100%",backgroundColor:"white"}})),c=[4,6];export const WorkspaceCanvas=t(({store:t,layout:a="vertical",pageControlsEnabled:u,backgroundColor:d,pageBorderColor:h,activePageBorderColor:g,bleedColor:f,snapGuideStroke:p,snapGuideStrokeWidth:m,snapGuideDash:v,selectionRectFill:w,selectionRectStroke:b,selectionRectStrokeWidth:x,transformLabelFill:k,transformLabelTextFill:y,distanceGuideStroke:E,distanceLabelFill:T,distanceLabelTextFill:L,components:P,onKeyDown:M,paddingX:R,paddingY:S,altCloneEnabled:C=!0,visiblePagesOffset:F,renderOnlyActivePage:W,tooltipSafeArea:O})=>{var _;const j="horizontal"===a,z=null!=R?R:20,G=null!=S?S:55,[B,D]=e.useState({width:100,height:100}),H=e.useRef(B),N=e.useRef(null),A=e.useRef(null),Y=t.bleedVisible?Math.max(0,...t.pages.map(e=>e.bleed)):0,I=Math.max(...t.pages.map(e=>e.computedWidth)),K=Math.max(...t.pages.map(e=>e.computedHeight)),V=(null===(_=t.activePage)||void 0===_?void 0:_.computedHeight)||0,X=I+2*Y,q=(W?V:K)+2*Y,J=async({skipTimeout:e}={skipTimeout:!1})=>{if(e||await new Promise(e=>setTimeout(e,50)),null===N.current){return}const r=N.current.getBoundingClientRect();0!==r.width&&0!==r.height||(console.warn("Polotno warning: <Workspace /> component can not automatically detect its size.\nWidth or height of parent elements is equal 0.\nPlease make sure it has non-zero size. You may need to adjust it with your styles. <Workspace /> will automatically fit into parent container.\nFor simpler debugging here is the log of the parent element:"),console.log(N.current));const n=A.current.clientWidth||r.width,o={width:n,height:r.height};(H.current.width!==o.width||H.current.height!==o.height)&&(D(o),H.current=o);const i=(n-2*z)/X,a=t.pages.length>1?3.1:2,l=(r.height-G*a)/q,s=t.pages.length>1?3.1:2,c=(n-z*s)/X,u=(r.height-2*G)/q,d=t.pages.length?Math.max(Math.min(j?c:i,j?u:l),.01):1;t.scaleToFit!==d&&(t.setScale(d),t._setScaleToFit(d))};e.useLayoutEffect(()=>{J({skipTimeout:!0})},[]),e.useEffect(()=>{J()},[X,q,S,R]),e.useLayoutEffect(()=>{J({skipTimeout:!0})},[t.openedSidePanel]),e.useEffect(()=>{t.__()},[]),e.useEffect(()=>{const e=N.current;if(window.ResizeObserver){const t=new ResizeObserver(()=>{J({skipTimeout:!0})});return t.observe(e),()=>t.unobserve(e)}{const e=setInterval(()=>{J({skipTimeout:!0})},100);return()=>clearInterval(e)}},[X,q]);const Q=W?1:t.pages.length;let U,Z;if(j){const e=X*t.scale*Q;U=Math.max(z,(B.width-e)/Q/2),Z=Math.max(G,(B.height-q*t.scale)/2)}else{U=Math.max(z,(B.width-X*t.scale)/2);const e=q*t.scale*Q;Z=Math.max(G,(B.height-e)/Q/2)}e.useEffect(()=>{const e=e=>{(M||i)(e,t)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[]),e.useEffect(()=>{const e=e=>{if(e.ctrlKey||e.metaKey){e.preventDefault();const i=Math.max(5,t.scaleToFit);let a=Math.min(.1,t.scaleToFit);j&&X>0&&Number.isFinite(X)&&(a=Math.max(a,300/X)),a=Math.max(a,.01);const l=.03,s=(r=e.deltaY<0?t.scale*(1+l):t.scale/(1+l),n=a,o=i,Math.max(n,Math.min(o,r)));return void t.setScale(s)}var r,n,o},r=A.current;return null==r||r.addEventListener("wheel",e),()=>null==r?void 0:r.removeEventListener("wheel",e)},[j,X,t]);const $=e.useRef(!1);((t,r,n,o,i,a)=>{const l=e.useRef({width:r,height:n}),s=e.useRef({top:0,left:0}),c=e.useRef(!1),u=e.useRef(i.pages.length);c.current=u.current!==i.pages.length,u.current=i.pages.length,e.useEffect(()=>{const e=t.current,r=t=>{s.current={top:e.scrollTop,left:e.scrollLeft}};return e.addEventListener("scroll",r),()=>{e.removeEventListener("scroll",r)}},[]),e.useLayoutEffect(()=>{if(!t.current){return}if(c.current){return}const e=t.current,o=(s.current.left+e.offsetWidth/2)/l.current.width,i=(s.current.top+e.offsetHeight/2)/l.current.height;a.current=!0,e.scrollLeft=o*r-e.offsetWidth/2,e.scrollTop=i*n-e.offsetHeight/2,l.current={width:r,height:n}},[o,r,n])})(A,X*t.scale+2*U,q*t.scale+2*Z,t.scale,t,$);const ee=j?X*t.scale+2*U:q*t.scale+2*Z,{handleScroll:te}=((t,r,n,o,i,a,l)=>{const s=e.useRef(!1),c=e.useRef(null),u=e.useRef(!1),d="horizontal"===l;e.useEffect(()=>{const e=t.current,r=()=>{i.current};return e.addEventListener("scroll",r),()=>{e.removeEventListener("scroll",r)}},[]);const h=n.pages.indexOf(n.activePage);return e.useLayoutEffect(()=>{if(a){return}if(!n.activePage){return}if(!t.current){return}if(s.current){return}const e=t.current,o=n.pages.indexOf(n.activePage)*r,i=d?e.scrollLeft:e.scrollTop;let l=()=>{};return(Math.abs(o-i)>.5*r||u.current)&&(u.current=!0,l=(({element:e,scrollTop:t,scrollLeft:r,duration:n=300,onFinish:o=()=>{}})=>{const i=void 0!==t,a=i?e.scrollTop:e.scrollLeft,l=i?t:r,s=l-a;let c=0,u=!1;if(0===n){return i?e.scrollTop=l:e.scrollLeft=l,()=>{}}const d=()=>{if(u){return}c+=20;const t=h(c,a,s,n);i?e.scrollTop=t:e.scrollLeft=t,c<n?setTimeout(d,20):o()},h=(e,t,r,n)=>(e/=n/2)<1?r/2*e*e+t:-r/2*(--e*(e-2)-1)+t;return d(),()=>{u=!0}})(Object.assign(Object.assign({element:e},d?{scrollLeft:o}:{scrollTop:o}),{onFinish:()=>{u.current=!1},duration:n.isPlaying?0:300}))),l},[n.activePage,h,n.isPlaying,a,l]),{handleScroll:e=>{if(a){return}if(u.current){return}s.current=!0,clearTimeout(c.current),c.current=setTimeout(()=>{s.current=!1},300);const t=e.currentTarget.childNodes[0];if(!t){return}const r=d?t.offsetWidth:t.offsetHeight;if(!r){return}const i=d?e.currentTarget.scrollLeft:e.currentTarget.scrollTop,l=d?o.width:o.height,h=Math.floor((i+l/3)/r),g=n.pages[h];g&&n.activePage!==g&&g.select()}}})(A,ee,t,B,$,W,a),re=B.width>=X*t.scale+2*U,ne=d||"rgba(232, 232, 232, 0.9)",
|
|
1
|
+
import e from"react";import{observer as t}from"mobx-react-lite";import r from"./page.js";import{TopRules as n}from"./rules.js";import{AudioElement as o}from"./audio.js";import{handleHotkey as i}from"./hotkeys.js";import{t as a}from"../utils/l10n.js";const l=({store:t})=>e.createElement("div",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",textAlign:"center"}},e.createElement("p",null,a("workspace.noPages")),e.createElement("button",{onClick:()=>{t.addPage()}},a("workspace.addPage"))),s=({width:t,height:r,xPadding:n,yPadding:o,backgroundColor:i})=>e.createElement("div",{style:{width:t+"px",height:r+"px",backgroundColor:i,paddingLeft:n+"px",paddingRight:n+"px",paddingTop:o+"px",paddingBottom:o+"px",flexShrink:0}},e.createElement("div",{style:{width:" 100%",height:"100%",backgroundColor:"white"}})),c=[4,6];export const WorkspaceCanvas=t(({store:t,layout:a="vertical",pageControlsEnabled:u,backgroundColor:d,pageBorderColor:h,activePageBorderColor:g,bleedColor:f,snapGuideStroke:p,snapGuideStrokeWidth:m,snapGuideDash:v,selectionRectFill:w,selectionRectStroke:b,selectionRectStrokeWidth:x,transformLabelFill:k,transformLabelTextFill:y,distanceGuideStroke:E,distanceLabelFill:T,distanceLabelTextFill:L,components:P,onKeyDown:M,paddingX:R,paddingY:S,altCloneEnabled:C=!0,visiblePagesOffset:F,renderOnlyActivePage:W,tooltipSafeArea:O})=>{var _;const j="horizontal"===a,z=null!=R?R:20,G=null!=S?S:55,[B,D]=e.useState({width:100,height:100}),H=e.useRef(B),N=e.useRef(null),A=e.useRef(null),Y=t.bleedVisible?Math.max(0,...t.pages.map(e=>e.bleed)):0,I=Math.max(...t.pages.map(e=>e.computedWidth)),K=Math.max(...t.pages.map(e=>e.computedHeight)),V=(null===(_=t.activePage)||void 0===_?void 0:_.computedHeight)||0,X=I+2*Y,q=(W?V:K)+2*Y,J=async({skipTimeout:e}={skipTimeout:!1})=>{if(e||await new Promise(e=>setTimeout(e,50)),null===N.current){return}const r=N.current.getBoundingClientRect();0!==r.width&&0!==r.height||(console.warn("Polotno warning: <Workspace /> component can not automatically detect its size.\nWidth or height of parent elements is equal 0.\nPlease make sure it has non-zero size. You may need to adjust it with your styles. <Workspace /> will automatically fit into parent container.\nFor simpler debugging here is the log of the parent element:"),console.log(N.current));const n=A.current.clientWidth||r.width,o={width:n,height:r.height};(H.current.width!==o.width||H.current.height!==o.height)&&(D(o),H.current=o);const i=(n-2*z)/X,a=t.pages.length>1?3.1:2,l=(r.height-G*a)/q,s=t.pages.length>1?3.1:2,c=(n-z*s)/X,u=(r.height-2*G)/q,d=t.pages.length?Math.max(Math.min(j?c:i,j?u:l),.01):1;t.scaleToFit!==d&&(t.setScale(d),t._setScaleToFit(d))};e.useLayoutEffect(()=>{J({skipTimeout:!0})},[]),e.useEffect(()=>{J()},[X,q,S,R]),e.useLayoutEffect(()=>{J({skipTimeout:!0})},[t.openedSidePanel]),e.useEffect(()=>{t.__()},[]),e.useEffect(()=>{const e=N.current;if(window.ResizeObserver){const t=new ResizeObserver(()=>{J({skipTimeout:!0})});return t.observe(e),()=>t.unobserve(e)}{const e=setInterval(()=>{J({skipTimeout:!0})},100);return()=>clearInterval(e)}},[X,q]);const Q=W?1:t.pages.length;let U,Z;if(j){const e=X*t.scale*Q;U=Math.max(z,(B.width-e)/Q/2),Z=Math.max(G,(B.height-q*t.scale)/2)}else{U=Math.max(z,(B.width-X*t.scale)/2);const e=q*t.scale*Q;Z=Math.max(G,(B.height-e)/Q/2)}e.useEffect(()=>{const e=e=>{(M||i)(e,t)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[]),e.useEffect(()=>{const e=e=>{if(e.ctrlKey||e.metaKey){e.preventDefault();const i=Math.max(5,t.scaleToFit);let a=Math.min(.1,t.scaleToFit);j&&X>0&&Number.isFinite(X)&&(a=Math.max(a,300/X)),a=Math.max(a,.01);const l=.03,s=(r=e.deltaY<0?t.scale*(1+l):t.scale/(1+l),n=a,o=i,Math.max(n,Math.min(o,r)));return void t.setScale(s)}var r,n,o},r=A.current;return null==r||r.addEventListener("wheel",e),()=>null==r?void 0:r.removeEventListener("wheel",e)},[j,X,t]);const $=e.useRef(!1);((t,r,n,o,i,a)=>{const l=e.useRef({width:r,height:n}),s=e.useRef({top:0,left:0}),c=e.useRef(!1),u=e.useRef(i.pages.length);c.current=u.current!==i.pages.length,u.current=i.pages.length,e.useEffect(()=>{const e=t.current,r=t=>{s.current={top:e.scrollTop,left:e.scrollLeft}};return e.addEventListener("scroll",r),()=>{e.removeEventListener("scroll",r)}},[]),e.useLayoutEffect(()=>{if(!t.current){return}if(c.current){return}const e=t.current,o=(s.current.left+e.offsetWidth/2)/l.current.width,i=(s.current.top+e.offsetHeight/2)/l.current.height;a.current=!0,e.scrollLeft=o*r-e.offsetWidth/2,e.scrollTop=i*n-e.offsetHeight/2,l.current={width:r,height:n}},[o,r,n])})(A,X*t.scale+2*U,q*t.scale+2*Z,t.scale,t,$);const ee=j?X*t.scale+2*U:q*t.scale+2*Z,{handleScroll:te}=((t,r,n,o,i,a,l)=>{const s=e.useRef(!1),c=e.useRef(null),u=e.useRef(!1),d="horizontal"===l;e.useEffect(()=>{const e=t.current,r=()=>{i.current};return e.addEventListener("scroll",r),()=>{e.removeEventListener("scroll",r)}},[]);const h=n.pages.indexOf(n.activePage);return e.useLayoutEffect(()=>{if(a){return}if(!n.activePage){return}if(!t.current){return}if(s.current){return}const e=t.current,o=n.pages.indexOf(n.activePage)*r,i=d?e.scrollLeft:e.scrollTop;let l=()=>{};return(Math.abs(o-i)>.5*r||u.current)&&(u.current=!0,l=(({element:e,scrollTop:t,scrollLeft:r,duration:n=300,onFinish:o=()=>{}})=>{const i=void 0!==t,a=i?e.scrollTop:e.scrollLeft,l=i?t:r,s=l-a;let c=0,u=!1;if(0===n){return i?e.scrollTop=l:e.scrollLeft=l,()=>{}}const d=()=>{if(u){return}c+=20;const t=h(c,a,s,n);i?e.scrollTop=t:e.scrollLeft=t,c<n?setTimeout(d,20):o()},h=(e,t,r,n)=>(e/=n/2)<1?r/2*e*e+t:-r/2*(--e*(e-2)-1)+t;return d(),()=>{u=!0}})(Object.assign(Object.assign({element:e},d?{scrollLeft:o}:{scrollTop:o}),{onFinish:()=>{u.current=!1},duration:n.isPlaying?0:300}))),l},[n.activePage,h,n.isPlaying,a,l]),{handleScroll:e=>{if(a){return}if(u.current){return}s.current=!0,clearTimeout(c.current),c.current=setTimeout(()=>{s.current=!1},300);const t=e.currentTarget.childNodes[0];if(!t){return}const r=d?t.offsetWidth:t.offsetHeight;if(!r){return}const i=d?e.currentTarget.scrollLeft:e.currentTarget.scrollTop,l=d?o.width:o.height,h=Math.floor((i+l/3)/r),g=n.pages[h];g&&n.activePage!==g&&g.select()}}})(A,ee,t,B,$,W,a),re=B.width>=X*t.scale+2*U,ne=B.height>=q*t.scale+2*Z,oe=d||"rgba(232, 232, 232, 0.9)",ie=t.pages.indexOf(t.activePage),ae=(null==P?void 0:P.NoPages)||l,le=null!=F?F:Math.min(3,Math.max(1,Math.ceil(j?B.width/2/(X*t.scale):B.height/2/(q*t.scale))));return e.createElement("div",{ref:N,style:{width:"100%",height:"100%",position:"relative",outline:"none",flex:1,backgroundColor:oe,overflow:"hidden"},tabIndex:0,className:"polotno-workspace-container"},e.createElement("div",{ref:A,onScroll:te,style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",display:"flex",flexDirection:j?"row":"column",overflow:"auto",overflowX:j?"auto":re?"hidden":"auto",overflowY:j&&ne?"hidden":"auto"},className:"polotno-workspace-inner"},t.pages.map((n,o)=>{const i=n===t.activePage;if(W&&!i&&!n._exportingOrRendering&&!n._forceMount){return null}if(!(Math.abs(o-ie)<=le||n._exportingOrRendering||n._forceMount)){return e.createElement("div",{key:n.id,style:{flexShrink:0}},e.createElement(s,{width:X*t.scale+2*U,height:q*t.scale+2*Z,backgroundColor:oe,xPadding:U,yPadding:Z}))}const l=e.createElement(r,{key:n.id,page:n,xPadding:U,yPadding:Z,width:X*t.scale+2*U,height:q*t.scale+2*Z,store:t,pageControlsEnabled:u,backColor:oe,pageBorderColor:h||"lightgrey",activePageBorderColor:g||"rgb(0, 161, 255)",altCloneEnabled:C,bleedColor:f||"rgba(255, 0, 0, 0.1)",selectionRectFill:w,selectionRectStroke:b,selectionRectStrokeWidth:x,snapGuideStroke:p||"rgb(0, 161, 255)",snapGuideStrokeWidth:m||1,snapGuideDash:v||c,transformLabelFill:k,transformLabelTextFill:y,distanceGuideStroke:E||"rgb(0, 161, 255)",distanceLabelFill:T||"rgb(0, 161, 255)",distanceLabelTextFill:L||"white",components:P,viewportSize:B,layout:a,tooltipSafeArea:O});return(n._exportingOrRendering||n._forceMount)&&!i&&W?e.createElement("div",{style:{display:"none",flexShrink:0},key:n.id},l):l}),t.rulesVisible&&e.createElement(n,{store:t,xPadding:U,yPadding:Z,width:X*t.scale+2*U,height:q*t.scale+2*Z,layout:a}),0===t.pages.length&&e.createElement(ae,{store:t}),t.audios.map(r=>e.createElement(o,{key:r.id,audio:r,store:t}))))});export default WorkspaceCanvas;
|
package/model/store.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Instance } from 'mobx-state-tree';
|
|
2
2
|
import * as fonts from '../utils/fonts.js';
|
|
3
|
+
import { createExportCanvases } from '../utils/canvas.js';
|
|
3
4
|
import { PageType } from './page-model.js';
|
|
4
5
|
import { ElementsArray, ElementType } from './group-model.js';
|
|
5
6
|
import { NodeType } from './node-model.js';
|
|
@@ -20,6 +21,7 @@ export interface ExportOptions {
|
|
|
20
21
|
quality?: number;
|
|
21
22
|
_skipTimeout?: boolean;
|
|
22
23
|
quickMode?: boolean;
|
|
24
|
+
_exportCanvases?: ReturnType<typeof createExportCanvases>;
|
|
23
25
|
}
|
|
24
26
|
export interface ImageExportOptions extends ExportOptions {
|
|
25
27
|
dpi?: number;
|
|
@@ -954,7 +956,7 @@ export declare const Store: import("mobx-state-tree").IModelType<{
|
|
|
954
956
|
ungroupElements(ids: Array<string>): void;
|
|
955
957
|
deleteElements(ids: Array<string>): void;
|
|
956
958
|
on(event: any, callback: any): import("mobx-state-tree").IDisposer;
|
|
957
|
-
_toCanvas({ pixelRatio, ignoreBackground, pageId, mimeType, includeBleed, _skipTimeout, quickMode, }?: ExportOptions): Promise<HTMLCanvasElement>;
|
|
959
|
+
_toCanvas({ pixelRatio, ignoreBackground, pageId, mimeType, includeBleed, _skipTimeout, quickMode, _exportCanvases, }?: ExportOptions): Promise<HTMLCanvasElement>;
|
|
958
960
|
toDataURL({ mimeType, quality, dpi, dpiMetadata, ...rest }?: ImageExportOptions): Promise<string>;
|
|
959
961
|
toBlob({ mimeType, quality, ...rest }?: ExportOptions): Promise<Blob>;
|
|
960
962
|
saveAsImage({ fileName, ...exportProps }?: ImageExportOptions & {
|
package/model/store.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=this&&this.__rest||function(e,t){var i={};for(var o in e){Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(i[o]=e[o])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(e);n<o.length;n++){t.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(e,o[n])&&(i[o[n]]=e[o[n]])}}return i};import{applySnapshot as t,cast as i,destroy as o,detach as n,getSnapshot as a,onSnapshot as s,setLivelinessChecking as r,types as l}from"mobx-state-tree";import{UndoManager as d}from"./history.js";import{nanoid as c}from"nanoid";import p from"konva";import{computed as g}from"mobx";import{downloadFile as m}from"../utils/download.js";import{getJsPDF as u}from"../utils/pdf.js";import{createGIF as f}from"../utils/gif-lib.js";import{validateKey as h}from"../utils/validate-key.js";import*as b from"../utils/fonts.js";import{flags as y}from"../utils/flags.js";import{addDpiMetadataToImage as w}from"../utils/image-dpi.js";import{whenLoaded as v}from"../utils/loader.js";import{pxToUnit as P}from"../utils/unit.js";import{deepEqual as E}from"../utils/deep-equal.js";import{waitTillAvailable as x}from"../utils/wait.js";import{jsonToHTML as _}from"../utils/to-html.js";import{jsonToSVG as k}from"../utils/to-svg.js";import{Page as I}from"./page-model.js";import{forEveryChild as O}from"./group-model.js";import{Audio as T}from"./audio-model.js";r("ignore");export const Font=l.model("Font",{fontFamily:l.string,url:l.optional(l.string,""),styles:l.frozen()}).preProcessSnapshot(e=>Object.assign(Object.assign({},e),{fontFamily:e.fontFamily||e.name}));export const Store=l.model("Store",{role:"",pages:l.array(I),fonts:l.array(Font),audios:l.array(T),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:"px",dpi:72,schemaVersion:2,bleedVisible:!1,rulesVisible:!1,distanceGuidesVisible:!1,openedSidePanel:"",previousOpenedSidePanel:"",custom:l.frozen(),tool:l.optional(l.enumeration("Tool",["selection","draw","pan","text","eraser"]),"selection"),toolOptions:l.optional(l.model({brushType:l.optional(l.enumeration("BrushType",["brush","highlighter"]),"brush"),strokeWidth:l.optional(l.number,5),stroke:l.optional(l.string,"#000000"),opacity:l.optional(l.number,1)}),{}),selectedElementsIds:l.array(l.string),animatedElementsIds:l.array(l.string),history:l.optional(d,{targetPath:"../pages"}),_elementsPixelRatio:Math.min(2,"undefined"!=typeof window&&window.devicePixelRatio||1),_activePageId:"",_selectedPagesIds:l.array(l.string),_forceShowCredit:!1,_key:"",_validated:!1}).views(e=>{const t=g(()=>{const t={};return O({children:e.pages},e=>(t[e.id]=e,!1)),t},{keepAlive:!0});return{get _idsMap(){return t.get()}}}).views(e=>({get _bleedVisible(){return console.warn("store._bleedVisible is deprecated. Please use store.bleedVisible instead."),e.bleedVisible},get selectedElements(){return e.selectedElementsIds.map(t=>{for(const i of e.pages){for(const e of i.children){if(e.id===t){return e}}}}).filter(e=>!!e)},get children(){return e.pages},get selectedShapes(){const t=[];return O({children:e.selectedElements},e=>{"group"!==e.type&&t.push(e)}),t},get activePage(){return e.pages.slice().find(t=>t.id===e._activePageId)||(e.pages.length?e.pages[0]:null)},get selectedPages(){return e._selectedPagesIds.map(t=>e.pages.find(e=>e.id===t))},get duration(){let t=0;return e.pages.forEach(e=>{t+=e.duration}),t},get _hasCroppedImages(){return e.find(e=>"image"===e.type&&e._cropModeEnabled)},find(t){let i;return O({children:e.pages},e=>{if(!i&&t(e)){return i=e,!0}}),i},getElementById:t=>e._idsMap[t]})).actions(e=>{let t=0,o=null,n=!1;return{afterCreate(){e.history.canUndo},setCurrentTime(t){e.currentTime=t},_togglePlaying(t=!e.isPlaying){e.isPlaying=t},play({animatedElementsIds:a=[],startTime:s=0,currentTime:r=0,endTime:l=e.duration,repeat:d=!1}={}){r&&(console.warn("currentTime property of store.play() is deprecated. Please use startTime instead."),s=r),e.animatedElementsIds=i(a),e.currentTime=s,e.isPlaying=!0,t=Date.now(),o=l,n=d,requestAnimationFrame(e.seek)},checkActivePage(){let t=0;for(const i of e.pages){if(e.currentTime>=i.startTime&&e.currentTime<i.startTime+i.duration){e.selectPage(i.id);break}t+=i.duration}},seek(){if(!e.isPlaying){return}const i=Date.now(),a=i-t;t=i,e.currentTime+=a,e.checkActivePage();const s=o||e.duration;e.isPlaying&&e.currentTime<s?requestAnimationFrame(e.seek):e.isPlaying&&n?(e.currentTime=0,requestAnimationFrame(e.seek)):e.stop()},stop(){e.isPlaying=!1,e.currentTime=0,e.animatedElementsIds=i([]),e.checkActivePage()}}}).actions(r=>({__(){r._validated||(h(r._key,r._forceShowCredit),r._validated=!0)},set(e){Object.assign(r,e)},setUnit({unit:e,dpi:t}){r.unit=e||r.unit,r.dpi=t||r.dpi},setRole(e){r.role=e},setTool(e){r.tool=e},setToolOptions(e){Object.assign(r.toolOptions,e)},addPage(e){const t=I.create(Object.assign({id:c(10)},e));return r.pages.push(t),r._activePageId=t.id,t},selectPage(e){r._activePageId=e,1===r._selectedPagesIds.length&&(r._selectedPagesIds=i([e]))},selectPages(e){r._selectedPagesIds=i(e),1===r._selectedPagesIds.length&&(r._activePageId=r._selectedPagesIds[0])},selectElements(e){const t=e.map(e=>r.getElementById(e)).sort((e,t)=>e.page.children.indexOf(e)-e.page.children.indexOf(t)).filter(e=>!!e).map(e=>e.id);r.selectedElementsIds=i(t)},toggleBleed(e){r.bleedVisible=null!=e?e:!r.bleedVisible},toggleRulers(e){r.rulesVisible=null!=e?e:!r.rulesVisible},toggleDistanceGuides(e){r.distanceGuidesVisible=null!=e?e:!r.distanceGuidesVisible},openSidePanel(e){r.openedSidePanel!==e&&(r.previousOpenedSidePanel=r.openedSidePanel,r.openedSidePanel=e)},setScale(e){r.scale=e},_setScaleToFit(e){r.scaleToFit=e},setElementsPixelRatio(e){r._elementsPixelRatio=e},setSize(e,t,i){r.pages.forEach(o=>{o.setSize({width:e,height:t,useMagic:i,softChange:!0})}),r.width=e,r.height=t},setPageZIndex(e,t){const i=r.pages.find(t=>t.id===e);i&&(n(i),r.pages.remove(i),r.pages.splice(t,0,i))},deletePages(e){const t=r.pages.indexOf(r.activePage);e.forEach(e=>{const t=r.pages.find(t=>t.id===e);o(t)});const n=Math.min(r.pages.length-1,t),a=r.pages[n];a&&(r._activePageId=a.id),r.selectedElementsIds=i(r.selectedElementsIds.filter(e=>r.getElementById(e)))},groupElements(e,t={}){const o=e.map(e=>r.getElementById(e)),a=o[0].page;if(o.forEach(e=>{e&&n(e)}),!o.length){return}const s=a.children.reduce((e,t)=>{if("group"===t.type){const i=t.name.match(/group-(\d+)/);if(i){const t=parseInt(i[1],10);return Math.max(e,t)}}return e},0),l=Object.assign({id:c(10),name:`group-${s+1}`,children:o,type:"group"},t);return a.children.push(l),r.selectedElementsIds=i([l.id]),a.children.find(e=>e.id===l.id)},ungroupElements(e){const t=e.map(e=>r.getElementById(e)),o=[];t.forEach(e=>{if(e&&"group"===e.type){const t=e.page,i=t.children.indexOf(e);e.children.forEach(e=>{o.push(e.id)}),e.children.forEach(e=>{n(e),t.children.push(e)}),t.children.splice(i,1)}}),r.selectedElementsIds=i(o)},deleteElements(e){const t=[];r.find(i=>(e.includes(i.id)&&t.push(i),!1)),t.forEach(e=>{o(e)}),r.selectedElementsIds=i(r.selectedElementsIds.filter(e=>r.getElementById(e)))},on(e,t){if("change"===e){let e=r.toJSON();return s(r,i=>{const o=r.toJSON();!E(e,o)&&(e=o,t(o))})}},async _toCanvas({pixelRatio:e,ignoreBackground:t,pageId:i,mimeType:o,includeBleed:n,_skipTimeout:a,quickMode:s=!1}={}){var l;const d=e||1;i=i||(null===(l=r.pages[0])||void 0===l?void 0:l.id);const c=r.pages.find(e=>e.id===i);if(!c){throw new Error(`No page for export with id ${i}`)}const g=r._elementsPixelRatio;d>r._elementsPixelRatio&&r.setElementsPixelRatio(d),s?null==c||c.set({_forceMount:!0}):null==c||c.set({_exporting:!0});const m=await x(()=>{const e=p.stages.filter(e=>e.getAttr("pageId")===i);return 0===e.length?null:e});if(!m){throw null==c||c.set({_forceMount:!1,_exporting:!1}),r.setElementsPixelRatio(g),new Error(`Export is failed. Can not find stage for page ${i}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`)}m.length>1&&console.error(`Polotno error: Detected several canvas elements for page "${i}" in the document. This is not supported and will lead to incorrect export. Make sure to use unique ids for all pages and make sure you unmount <Workspace /> when it is not needed.`);const u=m[0];await r.waitLoading({_skipTimeout:a});const f=u.findOne(".page-container");if(!f){throw r.setElementsPixelRatio(g),null==c||c.set({_forceMount:!1,_exporting:!1}),new Error("Export is failed. Canvas was unmounted.")}const h=u.position();u.position({x:0,y:0}),u.find("Transformer").forEach(e=>{e.setAttr("oldVisible",e.visible()),e.visible(!1)}),f.find(".page-background").forEach(e=>e.shadowEnabled(!1)),f.find(".page-background").forEach(e=>e.strokeEnabled(!1)),f.find(".highlighter").forEach(e=>e.visible(!1));const b=f.findOne(".page-background-group"),y=b.clip();b.clip({x:null,y:null,width:null,height:null});const w=f.findOne(".elements-container"),v=w.clip();w.clip({x:null,y:null,width:null,height:null});const P=f.find(e=>!e.visible()&&e.getAttr("editModeEnabled")&&!e.getAttr("hideInExport"));P.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.show()});const E=f.find(e=>e.getAttr("hideInExport"));E.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.hide()}),t&&f.find(".page-background").forEach(e=>e.hide());const _=n?c.bleed:0;let k=_;!r.bleedVisible&&n||(r.bleedVisible||n?r.bleedVisible&&n?k=0:r.bleedVisible&&!n&&(k=-c.bleed):k=0);const I=document.createElement("canvas");I.width=Math.round((c.computedWidth+2*_)*d),I.height=Math.round((c.computedHeight+2*_)*d);const O=I.getContext("2d");"image/jpeg"===o&&(O.fillStyle="white",O.fillRect(0,0,I.width,I.height));const T=f.scale();f.scale({x:1,y:1});const j=f.toCanvas({x:f.x()-k,y:f.y()-k,width:c.computedWidth+2*_,height:c.computedHeight+2*_,pixelRatio:d});return f.scale(T),O.drawImage(j,0,0,I.width,I.height),p.Util.releaseCanvas(j),t&&f.find(".page-background").forEach(e=>e.show()),E.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),P.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),f.find(".page-background").forEach(e=>e.shadowEnabled(!0)),f.find(".page-background").forEach(e=>e.strokeEnabled(!0)),u.find("Transformer").forEach(e=>{e.visible(e.getAttr("oldVisible"))}),f.find(".highlighter").forEach(e=>e.visible(!0)),b.clip(y),w.clip(v),u.position(h),null==c||c.set({_exporting:!1,_forceMount:!1}),await new Promise(e=>setTimeout(e)),r.setElementsPixelRatio(g),I},async toDataURL(t={}){var{mimeType:i,quality:o,dpi:n,dpiMetadata:a="auto"}=t,s=e(t,["mimeType","quality","dpi","dpiMetadata"]);const l=await r._toCanvas(Object.assign({mimeType:i},s)),d=i||"image/png",c=l.toDataURL(d,o);p.Util.releaseCanvas(l);const g=null!=n?n:r.dpi;return"image/png"!==d&&"image/jpeg"!==d||"never"===a||"auto"===a&&72===g?c:w(c,d,g)},async toBlob(t={}){var{mimeType:i,quality:o}=t,n=e(t,["mimeType","quality"]);const a=await r._toCanvas(Object.assign({mimeType:i},n)),s=await new Promise(e=>{a.toBlob(e,i,o)});return p.Util.releaseCanvas(a),s},async saveAsImage(t={}){var{fileName:i}=t,o=e(t,["fileName"]);const n=o.mimeType||"image/png",a=n.split("/")[1];m(await r.toDataURL(o),i||"polotno."+a,n)},async _toPDF(e){const t=e.dpi||r.dpi,i=e.parallel||1,o=e.unit||("px"===r.unit?"mm":r.unit),n=e.pixelRatio||1,a=e.pageIds||r.pages.map(e=>e.id),s=r.pages.filter(e=>a.includes(e.id)),l=await u(),d=e=>P({px:e,unit:o,dpi:t}),c=e.cropMarkSize||0,p=d(c),g=s[0]||{},m=e.includeBleed?g.bleed:0,f=d(g.computedWidth+2*m+2*p),h=d(g.computedHeight+2*m+2*p);var b=new l({unit:o,orientation:f>h?"landscape":"portrait",format:[f,h],compress:!0,putOnlyUsedFonts:!0});b.deletePage(1);const y=((e,t)=>{for(var i=[],o=0;o<e.length;o+=t){i.push(e.slice(o,o+t))}return i})(s,i);let w=0;for(const u of y){const t=u.map(async t=>{const i=e.includeBleed?t.bleed:0,o=t.computedWidth+2*i+2*c,s=t.computedHeight+2*i+2*c,l=d(o),p=d(s);let g=0,m=n;for(;g<10;){g+=1,2===g&&console.error("Polotno can not export PDF with current settings. Quality is automatically reduced.");const i=await r.toDataURL(Object.assign(Object.assign({},e),{pageId:t.id,pixelRatio:m}));if(i.length>20){return e.onProgress&&e.onProgress(++w/a.length*.9),{url:i,width:l,height:p,widthPx:o,heightPx:s}}m*=.8}});(await Promise.all(t)).forEach(({url:e,width:t,height:i,widthPx:n,heightPx:a})=>{b.addPage([t,i],t>i?"landscape":"portrait");const s=b.getCurrentPageInfo();var r;switch(o){case"pt":r=1;break;case"mm":r=72/25.4;break;case"cm":r=72/2.54;break;case"in":r=72;break;case"px":r=.75;break;case"pc":case"em":r=12;break;case"ex":r=6;break;default:throw"Invalid unit: "+o}if(s.pageContext.cropBox={bottomLeftX:0,bottomLeftY:0,topRightX:t*r,topRightY:i*r},s.pageContext.artBox={bottomLeftX:d(c+m)*r,bottomLeftY:d(c+m)*r,topRightX:d(n-c-m)*r,topRightY:d(a-c-m)*r},s.pageContext.bleedBox={bottomLeftX:d(c+m)*r,bottomLeftY:d(c+m)*r,topRightX:d(n-c-m)*r,topRightY:d(a-c-m)*r},p){b.setLineWidth(d(1));const e=p+d(m);b.line(e,0,e,p),b.line(0,e,p,e),b.line(t-e,0,t-e,p),b.line(t,e,t-p,e),b.line(0,i-e,p,i-e),b.line(e,i,e,i-p),b.line(t,i-e,t-p,i-e),b.line(t-e,i,t-e,i-p)}b.addImage(e,p,p,t-2*p,i-2*p,void 0,"FAST")})}return b},toPDFDataURL:async e=>(await r._toPDF(Object.assign({mimeType:"image/jpeg"},e))).output("datauristring"),async toGIFDataURL(e={}){const t=e.pixelRatio||1,i=await f({width:r.width*t,height:r.height*t}),o=1e3/(e.fps||10),n=r.duration/o;for(let a=0;a<n-1;a++){const e=a*o||1;r.setCurrentTime(e);let n=0,s="";for(const t of r.pages){if(n+=t.duration,t.set({_rendering:n>e}),n>e){s=t.id;break}}const l=await r._toCanvas({pixelRatio:t,pageId:s,_skipTimeout:!0});i.addFrame(l.getContext("2d"),{delay:o,copy:!0})}for(const a of r.pages){a.set({_rendering:!1})}return r.stop(),i.render(),new Promise(e=>{i.on("finished",function(t){!function(e,t){var i=new FileReader;i.onload=function(e){t(e.target.result)},i.readAsDataURL(e)}(t,e)})})},async saveAsGIF(t={}){var{fileName:i}=t,o=e(t,["fileName"]);const n=await r.toGIFDataURL(o);m(n,i||"polotno.gif")},async toHTML({elementHook:e}={elementHook:void 0}){const t=r.toJSON();return _({json:t,elementHook:e})},async saveAsHTML({fileName:e,elementHook:t}={}){const i=await r.toHTML({elementHook:t}),o="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(i)));m(o,e||"polotno.html")},async toSVG({elementHook:e,pageId:t,fontEmbedding:i="inline"}={fontEmbedding:"inline"}){var o;const n=r.toJSON();t=t||(null===(o=n.pages[0])||void 0===o?void 0:o.id);const a=n.pages.find(e=>e.id===t);return k({json:Object.assign(Object.assign({},n),{pages:a?[a]:[]}),elementHook:e,fontEmbedding:i})},async saveAsSVG({fileName:e,elementHook:t,pageId:i,fontEmbedding:o="inline"}={}){const n=await r.toSVG({elementHook:t,pageId:i,fontEmbedding:o}),a="data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(n)));m(a,e||"polotno.svg")},async saveAsPDF(t={}){var{fileName:i}=t,o=e(t,["fileName"]);(await r._toPDF(Object.assign({mimeType:"image/jpeg"},o))).save(i||"polotno.pdf")},async waitLoading({_skipTimeout:e=!1}={}){e||await new Promise(e=>setTimeout(e,50)),await v()},toJSON:()=>({width:r.width,height:r.height,fonts:a(r.fonts),pages:a(r.pages),audios:a(r.audios),unit:r.unit,dpi:r.dpi,custom:r.custom,schemaVersion:r.schemaVersion}),loadJSON(e,i=!1){var o;const n=JSON.parse(JSON.stringify(e)),s=n.schemaVersion||0;s<1&&y.htmlRenderEnabled&&O({children:n.pages},e=>{if("text"===e.type){const t=16,i=e.letterSpacing*t;e.letterSpacing=i/e.fontSize}}),s<2&&O({children:n.pages},e=>{e.filters&&Object.keys(e.filters).forEach(t=>{if(["warm","cold","natural"].includes(t)){return}const i=e.filters[t];i&&"number"==typeof i.intensity&&(i.intensity=i.intensity/100)})}),delete n.schemaVersion;const l=r.pages.indexOf(r.activePage);let d=null===(o=n.pages[l]||n.pages[0])||void 0===o?void 0:o.id;n._activePageId=d;const c=Object.assign({},a(r));Object.assign(c,n),c.history=i?r.history.toJSON():{history:[],undoIdx:-1},t(r,c)},clear({keepHistory:e=!1}={}){const t=r.pages.map(e=>e.id);r.deletePages(t),r.custom=null,e||r.history.clear()},addFont(e){r.removeFont(e.fontFamily),r.fonts.push(e)},removeFont(e){r.fonts.filter(t=>t.fontFamily===e).forEach(e=>o(e))},addAudio(e){const t=T.create(Object.assign({id:c(10)},e));r.audios.push(t)},removeAudio(e){const t=r.audios.find(t=>t.id===e);t&&r.audios.remove(t)},async loadFont(e,t=""){const i=r.fonts.find(t=>t.fontFamily===e)||b.globalFonts.find(t=>t.fontFamily===e);let o=[{fontStyle:"normal",fontWeight:"normal"},{fontStyle:"normal",fontWeight:"bold"}];return i?(i.styles&&(o=i.styles.map(e=>({fontStyle:e.fontStyle||"normal",fontWeight:e.fontWeight||"normal"}))),b.injectCustomFont(i)):b.injectGoogleFont(e),Promise.all(o.map(i=>b.loadFont(e,i.fontStyle,i.fontWeight,t)))},validate:e=>Store.validate(e,[{path:"",type:Store}]).map(e=>({path:"store"+e.context.map(e=>e.path).join("."),message:e.message}))}));export function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){return Store.create({_forceShowCredit:t,_key:e})}export default createStore;
|
|
1
|
+
var e=this&&this.__rest||function(e,t){var i={};for(var o in e){Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(i[o]=e[o])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(e);n<o.length;n++){t.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(e,o[n])&&(i[o[n]]=e[o[n]])}}return i};import{applySnapshot as t,cast as i,destroy as o,detach as n,getSnapshot as s,onSnapshot as a,setLivelinessChecking as r,types as l}from"mobx-state-tree";import{UndoManager as d}from"./history.js";import{nanoid as c}from"nanoid";import p from"konva";import{computed as g}from"mobx";import{downloadFile as m}from"../utils/download.js";import{getJsPDF as u}from"../utils/pdf.js";import{createGIF as f}from"../utils/gif-lib.js";import{validateKey as h}from"../utils/validate-key.js";import*as b from"../utils/fonts.js";import{flags as y}from"../utils/flags.js";import{addDpiMetadataToImage as v}from"../utils/image-dpi.js";import{nodeToCanvas as w}from"../utils/canvas.js";import{whenLoaded as P}from"../utils/loader.js";import{pxToUnit as E}from"../utils/unit.js";import{deepEqual as x}from"../utils/deep-equal.js";import{waitTillAvailable as _}from"../utils/wait.js";import{jsonToHTML as k}from"../utils/to-html.js";import{jsonToSVG as I}from"../utils/to-svg.js";import{Page as O}from"./page-model.js";import{forEveryChild as j}from"./group-model.js";import{Audio as S}from"./audio-model.js";r("ignore");export const Font=l.model("Font",{fontFamily:l.string,url:l.optional(l.string,""),styles:l.frozen()}).preProcessSnapshot(e=>Object.assign(Object.assign({},e),{fontFamily:e.fontFamily||e.name}));export const Store=l.model("Store",{role:"",pages:l.array(O),fonts:l.array(Font),audios:l.array(S),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:"px",dpi:72,schemaVersion:2,bleedVisible:!1,rulesVisible:!1,distanceGuidesVisible:!1,openedSidePanel:"",previousOpenedSidePanel:"",custom:l.frozen(),tool:l.optional(l.enumeration("Tool",["selection","draw","pan","text","eraser"]),"selection"),toolOptions:l.optional(l.model({brushType:l.optional(l.enumeration("BrushType",["brush","highlighter"]),"brush"),strokeWidth:l.optional(l.number,5),stroke:l.optional(l.string,"#000000"),opacity:l.optional(l.number,1)}),{}),selectedElementsIds:l.array(l.string),animatedElementsIds:l.array(l.string),history:l.optional(d,{targetPath:"../pages"}),_elementsPixelRatio:Math.min(2,"undefined"!=typeof window&&window.devicePixelRatio||1),_activePageId:"",_selectedPagesIds:l.array(l.string),_forceShowCredit:!1,_key:"",_validated:!1}).views(e=>{const t=g(()=>{const t={};return j({children:e.pages},e=>(t[e.id]=e,!1)),t},{keepAlive:!0});return{get _idsMap(){return t.get()}}}).views(e=>({get _bleedVisible(){return console.warn("store._bleedVisible is deprecated. Please use store.bleedVisible instead."),e.bleedVisible},get selectedElements(){return e.selectedElementsIds.map(t=>{for(const i of e.pages){for(const e of i.children){if(e.id===t){return e}}}}).filter(e=>!!e)},get children(){return e.pages},get selectedShapes(){const t=[];return j({children:e.selectedElements},e=>{"group"!==e.type&&t.push(e)}),t},get activePage(){return e.pages.slice().find(t=>t.id===e._activePageId)||(e.pages.length?e.pages[0]:null)},get selectedPages(){return e._selectedPagesIds.map(t=>e.pages.find(e=>e.id===t))},get duration(){let t=0;return e.pages.forEach(e=>{t+=e.duration}),t},get _hasCroppedImages(){return e.find(e=>"image"===e.type&&e._cropModeEnabled)},find(t){let i;return j({children:e.pages},e=>{if(!i&&t(e)){return i=e,!0}}),i},getElementById:t=>e._idsMap[t]})).actions(e=>{let t=0,o=null,n=!1;return{afterCreate(){e.history.canUndo},setCurrentTime(t){e.currentTime=t},_togglePlaying(t=!e.isPlaying){e.isPlaying=t},play({animatedElementsIds:s=[],startTime:a=0,currentTime:r=0,endTime:l=e.duration,repeat:d=!1}={}){r&&(console.warn("currentTime property of store.play() is deprecated. Please use startTime instead."),a=r),e.animatedElementsIds=i(s),e.currentTime=a,e.isPlaying=!0,t=Date.now(),o=l,n=d,requestAnimationFrame(e.seek)},checkActivePage(){let t=0;for(const i of e.pages){if(e.currentTime>=i.startTime&&e.currentTime<i.startTime+i.duration){e.selectPage(i.id);break}t+=i.duration}},seek(){if(!e.isPlaying){return}const i=Date.now(),s=i-t;t=i,e.currentTime+=s,e.checkActivePage();const a=o||e.duration;e.isPlaying&&e.currentTime<a?requestAnimationFrame(e.seek):e.isPlaying&&n?(e.currentTime=0,requestAnimationFrame(e.seek)):e.stop()},stop(){e.isPlaying=!1,e.currentTime=0,e.animatedElementsIds=i([]),e.checkActivePage()}}}).actions(r=>({__(){r._validated||(h(r._key,r._forceShowCredit),r._validated=!0)},set(e){Object.assign(r,e)},setUnit({unit:e,dpi:t}){r.unit=e||r.unit,r.dpi=t||r.dpi},setRole(e){r.role=e},setTool(e){r.tool=e},setToolOptions(e){Object.assign(r.toolOptions,e)},addPage(e){const t=O.create(Object.assign({id:c(10)},e));return r.pages.push(t),r._activePageId=t.id,t},selectPage(e){r._activePageId=e,1===r._selectedPagesIds.length&&(r._selectedPagesIds=i([e]))},selectPages(e){r._selectedPagesIds=i(e),1===r._selectedPagesIds.length&&(r._activePageId=r._selectedPagesIds[0])},selectElements(e){const t=e.map(e=>r.getElementById(e)).sort((e,t)=>e.page.children.indexOf(e)-e.page.children.indexOf(t)).filter(e=>!!e).map(e=>e.id);r.selectedElementsIds=i(t)},toggleBleed(e){r.bleedVisible=null!=e?e:!r.bleedVisible},toggleRulers(e){r.rulesVisible=null!=e?e:!r.rulesVisible},toggleDistanceGuides(e){r.distanceGuidesVisible=null!=e?e:!r.distanceGuidesVisible},openSidePanel(e){r.openedSidePanel!==e&&(r.previousOpenedSidePanel=r.openedSidePanel,r.openedSidePanel=e)},setScale(e){r.scale=e},_setScaleToFit(e){r.scaleToFit=e},setElementsPixelRatio(e){r._elementsPixelRatio=e},setSize(e,t,i){r.pages.forEach(o=>{o.setSize({width:e,height:t,useMagic:i,softChange:!0})}),r.width=e,r.height=t},setPageZIndex(e,t){const i=r.pages.find(t=>t.id===e);i&&(n(i),r.pages.remove(i),r.pages.splice(t,0,i))},deletePages(e){const t=r.pages.indexOf(r.activePage);e.forEach(e=>{const t=r.pages.find(t=>t.id===e);o(t)});const n=Math.min(r.pages.length-1,t),s=r.pages[n];s&&(r._activePageId=s.id),r.selectedElementsIds=i(r.selectedElementsIds.filter(e=>r.getElementById(e)))},groupElements(e,t={}){const o=e.map(e=>r.getElementById(e)),s=o[0].page;if(o.forEach(e=>{e&&n(e)}),!o.length){return}const a=s.children.reduce((e,t)=>{if("group"===t.type){const i=t.name.match(/group-(\d+)/);if(i){const t=parseInt(i[1],10);return Math.max(e,t)}}return e},0),l=Object.assign({id:c(10),name:`group-${a+1}`,children:o,type:"group"},t);return s.children.push(l),r.selectedElementsIds=i([l.id]),s.children.find(e=>e.id===l.id)},ungroupElements(e){const t=e.map(e=>r.getElementById(e)),o=[];t.forEach(e=>{if(e&&"group"===e.type){const t=e.page,i=t.children.indexOf(e);e.children.forEach(e=>{o.push(e.id)}),e.children.forEach(e=>{n(e),t.children.push(e)}),t.children.splice(i,1)}}),r.selectedElementsIds=i(o)},deleteElements(e){const t=[];r.find(i=>(e.includes(i.id)&&t.push(i),!1)),t.forEach(e=>{o(e)}),r.selectedElementsIds=i(r.selectedElementsIds.filter(e=>r.getElementById(e)))},on(e,t){if("change"===e){let e=r.toJSON();return a(r,i=>{const o=r.toJSON();!x(e,o)&&(e=o,t(o))})}},async _toCanvas({pixelRatio:e,ignoreBackground:t,pageId:i,mimeType:o,includeBleed:n,_skipTimeout:s,quickMode:a=!1,_exportCanvases:l}={}){var d;const c=e||1;i=i||(null===(d=r.pages[0])||void 0===d?void 0:d.id);const g=r.pages.find(e=>e.id===i);if(!g){throw new Error(`No page for export with id ${i}`)}const m=r._elementsPixelRatio;c>r._elementsPixelRatio&&r.setElementsPixelRatio(c),a?null==g||g.set({_forceMount:!0}):null==g||g.set({_exporting:!0});const u=await _(()=>{const e=p.stages.filter(e=>e.getAttr("pageId")===i);return 0===e.length?null:e});if(!u){throw null==g||g.set({_forceMount:!1,_exporting:!1}),r.setElementsPixelRatio(m),new Error(`Export is failed. Can not find stage for page ${i}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`)}u.length>1&&console.error(`Polotno error: Detected several canvas elements for page "${i}" in the document. This is not supported and will lead to incorrect export. Make sure to use unique ids for all pages and make sure you unmount <Workspace /> when it is not needed.`);const f=u[0];await r.waitLoading({_skipTimeout:s});const h=f.findOne(".page-container");if(!h){throw r.setElementsPixelRatio(m),null==g||g.set({_forceMount:!1,_exporting:!1}),new Error("Export is failed. Canvas was unmounted.")}const b=f.position();f.position({x:0,y:0}),f.find("Transformer").forEach(e=>{e.setAttr("oldVisible",e.visible()),e.visible(!1)}),h.find(".page-background").forEach(e=>e.shadowEnabled(!1)),h.find(".page-background").forEach(e=>e.strokeEnabled(!1)),h.find(".highlighter").forEach(e=>e.visible(!1));const y=h.findOne(".page-background-group"),v=y.clip();y.clip({x:null,y:null,width:null,height:null});const P=h.findOne(".elements-container"),E=P.clip();P.clip({x:null,y:null,width:null,height:null});const x=h.find(e=>!e.visible()&&e.getAttr("editModeEnabled")&&!e.getAttr("hideInExport"));x.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.show()});const k=h.find(e=>e.getAttr("hideInExport"));k.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.hide()}),t&&h.find(".page-background").forEach(e=>e.hide());const I=n?g.bleed:0;let O=I;!r.bleedVisible&&n||(r.bleedVisible||n?r.bleedVisible&&n?O=0:r.bleedVisible&&!n&&(O=-g.bleed):O=0);const j=g.computedWidth+2*I,S=g.computedHeight+2*I,T=h.scale();h.scale({x:1,y:1});const F=w(h,{x:h.x()-O,y:h.y()-O,width:j,height:S,pixelRatio:c,sceneCanvas:null==l?void 0:l.sceneCanvas,bufferCanvas:null==l?void 0:l.bufferCanvas});h.scale(T);const R=F._canvas;if("image/jpeg"===o){const e=R.getContext("2d");e.save(),e.globalCompositeOperation="destination-over",e.fillStyle="white",e.fillRect(0,0,R.width,R.height),e.restore()}return t&&h.find(".page-background").forEach(e=>e.show()),k.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),x.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),h.find(".page-background").forEach(e=>e.shadowEnabled(!0)),h.find(".page-background").forEach(e=>e.strokeEnabled(!0)),f.find("Transformer").forEach(e=>{e.visible(e.getAttr("oldVisible"))}),h.find(".highlighter").forEach(e=>e.visible(!0)),y.clip(v),P.clip(E),f.position(b),null==g||g.set({_exporting:!1,_forceMount:!1}),await Promise.resolve(),r.setElementsPixelRatio(m),R},async toDataURL(t={}){var{mimeType:i,quality:o,dpi:n,dpiMetadata:s="auto"}=t,a=e(t,["mimeType","quality","dpi","dpiMetadata"]);const l=await r._toCanvas(Object.assign({mimeType:i},a)),d=i||"image/png",c=l.toDataURL(d,o);p.Util.releaseCanvas(l);const g=null!=n?n:r.dpi;return"image/png"!==d&&"image/jpeg"!==d||"never"===s||"auto"===s&&72===g?c:v(c,d,g)},async toBlob(t={}){var{mimeType:i,quality:o}=t,n=e(t,["mimeType","quality"]);const s=await r._toCanvas(Object.assign({mimeType:i},n)),a=await new Promise(e=>{s.toBlob(e,i,o)});return p.Util.releaseCanvas(s),a},async saveAsImage(t={}){var{fileName:i}=t,o=e(t,["fileName"]);const n=o.mimeType||"image/png",s=n.split("/")[1];m(await r.toDataURL(o),i||"polotno."+s,n)},async _toPDF(e){const t=e.dpi||r.dpi,i=e.parallel||1,o=e.unit||("px"===r.unit?"mm":r.unit),n=e.pixelRatio||1,s=e.pageIds||r.pages.map(e=>e.id),a=r.pages.filter(e=>s.includes(e.id)),l=await u(),d=e=>E({px:e,unit:o,dpi:t}),c=e.cropMarkSize||0,p=d(c),g=a[0]||{},m=e.includeBleed?g.bleed:0,f=d(g.computedWidth+2*m+2*p),h=d(g.computedHeight+2*m+2*p);var b=new l({unit:o,orientation:f>h?"landscape":"portrait",format:[f,h],compress:!0,putOnlyUsedFonts:!0});b.deletePage(1);const y=((e,t)=>{for(var i=[],o=0;o<e.length;o+=t){i.push(e.slice(o,o+t))}return i})(a,i);let v=0;for(const u of y){const t=u.map(async t=>{const i=e.includeBleed?t.bleed:0,o=t.computedWidth+2*i+2*c,a=t.computedHeight+2*i+2*c,l=d(o),p=d(a);let g=0,m=n;for(;g<10;){g+=1,2===g&&console.error("Polotno can not export PDF with current settings. Quality is automatically reduced.");const i=await r.toDataURL(Object.assign(Object.assign({},e),{pageId:t.id,pixelRatio:m}));if(i.length>20){return e.onProgress&&e.onProgress(++v/s.length*.9),{url:i,width:l,height:p,widthPx:o,heightPx:a}}m*=.8}});(await Promise.all(t)).forEach(({url:e,width:t,height:i,widthPx:n,heightPx:s})=>{b.addPage([t,i],t>i?"landscape":"portrait");const a=b.getCurrentPageInfo();var r;switch(o){case"pt":r=1;break;case"mm":r=72/25.4;break;case"cm":r=72/2.54;break;case"in":r=72;break;case"px":r=.75;break;case"pc":case"em":r=12;break;case"ex":r=6;break;default:throw"Invalid unit: "+o}if(a.pageContext.cropBox={bottomLeftX:0,bottomLeftY:0,topRightX:t*r,topRightY:i*r},a.pageContext.artBox={bottomLeftX:d(c+m)*r,bottomLeftY:d(c+m)*r,topRightX:d(n-c-m)*r,topRightY:d(s-c-m)*r},a.pageContext.bleedBox={bottomLeftX:d(c+m)*r,bottomLeftY:d(c+m)*r,topRightX:d(n-c-m)*r,topRightY:d(s-c-m)*r},p){b.setLineWidth(d(1));const e=p+d(m);b.line(e,0,e,p),b.line(0,e,p,e),b.line(t-e,0,t-e,p),b.line(t,e,t-p,e),b.line(0,i-e,p,i-e),b.line(e,i,e,i-p),b.line(t,i-e,t-p,i-e),b.line(t-e,i,t-e,i-p)}b.addImage(e,p,p,t-2*p,i-2*p,void 0,"FAST")})}return b},toPDFDataURL:async e=>(await r._toPDF(Object.assign({mimeType:"image/jpeg"},e))).output("datauristring"),async toGIFDataURL(e={}){const t=e.pixelRatio||1,i=await f({width:r.width*t,height:r.height*t}),o=1e3/(e.fps||10),n=r.duration/o;for(let s=0;s<n-1;s++){const e=s*o||1;r.setCurrentTime(e);let n=0,a="";for(const t of r.pages){if(n+=t.duration,t.set({_rendering:n>e}),n>e){a=t.id;break}}const l=await r._toCanvas({pixelRatio:t,pageId:a,_skipTimeout:!0});i.addFrame(l.getContext("2d"),{delay:o,copy:!0})}for(const s of r.pages){s.set({_rendering:!1})}return r.stop(),i.render(),new Promise(e=>{i.on("finished",function(t){!function(e,t){var i=new FileReader;i.onload=function(e){t(e.target.result)},i.readAsDataURL(e)}(t,e)})})},async saveAsGIF(t={}){var{fileName:i}=t,o=e(t,["fileName"]);const n=await r.toGIFDataURL(o);m(n,i||"polotno.gif")},async toHTML({elementHook:e}={elementHook:void 0}){const t=r.toJSON();return k({json:t,elementHook:e})},async saveAsHTML({fileName:e,elementHook:t}={}){const i=await r.toHTML({elementHook:t}),o="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(i)));m(o,e||"polotno.html")},async toSVG({elementHook:e,pageId:t,fontEmbedding:i="inline"}={fontEmbedding:"inline"}){var o;const n=r.toJSON();t=t||(null===(o=n.pages[0])||void 0===o?void 0:o.id);const s=n.pages.find(e=>e.id===t);return I({json:Object.assign(Object.assign({},n),{pages:s?[s]:[]}),elementHook:e,fontEmbedding:i})},async saveAsSVG({fileName:e,elementHook:t,pageId:i,fontEmbedding:o="inline"}={}){const n=await r.toSVG({elementHook:t,pageId:i,fontEmbedding:o}),s="data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(n)));m(s,e||"polotno.svg")},async saveAsPDF(t={}){var{fileName:i}=t,o=e(t,["fileName"]);(await r._toPDF(Object.assign({mimeType:"image/jpeg"},o))).save(i||"polotno.pdf")},async waitLoading({_skipTimeout:e=!1}={}){e||await new Promise(e=>setTimeout(e,50)),await P()},toJSON:()=>({width:r.width,height:r.height,fonts:s(r.fonts),pages:s(r.pages),audios:s(r.audios),unit:r.unit,dpi:r.dpi,custom:r.custom,schemaVersion:r.schemaVersion}),loadJSON(e,i=!1){var o;const n=JSON.parse(JSON.stringify(e)),a=n.schemaVersion||0;a<1&&y.htmlRenderEnabled&&j({children:n.pages},e=>{if("text"===e.type){const t=16,i=e.letterSpacing*t;e.letterSpacing=i/e.fontSize}}),a<2&&j({children:n.pages},e=>{e.filters&&Object.keys(e.filters).forEach(t=>{if(["warm","cold","natural"].includes(t)){return}const i=e.filters[t];i&&"number"==typeof i.intensity&&(i.intensity=i.intensity/100)})}),delete n.schemaVersion;const l=r.pages.indexOf(r.activePage);let d=null===(o=n.pages[l]||n.pages[0])||void 0===o?void 0:o.id;n._activePageId=d;const c=Object.assign({},s(r));Object.assign(c,n),c.history=i?r.history.toJSON():{history:[],undoIdx:-1},t(r,c)},clear({keepHistory:e=!1}={}){const t=r.pages.map(e=>e.id);r.deletePages(t),r.custom=null,e||r.history.clear()},addFont(e){r.removeFont(e.fontFamily),r.fonts.push(e)},removeFont(e){r.fonts.filter(t=>t.fontFamily===e).forEach(e=>o(e))},addAudio(e){const t=S.create(Object.assign({id:c(10)},e));r.audios.push(t)},removeAudio(e){const t=r.audios.find(t=>t.id===e);t&&r.audios.remove(t)},async loadFont(e,t=""){const i=r.fonts.find(t=>t.fontFamily===e)||b.globalFonts.find(t=>t.fontFamily===e);let o=[{fontStyle:"normal",fontWeight:"normal"},{fontStyle:"normal",fontWeight:"bold"}];return i?(i.styles&&(o=i.styles.map(e=>({fontStyle:e.fontStyle||"normal",fontWeight:e.fontWeight||"normal"}))),b.injectCustomFont(i)):b.injectGoogleFont(e),Promise.all(o.map(i=>b.loadFont(e,i.fontStyle,i.fontWeight,t)))},validate:e=>Store.validate(e,[{path:"",type:Store}]).map(e=>({path:"store"+e.context.map(e=>e.path).join("."),message:e.message}))}));export function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){return Store.create({_forceShowCredit:t,_key:e})}export default createStore;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "polotno",
|
|
3
|
-
"version": "2.34.
|
|
3
|
+
"version": "2.34.2",
|
|
4
4
|
"description": "Design Editor Framework",
|
|
5
5
|
"author": "Anton Lavrenov",
|
|
6
6
|
"keywords": [
|
|
@@ -67,6 +67,7 @@
|
|
|
67
67
|
"functions-have-names": "^1.2.3",
|
|
68
68
|
"gifuct-js": "^2.1.2",
|
|
69
69
|
"gradient-parser": "^1.1.1",
|
|
70
|
+
"mediabunny": "^1.24.1",
|
|
70
71
|
"konva": "^10.0.12",
|
|
71
72
|
"mensch": "^0.3.4",
|
|
72
73
|
"mobx": "6.15.0",
|