polotno 2.23.4 → 2.23.6
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/hotkeys.js +1 -1
- package/canvas/html-element.js +2 -2
- package/canvas/image-element.js +1 -1
- package/canvas/text-element.js +1 -1
- package/model/group-model.js +1 -1
- package/model/page-model.js +1 -1
- package/model/store.d.ts +1 -1
- package/model/store.js +1 -1
- package/package.json +2 -2
- package/polotno-app.d.ts +2 -2
- package/polotno.bundle.js +15 -13
- package/side-panel/animations-panel.js +1 -1
- package/utils/html2canvas.d.ts +1 -1
- package/utils/html2canvas.js +1 -1
- package/utils/validate-key.js +1 -1
package/canvas/hotkeys.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleHotkey=function(t,o){var l,r,
|
|
1
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleHotkey=function(t,o){var a,l,r,d;if("INPUT"===(null===(a=document.activeElement)||void 0===a?void 0:a.tagName)||"TEXTAREA"===(null===(l=document.activeElement)||void 0===l?void 0:l.tagName)||"true"===(null===(r=document.activeElement)||void 0===r?void 0:r.contentEditable)){return}const c=o.selectedElements.filter((e=>e.removable)).map((e=>e.id));46!==t.keyCode&&8!==t.keyCode||o.deleteElements(c);const n=t.ctrlKey||t.metaKey,s=t.shiftKey;if(!n||s||"z"!==t.key.toLowerCase()&&"y"!==t.key.toLowerCase()||(t.preventDefault(),o.history.undo()),n&&s&&("z"===t.key.toLowerCase()||"y"===t.key.toLowerCase())&&(t.preventDefault(),o.history.redo()),n&&"KeyA"===t.code){t.preventDefault();const e=null===(d=o.activePage)||void 0===d?void 0:d.children.filter((e=>e.selectable)),a=(null==e?void 0:e.map((e=>e.id)))||[];o.selectElements(a)}n&&"KeyC"===t.code&&(t.preventDefault(),(0,e.copy)(o)),n&&"KeyX"===t.code&&(t.preventDefault(),(0,e.cut)(o)),n&&"KeyV"===t.code&&(t.preventDefault(),(0,e.paste)(o)),"ArrowDown"===t.code&&(t.preventDefault(),o.selectedShapes.forEach((e=>{e.draggable&&e.set({y:e.y+1})}))),"ArrowUp"===t.code&&(t.preventDefault(),o.selectedShapes.forEach((e=>{e.draggable&&e.set({y:e.y-1})}))),"ArrowLeft"===t.code&&(t.preventDefault(),o.selectedShapes.forEach((e=>{e.draggable&&e.set({x:e.x-1})}))),"ArrowRight"===t.code&&(t.preventDefault(),o.selectedShapes.forEach((e=>{e.draggable&&e.set({x:e.x+1})})))};const e=require("../utils/clipboard");
|
package/canvas/html-element.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var e,t=this&&this.__createBinding||(Object.create?function(e,t,n
|
|
1
|
+
var e,t=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||(e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e){Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r)}return t},e(t)},function(n){if(n&&n.__esModule){return n}var i={};if(null!=n){for(var o=e(n),a=0;a<o.length;a++){"default"!==o[a]&&t(i,n,o[a])}}return r(i,n),i}),i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.HTMLElement=exports.setQuillContent=exports.createQuill=exports.setQuillFormats=exports.quillRef=void 0;const o=i(require("react")),a=require("mobx-react-lite"),l=require("react-konva"),s=i(require("quill")),u=n(require("mobx")),c=require("../utils/flags"),d=require("./apply-filters"),f=require("./text-element"),g=require("./use-color"),h=require("../utils/html2canvas"),m=require("./use-fadein"),p=require("react-konva-utils"),x=i(require("../utils/styled")),b=require("../utils/loader"),y=require("../utils/text"),w=n(require("../utils/fonts")),v=require("../utils/screen"),S=require("./text-element/max-font-size"),E=require("mobx");exports.quillRef=u.observable({enabled:!1,currentFormat:{},editor:u.observable.object({instance:null},{},{deep:!1})});const k=(0,x.default)("div",o.default.forwardRef)`
|
|
2
2
|
.ql-editor {
|
|
3
3
|
outline: none;
|
|
4
4
|
}
|
|
@@ -12,4 +12,4 @@ var e,t=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&
|
|
|
12
12
|
.ql-direction-rtl {
|
|
13
13
|
direction: rtl;
|
|
14
14
|
}
|
|
15
|
-
`;let k=["bold","color","font","italic","size","strike","underline","indent","list","direction"];exports.setQuillFormats=e=>{k=e},exports.createQuill=e=>new s.default(e,{toolbar:!1,keyboard:!1,clipboard:{matchVisual:!1},formats:k}),exports.setQuillContent=(e,t)=>{var n=e.clipboard.convert("<div class='ql-editor' style='outline: none;'>"+t+"<p><br></p></div>");e.setContents(n),e.history.clear()};const z=({html:e,onBlur:t,onChange:n,element:r})=>{const i=o.default.useRef(null);o.default.useEffect((()=>{if(!i.current){return}const e=(0,exports.createQuill)(i.current);return u.runInAction((()=>{exports.quillRef.editor.instance=e})),window.__polotnoQuill=e,e.on("text-change",(()=>{e.getSelection()&&u.runInAction((()=>{exports.quillRef.currentFormat=e.getFormat()})),setTimeout((()=>{var e;const t=null===(e=i.current)||void 0===e?void 0:e.childNodes[0];n(t.innerHTML)}),10)})),e.setSelection(0,0,"api"),e.on("selection-change",((t,n,r)=>{t&&u.runInAction((()=>{exports.quillRef.currentFormat=e.getFormat()}))})),i.current.childNodes[0].addEventListener("blur",(e=>{var n;if(null===(n=e.relatedTarget)||void 0===n?void 0:n.classList.contains("ql-clipboard")){return}const r=function(e){return!!e&&!!e.closest(".sketch-picker")}(e.relatedTarget);r||t()})),()=>{u.runInAction((()=>{exports.quillRef.editor.instance=null,exports.quillRef.currentFormat={}})),delete window.__polotnoQuill}}),[]),o.default.useEffect((()=>{var t;const n=exports.quillRef.editor.instance;if(!n){return}const o=n.getSelection();(null===(t=i.current)||void 0===t?void 0:t.childNodes[0].innerHTML)===r.text||((0,exports.setQuillContent)(n,e),o&&(n.setSelection(o.index,o.length),u.runInAction((()=>{exports.quillRef.currentFormat=n.getFormat()}))))}),[r.text]);const l={color:r.fill};return r.fill.indexOf("gradient")>=0&&(l.backgroundColor=r.fill,l.backgroundImage=r.fill,l.backgroundSize="100% 100%",l.backgroundRepeat="repeat",l.webkitBackgroundClip="text",l.MozBackgroundClip="text",l.WebkitTextFillColor="transparent",l.MozTextFillColor="transparent"),o.default.createElement(E,{ref:i,style:Object.assign(Object.assign({},l),{fontSize:r.fontSize,fontWeight:r.fontWeight,width:r.a.width,fontFamily:'"'+r.fontFamily+'"',lineHeight:r.lineHeight,letterSpacing:r.letterSpacing*r.fontSize+"px",textAlign:r.align}),dir:(0,f.getDir)((0,y.removeTags)(r.text))})},O=(e,t=100,n=!1,r="")=>{const[i,l]=o.default.useState(e),a=o.default.useRef(null);return o.default.useEffect((()=>e===n?(a.current&&(clearTimeout(a.current),a.current=null),void l(n)):(a.current&&clearTimeout(a.current),a.current=setTimeout((()=>{l(e),a.current=null}),t),()=>{a.current&&clearTimeout(a.current)})),[e,t]),[i,l]};function q(e,{fontFamily:t="",color:n="black"}={}){let r=`color: ${n||e.fill}`;return e.fill.indexOf("gradient")>=0&&(r=`\n background-color: ${n};\n background-image: ${e.fill};\n background-size: 100% 100%;\n background-repeat: repeat;\n -webkit-background-clip: text;\n -moz-background-clip: text;\n -webkit-text-fill-color: transparent;\n -moz-text-fill-color: transparent;\n `),`<div style="${["white-space: pre-wrap",`width: ${Math.round(e.width||100)}px`,r,`font-size: ${e.fontSize}px`,`font-family: '${t}'`,`text-align: ${e.align}`,e.textDecoration?`text-decoration: ${e.textDecoration}; text-decoration-color: ${n||e.fill}; text-decoration-layer: over`:"",e.lineHeight?`line-height: ${e.lineHeight}`:"",e.letterSpacing?`letter-spacing: ${e.letterSpacing*e.fontSize}px`:"",e.fontStyle?`font-style: ${e.fontStyle}`:"",e.fontWeight?`font-weight: ${e.fontWeight}`:"",e.strokeWidth?`-webkit-text-stroke: ${e.strokeWidth}px ${e.stroke}`:"",e.strokeWidth?"paint-order: stroke fill":""].filter(Boolean).join("; ")}" contentEditable dir="${(0,f.getDir)((0,y.removeTags)(e.text))}">${(0,y.sanitizeHtml)(e.text).replace(/\n/g,"</br>")}</div>`}const F=/^((?!chrome|android).)*safari/i.test(navigator.userAgent);exports.HTMLElement=(0,l.observer)((({element:e,store:t})=>{const n=o.default.useRef(null),[r,i]=o.default.useState(),[l,s]=o.default.useState(!1),[x,k]=o.default.useState(!0),[R,T]=o.default.useState(!1),_=o.default.useRef(e.height),C=t.selectedShapes.indexOf(e)>=0&&e.selectable,M=e.fontSize/3,{textVerticalResizeEnabled:$}=c.flags,A=(0,f.usePrevious)(e.fontFamily),[H]=(0,f.useFontLoader)(t,e.fontFamily),I=e._editModeEnabled;(0,m.useFadeIn)(n);const j=H?e.fontFamily:A!==e.fontFamily?A:"Arial",P=(0,g.useColor)(e).fill,D=q(e,{fontFamily:j,color:P}),{width:L,height:X}=function(e,t,n){return o.default.useMemo((()=>(0,h.detectSize)(e)),[e,t.width,n])}(D,e,H);o.default.useEffect((()=>{if(!H){return}if(!e.height){return void e.set({height:X})}const{textOverflow:n}=c.flags;if("change-font-size"!==n||l){"resize"===n&&($&&e.height<X&&t.history.ignore((()=>{e.set({height:X})})),$||e.height===X||t.history.ignore((()=>{e.set({height:X})})))}else{const n=(e=>{let t=e.fontSize;for(let n=1;n<50;n++){const n=q(Object.assign(Object.assign({},e.toJSON()),{fontSize:t}),{fontFamily:e.fontFamily}),{height:r}=(0,h.detectSize)(n),i=e.height&&r>e.height,o=(0,h.isContentWrapping)({html:n});if(!i&&!o){break}t-=.5}return t})(e);n!==e.fontSize?t.history.ignore((()=>{e.set({fontSize:n})})):e.height!==X&&($&&e.height<X?t.history.ignore((()=>{e.set({height:X})})):$||t.history.ignore((()=>{e.set({height:X})})))}}));const Y=o.default.useRef(0),W=o.default.useMemo((()=>{const e={lastArgs:null,lastResult:null};return async function(t){return e.lastArgs&&e.lastResult&&(n=e.lastArgs,r=t,JSON.stringify(n)===JSON.stringify(r))||(e.lastResult=await(0,h.htmlToCanvas)(t),e.lastArgs=Object.assign({},t)),e.lastResult;var n,r}}),[]),B=o.default.useRef(null);o.default.useEffect((()=>{l||I||(async()=>{Y.current++;const n=Y.current,r=(0,b.incrementLoader)(`text ${e.id}`);B.current=r,k(!0);let o=null;const l=F?5:1;for(let i=0;i<l;i++){const l=i>0?W:h.htmlToCanvas;try{if(o=await l({skipCache:i>0,html:D,width:e.width||1,height:e.height||X||1,fontFamily:j,padding:M,pixelRatio:t._elementsPixelRatio,font:t.fonts.find((e=>e.fontFamily===j))||w.globalFonts.find((e=>e.fontFamily===j))}),n!==Y.current){return void r()}if(!function(e){const t=e.getContext("2d").getImageData(0,0,e.width,e.height).data;for(let n=0;n<t.length;n+=4){if(0!==t[n+3]){return!0}}return!1}(o)&&F){await new Promise((e=>setTimeout(e,50*(i+1))));continue}}catch(a){(0,b.triggerLoadError)(`Error rendering rich text with id ${e.id}`);break}}if(!o){return B.current=null,void r()}i(o),k(!1)})()}),[D,l,X,I,j,e.height,t._elementsPixelRatio,H]);const[Q,N]=O(x),[J]=O(l,100,!0),V=J||Q;o.default.useEffect((()=>u.autorun((()=>{const t=n.current;(0,d.applyFilter)(t,e)}))),[r,V,e.shadowColor,e.shadowOffsetX,e.shadowOffsetY,e.shadowOpacity]),o.default.useEffect((()=>{r&&!x&&B.current&&(B.current(),B.current=null)}),[r,x]);let G=0;"middle"===e.verticalAlign&&(G=(e.height-X)/2),"bottom"===e.verticalAlign&&(G=e.height-X);const K=(0,f.getLineHeight)({fontLoaded:H,fontFamily:e.fontFamily,fontSize:e.fontSize,lineHeight:e.lineHeight}),U=(0,v.isTouchDevice)();return o.default.createElement(o.default.Fragment,null,o.default.createElement(a.Rect,{x:e.a.x,y:e.a.y,offsetX:e.backgroundPadding*(e.fontSize*K*.5),offsetY:e.backgroundPadding*(e.fontSize*K*.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*K),height:e.a.height+e.backgroundPadding*(e.fontSize*K),cornerRadius:e.backgroundCornerRadius*(e.fontSize*K*.5)}),o.default.createElement(a.Rect,{ref:n,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:!V,draggable:U?e.draggable&&C:e.draggable,preventDefault:!U||C,opacity:I?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:()=>{e.contentEditable&&e.toggleEditMode(!0)},onDblTap:()=>{e.contentEditable&&e.toggleEditMode(!0)},onTransformStart:t=>{s(!0),_.current=e.height},onTransform:t=>{var n;const r=t.target,i=(null===(n=r.getStage())||void 0===n?void 0:n.findOne("Transformer")).getActiveAnchor(),o="middle-left"===i||"middle-right"===i,l="top-center"===i||"bottom-center"===i,a=r.scaleX();if(o){const t=r.scaleX(),n=Math.max(r.width()*t,e.fontSize);if(r.width(n),r.scaleX(1),c.flags.textVerticalResizeEnabled){const t=Math.max(X,_.current);e.set({height:t})}e.set({width:n,x:r.x(),y:r.y()})}else if(l){let n="resize"===c.flags.textOverflow?X:e.lineHeight*e.fontSize;const i=Math.max(n,t.target.height()*t.target.scaleY());r.scaleY(1),e.set({x:r.x(),y:r.y(),height:i,rotation:r.rotation()})}else{r.scaleX(1),r.scaleY(1),e.set({fontSize:e.fontSize*a,letterSpacing:e.letterSpacing,width:r.width()*a,x:r.x(),y:r.y(),rotation:r.rotation(),height:r.height()*a})}},onTransformEnd:t=>{s(!1),k(!0);const n=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),e.set({fontSize:e.fontSize*n,width:t.target.width()*n,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),shadowBlur:e.shadowBlur*n,shadowOffsetX:e.shadowOffsetX*n,shadowOffsetY:e.shadowOffsetY*n,strokeWidth:e.strokeWidth*n})}}),o.default.createElement(a.Image,{ref:n,image:r,x:e.a.x,y:e.a.y,offsetX:M,offsetY:M-G,listening:!1,rotation:e.rotation,width:e.a.width+2*M,height:e.a.height+2*M,visible:!V,opacity:I?0:e.a.opacity,shadowEnabled:e.shadowEnabled,shadowBlur:e.shadowBlur,shadowOffsetX:e.shadowOffsetX,shadowOffsetY:e.shadowOffsetY,shadowColor:e.shadowColor,shadowOpacity:e.shadowOpacity,hideInExport:!e.showInExport}),V&&o.default.createElement(a.Group,{x:e.a.x,y:e.a.y,rotation:e.rotation,offsetY:-G},o.default.createElement(p.Html,{divProps:{style:{pointerEvents:"none"}}},o.default.createElement(E,{dangerouslySetInnerHTML:{__html:D},style:{pointerEvents:"none"}}))),I&&o.default.createElement(a.Group,{x:e.a.x,y:e.a.y,rotation:e.rotation,offsetY:-G},o.default.createElement(p.Html,null,o.default.createElement(z,{html:D,element:e,onChange:t=>{const n=(0,S.getLimitedFontSize)({oldText:(0,y.removeTags)(e.text),newText:(0,y.removeTags)(t),element:e});e.set({text:t,fontSize:n})},onBlur:t=>{e.toggleEditMode(!1),N(!0)}}))))}));
|
|
15
|
+
`;let z=["bold","color","font","italic","size","strike","underline","indent","list","direction"];exports.setQuillFormats=e=>{z=e},exports.createQuill=e=>new s.default(e,{toolbar:!1,keyboard:!1,clipboard:{matchVisual:!1},formats:z}),exports.setQuillContent=(e,t)=>{var r=e.clipboard.convert("<div class='ql-editor' style='outline: none;'>"+t+"<p><br></p></div>");e.setContents(r),e.history.clear()};const O=({html:e,onBlur:t,onChange:r,element:n})=>{const i=o.default.useRef(null);o.default.useEffect((()=>{if(!i.current){return}const e=(0,exports.createQuill)(i.current);return u.runInAction((()=>{exports.quillRef.editor.instance=e})),window.__polotnoQuill=e,e.on("text-change",(()=>{e.getSelection()&&u.runInAction((()=>{exports.quillRef.currentFormat=e.getFormat()})),setTimeout((()=>{var e;const t=null===(e=i.current)||void 0===e?void 0:e.childNodes[0];r(t.innerHTML)}),10)})),e.setSelection(0,0,"api"),e.on("selection-change",((t,r,n)=>{t&&u.runInAction((()=>{exports.quillRef.currentFormat=e.getFormat()}))})),i.current.childNodes[0].addEventListener("blur",(e=>{var r;if(null===(r=e.relatedTarget)||void 0===r?void 0:r.classList.contains("ql-clipboard")){return}const n=function(e){return!!e&&!!e.closest(".sketch-picker")}(e.relatedTarget);n||t()})),()=>{u.runInAction((()=>{exports.quillRef.editor.instance=null,exports.quillRef.currentFormat={}})),delete window.__polotnoQuill}}),[]),o.default.useEffect((()=>(0,E.reaction)((()=>n.text),(()=>{var t;const r=exports.quillRef.editor.instance;if(!r){return}const o=r.getSelection();(null===(t=i.current)||void 0===t?void 0:t.childNodes[0].innerHTML)===n.text||((0,exports.setQuillContent)(r,e),o&&(r.setSelection(o.index,o.length),u.runInAction((()=>{exports.quillRef.currentFormat=r.getFormat()}))))}),{fireImmediately:!0})),[]);const a={color:n.fill};return n.fill.indexOf("gradient")>=0&&(a.backgroundColor=n.fill,a.backgroundImage=n.fill,a.backgroundSize="100% 100%",a.backgroundRepeat="repeat",a.webkitBackgroundClip="text",a.MozBackgroundClip="text",a.WebkitTextFillColor="transparent",a.MozTextFillColor="transparent"),o.default.createElement(k,{ref:i,style:Object.assign(Object.assign({},a),{fontSize:n.fontSize,fontWeight:n.fontWeight,width:n.a.width,fontFamily:'"'+n.fontFamily+'"',lineHeight:n.lineHeight,letterSpacing:n.letterSpacing*n.fontSize+"px",textAlign:n.align,opacity:Math.max(n.a.opacity,.2)}),dir:(0,f.getDir)((0,y.removeTags)(n.text))})},q=(e,t=100,r=!1,n="")=>{const[i,a]=o.default.useState(e),l=o.default.useRef(null);return o.default.useEffect((()=>e===r?(l.current&&(clearTimeout(l.current),l.current=null),void a(r)):(l.current&&clearTimeout(l.current),l.current=setTimeout((()=>{a(e),l.current=null}),t),()=>{l.current&&clearTimeout(l.current)})),[e,t]),[i,a]};function F(e,{fontFamily:t="",color:r="black"}={}){let n=`color: ${r||e.fill}`;return e.fill.indexOf("gradient")>=0&&(n=`\n background-color: ${r};\n background-image: ${e.fill};\n background-size: 100% 100%;\n background-repeat: repeat;\n -webkit-background-clip: text;\n -moz-background-clip: text;\n -webkit-text-fill-color: transparent;\n -moz-text-fill-color: transparent;\n `),`<div style="${["white-space: pre-wrap",`width: ${Math.round(e.width||100)}px`,n,`font-size: ${e.fontSize}px`,`font-family: '${t}'`,`text-align: ${e.align}`,e.textDecoration?`text-decoration: ${e.textDecoration}; text-decoration-color: ${r||e.fill}; text-decoration-layer: over`:"",e.lineHeight?`line-height: ${e.lineHeight}`:"",e.letterSpacing?`letter-spacing: ${e.letterSpacing*e.fontSize}px`:"",e.fontStyle?`font-style: ${e.fontStyle}`:"",e.fontWeight?`font-weight: ${e.fontWeight}`:"",e.strokeWidth?`-webkit-text-stroke: ${e.strokeWidth}px ${e.stroke}`:"",e.strokeWidth?"paint-order: stroke fill":""].filter(Boolean).join("; ")}" contentEditable dir="${(0,f.getDir)((0,y.removeTags)(e.text))}">${(0,y.sanitizeHtml)(e.text).replace(/\n/g,"</br>")}</div>`}const R=/^((?!chrome|android).)*safari/i.test(navigator.userAgent);exports.HTMLElement=(0,a.observer)((({element:e,store:t})=>{const r=o.default.useRef(null),[n,i]=o.default.useState(),[a,s]=o.default.useState(!1),[x,E]=o.default.useState(!0),z=o.default.useRef(e.height),T=t.selectedShapes.indexOf(e)>=0&&e.selectable,_=e.fontSize/3,{textVerticalResizeEnabled:C}=c.flags,M=(0,f.usePrevious)(e.fontFamily),[$]=(0,f.useFontLoader)(t,e.fontFamily),I=e._editModeEnabled;(0,m.useFadeIn)(r);const A=$?e.fontFamily:M!==e.fontFamily?M:"Arial",H=(0,g.useColor)(e).fill,j=F(e,{fontFamily:A,color:H}),{width:P,height:D}=function(e,t,r){return o.default.useMemo((()=>(0,h.detectSize)(e)),[e,t.width,r])}(j,e,$);o.default.useEffect((()=>{if(!$){return}if(!e.height){return void e.set({height:D})}const{textOverflow:r}=c.flags;if("change-font-size"!==r||a){"resize"===r&&(C&&e.height<D&&t.history.ignore((()=>{e.set({height:D})})),C||e.height===D||t.history.ignore((()=>{e.set({height:D})})))}else{const r=(e=>{let t=e.fontSize;for(let r=1;r<50;r++){const r=F(Object.assign(Object.assign({},e.toJSON()),{fontSize:t}),{fontFamily:e.fontFamily}),{height:n}=(0,h.detectSize)(r),i=e.height&&n>e.height,o=(0,h.isContentWrapping)({html:r});if(!i&&!o){break}t-=.5}return t})(e);r!==e.fontSize?t.history.ignore((()=>{e.set({fontSize:r})})):e.height!==D&&(C&&e.height<D?t.history.ignore((()=>{e.set({height:D})})):C||t.history.ignore((()=>{e.set({height:D})})))}}));const L=o.default.useRef(0),X=o.default.useMemo((()=>{const e={lastArgs:null,lastResult:null};return async function(t){return e.lastArgs&&e.lastResult&&(r=e.lastArgs,n=t,JSON.stringify(r)===JSON.stringify(n))||(e.lastResult=await(0,h.htmlToCanvas)(t),e.lastArgs=Object.assign({},t)),e.lastResult;var r,n}}),[]),Y=o.default.useRef(null);o.default.useEffect((()=>{a||I||(async()=>{L.current++;const r=L.current,n=(0,b.incrementLoader)(`text ${e.id}`);Y.current=n,E(!0);let o=null;const a=R?5:1;for(let i=0;i<a;i++){const a=i>0?X:h.htmlToCanvas;try{if(o=await a({skipCache:i>0,html:j,width:e.width||1,height:e.height||D||1,fontFamily:A,padding:_,pixelRatio:t._elementsPixelRatio,font:t.fonts.find((e=>e.fontFamily===A))||w.globalFonts.find((e=>e.fontFamily===A))}),r!==L.current){return void n()}if(!function(e){const t=e.getContext("2d").getImageData(0,0,e.width,e.height).data;for(let r=0;r<t.length;r+=4){if(0!==t[r+3]){return!0}}return!1}(o)&&R){await new Promise((e=>setTimeout(e,50*(i+1))));continue}}catch(l){(0,b.triggerLoadError)(`Error rendering rich text with id ${e.id}`);break}}if(!o){return Y.current=null,void n()}i(o),E(!1)})()}),[j,a,D,I,A,e.height,t._elementsPixelRatio,$]);const[W,B]=q(x),[Q]=q(a,100,!0),N=Q||W;o.default.useEffect((()=>{if(!N){return u.autorun((()=>{const t=r.current;(0,d.applyFilter)(t,e)}))}}),[n,N,e.shadowColor,e.shadowOffsetX,e.shadowOffsetY,e.shadowOpacity]),o.default.useEffect((()=>{n&&!x&&Y.current&&(Y.current(),Y.current=null)}),[n,x]);let J=0;"middle"===e.verticalAlign&&(J=(e.height-D)/2),"bottom"===e.verticalAlign&&(J=e.height-D);const V=(0,f.getLineHeight)({fontLoaded:$,fontFamily:e.fontFamily,fontSize:e.fontSize,lineHeight:e.lineHeight}),G=(0,v.isTouchDevice)();return o.default.createElement(o.default.Fragment,null,o.default.createElement(l.Rect,{x:e.a.x,y:e.a.y,offsetX:e.backgroundPadding*(e.fontSize*V*.5),offsetY:e.backgroundPadding*(e.fontSize*V*.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*V),height:e.a.height+e.backgroundPadding*(e.fontSize*V),cornerRadius:e.backgroundCornerRadius*(e.fontSize*V*.5)}),o.default.createElement(l.Rect,{ref:r,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:!N,draggable:G?e.draggable&&T:e.draggable,preventDefault:!G||T,opacity:I?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:()=>{e.contentEditable&&e.toggleEditMode(!0)},onDblTap:()=>{e.contentEditable&&e.toggleEditMode(!0)},onTransformStart:t=>{s(!0),z.current=e.height},onTransform:t=>{var r;const n=t.target,i=(null===(r=n.getStage())||void 0===r?void 0:r.findOne("Transformer")).getActiveAnchor(),o="middle-left"===i||"middle-right"===i,a="top-center"===i||"bottom-center"===i,l=n.scaleX();if(o){const t=n.scaleX(),r=Math.max(n.width()*t,e.fontSize);if(n.width(r),n.scaleX(1),c.flags.textVerticalResizeEnabled){const t=Math.max(D,z.current);e.set({height:t})}e.set({width:r,x:n.x(),y:n.y()})}else if(a){let r="resize"===c.flags.textOverflow?D:e.lineHeight*e.fontSize;const i=Math.max(r,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})}},onTransformEnd:t=>{s(!1),E(!0);const r=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),e.set({fontSize:e.fontSize*r,width:t.target.width()*r,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),shadowBlur:e.shadowBlur*r,shadowOffsetX:e.shadowOffsetX*r,shadowOffsetY:e.shadowOffsetY*r,strokeWidth:e.strokeWidth*r})}}),o.default.createElement(l.Image,{ref:r,image:n,x:e.a.x,y:e.a.y,offsetX:_,offsetY:_-J,listening:!1,rotation:e.a.rotation,width:e.a.width+2*_,height:e.a.height+2*_,visible:!N,opacity:I?0:e.a.opacity,shadowEnabled:e.shadowEnabled,shadowBlur:e.shadowBlur,shadowOffsetX:e.shadowOffsetX,shadowOffsetY:e.shadowOffsetY,shadowColor:e.shadowColor,shadowOpacity:e.shadowOpacity,hideInExport:!e.showInExport}),N&&o.default.createElement(l.Group,{x:e.a.x,y:e.a.y,rotation:e.a.rotation,offsetY:-J},o.default.createElement(p.Html,{divProps:{style:{pointerEvents:"none"}}},o.default.createElement(k,{dangerouslySetInnerHTML:{__html:j},style:{pointerEvents:"none",opacity:e.a.opacity}}))),I&&o.default.createElement(l.Group,{x:e.a.x,y:e.a.y,rotation:e.a.rotation,offsetY:-J},o.default.createElement(p.Html,null,o.default.createElement(O,{html:j,element:e,onChange:t=>{const r=(0,S.getLimitedFontSize)({oldText:(0,y.removeTags)(e.text),newText:(0,y.removeTags)(t),element:e});e.set({text:t,fontSize:r})},onBlur:r=>{e.toggleEditMode(!1),B(!0),""===(0,y.removeTags)(e.text)&&e.removable&&!e.placeholder&&t.deleteElements([e.id])}}))))}));
|
package/canvas/image-element.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e,t=this&&this.__createBinding||(Object.create?function(e,t,r,a){void 0===a&&(a=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,a,i)}:function(e,t,r,a){void 0===a&&(a=r),e[a]=t[r]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e){Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r)}return t},e(t)},function(a){if(a&&a.__esModule){return a}var i={};if(null!=a){for(var o=e(a),n=0;n<o.length;n++){"default"!==o[n]&&t(i,a,o[n])}}return r(i,a),i}),i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.ImageElement=exports.useImageLoader=exports.setImageLoaderHook=exports.useCornerRadiusAndCrop=exports.setOuterImageCropTransformerStyle=exports.setInnerImageCropTransformerStyle=exports.useSizeFixer=void 0;const o=i(require("react")),n=require("mobx-react-lite"),h=require("mobx"),d=require("react-konva"),l=i(require("use-image")),s=i(require("konva")),c=require("react-konva-utils"),u=require("../utils/loader"),g=a(require("../utils/svg")),f=require("../utils/flags"),p=require("../utils/canvas"),m=require("./apply-filters"),w=require("./use-fadein"),x=require("../utils/screen");function y(){return document.createElement("canvas")}function M(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}exports.useSizeFixer=e=>{const[t,r]=o.default.useState(e);return o.default.useEffect((()=>{(async()=>{const a=await async function(e){if(!(e.indexOf("data:image/svg+xml")>=0||e.indexOf(".svg")>=0)){return e}const t=await g.urlToString(e),r=g.fixSize(t);return g.svgToURL(r)}(e);a!==t&&r(a)})()}),[e]),t};const v={boundBoxFunc:(e,t)=>t.width<5||t.height<5?e:t,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],keepRatio:!1,rotateEnabled:!1,anchorFill:"rgb(240, 240, 240)",anchorStrokeWidth:2,borderStrokeWidth:2};exports.setInnerImageCropTransformerStyle=e=>{Object.assign(v,e)};const b={boundBoxFunc:(e,t)=>t.width<5||t.height<5?e:t,anchorSize:20,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],rotateEnabled:!1,borderEnabled:!1,anchorCornerRadius:10,anchorStrokeWidth:2,borderStrokeWidth:2};exports.setOuterImageCropTransformerStyle=e=>{Object.assign(b,e)};const E=(e,t,r)=>Math.max(t,Math.min(r,e));exports.useCornerRadiusAndCrop=(e,t,r,a,i=0,n=!1,h=!0)=>{const d=Math.floor(E(e.a.width*a,1,1e4)),l=Math.floor(E(e.a.height*a,1,1e4)),c=Math.min(i*a,d/2,l/2),u=Math.max(e.a.width/r.width,e.a.height/r.height)*a,g=e.page._exportingOrRendering&&f.flags.imageDownScalingEnabled&&u<1&&!n,m=0===r.x&&0===r.y&&r.width===(null==t?void 0:t.width)&&r.height===(null==t?void 0:t.height),w=o.default.useMemo((()=>{if(t&&t.width&&t.height){return m&&0===c&&!g?void 0:y()}}),[t,c,g,m]);return o.default.useLayoutEffect((()=>{if(!w||!t){return}(0,p.trySetCanvasSize)(w,d,l);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,l-c),e.arc(d-c,l-c,c,0,Math.PI/2,!1),e.lineTo(c,l),e.arc(c,l-c,c,Math.PI/2,Math.PI,!1),e.lineTo(0,c),e.arc(c,c,c,Math.PI,3*Math.PI/2,!1),e.clip());const a=g?function(e,t){var r,a;const i=y();i.width=e.width,i.height=e.height;const o=Math.max(1,Math.floor(i.width*t)),n=Math.max(1,Math.floor(i.height*t));null===(r=i.getContext("2d"))||void 0===r||r.drawImage(e,0,0,i.width,i.height);const h=function(e,t,r,a,i,o,n){for(var h=new ImageData(t,r),d=new Int32Array(e.data.buffer),l=e.width,s=new Int32Array(h.data.buffer),c=h.width,u=t/o,g=r/n,f=Math.round(1/u),p=Math.round(1/g),m=f*p,w=0;w<h.height;w++){for(var x=0;x<c;x++){for(var y=0+Math.round(x/u)+(0+Math.round(w/g))*l,M=0,v=0,b=0,E=0,S=0;S<p;S++){for(var I=0;I<f;I++){var O=d[y+I+S*l];M+=O<<24>>>24,v+=O<<16>>>24,b+=O<<8>>>24,E+=O>>>24}}M=Math.round(M/m),v=Math.round(v/m),b=Math.round(b/m),E=Math.round(E/m),s[x+w*c]=E<<24|b<<16|v<<8|M}}return h}(i.getContext("2d").getImageData(0,0,i.width,i.height),o,n,0,0,i.width,i.height);return i.width=o,i.height=n,null===(a=i.getContext("2d"))||void 0===a||a.putImageData(h,0,0),i}(t,u):t,i=g?{x:Math.floor(r.x*u),y:Math.floor(r.y*u),width:Math.floor(r.width*u),height:Math.floor(r.height*u)}:r;e.drawImage(a,i.x,i.y,i.width,i.height,0,0,w.width,w.height)}),[w,e.a.width,e.a.height,r.x,r.y,r.width,r.height,i,a,n,e.page._exportingOrRendering,g]),o.default.useEffect((()=>()=>{w&&"CANVAS"===w.nodeName&&s.default.Util.releaseCanvas(w)}),[w]),w||t};const S=y(),I=(0,n.observer)((({element:e})=>{const t=Math.min(30,e.a.width/4,e.a.height/4),r=o.default.useRef(null);return o.default.useEffect((()=>{const e=r.current;if(!e){return}const t=new s.default.Animation((t=>{e.rotate(((null==t?void 0:t.timeDiff)||0)/2)}),e.getLayer());return t.start(),()=>{t.stop()}})),o.default.createElement(d.Group,{x:e.x,y:e.y,rotation:e.rotation,listening:!1,opacity:e.a.opacity,hideInExport:!e.showInExport},o.default.createElement(d.Rect,{width:e.a.width,height:e.a.height,fill:"rgba(124, 173, 212, 0.8)"}),o.default.createElement(d.Arc,{ref:r,x:e.a.width/2,y:e.a.height/2,fill:"white",outerRadius:Math.abs(t),innerRadius:Math.max(1,t-5),angle:270}))})),O=(0,n.observer)((({element:e})=>{const t=Math.max(10,Math.min(30,e.a.width/25));return o.default.createElement(d.Group,{x:e.x,y:e.y,rotation:e.rotation,listening:!1,opacity:e.a.opacity,hideInExport:!e.showInExport},o.default.createElement(d.Rect,{width:e.a.width,height:e.a.height,fill:"rgba(223, 102, 102, 0.8)"}),o.default.createElement(d.Text,{text:"Can not load the image...",fontSize:t,width:e.a.width,height:e.a.height,align:"center",fill:"white",verticalAlign:"middle",padding:5}))}));let C=l.default;exports.setImageLoaderHook=e=>{C=e},exports.useImageLoader=(e,t="",r="")=>{const a=o.default.useRef(),i=()=>{var e;null===(e=a.current)||void 0===e||e.call(a),a.current=void 0};o.default.useEffect((()=>i),[]),o.default.useLayoutEffect((()=>{const o=t.slice(0,200),n=`image with id ${r} url: ${o}`;"loading"!==e||a.current||(a.current=(0,u.incrementLoader)(n)),"loading"!==e&&i(),"failed"===e&&(0,u.triggerLoadError)(n)}),[e])},exports.ImageElement=(0,n.observer)((({element:e,store:t})=>{var r;const[a,i]=o.default.useState(!1),n=o.default.useRef(null),l=o.default.useRef(null),u=t.selectedShapes.indexOf(e)>=0&&e.selectable,[f,E]=(e=>{const[t,r]=o.default.useReducer((e=>e+1),0),a=o.default.useRef("loading"),i=o.default.useRef(e.src),n=o.default.useRef(e.src);return n.current!==e.src&&(n.current=e.src,a.current="loading"),o.default.useEffect((()=>{if("svg"!==e.type){return}if(!e.src){return}let t=!1;return(async()=>{a.current="loading",r();const o=await g.urlToString(e.src),n=g.fixSize(o),h=g.replaceColors(n,e.colorsReplace);t||(i.current=h,a.current="loaded",r())})(),()=>{t=!0}}),[e.src,JSON.stringify(e.colorsReplace)]),"svg"!==e.type?[e.src,"loaded"]:[i.current,a.current]})(e),[R,_]=C(f,"anonymous"),T="svg"!==e.type||"loaded"===E?_:"loading";(0,exports.useImageLoader)(T,e.src,e.id);const X=e.page._exportingOrRendering?1:Math.max(1,t.scale),Y=t._elementsPixelRatio*X,k=(({image:e,status:t,type:r})=>{const a=o.default.useRef();return o.default.useEffect((()=>{a.current=e||a.current}),[e]),"failed"!==t||"failed"!==t&&"svg"===r?a.current:void 0})({image:R,status:_,type:e.type}),D=((e,t,r)=>{const a=o.default.useMemo((()=>{var a,i;const{flipX:o,flipY:n}=e,h="svg"===e.type||e.src.indexOf("data:image/svg+xml")>=0||e.src.indexOf(".svg")>=0,d=navigator.userAgent.toLowerCase().indexOf("firefox")>-1,l=(/^((?!chrome|android).)*safari/i.test(navigator.userAgent)||d)&&h||e.maskSrc;if(!o&&!n&&!l){return t}if(!t||!t.width||!t.height){return null}const s=y();let c=1;"svg"===e.type&&(c=Math.max(e.a.width/t.width*r,e.a.height/t.height*r)),(0,p.trySetCanvasSize)(s,Math.max(t.width*c,1),Math.max(t.height*c,1));let u=o?-s.width:0,g=n?-s.height:0;return null===(a=s.getContext("2d"))||void 0===a||a.scale(o?-1:1,n?-1:1),null===(i=s.getContext("2d"))||void 0===i||i.drawImage(t,u,g,s.width,s.height),s}),[e.maskSrc,e.flipX,e.flipY,t,e.a.width,e.a.height,r]);return o.default.useEffect((()=>()=>{a&&"CANVAS"===a.nodeName&&s.default.Util.releaseCanvas(a)}),[a]),a})(e,R||k,Y),W=((e,t)=>{const[r,a]=C(e.maskSrc,"anonymous"),i=e.maskSrc?a:"loaded";return(0,exports.useImageLoader)(i,e.maskSrc||"",e.id),o.default.useMemo((()=>{if(!r){return t}if(!t||!t.width||!t.height){return t}const a=y();a.width=Math.max(t.width,1),a.height=Math.max(t.height,1);const i=a.getContext("2d");if(!i){return t}i.drawImage(t,0,0),i.globalCompositeOperation="source-in";const o=function(e,t){const r=t.width/t.height;let a,i;return r>=e.width/e.height?(a=e.width,i=e.width/r):(a=e.height*r,i=e.height),{x:(e.width-a)/2,y:(e.height-i)/2,width:a,height:i}}(r,e);return i.drawImage(r,o.x,o.y,o.width,o.height,0,0,t.width,t.height),a}),[t,r,e.a.width,e.a.height])})(e,D)||S;let{cropX:A,cropY:L,cropWidth:P,cropHeight:z}=e.a;"loaded"!==_&&(A=L=0,P=z=1);const q=W.width*P,H=W.height*z,j=e.a.width/e.a.height;let F,B;const N=q/H,U=e.stretchEnabled;U?(F=q,B=H):j>=N?(F=q,B=q/j):(F=H*j,B=H);const G={x:W.width*A,y:W.height*L,width:F,height:B},V=null!==(r=e.cornerRadius)&&void 0!==r?r:0,$=e.page._exportingOrRendering?1:Math.min(2,t.scale),J=t._elementsPixelRatio*$;let K=((e,t,r,a)=>{const i=(0,exports.useSizeFixer)(e.clipSrc||""),[n,h]=C(i,"anonymous"),d=e.clipSrc?h:"loaded";(0,exports.useImageLoader)(d,e.clipSrc,e.id);const l=o.default.useMemo((()=>{if(t&&n){return y()}}),[t,n]);return o.default.useLayoutEffect((()=>{var a;if(!n){return}if(!t||!t.width||!t.height){return}if(!n||!n.width||!n.height){return}if(!l){return}const i=y(),o=Math.max(e.a.width/n.width*r,e.a.height/n.height*r);i.width=Math.max(n.width*o,1),i.height=Math.max(n.height*o,1),null===(a=i.getContext("2d"))||void 0===a||a.drawImage(n,0,0,i.width,i.height),l.width=Math.max(t.width,1),l.height=Math.max(t.height,1);const h=l.getContext("2d");h&&(h.save(),h.drawImage(i,0,0,t.width,t.height),s.default.Util.releaseCanvas(i),h.globalCompositeOperation="source-in",h.drawImage(t,0,0,l.width,l.height),h.restore())}),[l,t,n,e.a.width,e.a.height,r,...a]),e.clipSrc&&n?l:t})(e,(0,exports.useCornerRadiusAndCrop)(e,W,G,J,V,a||e._cropModeEnabled||"svg"===e.type,!0),J,[G,V,J]);const Q=Math.max(e.a.width/F,e.a.height/B);o.default.useEffect((()=>{var t;if(!e._cropModeEnabled){return}const r=null===(t=n.current)||void 0===t?void 0:t.getStage();function a(t){e._cropModeEnabled&&t.target!==l.current&&e.toggleCropMode(!1)}function i(t){e._cropModeEnabled&&t.target.parentNode!==r.content&&e.toggleCropMode(!1)}return document.body.addEventListener("click",i),null==r||r.on("click",a),null==r||r.on("tap",a),()=>{document.body.removeEventListener("click",i),document.body.removeEventListener("touchstart",i),null==r||r.off("click",a),null==r||r.off("click",a)}}),[e._cropModeEnabled]),o.default.useLayoutEffect((()=>{if(!a&&!e._cropModeEnabled){return(0,m.applyFilter)(n.current,e),(0,h.autorun)((()=>{(0,m.applyFilter)(n.current,e)}),{delay:100})}}),[K,e.page._exportingOrRendering,a,P,z,e._cropModeEnabled]),o.default.useLayoutEffect((()=>{var t;a||e._cropModeEnabled?null===(t=n.current)||void 0===t||t.clearCache():(0,m.applyFilter)(n.current,e)}),[a,e.a.width,e.a.height,e._cropModeEnabled]),o.default.useEffect((()=>{(0,m.applyFilter)(n.current,e)}),[e.shadowEnabled,e.shadowBlur,e.cornerRadius,e.shadowColor,e.shadowOffsetX,e.shadowOffsetY,e.shadowOpacity]);const Z=o.default.useRef(null),ee=o.default.useRef(null),te=o.default.useRef(null);o.default.useLayoutEffect((()=>{e._cropModeEnabled&&(ee.current.nodes([Z.current]),te.current.nodes([l.current]))}),[e._cropModeEnabled]);var re=o.default.useRef(null),ae=o.default.useRef(0),ie=o.default.useRef(!1);const oe=t=>{var r;(null===(r=t.evt.touches)||void 0===r?void 0:r.length)>2&&t.target.stopDrag(),Math.round(t.target.x())>0&&(t.target.x(0),t.target.scaleX(1)),Math.round(t.target.y())>0&&(t.target.y(0),t.target.scaleY(1));const a=t.target.width()*t.target.scaleX(),i=t.target.height()*t.target.scaleY(),o=Math.min(1,F/a),n=Math.min(1,B/i),h=1-o,d=Math.min(h,Math.max(0,Math.round(-t.target.x())/a)),l=1-n,s=Math.min(l,Math.max(0,Math.round(-t.target.y())/i));t.target.setAttrs({x:-d*W.width,y:-s*W.height,scaleX:1,scaleY:1}),e.set({cropX:d,cropY:s,cropWidth:o,cropHeight:n})},ne=()=>{"svg"!==e.type&&e.contentEditable&&(e.stretchEnabled||setTimeout((()=>{e.toggleCropMode(!0)})))},he="svg"===e.type&&k,de="loading"===_&&!he,le="failed"===_,se=!de&&!le,ce=o.default.useRef({cropX:0,cropY:0,cropWidth:0,cropHeight:0}),ue=se?e.a.opacity:0;(0,w.useFadeIn)(n,ue);const ge=e.selectable||"admin"===t.role,fe=(0,x.isTouchDevice)();return o.default.createElement(o.default.Fragment,null,de&&o.default.createElement(I,{element:e}),le&&o.default.createElement(O,{element:e}),o.default.createElement(d.Image,{ref:n,name:"element",id:e.id,image:K,x:e.a.x,y:e.a.y,width:e.a.width||1,height:e.a.height||1,rotation:e.a.rotation,opacity:ue,shadowEnabled:e.shadowEnabled,shadowBlur:e.shadowBlur,shadowOffsetX:e.shadowOffsetX,shadowOffsetY:e.shadowOffsetY,shadowColor:e.shadowColor,shadowOpacity:e.shadowOpacity,customCrop:G,listening:ge,draggable:fe?e.draggable&&u:e.draggable,preventDefault:!fe||u,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()})},onDblClick:ne,onDblTap:ne,onTransformStart:()=>{i(!0),ce.current={cropX:e.cropX,cropY:e.cropY,cropWidth:e.cropWidth,cropHeight:e.cropHeight}},onTransform:t=>{var r;const a=t.currentTarget,i=Math.abs(a.scaleX()-1)<1e-7?1:a.scaleX(),o=Math.abs(a.scaleY()-1)<1e-7?1:a.scaleY();a.scaleX(1),a.scaleY(1);const n=null===(r=t.target.getStage())||void 0===r?void 0:r.findOne("Transformer"),h=1-F/W.width,d=Math.min(h,Math.max(0,e.cropX)),l=1-B/W.height,s=Math.min(l,Math.max(0,e.cropY)),c=n.getActiveAnchor(),u=!(c.indexOf("middle")>=0||c.indexOf("center")>=0),g=!u&&i<1&&ce.current.cropHeight>B/W.height;let f=u?e.cropWidth:e.cropWidth*i;g&&(f=e.cropWidth);const p=!u&&o<1&&ce.current.cropWidth>F/W.width;let m=u?e.cropHeight:e.cropHeight*o;p&&(m=e.cropHeight),U&&(f=e.cropWidth,m=e.cropHeight),e.set({cropX:d,cropY:s,x:a.x(),y:a.y(),width:a.width()*i,height:a.height()*o,rotation:t.target.rotation(),cropWidth:Math.min(f,1-d),cropHeight:Math.min(m,1-s)})},onTransformEnd:t=>{const r=t.currentTarget;e.set({width:r.width(),height:r.height(),x:r.x(),y:r.y(),rotation:t.target.rotation(),cropWidth:F/W.width,cropHeight:B/W.height}),i(!1)}}),o.default.createElement(d.Rect,{x:e.x,y:e.y,width:Math.max(e.a.width-e.borderSize,0),height:Math.max(e.a.height-e.borderSize,0),opacity:ue,offsetX:-e.borderSize/2,offsetY:-e.borderSize/2,stroke:e.borderColor,strokeWidth:e.borderSize,listening:!1,visible:!!e.borderSize,rotation:e.rotation,cornerRadius:Math.max(0,V-e.borderSize),hideInExport:!e.showInExport}),e._cropModeEnabled&&o.default.createElement(c.Portal,{selector:".page-abs-container",enabled:!0},o.default.createElement(d.Rect,{x:-window.innerWidth/t.scale,y:-window.innerWidth/t.scale,width:window.innerWidth/t.scale*3,height:window.innerWidth/t.scale*3,fill:"rgba(0,0,0,0.3)"}),o.default.createElement(d.Image,{listening:!1,image:K,x:e.x,y:e.y,width:e.a.width,height:e.a.height,rotation:e.rotation,shadowEnabled:e.shadowEnabled,shadowBlur:e.shadowBlur}),o.default.createElement(d.Group,{x:e.x,y:e.y,rotation:e.rotation,scaleX:Q,scaleY:Q},o.default.createElement(d.Image,{image:W,ref:l,opacity:.4,draggable:!0,x:-e.cropX*W.width,y:-e.cropY*W.height,onDragMove:oe,onTransform:oe,onTouchMove:e=>{e.evt.preventDefault();const t=e.target.getStage().getPointersPositions();var r=t[0],a=t[1];const i=e.target;if(r&&!a&&!i.isDragging()&&ie.current&&(i.startDrag(),ie.current=!1),r&&a){s.default.hitOnDragEnabled=!0,i.isDragging()&&(ie.current=!0,i.stopDrag());const t=e.target.getAbsoluteTransform().copy();t.invert();var o={x:r.x,y:r.y},n={x:a.x,y:a.y};if(!re.current){return void(re.current=M(o,n))}var h=M(o,n),d=function(e,t){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}(o,n);ae.current||(ae.current=d);const p=i.position();var l={x:h.x-p.x,y:h.y-p.y},c=d/ae.current;i.scaleX(c),i.scaleY(c);const m=t.point(h),w=t.point(re.current);var u=m.x-w.x,g=m.y-w.y,f={x:Math.min(0,h.x-l.x*c+u),y:Math.min(0,h.y-l.y*c+g)};i.position(f),ae.current=d,re.current=h,oe(e)}},onTouchEnd:e=>{ae.current=0,re.current=null,s.default.hitOnDragEnabled=!1}}),o.default.createElement(d.Transformer,Object.assign({ref:te},b)),o.default.createElement(d.Rect,{width:F,height:B,ref:Z,listening:!1,onTransform:t=>{t.target.x()<-e.cropX*W.width-1e-9&&(t.target.x(-e.cropX*W.width),t.target.scaleX(1)),t.target.y()<-e.cropY*W.height-1e-9&&(t.target.y(-e.cropY*W.height),t.target.scaleY(1));const r=Math.min(1,Math.max(0,e.cropX+t.target.x()/W.width)),a=Math.min(1,Math.max(0,t.target.y()/W.height+e.cropY)),i=t.target.width()*t.target.scaleX(),o=t.target.height()*t.target.scaleY(),n=Math.min(1-r,i/W.width),h=Math.min(1-a,o/W.height),d=t.target.getAbsolutePosition(t.target.getParent().getParent());t.target.scale({x:1,y:1}),t.target.position({x:0,y:0}),e.set({x:d.x,y:d.y,cropX:r,cropY:a,cropWidth:n,cropHeight:h,width:Math.min(i*Q,W.width*(1-r)*Q),height:Math.min(o*Q,W.height*(1-a)*Q)})}}),o.default.createElement(d.Transformer,Object.assign({ref:ee},v,{visible:e.resizable})))))}));
|
|
1
|
+
var e,t=this&&this.__createBinding||(Object.create?function(e,t,r,a){void 0===a&&(a=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,a,i)}:function(e,t,r,a){void 0===a&&(a=r),e[a]=t[r]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e){Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r)}return t},e(t)},function(a){if(a&&a.__esModule){return a}var i={};if(null!=a){for(var o=e(a),n=0;n<o.length;n++){"default"!==o[n]&&t(i,a,o[n])}}return r(i,a),i}),i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.ImageElement=exports.useImageLoader=exports.setImageLoaderHook=exports.useCornerRadiusAndCrop=exports.setOuterImageCropTransformerStyle=exports.setInnerImageCropTransformerStyle=exports.useSizeFixer=void 0;const o=i(require("react")),n=require("mobx-react-lite"),h=require("mobx"),d=require("react-konva"),l=i(require("use-image")),c=i(require("konva")),s=require("react-konva-utils"),u=require("../utils/loader"),g=a(require("../utils/svg")),f=require("../utils/flags"),p=require("../utils/canvas"),m=require("./apply-filters"),w=require("./use-fadein"),x=require("../utils/screen");function y(){return document.createElement("canvas")}function M(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}exports.useSizeFixer=e=>{const[t,r]=o.default.useState(e);return o.default.useEffect((()=>{(async()=>{const a=await async function(e){if(!(e.indexOf("data:image/svg+xml")>=0||e.indexOf(".svg")>=0)){return e}const t=await g.urlToString(e),r=g.fixSize(t);return g.svgToURL(r)}(e);a!==t&&r(a)})()}),[e]),t};const v={boundBoxFunc:(e,t)=>t.width<5||t.height<5?e:t,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],keepRatio:!1,rotateEnabled:!1,anchorFill:"rgb(240, 240, 240)",anchorStrokeWidth:2,borderStrokeWidth:2};exports.setInnerImageCropTransformerStyle=e=>{Object.assign(v,e)};const b={boundBoxFunc:(e,t)=>t.width<5||t.height<5?e:t,anchorSize:20,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],rotateEnabled:!1,borderEnabled:!1,anchorCornerRadius:10,anchorStrokeWidth:2,borderStrokeWidth:2};exports.setOuterImageCropTransformerStyle=e=>{Object.assign(b,e)};const E=(e,t,r)=>Math.max(t,Math.min(r,e));exports.useCornerRadiusAndCrop=(e,t,r,a,i=0,n=!1,h=!0)=>{const d=Math.floor(E(e.a.width*a,1,1e4)),l=Math.floor(E(e.a.height*a,1,1e4)),s=Math.min(i*a,d/2,l/2),u=Math.max(e.a.width/r.width,e.a.height/r.height)*a,g=e.page._exportingOrRendering&&f.flags.imageDownScalingEnabled&&u<1&&!n,m=0===r.x&&0===r.y&&r.width===(null==t?void 0:t.width)&&r.height===(null==t?void 0:t.height),w=o.default.useMemo((()=>{if(t&&t.width&&t.height){return m&&0===s&&!g?void 0:y()}}),[t,s,g,m]);return o.default.useLayoutEffect((()=>{if(!w||!t){return}(0,p.trySetCanvasSize)(w,d,l);const e=w.getContext("2d");if(!e){return}s&&(e.beginPath(),e.moveTo(s,0),e.lineTo(d-s,0),e.arc(d-s,s,s,3*Math.PI/2,0,!1),e.lineTo(d,l-s),e.arc(d-s,l-s,s,0,Math.PI/2,!1),e.lineTo(s,l),e.arc(s,l-s,s,Math.PI/2,Math.PI,!1),e.lineTo(0,s),e.arc(s,s,s,Math.PI,3*Math.PI/2,!1),e.clip());const a=g?function(e,t){var r,a;const i=y();i.width=e.width,i.height=e.height;const o=Math.max(1,Math.floor(i.width*t)),n=Math.max(1,Math.floor(i.height*t));null===(r=i.getContext("2d"))||void 0===r||r.drawImage(e,0,0,i.width,i.height);const h=function(e,t,r,a,i,o,n){for(var h=new ImageData(t,r),d=new Int32Array(e.data.buffer),l=e.width,c=new Int32Array(h.data.buffer),s=h.width,u=t/o,g=r/n,f=Math.round(1/u),p=Math.round(1/g),m=f*p,w=0;w<h.height;w++){for(var x=0;x<s;x++){for(var y=0+Math.round(x/u)+(0+Math.round(w/g))*l,M=0,v=0,b=0,E=0,S=0;S<p;S++){for(var I=0;I<f;I++){var O=d[y+I+S*l];M+=O<<24>>>24,v+=O<<16>>>24,b+=O<<8>>>24,E+=O>>>24}}M=Math.round(M/m),v=Math.round(v/m),b=Math.round(b/m),E=Math.round(E/m),c[x+w*s]=E<<24|b<<16|v<<8|M}}return h}(i.getContext("2d").getImageData(0,0,i.width,i.height),o,n,0,0,i.width,i.height);return i.width=o,i.height=n,null===(a=i.getContext("2d"))||void 0===a||a.putImageData(h,0,0),i}(t,u):t,i=g?{x:Math.floor(r.x*u),y:Math.floor(r.y*u),width:Math.floor(r.width*u),height:Math.floor(r.height*u)}:r;e.drawImage(a,i.x,i.y,i.width,i.height,0,0,w.width,w.height)}),[w,e.a.width,e.a.height,r.x,r.y,r.width,r.height,i,a,n,e.page._exportingOrRendering,g]),o.default.useEffect((()=>()=>{w&&"CANVAS"===w.nodeName&&c.default.Util.releaseCanvas(w)}),[w]),w||t};const S=y(),I=(0,n.observer)((({element:e})=>{const t=Math.min(30,e.a.width/4,e.a.height/4),r=o.default.useRef(null);return o.default.useEffect((()=>{const e=r.current;if(!e){return}const t=new c.default.Animation((t=>{e.rotate(((null==t?void 0:t.timeDiff)||0)/2)}),e.getLayer());return t.start(),()=>{t.stop()}})),o.default.createElement(d.Group,{x:e.x,y:e.y,rotation:e.rotation,listening:!1,opacity:e.a.opacity,hideInExport:!e.showInExport},o.default.createElement(d.Rect,{width:e.a.width,height:e.a.height,fill:"rgba(124, 173, 212, 0.8)"}),o.default.createElement(d.Arc,{ref:r,x:e.a.width/2,y:e.a.height/2,fill:"white",outerRadius:Math.abs(t),innerRadius:Math.max(1,t-5),angle:270}))})),O=(0,n.observer)((({element:e})=>{const t=Math.max(10,Math.min(30,e.a.width/25));return o.default.createElement(d.Group,{x:e.x,y:e.y,rotation:e.rotation,listening:!1,opacity:e.a.opacity,hideInExport:!e.showInExport},o.default.createElement(d.Rect,{width:e.a.width,height:e.a.height,fill:"rgba(223, 102, 102, 0.8)"}),o.default.createElement(d.Text,{text:"Can not load the image...",fontSize:t,width:e.a.width,height:e.a.height,align:"center",fill:"white",verticalAlign:"middle",padding:5}))}));let C=l.default;exports.setImageLoaderHook=e=>{C=e},exports.useImageLoader=(e,t="",r="")=>{const a=o.default.useRef(),i=()=>{var e;null===(e=a.current)||void 0===e||e.call(a),a.current=void 0};o.default.useEffect((()=>i),[]),o.default.useLayoutEffect((()=>{const o=t.slice(0,200),n=`image with id ${r} url: ${o}`;"loading"!==e||a.current||(a.current=(0,u.incrementLoader)(n)),"loading"!==e&&i(),"failed"===e&&(0,u.triggerLoadError)(n)}),[e])},exports.ImageElement=(0,n.observer)((({element:e,store:t})=>{var r;const[a,i]=o.default.useState(!1),n=o.default.useRef(null),l=o.default.useRef(null),u=t.selectedShapes.indexOf(e)>=0&&e.selectable,[f,E]=(e=>{const[t,r]=o.default.useReducer((e=>e+1),0),a=o.default.useRef("loading"),i=o.default.useRef(e.src),n=o.default.useRef(e.src);return n.current!==e.src&&(n.current=e.src,a.current="loading"),o.default.useEffect((()=>{if("svg"!==e.type){return}if(!e.src){return}let t=!1;return(async()=>{a.current="loading",r();const o=await g.urlToString(e.src),n=g.fixSize(o),h=g.replaceColors(n,e.colorsReplace);t||(i.current=h,a.current="loaded",r())})(),()=>{t=!0}}),[e.src,JSON.stringify(e.colorsReplace)]),"svg"!==e.type?[e.src,"loaded"]:[i.current,a.current]})(e),[R,_]=C(f,"anonymous"),X="svg"!==e.type||"loaded"===E?_:"loading";(0,exports.useImageLoader)(X,e.src,e.id);const Y=e.page._exportingOrRendering?1:Math.max(1,t.scale),T=t._elementsPixelRatio*Y,k=(({image:e,status:t,type:r})=>{const a=o.default.useRef();return o.default.useEffect((()=>{a.current=e||a.current}),[e]),"failed"!==t||"failed"!==t&&"svg"===r?a.current:void 0})({image:R,status:_,type:e.type}),D=((e,t,r)=>{const a=o.default.useMemo((()=>{var a,i;const{flipX:o,flipY:n}=e,h="svg"===e.type||e.src.indexOf("data:image/svg+xml")>=0||e.src.indexOf(".svg")>=0,d=navigator.userAgent.toLowerCase().indexOf("firefox")>-1,l=(/^((?!chrome|android).)*safari/i.test(navigator.userAgent)||d)&&h||e.maskSrc;if(!o&&!n&&!l){return t}if(!t||!t.width||!t.height){return null}const c=y();let s=1;"svg"===e.type&&(s=Math.max(e.a.width/t.width*r,e.a.height/t.height*r)),(0,p.trySetCanvasSize)(c,Math.max(t.width*s,1),Math.max(t.height*s,1));let u=o?-c.width:0,g=n?-c.height:0;return null===(a=c.getContext("2d"))||void 0===a||a.scale(o?-1:1,n?-1:1),null===(i=c.getContext("2d"))||void 0===i||i.drawImage(t,u,g,c.width,c.height),c}),[e.maskSrc,e.flipX,e.flipY,t,e.a.width,e.a.height,r]);return o.default.useEffect((()=>()=>{a&&"CANVAS"===a.nodeName&&c.default.Util.releaseCanvas(a)}),[a]),a})(e,R||k,T),W=((e,t)=>{const[r,a]=C(e.maskSrc,"anonymous"),i=e.maskSrc?a:"loaded";return(0,exports.useImageLoader)(i,e.maskSrc||"",e.id),o.default.useMemo((()=>{if(!r){return t}if(!t||!t.width||!t.height){return t}const a=y();a.width=Math.max(t.width,1),a.height=Math.max(t.height,1);const i=a.getContext("2d");if(!i){return t}i.drawImage(t,0,0),i.globalCompositeOperation="source-in";const o=function(e,t){const r=t.width/t.height;let a,i;return r>=e.width/e.height?(a=e.width,i=e.width/r):(a=e.height*r,i=e.height),{x:(e.width-a)/2,y:(e.height-i)/2,width:a,height:i}}(r,e);return i.drawImage(r,o.x,o.y,o.width,o.height,0,0,t.width,t.height),a}),[t,r,e.a.width,e.a.height])})(e,D)||S;let{cropX:A,cropY:L,cropWidth:P,cropHeight:z}=e.a;"loaded"!==_&&(A=L=0,P=z=1);const H=W.width*P,q=W.height*z,j=e.a.width/e.a.height;let F,B;const N=H/q,U=e.stretchEnabled;U?(F=H,B=q):j>=N?(F=H,B=H/j):(F=q*j,B=q);const G={x:W.width*A,y:W.height*L,width:F,height:B},V=null!==(r=e.cornerRadius)&&void 0!==r?r:0,$=e.page._exportingOrRendering?1:Math.min(2,t.scale),J=t._elementsPixelRatio*$;let K=((e,t,r,a)=>{const i=(0,exports.useSizeFixer)(e.clipSrc||""),[n,h]=C(i,"anonymous"),d=e.clipSrc?h:"loaded";(0,exports.useImageLoader)(d,e.clipSrc,e.id);const l=o.default.useMemo((()=>{if(t&&n){return y()}}),[t,n]);return o.default.useLayoutEffect((()=>{var a;if(!n){return}if(!t||!t.width||!t.height){return}if(!n||!n.width||!n.height){return}if(!l){return}const i=y(),o=Math.max(e.a.width/n.width*r,e.a.height/n.height*r);i.width=Math.max(n.width*o,1),i.height=Math.max(n.height*o,1),null===(a=i.getContext("2d"))||void 0===a||a.drawImage(n,0,0,i.width,i.height),l.width=Math.max(t.width,1),l.height=Math.max(t.height,1);const h=l.getContext("2d");h&&(h.save(),h.drawImage(i,0,0,t.width,t.height),c.default.Util.releaseCanvas(i),h.globalCompositeOperation="source-in",h.drawImage(t,0,0,l.width,l.height),h.restore())}),[l,t,n,e.a.width,e.a.height,r,...a]),e.clipSrc&&n?l:t})(e,(0,exports.useCornerRadiusAndCrop)(e,W,G,J,V,a||e._cropModeEnabled||"svg"===e.type,!0),J,[G,V,J]);const Q=Math.max(e.a.width/F,e.a.height/B);o.default.useEffect((()=>{var t;if(!e._cropModeEnabled){return}const r=null===(t=n.current)||void 0===t?void 0:t.getStage();function a(t){e._cropModeEnabled&&t.target!==l.current&&e.toggleCropMode(!1)}function i(t){e._cropModeEnabled&&t.target.parentNode!==r.content&&e.toggleCropMode(!1)}return document.body.addEventListener("click",i),null==r||r.on("click",a),null==r||r.on("tap",a),()=>{document.body.removeEventListener("click",i),document.body.removeEventListener("touchstart",i),null==r||r.off("click",a),null==r||r.off("click",a)}}),[e._cropModeEnabled]),o.default.useLayoutEffect((()=>{if(!a&&!e._cropModeEnabled){return(0,m.applyFilter)(n.current,e),(0,h.autorun)((()=>{(0,m.applyFilter)(n.current,e)}),{delay:100})}}),[K,e.page._exportingOrRendering,a,P,z,e._cropModeEnabled]),o.default.useLayoutEffect((()=>{var t;a||e._cropModeEnabled?null===(t=n.current)||void 0===t||t.clearCache():(0,m.applyFilter)(n.current,e)}),[a,e.a.width,e.a.height,e._cropModeEnabled]),o.default.useEffect((()=>{(0,m.applyFilter)(n.current,e)}),[e.shadowEnabled,e.shadowBlur,e.cornerRadius,e.shadowColor,e.shadowOffsetX,e.shadowOffsetY,e.shadowOpacity]);const Z=o.default.useRef(null),ee=o.default.useRef(null),te=o.default.useRef(null);o.default.useLayoutEffect((()=>{e._cropModeEnabled&&(ee.current.nodes([Z.current]),te.current.nodes([l.current]))}),[e._cropModeEnabled]);var re=o.default.useRef(null),ae=o.default.useRef(0),ie=o.default.useRef(!1);const oe=t=>{var r;(null===(r=t.evt.touches)||void 0===r?void 0:r.length)>2&&t.target.stopDrag(),Math.round(t.target.x())>0&&(t.target.x(0),t.target.scaleX(1)),Math.round(t.target.y())>0&&(t.target.y(0),t.target.scaleY(1));const a=t.target.width()*t.target.scaleX(),i=t.target.height()*t.target.scaleY(),o=Math.min(1,F/a),n=Math.min(1,B/i),h=1-o,d=Math.min(h,Math.max(0,Math.round(-t.target.x())/a)),l=1-n,c=Math.min(l,Math.max(0,Math.round(-t.target.y())/i));t.target.setAttrs({x:-d*W.width,y:-c*W.height,scaleX:1,scaleY:1}),e.set({cropX:d,cropY:c,cropWidth:o,cropHeight:n})},ne=()=>{"svg"!==e.type&&e.contentEditable&&(e.stretchEnabled||setTimeout((()=>{e.toggleCropMode(!0)})))},he="svg"===e.type&&k,de="loading"===_&&!he,le="failed"===_,ce=!de&&!le,se=o.default.useRef({cropX:0,cropY:0,cropWidth:0,cropHeight:0}),ue=ce?e.a.opacity:0;(0,w.useFadeIn)(n,ue);const ge=e.selectable||"admin"===t.role,fe=(0,x.isTouchDevice)();return o.default.createElement(o.default.Fragment,null,de&&o.default.createElement(I,{element:e}),le&&o.default.createElement(O,{element:e}),o.default.createElement(d.Image,{ref:n,name:"element",id:e.id,image:K,x:e.a.x,y:e.a.y,width:e.a.width||1,height:e.a.height||1,rotation:e.a.rotation,opacity:ue,shadowEnabled:e.shadowEnabled,shadowBlur:e.shadowBlur,shadowOffsetX:e.shadowOffsetX,shadowOffsetY:e.shadowOffsetY,shadowColor:e.shadowColor,shadowOpacity:e.shadowOpacity,customCrop:G,listening:ge,draggable:fe?e.draggable&&u:e.draggable,preventDefault:!fe||u,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()})},onDblClick:ne,onDblTap:ne,onTransformStart:()=>{i(!0),se.current={cropX:e.cropX,cropY:e.cropY,cropWidth:e.cropWidth,cropHeight:e.cropHeight}},onTransform:t=>{var r;const a=t.currentTarget,i=Math.abs(a.scaleX()-1)<1e-7?1:a.scaleX(),o=Math.abs(a.scaleY()-1)<1e-7?1:a.scaleY();a.scaleX(1),a.scaleY(1);const n=null===(r=t.target.getStage())||void 0===r?void 0:r.findOne("Transformer"),h=1-F/W.width,d=Math.min(h,Math.max(0,e.cropX)),l=1-B/W.height,c=Math.min(l,Math.max(0,e.cropY)),s=n.getActiveAnchor(),u=!(s.indexOf("middle")>=0||s.indexOf("center")>=0),g=!u&&i<1&&se.current.cropHeight>B/W.height;let f=u?e.cropWidth:e.cropWidth*i;g&&(f=e.cropWidth);const p=!u&&o<1&&se.current.cropWidth>F/W.width;let m=u?e.cropHeight:e.cropHeight*o;p&&(m=e.cropHeight),U&&(f=e.cropWidth,m=e.cropHeight),e.set({cropX:d,cropY:c,x:a.x(),y:a.y(),width:a.width()*i,height:a.height()*o,rotation:t.target.rotation(),cropWidth:Math.min(f,1-d),cropHeight:Math.min(m,1-c)})},onTransformEnd:t=>{const r=t.currentTarget;e.set({width:r.width(),height:r.height(),x:r.x(),y:r.y(),rotation:t.target.rotation(),cropWidth:F/W.width,cropHeight:B/W.height}),i(!1)}}),o.default.createElement(d.Rect,{x:e.x,y:e.y,width:Math.max(e.a.width-e.borderSize,0),height:Math.max(e.a.height-e.borderSize,0),opacity:ue,offsetX:-e.borderSize/2,offsetY:-e.borderSize/2,stroke:e.borderColor,strokeWidth:e.borderSize,listening:!1,visible:!!e.borderSize,rotation:e.rotation,cornerRadius:Math.max(0,V-e.borderSize),hideInExport:!e.showInExport}),e._cropModeEnabled&&o.default.createElement(s.Portal,{selector:".page-abs-container",enabled:!0},o.default.createElement(d.Rect,{x:-window.innerWidth/t.scale,y:-window.innerWidth/t.scale,width:window.innerWidth/t.scale*3,height:window.innerWidth/t.scale*3,fill:"rgba(0,0,0,0.3)"}),o.default.createElement(d.Image,{listening:!1,image:K,x:e.x,y:e.y,width:e.a.width,height:e.a.height,rotation:e.rotation,shadowEnabled:e.shadowEnabled,shadowBlur:e.shadowBlur}),o.default.createElement(d.Group,{x:e.x,y:e.y,rotation:e.rotation,scaleX:Q,scaleY:Q},o.default.createElement(d.Image,{image:W,ref:l,opacity:.4,draggable:!0,x:-e.cropX*W.width,y:-e.cropY*W.height,onDragMove:oe,onTransform:oe,onTouchMove:e=>{e.evt.preventDefault();const t=e.target.getStage().getPointersPositions();var r=t[0],a=t[1];const i=e.target;if(r&&!a&&!i.isDragging()&&ie.current&&(i.startDrag(),ie.current=!1),r&&a){c.default.hitOnDragEnabled=!0,i.isDragging()&&(ie.current=!0,i.stopDrag());const t=e.target.getAbsoluteTransform().copy();t.invert();var o={x:r.x,y:r.y},n={x:a.x,y:a.y};if(!re.current){return void(re.current=M(o,n))}var h=M(o,n),d=function(e,t){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}(o,n);ae.current||(ae.current=d);const p=i.position();var l={x:h.x-p.x,y:h.y-p.y},s=d/ae.current;i.scaleX(s),i.scaleY(s);const m=t.point(h),w=t.point(re.current);var u=m.x-w.x,g=m.y-w.y,f={x:Math.min(0,h.x-l.x*s+u),y:Math.min(0,h.y-l.y*s+g)};i.position(f),ae.current=d,re.current=h,oe(e)}},onTouchEnd:e=>{ae.current=0,re.current=null,c.default.hitOnDragEnabled=!1}}),o.default.createElement(d.Transformer,Object.assign({ref:te},b)),o.default.createElement(d.Rect,{width:F,height:B,ref:Z,listening:!1,onTransform:t=>{if(e.cropX<Math.abs(t.target.x()/W.width)&&t.target.x()<0&&e.cropX>0){const r=(e.cropWidth+e.cropX)*W.width;t.target.scaleX(1),t.target.width(r)}if(e.cropY<Math.abs(t.target.y()/W.height)&&t.target.y()<0&&e.cropY>0){const r=(e.cropHeight+e.cropY)*W.height;t.target.scaleY(1),t.target.height(r)}t.target.x()<-e.cropX*W.width-1e-9&&(t.target.x(-e.cropX*W.width),t.target.scaleX(1)),t.target.y()<-e.cropY*W.height-1e-9&&(t.target.y(-e.cropY*W.height),t.target.scaleY(1));const r=Math.min(1,Math.max(0,e.cropX+t.target.x()/W.width)),a=Math.min(1,Math.max(0,t.target.y()/W.height+e.cropY)),i=t.target.width()*t.target.scaleX(),o=t.target.height()*t.target.scaleY(),n=Math.min(1-r,i/W.width),h=Math.min(1-a,o/W.height),d=t.target.getAbsolutePosition(t.target.getParent().getParent());t.target.scale({x:1,y:1}),t.target.position({x:0,y:0}),e.set({x:d.x,y:d.y,cropX:r,cropY:a,cropWidth:n,cropHeight:h,width:Math.min(i*Q,W.width*(1-r)*Q),height:Math.min(o*Q,W.height*(1-a)*Q)})}}),o.default.createElement(d.Transformer,Object.assign({ref:ee},v,{visible:e.resizable})))))}));
|
package/canvas/text-element.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.TextElement=exports.getLineHeight=exports.useFontLoader=void 0,exports.isRTLText=y,exports.getDir=S,exports.usePrevious=z;const t=e(require("react")),n=require("mobx-react-lite"),i=require("react-konva"),r=require("react-konva-utils"),o=require("mobx"),a=e(require("konva")),l=require("svg-round-corners"),s=require("./use-color"),d=require("../utils/loader"),u=require("../utils/fonts"),c=require("../utils/flags"),f=require("../utils/text"),h=require("./apply-filters"),g=require("./use-fadein"),x=require("../utils/screen"),p=require("mobx-state-tree"),w=require("./text-element/max-font-size");a.default._fixTextRendering=!0;const m=document.createElement("style");m.type="text/css",document.head.appendChild(m);const v={border:"none",padding:"0px",overflow:"hidden",background:"none",outline:"none",resize:"none",overflowWrap:"break-word",whiteSpace:"pre-wrap",userSelect:"text",wordBreak:"normal"};function y(e){e=e.replace(/\s/g,"");let t=0;for(var n=0;n<e.length;n++){i=e[n],void 0,r="֑-߿יִ-﷽ﹰ-ﻼ",new RegExp("^[^"+r+"]*?["+r+"]").test(i)&&(t+=1)}var i,r;return t>e.length/2}function S(e){return y(e)?"rtl":"ltr"}const b=(0,n.observer)((({textNodeRef:e,element:n,onBlur:i,selectAll:r,cursorPosition:o})=>{const[a,l]=t.default.useState(v),s=e.current;t.default.useLayoutEffect((()=>{const e={};e.width=s.width()-2*s.padding()+"px",e.height=s.height()-2*s.padding()+s.fontSize()*s.lineHeight()+"px",e.fontSize=s.fontSize()+"px",e.lineHeight=s.lineHeight()+.01,e.fontFamily=s.fontFamily(),e.textAlign=s.align(),e.color=s.fill(),e.fontWeight=n.fontWeight,e.fontStyle=n.fontStyle,e.letterSpacing=n.letterSpacing+"em";const t=`\n .polotno-input::placeholder {\n color: ${a.color};\n opacity: 0.6;\n }\n `;m.innerHTML="",m.appendChild(document.createTextNode(t)),JSON.stringify(e)!==JSON.stringify(a)&&l(e)}));const d=t.default.useRef(null);t.default.useLayoutEffect((()=>{var e;const t=d.current;if(!t){return}null===(e=d.current)||void 0===e||e.focus();const n=o||t.value.length;t.selectionStart=t.selectionEnd=n,r&&(null==t||t.select(),document.execCommand("selectAll",!1,null))}),[]),t.default.useEffect((()=>{window.addEventListener("blur",i);const e=e=>{var t;(null===(t=d.current)||void 0===t?void 0:t.contains(e.target))||i()};return window.addEventListener("touchstart",e),()=>{window.removeEventListener("blur",i),window.removeEventListener("touchstart",e)}}),[]);let u=0;const c=s.textArr.length*s.lineHeight()*s.fontSize();"middle"===n.verticalAlign&&(u=(n.a.height-c)/2),"bottom"===n.verticalAlign&&(u=n.a.height-c);const h=(0,f.removeTags)(n.text);return t.default.createElement("textarea",{className:"polotno-input",ref:d,dir:S(h),style:Object.assign(Object.assign(Object.assign({},v),a),{paddingTop:u+"px"}),value:h,onChange:e=>{const t=(0,w.getLimitedFontSize)({oldText:n.text,newText:e.target.value,element:n});n.set({text:e.target.value,fontSize:t})},placeholder:n.placeholder,onBlur:i})})),E=e=>t.default.createElement(r.Html,null,t.default.createElement(b,Object.assign({},e)));function z(e){const n=t.default.useRef(e),i=t.default.useRef(e);return t.default.useMemo((()=>{i.current=n.current,n.current=e}),[e]),i.current}exports.useFontLoader=(e,n)=>{const[i,r]=t.default.useReducer((e=>e+1),0),o=t.default.useRef((0,u.isFontLoaded)(n));return t.default.useLayoutEffect((()=>{if(o.current=(0,u.isFontLoaded)(n),o.current){return}let t=!0;return(async()=>{o.current=!1,r();const i=(0,d.incrementLoader)(`text ${n}`);await e.loadFont(n),setTimeout(i,100),t&&(o.current=!0,r())})(),()=>{t=!1}}),[n]),[o.current]},exports.getLineHeight=({fontLoaded:e,fontFamily:n,fontSize:i,lineHeight:r})=>t.default.useMemo((()=>{if("number"==typeof r){return r}const e=document.createElement("div");e.style.fontFamily=n,e.style.fontSize=i+"px",e.style.lineHeight=r,e.innerText="Test text",document.body.appendChild(e);const t=e.offsetHeight;return document.body.removeChild(e),t/i}),[e,n,i,r]),exports.TextElement=(0,n.observer)((({element:e,store:n})=>{const r=t.default.useRef(null),a=t.default.useRef(null),{editorEnabled:d,selectAll:u}=(e=>{const[n,i]=t.default.useState(!1),r=t.default.useRef(!1);return t.default.useEffect((()=>{var t=!0;return setTimeout((()=>{t&&(e._editModeEnabled&&(r.current=!0),i(!0),setTimeout((()=>{r.current=!1}),50))}),50),()=>{t=!1}}),[]),{editorEnabled:n&&e._editModeEnabled,selectAll:r.current}})(e),[w,m]=t.default.useState(!1),v=t.default.useRef(e.a.height),y=n.selectedShapes.indexOf(e)>=0&&e.selectable,{textVerticalResizeEnabled:b}=c.flags,F=z(e.fontFamily),[L,A]=t.default.useState([]);t.default.useEffect((()=>{var e,t;const n=null!==(t=null===(e=r.current)||void 0===e?void 0:e.textArr)&&void 0!==t?t:[];JSON.stringify(n)!==JSON.stringify(L)&&A(n)})),t.default.useEffect((()=>{if(e.a.width){return}const t=r.current;t.width(600),e.set({width:1.4*t.getTextWidth()})}),[]),t.default.useLayoutEffect((()=>(0,o.autorun)((()=>{const t=r.current;(0,h.applyFilter)(t,e)}))));const[O]=(0,exports.useFontLoader)(n,e.fontFamily),T=(0,f.removeTags)(e.text),k=()=>{const e=r.current.clone({height:void 0}),t=Math.ceil(e.fontSize()*e.lineHeight()*e.textArr.length+1);return e.destroy(),t};t.default.useLayoutEffect((()=>{if(!O){return}const{textOverflow:t,textSplitAllowed:i}=c.flags;if(e.a.height){if(!n.isPlaying){if("change-font-size"!==t||w){if("resize"===t){const t=k();b&&e.a.height<t&&n.history.ignore((()=>{var n;(0,p.isAlive)(e)&&e.set({height:t}),null===(n=r.current)||void 0===n||n.height(t)}),!1,!0),b||e.a.height===t||w||n.history.ignore((()=>{var n;(0,p.isAlive)(e)&&e.set({height:t}),null===(n=r.current)||void 0===n||n.height(t)}),!1,!0)}}else{const t=function(e,t,n=!1){const i=e.fontSize(),r=e.height(),o=(0,f.removeTags)(t.text);let a=t.a.fontSize;e.height(void 0);const l=Math.round(2*t.a.fontSize)-1;for(let s=1;s<l;s++){const i=t.a.height&&e.height()>t.a.height;let r=o.split("\n").join(" ").split(/[\s-]+/).reduce(((e,t)=>/[\u3000-\u303F\u3040-\u309F\u30A0-\u30FF\uFF00-\uFFEF\u4E00-\u9FAF\uAC00-\uD7AF]/.test(t)?e.concat(t.split("")):e.concat(t)),[]),l=e.textArr.map((e=>e.text)).join(";");const s=r.find((e=>!l.includes(e)||(l=l.replace(e,""),!1)));if(!(i||s&&!n)){break}a-=.5,e.fontSize(a)}return e.fontSize(i),e.height(r),a}(r.current,e,i);if(t!==e.a.fontSize){return void n.history.ignore((()=>{e.set({fontSize:t})}),!1,!0)}const o=k();e.a.height===o||b||n.history.ignore((()=>{e.set({height:o})}),!1,!0)}}}else{const t=k();n.history.ignore((()=>{e.set({height:t})}),!1,!0)}})),t.default.useLayoutEffect((()=>{const t=r.current;t&&(t.width(t.width()+1e-8),t._setTextData(),(0,h.applyFilter)(t,e))}),[O]);const M=t.default.useRef(null),R=t.default.useRef(0),$=t=>{t.evt.preventDefault();const i=n.selectedShapes.find((t=>t===e));i&&e.contentEditable&&(R.current=function(e){var t;const n=e.target,i=function(e){var t=e.getAbsoluteTransform().copy();t.invert();var n=e.getStage().getPointerPosition();return t.point(n)}(n),r=n.textArr,o=Math.floor(i.y/(n.fontSize()*n.lineHeight())),a=r.slice(0,o).reduce(((e,t)=>e+t.text.length),o),l=null!==(t=r[o])&&void 0!==t?t:r[0];let s=0;return"right"===n.align()?s=n.width()-l.width:"center"===n.align()&&(s=n.width()/2-l.width/2),a+Math.round((i.x-s)/l.width*l.text.length)}(t),e.toggleEditMode())},H=!T&&e.placeholder?.6:e.a.opacity;(0,g.useFadeIn)(r,H);const q=(0,exports.getLineHeight)({fontLoaded:O,fontFamily:e.fontFamily,fontSize:e.a.fontSize,lineHeight:e.lineHeight}),C=e.selectable||"admin"===n.role,P=(0,s.useColor)(e),_=t.default.useMemo((()=>e.backgroundEnabled?function({lines:e,lineHeight:t,width:n,align:i="left",padding:r=0,cornerRadius:o=0}){var a;e.forEach(((e,t)=>{e.cx=n/2,"right"===i?e.cx=n-e.width/2:"left"===i&&(e.cx=e.width/2),"justify"!==i||e.lastInParagraph||(e.width=n),"justify"===i&&(e.cx=e.width/2)}));let s=`M ${null===(a=e[0])||void 0===a?void 0:a.cx} ${-r}`;e.forEach(((n,i)=>{const{cx:o}=n,a=e[i-1];a&&a.width>n.width?s+=` L ${o+n.width/2+r} ${i*t+r}`:s+=` L ${o+n.width/2+r} ${i*t-r}`;const l=e[i+1];l&&l.width>n.width?s+=` L ${o+n.width/2+r} ${(i+1)*t-r}`:s+=` L ${o+n.width/2+r} ${(i+1)*t+r}`}));for(var d=e.length-1;d>=0;d--){const n=e[d],{cx:i}=n,o=e[d+1];o&&o.width>n.width?s+=` L ${i-n.width/2-r} ${(d+1)*t-r}`:s+=` L ${i-n.width/2-r} ${(d+1)*t+r}`;const a=e[d-1];a&&a.width>n.width?s+=` L ${i-n.width/2-r} ${d*t+r}`:s+=` L ${i-n.width/2-r} ${d*t-r}`}s+=" Z";const u=(0,l.parsePath)(s);return(0,l.roundCommands)(u,o).path}({lines:JSON.parse(JSON.stringify(L)),cornerRadius:e.backgroundCornerRadius*(e.a.fontSize*q*.5),lineHeight:q*e.a.fontSize,padding:e.backgroundPadding*(e.a.fontSize*q*.5),width:e.a.width,align:e.align}):""),[e.backgroundEnabled,e.backgroundCornerRadius,e.a.fontSize,q,e.backgroundPadding,e.a.width,e.align,L]),D=(0,x.isTouchDevice)();let j=0;return"middle"===e.verticalAlign?j=(e.a.height-L.length*q*e.a.fontSize)/2:"bottom"===e.verticalAlign&&(j=e.a.height-L.length*q*e.a.fontSize),t.default.createElement(t.default.Fragment,null,t.default.createElement(i.Path,{ref:a,x:e.a.x,y:e.a.y,rotation:e.a.rotation,hideInExport:!e.showInExport,listening:!1,visible:e.backgroundEnabled,opacity:e.backgroundOpacity*H,data:_,fill:e.backgroundColor,offsetY:-j}),t.default.createElement(i.Text,Object.assign({ref:r,id:e.id,name:"element",hideInExport:!e.showInExport,editModeEnabled:e._editModeEnabled,x:e.a.x,y:e.a.y,rotation:e.a.rotation,width:e.a.width,height:e.a.height,text:T||e.placeholder,direction:S(T)},P,{stroke:e.stroke,lineJoin:"round",strokeWidth:e.strokeWidth,fillAfterStrokeEnabled:!0,fontSize:e.a.fontSize,fontFamily:`"${e.fontFamily}", "${F}"`,fontStyle:e.fontStyle+" "+e.fontWeight,textDecoration:e.textDecoration,align:e.align,verticalAlign:e.verticalAlign,draggable:D?e.draggable&&y:e.draggable,preventDefault:!D||y,opacity:H,visible:!e._editModeEnabled,ellipsis:"ellipsis"===c.flags.textOverflow,shadowEnabled:e.shadowEnabled,shadowBlur:e.shadowBlur,shadowOffsetX:e.shadowOffsetX,shadowOffsetY:e.shadowOffsetY,shadowColor:e.shadowColor,shadowOpacity:e.shadowOpacity,lineHeight:q,letterSpacing:e.letterSpacing*e.a.fontSize,listening:C,onDragMove:t=>{e.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{e.set({x:t.target.x(),y:t.target.y()})},onClick:$,onTap:$,onTransformStart:()=>{m(!0),v.current=r.current.height()},onTransform:t=>{var n,i;const r=t.target;null===(n=a.current)||void 0===n||n.setAttrs({x:r.x(),y:r.y(),rotation:r.rotation(),scale:r.scale()});const o=(null===(i=r.getStage())||void 0===i?void 0:i.findOne("Transformer")).getActiveAnchor();if("middle-left"===o||"middle-right"===o){const t=r.scaleX(),n=r.width()*t,i=e.a.fontSize;let o=n;n<i&&(o=i,M.current&&r.position(M.current)),r.width(o),r.scaleX(1),r.scaleY(1);const a=k();if("ellipsis"!==c.flags.textOverflow){const t=Math.max(a,v.current);r.height(t),e.set({height:r.height()})}const l=c.flags.textVerticalResizeEnabled?Math.max(a,v.current):k();e.set({x:r.x(),width:r.width(),rotation:r.rotation(),height:l}),(0,h.applyFilter)(r,e)}if("top-center"===o||"bottom-center"===o){let n="resize"===c.flags.textOverflow?k():q*e.a.fontSize;t.target.height(Math.max(n,t.target.height()*t.target.scaleY())),t.target.scaleY(1)}M.current=t.target.position()},onTransformEnd:t=>{var n;const i=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),e.set({fontSize:Math.round(e.a.fontSize*i),width:Math.ceil(t.target.width()*i),x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),height:t.target.height()*i,shadowBlur:e.shadowBlur*i,shadowOffsetX:e.shadowOffsetX*i,shadowOffsetY:e.shadowOffsetY*i,strokeWidth:e.strokeWidth*i}),null===(n=a.current)||void 0===n||n.setAttrs({scaleX:1,scaleY:1}),m(!1)}})),d&&t.default.createElement(i.Group,{x:e.a.x,y:e.a.y,rotation:e.a.rotation},t.default.createElement(E,{textNodeRef:r,element:e,selectAll:u,cursorPosition:R.current,onBlur:()=>{e.toggleEditMode(!1)}})))}));
|
|
1
|
+
var e=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.TextElement=exports.getLineHeight=exports.useFontLoader=void 0,exports.isRTLText=y,exports.getDir=S,exports.usePrevious=z;const t=e(require("react")),n=require("mobx-react-lite"),r=require("react-konva"),i=require("react-konva-utils"),o=require("mobx"),a=e(require("konva")),l=require("svg-round-corners"),s=require("./use-color"),d=require("../utils/loader"),u=require("../utils/fonts"),c=require("../utils/flags"),h=require("../utils/text"),f=require("./apply-filters"),g=require("./use-fadein"),x=require("../utils/screen"),p=require("mobx-state-tree"),w=require("./text-element/max-font-size");a.default._fixTextRendering=!0;const m=document.createElement("style");m.type="text/css",document.head.appendChild(m);const v={border:"none",padding:"0px",overflow:"hidden",background:"none",outline:"none",resize:"none",overflowWrap:"break-word",whiteSpace:"pre-wrap",userSelect:"text",wordBreak:"normal"};function y(e){e=e.replace(/\s/g,"");let t=0;for(var n=0;n<e.length;n++){r=e[n],void 0,i="֑-߿יִ-﷽ﹰ-ﻼ",new RegExp("^[^"+i+"]*?["+i+"]").test(r)&&(t+=1)}var r,i;return t>e.length/2}function S(e){return y(e)?"rtl":"ltr"}const b=(0,n.observer)((({textNodeRef:e,element:n,onBlur:r,selectAll:i,cursorPosition:o})=>{const[a,l]=t.default.useState(v),s=e.current;t.default.useLayoutEffect((()=>{const e={};e.width=s.width()-2*s.padding()+"px",e.height=s.height()-2*s.padding()+s.fontSize()*s.lineHeight()+"px",e.fontSize=s.fontSize()+"px",e.lineHeight=s.lineHeight()+.01,e.fontFamily=s.fontFamily(),e.textAlign=s.align(),e.color=s.fill(),e.fontWeight=n.fontWeight,e.fontStyle=n.fontStyle,e.letterSpacing=n.letterSpacing+"em",e.opacity=Math.max(n.a.opacity,.2);const t=`\n .polotno-input::placeholder {\n color: ${a.color};\n opacity: 0.6;\n }\n `;m.innerHTML="",m.appendChild(document.createTextNode(t)),JSON.stringify(e)!==JSON.stringify(a)&&l(e)}));const d=t.default.useRef(null);t.default.useLayoutEffect((()=>{var e;const t=d.current;if(!t){return}null===(e=d.current)||void 0===e||e.focus();const n=o||t.value.length;t.selectionStart=t.selectionEnd=n,i&&(null==t||t.select(),document.execCommand("selectAll",!1,null))}),[]),t.default.useEffect((()=>{window.addEventListener("blur",r);const e=e=>{var t;(null===(t=d.current)||void 0===t?void 0:t.contains(e.target))||r()};return window.addEventListener("touchstart",e),()=>{window.removeEventListener("blur",r),window.removeEventListener("touchstart",e)}}),[]);let u=0;const c=s.textArr.length*s.lineHeight()*s.fontSize();"middle"===n.verticalAlign&&(u=(n.a.height-c)/2),"bottom"===n.verticalAlign&&(u=n.a.height-c);const f=(0,h.removeTags)(n.text);return t.default.createElement("textarea",{className:"polotno-input",ref:d,dir:S(f),style:Object.assign(Object.assign(Object.assign({},v),a),{paddingTop:u+"px"}),value:f,onChange:e=>{const t=(0,w.getLimitedFontSize)({oldText:n.text,newText:e.target.value,element:n});n.set({text:e.target.value,fontSize:t})},placeholder:n.placeholder,onBlur:r})})),E=e=>t.default.createElement(i.Html,null,t.default.createElement(b,Object.assign({},e)));function z(e){const n=t.default.useRef(e),r=t.default.useRef(e);return t.default.useMemo((()=>{r.current=n.current,n.current=e}),[e]),r.current}exports.useFontLoader=(e,n)=>{const[r,i]=t.default.useReducer((e=>e+1),0),o=t.default.useRef((0,u.isFontLoaded)(n));return t.default.useLayoutEffect((()=>{if(o.current=(0,u.isFontLoaded)(n),o.current){return}let t=!0;return(async()=>{o.current=!1,i();const r=(0,d.incrementLoader)(`text ${n}`);await e.loadFont(n),setTimeout(r,100),t&&(o.current=!0,i())})(),()=>{t=!1}}),[n]),[o.current]},exports.getLineHeight=({fontLoaded:e,fontFamily:n,fontSize:r,lineHeight:i})=>t.default.useMemo((()=>{if("number"==typeof i){return i}const e=document.createElement("div");e.style.fontFamily=n,e.style.fontSize=r+"px",e.style.lineHeight=i,e.innerText="Test text",document.body.appendChild(e);const t=e.offsetHeight;return document.body.removeChild(e),t/r}),[e,n,r,i]),exports.TextElement=(0,n.observer)((({element:e,store:n})=>{const i=t.default.useRef(null),a=t.default.useRef(null),{editorEnabled:d,selectAll:u}=(e=>{const[n,r]=t.default.useState(!1),i=t.default.useRef(!1);return t.default.useEffect((()=>{var t=!0;return setTimeout((()=>{t&&(e._editModeEnabled&&(i.current=!0),r(!0),setTimeout((()=>{i.current=!1}),50))}),50),()=>{t=!1}}),[]),{editorEnabled:n&&e._editModeEnabled,selectAll:i.current}})(e),[w,m]=t.default.useState(!1),v=t.default.useRef(e.a.height),y=n.selectedShapes.indexOf(e)>=0&&e.selectable,{textVerticalResizeEnabled:b}=c.flags,F=z(e.fontFamily),[O,L]=t.default.useState([]);t.default.useEffect((()=>{var e,t;const n=null!==(t=null===(e=i.current)||void 0===e?void 0:e.textArr)&&void 0!==t?t:[];JSON.stringify(n)!==JSON.stringify(O)&&L(n)})),t.default.useEffect((()=>{if(e.a.width){return}const t=i.current;t.width(600),e.set({width:1.4*t.getTextWidth()})}),[]),t.default.useLayoutEffect((()=>(0,o.autorun)((()=>{const t=i.current;(0,f.applyFilter)(t,e)}))));const[A]=(0,exports.useFontLoader)(n,e.fontFamily),T=(0,h.removeTags)(e.text),k=()=>{const e=i.current.clone({height:void 0}),t=Math.ceil(e.fontSize()*e.lineHeight()*e.textArr.length+1);return e.destroy(),t};t.default.useLayoutEffect((()=>{if(!A){return}const{textOverflow:t,textSplitAllowed:r}=c.flags;if(e.a.height){if(!n.isPlaying){if("change-font-size"!==t||w){if("resize"===t){const t=k();b&&e.a.height<t&&n.history.ignore((()=>{var n;(0,p.isAlive)(e)&&e.set({height:t}),null===(n=i.current)||void 0===n||n.height(t)}),!1,!0),b||e.a.height===t||w||n.history.ignore((()=>{var n;(0,p.isAlive)(e)&&e.set({height:t}),null===(n=i.current)||void 0===n||n.height(t)}),!1,!0)}}else{const t=function(e,t,n=!1){const r=e.fontSize(),i=e.height(),o=(0,h.removeTags)(t.text);let a=t.a.fontSize;e.height(void 0);const l=Math.round(2*t.a.fontSize)-1;for(let s=1;s<l;s++){const r=t.a.height&&e.height()>t.a.height;let i=o.split("\n").join(" ").split(/[\s-]+/).reduce(((e,t)=>/[\u3000-\u303F\u3040-\u309F\u30A0-\u30FF\uFF00-\uFFEF\u4E00-\u9FAF\uAC00-\uD7AF]/.test(t)?e.concat(t.split("")):e.concat(t)),[]),l=e.textArr.map((e=>e.text)).join(";");const s=i.find((e=>!l.includes(e)||(l=l.replace(e,""),!1)));if(!(r||s&&!n)){break}a-=.5,e.fontSize(a)}return e.fontSize(r),e.height(i),a}(i.current,e,r);if(t!==e.a.fontSize){return void n.history.ignore((()=>{e.set({fontSize:t})}),!1,!0)}const o=k();e.a.height===o||b||n.history.ignore((()=>{e.set({height:o})}),!1,!0)}}}else{const t=k();n.history.ignore((()=>{e.set({height:t})}),!1,!0)}})),t.default.useLayoutEffect((()=>{const t=i.current;t&&(t.width(t.width()+1e-8),t._setTextData(),(0,f.applyFilter)(t,e))}),[A]);const M=t.default.useRef(null),R=t.default.useRef(0),$=t=>{t.evt.preventDefault();const r=n.selectedShapes.find((t=>t===e));r&&e.contentEditable&&(R.current=function(e){var t;const n=e.target,r=function(e){var t=e.getAbsoluteTransform().copy();t.invert();var n=e.getStage().getPointerPosition();return t.point(n)}(n),i=n.textArr,o=Math.floor(r.y/(n.fontSize()*n.lineHeight())),a=i.slice(0,o).reduce(((e,t)=>e+t.text.length),o),l=null!==(t=i[o])&&void 0!==t?t:i[0];let s=0;return"right"===n.align()?s=n.width()-l.width:"center"===n.align()&&(s=n.width()/2-l.width/2),a+Math.round((r.x-s)/l.width*l.text.length)}(t),e.toggleEditMode())},H=!T&&e.placeholder?.6:e.a.opacity;(0,g.useFadeIn)(i,H);const q=(0,exports.getLineHeight)({fontLoaded:A,fontFamily:e.fontFamily,fontSize:e.a.fontSize,lineHeight:e.lineHeight}),C=e.selectable||"admin"===n.role,X=(0,s.useColor)(e),Y=t.default.useMemo((()=>e.backgroundEnabled?function({lines:e,lineHeight:t,width:n,align:r="left",padding:i=0,cornerRadius:o=0}){var a;e.forEach(((e,t)=>{e.cx=n/2,"right"===r?e.cx=n-e.width/2:"left"===r&&(e.cx=e.width/2),"justify"!==r||e.lastInParagraph||(e.width=n),"justify"===r&&(e.cx=e.width/2)}));let s=`M ${null===(a=e[0])||void 0===a?void 0:a.cx} ${-i}`;e.forEach(((n,r)=>{const{cx:o}=n,a=e[r-1];a&&a.width>n.width?s+=` L ${o+n.width/2+i} ${r*t+i}`:s+=` L ${o+n.width/2+i} ${r*t-i}`;const l=e[r+1];l&&l.width>n.width?s+=` L ${o+n.width/2+i} ${(r+1)*t-i}`:s+=` L ${o+n.width/2+i} ${(r+1)*t+i}`}));for(var d=e.length-1;d>=0;d--){const n=e[d],{cx:r}=n,o=e[d+1];o&&o.width>n.width?s+=` L ${r-n.width/2-i} ${(d+1)*t-i}`:s+=` L ${r-n.width/2-i} ${(d+1)*t+i}`;const a=e[d-1];a&&a.width>n.width?s+=` L ${r-n.width/2-i} ${d*t+i}`:s+=` L ${r-n.width/2-i} ${d*t-i}`}s+=" Z";const u=(0,l.parsePath)(s);return(0,l.roundCommands)(u,o).path}({lines:JSON.parse(JSON.stringify(O)),cornerRadius:e.backgroundCornerRadius*(e.a.fontSize*q*.5),lineHeight:q*e.a.fontSize,padding:e.backgroundPadding*(e.a.fontSize*q*.5),width:e.a.width,align:e.align}):""),[e.backgroundEnabled,e.backgroundCornerRadius,e.a.fontSize,q,e.backgroundPadding,e.a.width,e.align,O]),P=(0,x.isTouchDevice)();let _=0;return"middle"===e.verticalAlign?_=(e.a.height-O.length*q*e.a.fontSize)/2:"bottom"===e.verticalAlign&&(_=e.a.height-O.length*q*e.a.fontSize),t.default.createElement(t.default.Fragment,null,t.default.createElement(r.Path,{ref:a,x:e.a.x,y:e.a.y,rotation:e.a.rotation,hideInExport:!e.showInExport,listening:!1,visible:e.backgroundEnabled,opacity:e.backgroundOpacity*H,data:Y,fill:e.backgroundColor,offsetY:-_}),t.default.createElement(r.Text,Object.assign({ref:i,id:e.id,name:"element",hideInExport:!e.showInExport,editModeEnabled:e._editModeEnabled,x:e.a.x,y:e.a.y,rotation:e.a.rotation,width:e.a.width,height:e.a.height,text:T||e.placeholder,direction:S(T)},X,{stroke:e.stroke,lineJoin:"round",strokeWidth:e.strokeWidth,fillAfterStrokeEnabled:!0,fontSize:e.a.fontSize,fontFamily:`"${e.fontFamily}", "${F}"`,fontStyle:e.fontStyle+" "+e.fontWeight,textDecoration:e.textDecoration,align:e.align,verticalAlign:e.verticalAlign,draggable:P?e.draggable&&y:e.draggable,preventDefault:!P||y,opacity:H,visible:!e._editModeEnabled,ellipsis:"ellipsis"===c.flags.textOverflow,shadowEnabled:e.shadowEnabled,shadowBlur:e.shadowBlur,shadowOffsetX:e.shadowOffsetX,shadowOffsetY:e.shadowOffsetY,shadowColor:e.shadowColor,shadowOpacity:e.shadowOpacity,lineHeight:q,letterSpacing:e.letterSpacing*e.a.fontSize,listening:C,onDragMove:t=>{e.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{e.set({x:t.target.x(),y:t.target.y()})},onClick:$,onTap:$,onTransformStart:()=>{m(!0),v.current=i.current.height()},onTransform:t=>{var n,r,i;const o=t.target;null===(n=a.current)||void 0===n||n.setAttrs({x:o.x(),y:o.y(),rotation:o.rotation(),scale:o.scale()});const l=(null===(r=o.getStage())||void 0===r?void 0:r.findOne("Transformer")).getActiveAnchor();if("middle-left"===l||"middle-right"===l){const t=o.scaleX(),n=o.width()*t,r=e.a.fontSize;let i=n;n<r&&(i=r,M.current&&o.position(M.current)),o.width(i),o.scaleX(1),o.scaleY(1);const a=k();if("ellipsis"!==c.flags.textOverflow){const t=Math.max(a,v.current);o.height(t),e.set({height:o.height()})}const l=c.flags.textVerticalResizeEnabled?Math.max(a,v.current):k();e.set({x:o.x(),width:o.width(),rotation:o.rotation(),height:l}),(0,f.applyFilter)(o,e)}if("top-center"===l||"bottom-center"===l){let n="resize"===c.flags.textOverflow?k():q*e.a.fontSize;t.target.height(Math.max(n,t.target.height()*t.target.scaleY())),t.target.scaleY(1)}M.current=t.target.position();const s=t.target.scaleX();null===(i=a.current)||void 0===i||i.setAttrs({scaleX:1,scaleY:1}),t.target.scaleX(1),t.target.scaleY(1),e.set({fontSize:e.a.fontSize*s,width:t.target.width()*s,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),height:t.target.height()*s,shadowBlur:e.shadowBlur*s,shadowOffsetX:e.shadowOffsetX*s,shadowOffsetY:e.shadowOffsetY*s,strokeWidth:e.strokeWidth*s})},onTransformEnd:t=>{var n;const r=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),e.set({fontSize:Math.round(e.a.fontSize*r),width:Math.ceil(t.target.width()*r),x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),height:t.target.height()*r,shadowBlur:e.shadowBlur*r,shadowOffsetX:e.shadowOffsetX*r,shadowOffsetY:e.shadowOffsetY*r,strokeWidth:e.strokeWidth*r}),null===(n=a.current)||void 0===n||n.setAttrs({scaleX:1,scaleY:1}),m(!1)}})),d&&t.default.createElement(r.Group,{x:e.a.x,y:e.a.y,rotation:e.a.rotation},t.default.createElement(E,{textNodeRef:i,element:e,selectAll:u,cursorPosition:R.current,onBlur:()=>{e.toggleEditMode(!1),""===e.text&&e.removable&&!e.placeholder&&n.deleteElements([e.id])}})))}));
|
package/model/group-model.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=this&&this.__rest||function(e,t){var r={};for(var o in e){Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(r[o]=e[o])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var l=0;for(o=Object.getOwnPropertySymbols(e);l<o.length;l++){t.indexOf(o[l])<0&&Object.prototype.propertyIsEnumerable.call(e,o[l])&&(r[o[l]]=e[o[l]])}}return r};Object.defineProperty(exports,"__esModule",{value:!0}),exports.TYPES_MAP=exports.GroupElement=exports.ElementTypes=exports.forEveryChild=void 0,exports.registerShapeModel=function(e,t){const r=e.type;if(!r){throw new Error('You must pass "type" attribute to custom model.')}let o=l.Shape.named(r).props(e);t&&(o=t(o)),exports.TYPES_MAP[r]=o,c.push(o)};const t=require("mobx-state-tree"),r=require("nanoid"),o=require("./node-model"),l=require("./shape-model"),n=require("./text-model"),i=require("./image-model"),s=require("./video-model"),d=require("./line-model"),p=require("./svg-model"),a=require("./figure-model"),E=require("./gif-model");exports.forEveryChild=(e,t)=>{if(e.children){for(const r of e.children){if(!0===t(r)){break}(0,exports.forEveryChild)(r,t)}}};const m=[...new Array(20)].map(((e,r)=>t.types.late((()=>c[r]))));exports.ElementTypes=t.types.union({dispatcher:e=>{const t=exports.TYPES_MAP[e.type];if(!t){throw new Error(`Unknown element type: "${e.type}"`)}return t}},p.SVGElement,n.TextElement,i.ImageElement,d.LineElement,s.VideoElement,a.FigureElement,E.GifElement,t.types.late((()=>exports.GroupElement)),...m),exports.GroupElement=o.Node.named("Group").props({type:"group",children:t.types.array(exports.ElementTypes)}).views((e=>({get draggable(){let t=!0;return(0,exports.forEveryChild)(e,(e=>{e.draggable||(t=!1)})),t},get resizable(){let t=!0;return(0,exports.forEveryChild)(e,(e=>{e.resizable||(t=!1)})),t},get contentEditable(){let t=!0;return(0,exports.forEveryChild)(e,(e=>{e.contentEditable||(t=!1)})),t},get styleEditable(){let t=!0;return(0,exports.forEveryChild)(e,(e=>{e.styleEditable||(t=!1)})),t},get locked(){let t=!0;return(0,exports.forEveryChild)(e,(e=>{e.locked||(t=!1)})),t}}))).actions((o=>({set(t){var{draggable:r,contentEditable:l,styleEditable:n,resizable:i}=t,s=e(t,["draggable","contentEditable","styleEditable","resizable"]);void 0!==r&&(0,exports.forEveryChild)(o,(e=>{e.set({draggable:r})})),void 0!==l&&(0,exports.forEveryChild)(o,(e=>{e.set({contentEditable:l})})),void 0!==n&&(0,exports.forEveryChild)(o,(e=>{e.set({styleEditable:n})})),void 0!==i&&(0,exports.forEveryChild)(o,(e=>{e.set({resizable:i})})),Object.assign(o,s)},addElement(e,{skipSelect:t=!1}={}){const l=exports.TYPES_MAP[e.type];if(!l){return void console.error("Can not find model with type "+e.type)}e.children&&e.children.forEach((e=>{e.id=(0,r.nanoid)(10)}));const n=l.create(Object.assign({id:(0,r.nanoid)(10)},e));return o.children.push(n),n.selectable&&!t&&o.store.selectElements([n.id]),n},setElementZIndex(e,r){const l=o.children.find((t=>t.id===e));l&&((0,t.detach)(l),o.children.remove(l),o.children.splice(r,0,l))}})));const c=[];exports.TYPES_MAP={svg:p.SVGElement,text:n.TextElement,image:i.ImageElement,group:exports.GroupElement,line:d.LineElement,video:s.VideoElement,figure:a.FigureElement,gif:E.GifElement};
|
|
1
|
+
var e=this&&this.__rest||function(e,t){var r={};for(var o in e){Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(r[o]=e[o])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var l=0;for(o=Object.getOwnPropertySymbols(e);l<o.length;l++){t.indexOf(o[l])<0&&Object.prototype.propertyIsEnumerable.call(e,o[l])&&(r[o[l]]=e[o[l]])}}return r};Object.defineProperty(exports,"__esModule",{value:!0}),exports.TYPES_MAP=exports.GroupElement=exports.ElementTypes=exports.forEveryChild=void 0,exports.registerShapeModel=function(e,t){const r=e.type;if(!r){throw new Error('You must pass "type" attribute to custom model.')}let o=l.Shape.named(r).props(e);t&&(o=t(o)),exports.TYPES_MAP[r]=o,c.push(o)};const t=require("mobx-state-tree"),r=require("nanoid"),o=require("./node-model"),l=require("./shape-model"),n=require("./text-model"),i=require("./image-model"),s=require("./video-model"),d=require("./line-model"),p=require("./svg-model"),a=require("./figure-model"),E=require("./gif-model");exports.forEveryChild=(e,t)=>{if(e.children){for(const r of e.children){if(!0===t(r)){break}(0,exports.forEveryChild)(r,t)}}};const m=[...new Array(20)].map(((e,r)=>t.types.late((()=>c[r]))));exports.ElementTypes=t.types.union({dispatcher:e=>{const t=exports.TYPES_MAP[e.type];if(!t){throw new Error(`Unknown element type: "${e.type}"`)}return t}},p.SVGElement,n.TextElement,i.ImageElement,d.LineElement,s.VideoElement,a.FigureElement,E.GifElement,t.types.late((()=>exports.GroupElement)),...m),exports.GroupElement=o.Node.named("Group").props({type:"group",children:t.types.array(exports.ElementTypes)}).views((e=>({get draggable(){let t=!0;return(0,exports.forEveryChild)(e,(e=>{e.draggable||(t=!1)})),t},get resizable(){let t=!0;return(0,exports.forEveryChild)(e,(e=>{e.resizable||(t=!1)})),t},get contentEditable(){let t=!0;return(0,exports.forEveryChild)(e,(e=>{e.contentEditable||(t=!1)})),t},get styleEditable(){let t=!0;return(0,exports.forEveryChild)(e,(e=>{e.styleEditable||(t=!1)})),t},get locked(){let t=!0;return(0,exports.forEveryChild)(e,(e=>{e.locked||(t=!1)})),t}}))).actions((o=>({set(t){var{draggable:r,contentEditable:l,styleEditable:n,resizable:i}=t,s=e(t,["draggable","contentEditable","styleEditable","resizable"]);void 0!==r&&(0,exports.forEveryChild)(o,(e=>{e.set({draggable:r})})),void 0!==l&&(0,exports.forEveryChild)(o,(e=>{e.set({contentEditable:l})})),void 0!==n&&(0,exports.forEveryChild)(o,(e=>{e.set({styleEditable:n})})),void 0!==i&&(0,exports.forEveryChild)(o,(e=>{e.set({resizable:i})})),Object.assign(o,s)},addElement(e,{skipSelect:t=!1}={}){const l=exports.TYPES_MAP[e.type];if(!l){return void console.error("Can not find model with type "+e.type)}e.children&&e.children.forEach((e=>{e.id=e.id||(0,r.nanoid)(10)}));const n=l.create(Object.assign({id:(0,r.nanoid)(10)},e));return o.children.push(n),n.selectable&&!t&&o.store.selectElements([n.id]),n},setElementZIndex(e,r){const l=o.children.find((t=>t.id===e));l&&((0,t.detach)(l),o.children.remove(l),o.children.splice(r,0,l))}})));const c=[];exports.TYPES_MAP={svg:p.SVGElement,text:n.TextElement,image:i.ImageElement,group:exports.GroupElement,line:d.LineElement,video:s.VideoElement,figure:a.FigureElement,gif:E.GifElement};
|
package/model/page-model.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.Page=void 0;const e=require("mobx-state-tree"),t=require("nanoid"),n=require("./group-model"),i=require("./store"),o=require("./group-model"),r=require("../utils/math");exports.Page=e.types.model("Page",{id:e.types.identifier,children:e.types.array(e.types.late((()=>n.ElementTypes))),width:e.types.optional(e.types.union(e.types.number,e.types.literal("auto")),"auto"),height:e.types.optional(e.types.union(e.types.number,e.types.literal("auto")),"auto"),background:"white",bleed:0,custom:e.types.frozen(),duration:5e3,_exporting:!1,_rendering:!1,_forceMount:!1}).postProcessSnapshot((e=>{const t=Object.assign({},e),n={};for(var i in t){"_"!==i[0]&&(n[i]=e[i])}return n})).views((t=>({get store(){return(0,e.getParentOfType)(t,i.Store)}}))).views((e=>({get startTime(){let t=0;for(const n of e.store.pages){if(n.id===e.id){return t}t+=n.duration}return t},get _exportingOrRendering(){return e._exporting||e._rendering}}))).views((e=>({get computedWidth(){return"auto"===e.width?e.store.width:e.width},get computedHeight(){return"auto"===e.height?e.store.height:e.height}}))).actions((t=>({toJSON:()=>JSON.parse(JSON.stringify((0,e.getSnapshot)(t))),_forEachElementUp(e,n){const i=e.map((e=>({id:e,index:t.children.findIndex((t=>t.id===e))})));i.sort(((e,t)=>t.index-e.index));for(const{index:o}of i){if(-1==o){continue}const i=o<t.children.length-1&&t.children[o+1],r=e.indexOf(null==i?void 0:i.id)>=0;o===t.children.length-1||r||n(o)}},_forEachElementDown(e,n){const i=e.map((e=>({id:e,index:t.children.findIndex((t=>t.id===e))})));i.sort(((e,t)=>e.index-t.index));for(const{index:o}of i){if(-1==o){continue}const i=o>0&&t.children[o-1],r=e.indexOf(null==i?void 0:i.id)>=0;0===o||r||n(o)}return!1}}))).actions((n=>({clone(e={}){const i=n.toJSON();i.children.forEach((e=>{e.id=(0,t.nanoid)(10),(0,o.forEveryChild)(e,(e=>{e.id=(0,t.nanoid)(10)}))}));const r=Object.assign(Object.assign(Object.assign({},i),{id:(0,t.nanoid)(10)}),e),d=n.store.addPage(r),s=n.store.pages.indexOf(n);return d.setZIndex(s+1),d.select(),d},setZIndex(e){n.store.setPageZIndex(n.id,e)},set(e){Object.assign(n,e)},select(){n.store.selectPage(n.id)},addElement(e,{skipSelect:i=!1}={}){const r=o.TYPES_MAP[e.type];if(!r){return void console.error("Can not find model with type "+e.type)}"children"in e&&Array.isArray(e.children)&&(0,o.forEveryChild)(e,(e=>{e.id=(0,t.nanoid)(10)}));const d=r.create(Object.assign({id:(0,t.nanoid)(10)},e));return n.children.push(d),d.selectable&&!i&&n.store.selectElements([d.id]),d},canMoveElementsUp(e){let t=!1;return n._forEachElementUp(e,(()=>{t=t||!0})),t},moveElementsUp(t){n._forEachElementUp(t,(t=>{const i=n.children[t];(0,e.detach)(i),n.children.splice(t+1,0,i)}))},canMoveElementsTop(e){return this.canMoveElementsUp(e)},moveElementsTop(e){const t=[],i=[];n.children.forEach((n=>{e.indexOf(n.id)>=0?t.push(n):i.push(n)})),n.children.replace(i.concat(t))},canMoveElementsDown(e){let t=!1;return n._forEachElementDown(e,(()=>{t=t||!0})),t},moveElementsDown(t){n._forEachElementDown(t,(t=>{const i=n.children[t];(0,e.detach)(i),n.children.splice(t-1,0,i)}))},canMoveElementsBottom(e){return this.canMoveElementsDown(e)},moveElementsBottom(e){const t=[],i=[];n.children.forEach((n=>{e.indexOf(n.id)>=0?t.push(n):i.push(n)})),n.children.replace(t.concat(i))},setElementZIndex(t,i){const o=n.children.find((e=>e.id===t));o&&((0,e.detach)(o),n.children.remove(o),n.children.splice(i,0,o))},setSize({width:e,height:t,useMagic:i,softChange:d}){if(i){const i=[],d=e=>"image"===e.type&&e.x<1&&e.y<1&&e.width>=n.computedWidth-2&&e.height>=n.computedHeight-2;(0,o.forEveryChild)(n,(e=>{"group"!==e.type&&(d(e)||i.push(e))}));const s=i.length?(0,r.getTotalClientRect)(i):{x:0,y:0,width:n.computedWidth,height:n.computedHeight},a=1/4,c=Math.max(0,Math.min(s.x,n.computedWidth-s.x-s.width)),h=n.computedWidth*a,l=Math.max(0,c-h),p=Math.max(0,Math.min(s.y,n.computedHeight-s.y-s.height)),m=n.computedHeight*a,u=Math.max(0,p-m),g=n.computedWidth-2*l,E=n.computedHeight-2*u,f=e/g,y=t/E,v=Math.min(f,y),x=(e-g*v)/2-l*v,w=(t-E*v)/2-u*v;(0,o.forEveryChild)(n,(e=>{"group"!==e.type&&(d(e)?e.set({x:e.x*v,y:e.y*v,width:e.width*f,height:e.height*y,cropX:0,cropY:0,cropWidth:1,cropHeight:1}):(e.set({x:x+e.x*v,y:w+e.y*v,width:e.width*v,height:e.height*v}),"text"===e.type?e.set({fontSize:e.fontSize*v}):"figure"===e.type&&e.set({strokeWidth:e.strokeWidth*v})))}))}d||(n.width=e),d||(n.height=t)}}))).actions((e=>({moveElementUp(t){console.warn("page.moveElementUp(id) is deprecated. Please use page.moveElementsUp([id1, id2]) instead."),e.moveElementsUp([t])},moveElementDown(t){console.warn("page.moveElementDown(id) is deprecated. Please use page.moveElementsDown([id1, id2]) instead."),e.moveElementsDown([t])},moveElementTop(t){console.warn("page.moveElementTop(id) is deprecated. Please use page.moveElementsTop([id1, id2]) instead."),e.moveElementsTop([t])},moveElementBottom(t){console.warn("page.moveElementBottom(id) is deprecated. Please use page.moveElementsBottom([id1, id2]) instead."),e.moveElementsBottom([t])},play(){e.store.play({startTime:e.startTime,endTime:e.startTime+e.duration})}})));
|
|
1
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.Page=void 0;const e=require("mobx-state-tree"),t=require("nanoid"),n=require("./group-model"),i=require("./store"),o=require("./group-model"),r=require("../utils/math");exports.Page=e.types.model("Page",{id:e.types.identifier,children:e.types.array(e.types.late((()=>n.ElementTypes))),width:e.types.optional(e.types.union(e.types.number,e.types.literal("auto")),"auto"),height:e.types.optional(e.types.union(e.types.number,e.types.literal("auto")),"auto"),background:"white",bleed:0,custom:e.types.frozen(),duration:5e3,_exporting:!1,_rendering:!1,_forceMount:!1}).postProcessSnapshot((e=>{const t=Object.assign({},e),n={};for(var i in t){"_"!==i[0]&&(n[i]=e[i])}return n})).views((t=>({get store(){return(0,e.getParentOfType)(t,i.Store)}}))).views((e=>({get startTime(){let t=0;for(const n of e.store.pages){if(n.id===e.id){return t}t+=n.duration}return t},get _exportingOrRendering(){return e._exporting||e._rendering}}))).views((e=>({get computedWidth(){return"auto"===e.width?e.store.width:e.width},get computedHeight(){return"auto"===e.height?e.store.height:e.height}}))).actions((t=>({toJSON:()=>JSON.parse(JSON.stringify((0,e.getSnapshot)(t))),_forEachElementUp(e,n){const i=e.map((e=>({id:e,index:t.children.findIndex((t=>t.id===e))})));i.sort(((e,t)=>t.index-e.index));for(const{index:o}of i){if(-1==o){continue}const i=o<t.children.length-1&&t.children[o+1],r=e.indexOf(null==i?void 0:i.id)>=0;o===t.children.length-1||r||n(o)}},_forEachElementDown(e,n){const i=e.map((e=>({id:e,index:t.children.findIndex((t=>t.id===e))})));i.sort(((e,t)=>e.index-t.index));for(const{index:o}of i){if(-1==o){continue}const i=o>0&&t.children[o-1],r=e.indexOf(null==i?void 0:i.id)>=0;0===o||r||n(o)}return!1}}))).actions((n=>({clone(e={}){const i=n.toJSON();i.children.forEach((e=>{e.id=(0,t.nanoid)(10),(0,o.forEveryChild)(e,(e=>{e.id=(0,t.nanoid)(10)}))}));const r=Object.assign(Object.assign(Object.assign({},i),{id:(0,t.nanoid)(10)}),e),d=n.store.addPage(r),s=n.store.pages.indexOf(n);return d.setZIndex(s+1),d.select(),d},setZIndex(e){n.store.setPageZIndex(n.id,e)},set(e){Object.assign(n,e)},select(){n.store.selectPage(n.id)},addElement(e,{skipSelect:i=!1}={}){const r=o.TYPES_MAP[e.type];if(!r){return void console.error("Can not find model with type "+e.type)}"children"in e&&Array.isArray(e.children)&&(0,o.forEveryChild)(e,(e=>{e.id=e.id||(0,t.nanoid)(10)}));const d=r.create(Object.assign({id:(0,t.nanoid)(10)},e));return n.children.push(d),d.selectable&&!i&&n.store.selectElements([d.id]),d},canMoveElementsUp(e){let t=!1;return n._forEachElementUp(e,(()=>{t=t||!0})),t},moveElementsUp(t){n._forEachElementUp(t,(t=>{const i=n.children[t];(0,e.detach)(i),n.children.splice(t+1,0,i)}))},canMoveElementsTop(e){return this.canMoveElementsUp(e)},moveElementsTop(e){const t=[],i=[];n.children.forEach((n=>{e.indexOf(n.id)>=0?t.push(n):i.push(n)})),n.children.replace(i.concat(t))},canMoveElementsDown(e){let t=!1;return n._forEachElementDown(e,(()=>{t=t||!0})),t},moveElementsDown(t){n._forEachElementDown(t,(t=>{const i=n.children[t];(0,e.detach)(i),n.children.splice(t-1,0,i)}))},canMoveElementsBottom(e){return this.canMoveElementsDown(e)},moveElementsBottom(e){const t=[],i=[];n.children.forEach((n=>{e.indexOf(n.id)>=0?t.push(n):i.push(n)})),n.children.replace(t.concat(i))},setElementZIndex(t,i){const o=n.children.find((e=>e.id===t));o&&((0,e.detach)(o),n.children.remove(o),n.children.splice(i,0,o))},setSize({width:e,height:t,useMagic:i,softChange:d}){if(i){const i=[],d=e=>"image"===e.type&&e.x<1&&e.y<1&&e.width>=n.computedWidth-2&&e.height>=n.computedHeight-2;(0,o.forEveryChild)(n,(e=>{"group"!==e.type&&(d(e)||i.push(e))}));const s=i.length?(0,r.getTotalClientRect)(i):{x:0,y:0,width:n.computedWidth,height:n.computedHeight},a=1/4,c=Math.max(0,Math.min(s.x,n.computedWidth-s.x-s.width)),h=n.computedWidth*a,l=Math.max(0,c-h),p=Math.max(0,Math.min(s.y,n.computedHeight-s.y-s.height)),m=n.computedHeight*a,u=Math.max(0,p-m),g=n.computedWidth-2*l,E=n.computedHeight-2*u,f=e/g,y=t/E,v=Math.min(f,y),x=(e-g*v)/2-l*v,w=(t-E*v)/2-u*v;(0,o.forEveryChild)(n,(e=>{"group"!==e.type&&(d(e)?e.set({x:e.x*v,y:e.y*v,width:e.width*f,height:e.height*y,cropX:0,cropY:0,cropWidth:1,cropHeight:1}):(e.set({x:x+e.x*v,y:w+e.y*v,width:e.width*v,height:e.height*v}),"text"===e.type?e.set({fontSize:e.fontSize*v}):"figure"===e.type&&e.set({strokeWidth:e.strokeWidth*v})))}))}d||(n.width=e),d||(n.height=t)}}))).actions((e=>({moveElementUp(t){console.warn("page.moveElementUp(id) is deprecated. Please use page.moveElementsUp([id1, id2]) instead."),e.moveElementsUp([t])},moveElementDown(t){console.warn("page.moveElementDown(id) is deprecated. Please use page.moveElementsDown([id1, id2]) instead."),e.moveElementsDown([t])},moveElementTop(t){console.warn("page.moveElementTop(id) is deprecated. Please use page.moveElementsTop([id1, id2]) instead."),e.moveElementsTop([t])},moveElementBottom(t){console.warn("page.moveElementBottom(id) is deprecated. Please use page.moveElementsBottom([id1, id2]) instead."),e.moveElementsBottom([t])},play(){e.store.play({startTime:e.startTime,endTime:e.startTime+e.duration})}})));
|
package/model/store.d.ts
CHANGED
|
@@ -806,7 +806,7 @@ export declare const Store: import("mobx-state-tree").IModelType<{
|
|
|
806
806
|
setSize(width: number, height: number, useMagic?: boolean): void;
|
|
807
807
|
setPageZIndex(id: any, zIndex: any): void;
|
|
808
808
|
deletePages(ids: Array<string>): void;
|
|
809
|
-
groupElements(ids: Array<string
|
|
809
|
+
groupElements(ids: Array<string>, attrs?: any): any;
|
|
810
810
|
ungroupElements(ids: Array<string>): void;
|
|
811
811
|
deleteElements(ids: Array<string>): void;
|
|
812
812
|
on(event: any, callback: any): import("mobx-state-tree").IDisposer;
|
package/model/store.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e,t=this&&this.__createBinding||(Object.create?function(e,t,i,o){void 0===o&&(o=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,o,n)}:function(e,t,i,o){void 0===o&&(o=i),e[o]=t[i]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||(e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e){Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i)}return t},e(t)},function(o){if(o&&o.__esModule){return o}var n={};if(null!=o){for(var a=e(o),s=0;s<a.length;s++){"default"!==a[s]&&t(n,o,a[s])}}return i(n,o),n}),n=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},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.Store=exports.Font=void 0,exports.createStore=O;const s=require("mobx-state-tree"),r=require("./history"),l=require("nanoid"),d=a(require("konva")),c=require("../utils/download"),p=require("../utils/pdf"),u=require("../utils/gif-lib"),g=require("../utils/validate-key"),h=o(require("../utils/fonts")),m=require("../utils/flags"),f=require("../utils/loader"),y=require("../utils/unit"),b=require("../utils/deep-equal"),v=require("../utils/wait"),w=require("../utils/to-html"),P=require("../utils/to-svg"),x=require("./page-model"),E=require("./group-model"),_=require("./audio-model");function O({key:e,showCredit:t}={key:"",showCredit:!1}){return exports.Store.create({_forceShowCredit:t,_key:e})}(0,s.setLivelinessChecking)("ignore"),exports.Font=s.types.model("Font",{fontFamily:s.types.string,url:s.types.optional(s.types.string,""),styles:s.types.frozen()}).preProcessSnapshot((e=>Object.assign(Object.assign({},e),{fontFamily:e.fontFamily||e.name}))),exports.Store=s.types.model("Store",{role:"",pages:s.types.array(x.Page),fonts:s.types.array(exports.Font),audios:s.types.array(_.Audio),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:"px",dpi:72,schemaVersion:1,bleedVisible:!1,rulesVisible:!1,openedSidePanel:"",previousOpenedSidePanel:"",custom:s.types.frozen(),selectedElementsIds:s.types.array(s.types.string),animatedElementsIds:s.types.array(s.types.string),history:s.types.optional(r.UndoManager,{targetPath:"../pages"}),_elementsPixelRatio:Math.min(2,window.devicePixelRatio||1),_activePageId:"",_forceShowCredit:!1,_key:"",_validated:!1}).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(0,E.forEveryChild)({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 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(0,E.forEveryChild)({children:e.pages},(e=>{if(!i&&t(e)){return i=e,!0}})),i},getElementById:t=>e.find((e=>e.id===t))}))).actions((e=>{let t=0,i=null,o=!1;return{afterCreate(){e.history.canUndo},setCurrentTime(t){e.currentTime=t},_togglePlaying(t=!e.isPlaying){e.isPlaying=t},play({animatedElementsIds:n=[],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=(0,s.cast)(n),e.currentTime=a,e.isPlaying=!0,t=Date.now(),i=l,o=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 n=Date.now(),a=n-t;t=n,e.currentTime+=a,e.checkActivePage();const s=i||e.duration;e.isPlaying&&e.currentTime<s?requestAnimationFrame(e.seek):e.isPlaying&&o?(e.currentTime=0,requestAnimationFrame(e.seek)):e.stop()},stop(){e.isPlaying=!1,e.currentTime=0,e.animatedElementsIds=(0,s.cast)([]),e.checkActivePage()}}})).actions((e=>({__(){e._validated||((0,g.validateKey)(e._key,e._forceShowCredit),e._validated=!0)},set(t){Object.assign(e,t)},setUnit({unit:t,dpi:i}){e.unit=t||e.unit,e.dpi=i||e.dpi},setRole(t){e.role=t},addPage(t){const i=x.Page.create(Object.assign({id:(0,l.nanoid)(10)},t));return e.pages.push(i),e._activePageId=i.id,i},selectPage(t){e._activePageId=t},selectElements(t){const i=t.map((t=>e.getElementById(t))).sort(((e,t)=>e.page.children.indexOf(e)-e.page.children.indexOf(t))).filter((e=>!!e)).map((e=>e.id));e.selectedElementsIds=(0,s.cast)(i)},toggleBleed(t){e.bleedVisible=null!=t?t:!e.bleedVisible},toggleRulers(t){e.rulesVisible=null!=t?t:!e.rulesVisible},openSidePanel(t){e.openedSidePanel!==t&&(e.previousOpenedSidePanel=e.openedSidePanel,e.openedSidePanel=t)},setScale(t){e.scale=t},_setScaleToFit(t){e.scaleToFit=t},setElementsPixelRatio(t){e._elementsPixelRatio=t},setSize(t,i,o){e.pages.forEach((e=>{e.setSize({width:t,height:i,useMagic:o,softChange:!0})})),e.width=t,e.height=i},setPageZIndex(t,i){const o=e.pages.find((e=>e.id===t));o&&((0,s.detach)(o),e.pages.remove(o),e.pages.splice(i,0,o))},deletePages(t){const i=e.pages.indexOf(e.activePage);t.forEach((t=>{const i=e.pages.find((e=>e.id===t));(0,s.destroy)(i)}));const o=Math.min(e.pages.length-1,i),n=e.pages[o];n&&(e._activePageId=n.id),e.selectedElementsIds=(0,s.cast)(e.selectedElementsIds.filter((t=>e.getElementById(t))))},groupElements(t){const i=t.map((t=>e.getElementById(t))),o=i[0].page;if(i.forEach((e=>{e&&(0,s.detach)(e)})),!i.length){return}const n={id:(0,l.nanoid)(10),children:i,type:"group"};return o.children.push(n),e.selectedElementsIds=(0,s.cast)([n.id]),o.children.find((e=>e.id===n.id))},ungroupElements(t){const i=t.map((t=>e.getElementById(t))),o=[];i.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=>{(0,s.detach)(e),t.children.push(e)})),t.children.splice(i,1)}})),e.selectedElementsIds=(0,s.cast)(o)},deleteElements(t){const i=[];e.find((e=>(t.includes(e.id)&&i.push(e),!1))),i.forEach((e=>{(0,s.destroy)(e)})),e.selectedElementsIds=(0,s.cast)(e.selectedElementsIds.filter((t=>e.getElementById(t))))},on(t,i){if("change"===t){let t=e.toJSON();return(0,s.onSnapshot)(e,(o=>{const n=e.toJSON();!(0,b.deepEqual)(t,n)&&(t=n,i(n))}))}},async _toCanvas({pixelRatio:t,ignoreBackground:i,pageId:o,mimeType:n,includeBleed:a,_skipTimeout:s,quickMode:r=!1}={}){var l;const c=t||1;o=o||(null===(l=e.pages[0])||void 0===l?void 0:l.id);const p=e.pages.find((e=>e.id===o));if(!p){throw new Error(`No page for export with id ${o}`)}r?null==p||p.set({_forceMount:!0}):null==p||p.set({_exporting:!0});const u=await(0,v.waitTillAvailable)((()=>d.default.stages.find((e=>e.getAttr("pageId")===o))));if(!u){throw null==p||p.set({_forceMount:!1,_exporting:!1}),new Error(`Export is failed. Can not find stage for page ${o}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`)}const g=e._elementsPixelRatio;c>e._elementsPixelRatio&&e.setElementsPixelRatio(c),await e.waitLoading({_skipTimeout:s});const h=u.findOne(".page-container");if(!h){throw e.setElementsPixelRatio(g),null==p||p.set({_forceMount:!1,_exporting:!1}),new Error("Export is failed. Canvas was unmounted.")}const m=u.position();u.position({x:0,y:0}),u.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 f=h.findOne(".page-background-group"),y=f.clip();f.clip({x:null,y:null,width:null,height:null});const b=h.findOne(".elements-container"),w=b.clip();b.clip({x:null,y:null,width:null,height:null});const P=h.find((e=>e.getAttr("hideInExport")));P.forEach((e=>{e.setAttr("oldVisible",e.visible()),e.hide()}));const x=h.find((e=>!e.visible()&&e.getAttr("editModeEnabled")));x.forEach((e=>{e.setAttr("oldVisible",e.visible()),e.show()})),i&&h.find(".page-background").forEach((e=>e.hide()));const E=a?p.bleed:0;let _=E;!e.bleedVisible&&a||(e.bleedVisible||a?e.bleedVisible&&a?_=0:e.bleedVisible&&!a&&(_=-p.bleed):_=0);const O=document.createElement("canvas");O.width=Math.round((p.computedWidth+2*E)*c),O.height=Math.round((p.computedHeight+2*E)*c);const S=O.getContext("2d");"image/jpeg"===n&&(S.fillStyle="white",S.fillRect(0,0,O.width,O.height));const k=h.scale();h.scale({x:1,y:1});const I=h.toCanvas({x:h.x()-_,y:h.y()-_,width:p.computedWidth+2*E,height:p.computedHeight+2*E,pixelRatio:c});return h.scale(k),S.drawImage(I,0,0,O.width,O.height),d.default.Util.releaseCanvas(I),i&&h.find(".page-background").forEach((e=>e.show())),P.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))),u.find("Transformer").forEach((e=>{e.visible(e.getAttr("oldVisible"))})),h.find(".highlighter").forEach((e=>e.visible(!0))),f.clip(y),b.clip(w),u.position(m),e.setElementsPixelRatio(g),null==p||p.set({_exporting:!1,_forceMount:!1}),O},async toDataURL(t={}){var{mimeType:i,quality:o}=t,a=n(t,["mimeType","quality"]);const s=await e._toCanvas(Object.assign({mimeType:i},a)),r=s.toDataURL(i,o);return d.default.Util.releaseCanvas(s),r},async toBlob(t={}){var{mimeType:i,quality:o}=t,a=n(t,["mimeType","quality"]);const s=await e._toCanvas(Object.assign({mimeType:i},a)),r=await new Promise((e=>{s.toBlob(e,i,o)}));return d.default.Util.releaseCanvas(s),r},async saveAsImage(t={}){var{fileName:i}=t,o=n(t,["fileName"]);const a=o.mimeType||"image/png",s=a.split("/")[1];(0,c.downloadFile)(await e.toDataURL(o),i||"polotno."+s,a)},async _toPDF(t){const i=t.dpi||e.dpi,o=t.parallel||1,n=t.unit||("px"===e.unit?"mm":e.unit),a=t.pixelRatio||1,s=t.pageIds||e.pages.map((e=>e.id)),r=e.pages.filter((e=>s.includes(e.id))),l=await(0,p.getJsPDF)(),d=e=>(0,y.pxToUnit)({px:e,unit:n,dpi:i}),c=t.cropMarkSize||0,u=d(c),g=r[0]||{},h=t.includeBleed?g.bleed:0,m=d(g.computedWidth+2*h+2*u),f=d(g.computedHeight+2*h+2*u);var b=new l({unit:n,orientation:m>f?"landscape":"portrait",format:[m,f],compress:!0,putOnlyUsedFonts:!0});b.deletePage(1);const v=((e,t)=>{for(var i=[],o=0;o<e.length;o+=t){i.push(e.slice(o,o+t))}return i})(r,o);let w=0;for(const p of v){const i=p.map((async i=>{const o=t.includeBleed?i.bleed:0,n=i.computedWidth+2*o+2*c,r=i.computedHeight+2*o+2*c,l=d(n),p=d(r);let u=0,g=a;for(;u<10;){u+=1,2===u&&console.error("Polotno can not export PDF with current settings. Quality is automatically reduced.");const o=await e.toDataURL(Object.assign(Object.assign({},t),{pageId:i.id,pixelRatio:g}));if(o.length>20){return t.onProgress&&t.onProgress(++w/s.length*.9),{url:o,width:l,height:p,widthPx:n,heightPx:r}}g*=.8}}));(await Promise.all(i)).forEach((({url:e,width:t,height:i,widthPx:o,heightPx:a})=>{b.addPage([t,i],t>i?"landscape":"portrait");const s=b.getCurrentPageInfo();var r;switch(n){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: "+n}if(s.pageContext.cropBox={bottomLeftX:0,bottomLeftY:0,topRightX:t*r,topRightY:i*r},s.pageContext.artBox={bottomLeftX:d(c+h)*r,bottomLeftY:d(c+h)*r,topRightX:d(o-c-h)*r,topRightY:d(a-c-h)*r},s.pageContext.bleedBox={bottomLeftX:d(c+h)*r,bottomLeftY:d(c+h)*r,topRightX:d(o-c-h)*r,topRightY:d(a-c-h)*r},u){b.setLineWidth(d(1));const e=u+d(h);b.line(e,0,e,u),b.line(0,e,u,e),b.line(t-e,0,t-e,u),b.line(t,e,t-u,e),b.line(0,i-e,u,i-e),b.line(e,i,e,i-u),b.line(t,i-e,t-u,i-e),b.line(t-e,i,t-e,i-u)}b.addImage(e,u,u,t-2*u,i-2*u,void 0,"FAST")}))}return b},toPDFDataURL:async t=>(await e._toPDF(Object.assign({mimeType:"image/jpeg"},t))).output("datauristring"),async toGIFDataURL(t={}){const i=t.pixelRatio||1,o=await(0,u.createGIF)({width:e.width*i,height:e.height*i}),n=1e3/(t.fps||10),a=e.duration/n;for(let s=0;s<a-1;s++){const t=s*n||1;e.setCurrentTime(t);let a=0,r="";for(const i of e.pages){if(a+=i.duration,i.set({_rendering:a>t}),a>t){r=i.id;break}}const l=await e._toCanvas({pixelRatio:i,pageId:r,_skipTimeout:!0});o.addFrame(l.getContext("2d"),{delay:n,copy:!0})}for(const s of e.pages){s.set({_rendering:!1})}return e.stop(),o.render(),new Promise((e=>{o.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=n(t,["fileName"]);const a=await e.toGIFDataURL(o);(0,c.downloadFile)(a,i||"polotno.gif")},async toHTML({elementHook:t}={elementHook:void 0}){const i=e.toJSON();return(0,w.jsonToHTML)({json:i,elementHook:t})},async saveAsHTML({fileName:t}={}){const i=await e.toHTML(),o="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(i)));(0,c.downloadFile)(o,t||"polotno.html")},async toSVG({elementHook:t,pageId:i}={elementHook:void 0,pageId:void 0}){var o;const n=e.toJSON();i=i||(null===(o=n.pages[0])||void 0===o?void 0:o.id);const a=n.pages.find((e=>e.id===i));return(0,P.jsonToSVG)({json:Object.assign(Object.assign({},n),{pages:a?[a]:[]}),elementHook:t})},async saveAsSVG({fileName:t,elementHook:i,pageId:o}={}){const n=await e.toSVG({elementHook:i,pageId:o}),a="data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(n)));(0,c.downloadFile)(a,t||"polotno.svg")},async saveAsPDF(t={}){var{fileName:i}=t,o=n(t,["fileName"]);(await e._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(0,f.whenLoaded)()},toJSON:()=>({width:e.width,height:e.height,fonts:(0,s.getSnapshot)(e.fonts),pages:(0,s.getSnapshot)(e.pages),audios:(0,s.getSnapshot)(e.audios),unit:e.unit,dpi:e.dpi,custom:e.custom,schemaVersion:e.schemaVersion}),loadJSON(t,i=!1){var o;const n=Object.assign({},t);void 0===n.schemaVersion&&m.flags.htmlRenderEnabled&&(0,E.forEveryChild)({children:n.pages},(e=>{if("text"===e.type){const t=16,i=e.letterSpacing*t;e.letterSpacing=i/e.fontSize}}));const a=e.pages.indexOf(e.activePage);let r=null===(o=n.pages[a]||n.pages[0])||void 0===o?void 0:o.id;n._activePageId=r;const l=Object.assign({},(0,s.getSnapshot)(e));Object.assign(l,n),l.history=i?e.history.toJSON():{history:[],undoIdx:-1},(0,s.applySnapshot)(e,l)},clear({keepHistory:t=!1}={}){const i=e.pages.map((e=>e.id));e.deletePages(i),e.custom=null,t||e.history.clear()},addFont(t){e.removeFont(t.fontFamily),e.fonts.push(t),e.loadFont(t.fontFamily)},removeFont(t){e.fonts.filter((e=>e.fontFamily===t)).forEach((e=>(0,s.destroy)(e)))},addAudio(t){const i=_.Audio.create(Object.assign({id:(0,l.nanoid)(10)},t));e.audios.push(i)},removeAudio(t){const i=e.audios.find((e=>e.id===t));i&&e.audios.remove(i)},async loadFont(t){const i=e.fonts.find((e=>e.fontFamily===t))||h.globalFonts.find((e=>e.fontFamily===t));let o=[{fontStyle:"normal",fontWeight:"normal"}];return i?(i.styles&&(o=i.styles.map((e=>({fontStyle:e.fontStyle||"normal",fontWeight:e.fontWeight||"normal"})))),h.injectCustomFont(i)):h.injectGoogleFont(t),Promise.all(o.map((e=>h.loadFont(t,e.fontStyle,e.fontWeight))))},validate:e=>exports.Store.validate(e,[{path:"",type:exports.Store}]).map((e=>({path:"store"+e.context.map((e=>e.path)).join("."),message:e.message})))}))),exports.default=O;
|
|
1
|
+
var e,t=this&&this.__createBinding||(Object.create?function(e,t,i,o){void 0===o&&(o=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,o,n)}:function(e,t,i,o){void 0===o&&(o=i),e[o]=t[i]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||(e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e){Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i)}return t},e(t)},function(o){if(o&&o.__esModule){return o}var n={};if(null!=o){for(var a=e(o),s=0;s<a.length;s++){"default"!==a[s]&&t(n,o,a[s])}}return i(n,o),n}),n=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},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.Store=exports.Font=void 0,exports.createStore=O;const s=require("mobx-state-tree"),r=require("./history"),l=require("nanoid"),d=a(require("konva")),c=require("../utils/download"),p=require("../utils/pdf"),u=require("../utils/gif-lib"),g=require("../utils/validate-key"),h=o(require("../utils/fonts")),m=require("../utils/flags"),f=require("../utils/loader"),y=require("../utils/unit"),b=require("../utils/deep-equal"),v=require("../utils/wait"),w=require("../utils/to-html"),P=require("../utils/to-svg"),x=require("./page-model"),E=require("./group-model"),_=require("./audio-model");function O({key:e,showCredit:t}={key:"",showCredit:!1}){return exports.Store.create({_forceShowCredit:t,_key:e})}(0,s.setLivelinessChecking)("ignore"),exports.Font=s.types.model("Font",{fontFamily:s.types.string,url:s.types.optional(s.types.string,""),styles:s.types.frozen()}).preProcessSnapshot((e=>Object.assign(Object.assign({},e),{fontFamily:e.fontFamily||e.name}))),exports.Store=s.types.model("Store",{role:"",pages:s.types.array(x.Page),fonts:s.types.array(exports.Font),audios:s.types.array(_.Audio),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:"px",dpi:72,schemaVersion:1,bleedVisible:!1,rulesVisible:!1,openedSidePanel:"",previousOpenedSidePanel:"",custom:s.types.frozen(),selectedElementsIds:s.types.array(s.types.string),animatedElementsIds:s.types.array(s.types.string),history:s.types.optional(r.UndoManager,{targetPath:"../pages"}),_elementsPixelRatio:Math.min(2,window.devicePixelRatio||1),_activePageId:"",_forceShowCredit:!1,_key:"",_validated:!1}).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(0,E.forEveryChild)({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 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(0,E.forEveryChild)({children:e.pages},(e=>{if(!i&&t(e)){return i=e,!0}})),i},getElementById:t=>e.find((e=>e.id===t))}))).actions((e=>{let t=0,i=null,o=!1;return{afterCreate(){e.history.canUndo},setCurrentTime(t){e.currentTime=t},_togglePlaying(t=!e.isPlaying){e.isPlaying=t},play({animatedElementsIds:n=[],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=(0,s.cast)(n),e.currentTime=a,e.isPlaying=!0,t=Date.now(),i=l,o=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 n=Date.now(),a=n-t;t=n,e.currentTime+=a,e.checkActivePage();const s=i||e.duration;e.isPlaying&&e.currentTime<s?requestAnimationFrame(e.seek):e.isPlaying&&o?(e.currentTime=0,requestAnimationFrame(e.seek)):e.stop()},stop(){e.isPlaying=!1,e.currentTime=0,e.animatedElementsIds=(0,s.cast)([]),e.checkActivePage()}}})).actions((e=>({__(){e._validated||((0,g.validateKey)(e._key,e._forceShowCredit),e._validated=!0)},set(t){Object.assign(e,t)},setUnit({unit:t,dpi:i}){e.unit=t||e.unit,e.dpi=i||e.dpi},setRole(t){e.role=t},addPage(t){const i=x.Page.create(Object.assign({id:(0,l.nanoid)(10)},t));return e.pages.push(i),e._activePageId=i.id,i},selectPage(t){e._activePageId=t},selectElements(t){const i=t.map((t=>e.getElementById(t))).sort(((e,t)=>e.page.children.indexOf(e)-e.page.children.indexOf(t))).filter((e=>!!e)).map((e=>e.id));e.selectedElementsIds=(0,s.cast)(i)},toggleBleed(t){e.bleedVisible=null!=t?t:!e.bleedVisible},toggleRulers(t){e.rulesVisible=null!=t?t:!e.rulesVisible},openSidePanel(t){e.openedSidePanel!==t&&(e.previousOpenedSidePanel=e.openedSidePanel,e.openedSidePanel=t)},setScale(t){e.scale=t},_setScaleToFit(t){e.scaleToFit=t},setElementsPixelRatio(t){e._elementsPixelRatio=t},setSize(t,i,o){e.pages.forEach((e=>{e.setSize({width:t,height:i,useMagic:o,softChange:!0})})),e.width=t,e.height=i},setPageZIndex(t,i){const o=e.pages.find((e=>e.id===t));o&&((0,s.detach)(o),e.pages.remove(o),e.pages.splice(i,0,o))},deletePages(t){const i=e.pages.indexOf(e.activePage);t.forEach((t=>{const i=e.pages.find((e=>e.id===t));(0,s.destroy)(i)}));const o=Math.min(e.pages.length-1,i),n=e.pages[o];n&&(e._activePageId=n.id),e.selectedElementsIds=(0,s.cast)(e.selectedElementsIds.filter((t=>e.getElementById(t))))},groupElements(t,i={}){const o=t.map((t=>e.getElementById(t))),n=o[0].page;if(o.forEach((e=>{e&&(0,s.detach)(e)})),!o.length){return}const a=Object.assign({id:(0,l.nanoid)(10),children:o,type:"group"},i);return n.children.push(a),e.selectedElementsIds=(0,s.cast)([a.id]),n.children.find((e=>e.id===a.id))},ungroupElements(t){const i=t.map((t=>e.getElementById(t))),o=[];i.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=>{(0,s.detach)(e),t.children.push(e)})),t.children.splice(i,1)}})),e.selectedElementsIds=(0,s.cast)(o)},deleteElements(t){const i=[];e.find((e=>(t.includes(e.id)&&i.push(e),!1))),i.forEach((e=>{(0,s.destroy)(e)})),e.selectedElementsIds=(0,s.cast)(e.selectedElementsIds.filter((t=>e.getElementById(t))))},on(t,i){if("change"===t){let t=e.toJSON();return(0,s.onSnapshot)(e,(o=>{const n=e.toJSON();!(0,b.deepEqual)(t,n)&&(t=n,i(n))}))}},async _toCanvas({pixelRatio:t,ignoreBackground:i,pageId:o,mimeType:n,includeBleed:a,_skipTimeout:s,quickMode:r=!1}={}){var l;const c=t||1;o=o||(null===(l=e.pages[0])||void 0===l?void 0:l.id);const p=e.pages.find((e=>e.id===o));if(!p){throw new Error(`No page for export with id ${o}`)}r?null==p||p.set({_forceMount:!0}):null==p||p.set({_exporting:!0});const u=await(0,v.waitTillAvailable)((()=>d.default.stages.find((e=>e.getAttr("pageId")===o))));if(!u){throw null==p||p.set({_forceMount:!1,_exporting:!1}),new Error(`Export is failed. Can not find stage for page ${o}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`)}const g=e._elementsPixelRatio;c>e._elementsPixelRatio&&e.setElementsPixelRatio(c),await e.waitLoading({_skipTimeout:s});const h=u.findOne(".page-container");if(!h){throw e.setElementsPixelRatio(g),null==p||p.set({_forceMount:!1,_exporting:!1}),new Error("Export is failed. Canvas was unmounted.")}const m=u.position();u.position({x:0,y:0}),u.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 f=h.findOne(".page-background-group"),y=f.clip();f.clip({x:null,y:null,width:null,height:null});const b=h.findOne(".elements-container"),w=b.clip();b.clip({x:null,y:null,width:null,height:null});const P=h.find((e=>e.getAttr("hideInExport")));P.forEach((e=>{e.setAttr("oldVisible",e.visible()),e.hide()}));const x=h.find((e=>!e.visible()&&e.getAttr("editModeEnabled")));x.forEach((e=>{e.setAttr("oldVisible",e.visible()),e.show()})),i&&h.find(".page-background").forEach((e=>e.hide()));const E=a?p.bleed:0;let _=E;!e.bleedVisible&&a||(e.bleedVisible||a?e.bleedVisible&&a?_=0:e.bleedVisible&&!a&&(_=-p.bleed):_=0);const O=document.createElement("canvas");O.width=Math.round((p.computedWidth+2*E)*c),O.height=Math.round((p.computedHeight+2*E)*c);const S=O.getContext("2d");"image/jpeg"===n&&(S.fillStyle="white",S.fillRect(0,0,O.width,O.height));const k=h.scale();h.scale({x:1,y:1});const I=h.toCanvas({x:h.x()-_,y:h.y()-_,width:p.computedWidth+2*E,height:p.computedHeight+2*E,pixelRatio:c});return h.scale(k),S.drawImage(I,0,0,O.width,O.height),d.default.Util.releaseCanvas(I),i&&h.find(".page-background").forEach((e=>e.show())),P.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))),u.find("Transformer").forEach((e=>{e.visible(e.getAttr("oldVisible"))})),h.find(".highlighter").forEach((e=>e.visible(!0))),f.clip(y),b.clip(w),u.position(m),e.setElementsPixelRatio(g),null==p||p.set({_exporting:!1,_forceMount:!1}),O},async toDataURL(t={}){var{mimeType:i,quality:o}=t,a=n(t,["mimeType","quality"]);const s=await e._toCanvas(Object.assign({mimeType:i},a)),r=s.toDataURL(i,o);return d.default.Util.releaseCanvas(s),r},async toBlob(t={}){var{mimeType:i,quality:o}=t,a=n(t,["mimeType","quality"]);const s=await e._toCanvas(Object.assign({mimeType:i},a)),r=await new Promise((e=>{s.toBlob(e,i,o)}));return d.default.Util.releaseCanvas(s),r},async saveAsImage(t={}){var{fileName:i}=t,o=n(t,["fileName"]);const a=o.mimeType||"image/png",s=a.split("/")[1];(0,c.downloadFile)(await e.toDataURL(o),i||"polotno."+s,a)},async _toPDF(t){const i=t.dpi||e.dpi,o=t.parallel||1,n=t.unit||("px"===e.unit?"mm":e.unit),a=t.pixelRatio||1,s=t.pageIds||e.pages.map((e=>e.id)),r=e.pages.filter((e=>s.includes(e.id))),l=await(0,p.getJsPDF)(),d=e=>(0,y.pxToUnit)({px:e,unit:n,dpi:i}),c=t.cropMarkSize||0,u=d(c),g=r[0]||{},h=t.includeBleed?g.bleed:0,m=d(g.computedWidth+2*h+2*u),f=d(g.computedHeight+2*h+2*u);var b=new l({unit:n,orientation:m>f?"landscape":"portrait",format:[m,f],compress:!0,putOnlyUsedFonts:!0});b.deletePage(1);const v=((e,t)=>{for(var i=[],o=0;o<e.length;o+=t){i.push(e.slice(o,o+t))}return i})(r,o);let w=0;for(const p of v){const i=p.map((async i=>{const o=t.includeBleed?i.bleed:0,n=i.computedWidth+2*o+2*c,r=i.computedHeight+2*o+2*c,l=d(n),p=d(r);let u=0,g=a;for(;u<10;){u+=1,2===u&&console.error("Polotno can not export PDF with current settings. Quality is automatically reduced.");const o=await e.toDataURL(Object.assign(Object.assign({},t),{pageId:i.id,pixelRatio:g}));if(o.length>20){return t.onProgress&&t.onProgress(++w/s.length*.9),{url:o,width:l,height:p,widthPx:n,heightPx:r}}g*=.8}}));(await Promise.all(i)).forEach((({url:e,width:t,height:i,widthPx:o,heightPx:a})=>{b.addPage([t,i],t>i?"landscape":"portrait");const s=b.getCurrentPageInfo();var r;switch(n){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: "+n}if(s.pageContext.cropBox={bottomLeftX:0,bottomLeftY:0,topRightX:t*r,topRightY:i*r},s.pageContext.artBox={bottomLeftX:d(c+h)*r,bottomLeftY:d(c+h)*r,topRightX:d(o-c-h)*r,topRightY:d(a-c-h)*r},s.pageContext.bleedBox={bottomLeftX:d(c+h)*r,bottomLeftY:d(c+h)*r,topRightX:d(o-c-h)*r,topRightY:d(a-c-h)*r},u){b.setLineWidth(d(1));const e=u+d(h);b.line(e,0,e,u),b.line(0,e,u,e),b.line(t-e,0,t-e,u),b.line(t,e,t-u,e),b.line(0,i-e,u,i-e),b.line(e,i,e,i-u),b.line(t,i-e,t-u,i-e),b.line(t-e,i,t-e,i-u)}b.addImage(e,u,u,t-2*u,i-2*u,void 0,"FAST")}))}return b},toPDFDataURL:async t=>(await e._toPDF(Object.assign({mimeType:"image/jpeg"},t))).output("datauristring"),async toGIFDataURL(t={}){const i=t.pixelRatio||1,o=await(0,u.createGIF)({width:e.width*i,height:e.height*i}),n=1e3/(t.fps||10),a=e.duration/n;for(let s=0;s<a-1;s++){const t=s*n||1;e.setCurrentTime(t);let a=0,r="";for(const i of e.pages){if(a+=i.duration,i.set({_rendering:a>t}),a>t){r=i.id;break}}const l=await e._toCanvas({pixelRatio:i,pageId:r,_skipTimeout:!0});o.addFrame(l.getContext("2d"),{delay:n,copy:!0})}for(const s of e.pages){s.set({_rendering:!1})}return e.stop(),o.render(),new Promise((e=>{o.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=n(t,["fileName"]);const a=await e.toGIFDataURL(o);(0,c.downloadFile)(a,i||"polotno.gif")},async toHTML({elementHook:t}={elementHook:void 0}){const i=e.toJSON();return(0,w.jsonToHTML)({json:i,elementHook:t})},async saveAsHTML({fileName:t}={}){const i=await e.toHTML(),o="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(i)));(0,c.downloadFile)(o,t||"polotno.html")},async toSVG({elementHook:t,pageId:i}={elementHook:void 0,pageId:void 0}){var o;const n=e.toJSON();i=i||(null===(o=n.pages[0])||void 0===o?void 0:o.id);const a=n.pages.find((e=>e.id===i));return(0,P.jsonToSVG)({json:Object.assign(Object.assign({},n),{pages:a?[a]:[]}),elementHook:t})},async saveAsSVG({fileName:t,elementHook:i,pageId:o}={}){const n=await e.toSVG({elementHook:i,pageId:o}),a="data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(n)));(0,c.downloadFile)(a,t||"polotno.svg")},async saveAsPDF(t={}){var{fileName:i}=t,o=n(t,["fileName"]);(await e._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(0,f.whenLoaded)()},toJSON:()=>({width:e.width,height:e.height,fonts:(0,s.getSnapshot)(e.fonts),pages:(0,s.getSnapshot)(e.pages),audios:(0,s.getSnapshot)(e.audios),unit:e.unit,dpi:e.dpi,custom:e.custom,schemaVersion:e.schemaVersion}),loadJSON(t,i=!1){var o;const n=Object.assign({},t);void 0===n.schemaVersion&&m.flags.htmlRenderEnabled&&(0,E.forEveryChild)({children:n.pages},(e=>{if("text"===e.type){const t=16,i=e.letterSpacing*t;e.letterSpacing=i/e.fontSize}}));const a=e.pages.indexOf(e.activePage);let r=null===(o=n.pages[a]||n.pages[0])||void 0===o?void 0:o.id;n._activePageId=r;const l=Object.assign({},(0,s.getSnapshot)(e));Object.assign(l,n),l.history=i?e.history.toJSON():{history:[],undoIdx:-1},(0,s.applySnapshot)(e,l)},clear({keepHistory:t=!1}={}){const i=e.pages.map((e=>e.id));e.deletePages(i),e.custom=null,t||e.history.clear()},addFont(t){e.removeFont(t.fontFamily),e.fonts.push(t),e.loadFont(t.fontFamily)},removeFont(t){e.fonts.filter((e=>e.fontFamily===t)).forEach((e=>(0,s.destroy)(e)))},addAudio(t){const i=_.Audio.create(Object.assign({id:(0,l.nanoid)(10)},t));e.audios.push(i)},removeAudio(t){const i=e.audios.find((e=>e.id===t));i&&e.audios.remove(i)},async loadFont(t){const i=e.fonts.find((e=>e.fontFamily===t))||h.globalFonts.find((e=>e.fontFamily===t));let o=[{fontStyle:"normal",fontWeight:"normal"}];return i?(i.styles&&(o=i.styles.map((e=>({fontStyle:e.fontStyle||"normal",fontWeight:e.fontWeight||"normal"})))),h.injectCustomFont(i)):h.injectGoogleFont(t),Promise.all(o.map((e=>h.loadFont(t,e.fontStyle,e.fontWeight))))},validate:e=>exports.Store.validate(e,[{path:"",type:exports.Store}]).map((e=>({path:"store"+e.context.map((e=>e.path)).join("."),message:e.message})))}))),exports.default=O;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "polotno",
|
|
3
|
-
"version": "2.23.
|
|
3
|
+
"version": "2.23.6",
|
|
4
4
|
"description": "Design Editor Framework",
|
|
5
5
|
"author": "Anton Lavrenov",
|
|
6
6
|
"keywords": [
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
"sortablejs": "^1.15.6",
|
|
35
35
|
"svg-round-corners": "^0.4.3",
|
|
36
36
|
"swr": "^2.3.3",
|
|
37
|
-
"use-image": "^1.1.
|
|
37
|
+
"use-image": "^1.1.4"
|
|
38
38
|
},
|
|
39
39
|
"targets": {
|
|
40
40
|
"bundle": {
|
package/polotno-app.d.ts
CHANGED
|
@@ -1027,7 +1027,7 @@ export declare function createPolotnoApp({ container, key, showCredit, sections
|
|
|
1027
1027
|
setSize(width: number, height: number, useMagic?: boolean): void;
|
|
1028
1028
|
setPageZIndex(id: any, zIndex: any): void;
|
|
1029
1029
|
deletePages(ids: Array<string>): void;
|
|
1030
|
-
groupElements(ids: Array<string
|
|
1030
|
+
groupElements(ids: Array<string>, attrs?: any): any;
|
|
1031
1031
|
ungroupElements(ids: Array<string>): void;
|
|
1032
1032
|
deleteElements(ids: Array<string>): void;
|
|
1033
1033
|
on(event: any, callback: any): import("mobx-state-tree").IDisposer;
|
|
@@ -2114,7 +2114,7 @@ export declare function createPolotnoApp({ container, key, showCredit, sections
|
|
|
2114
2114
|
setSize(width: number, height: number, useMagic?: boolean): void;
|
|
2115
2115
|
setPageZIndex(id: any, zIndex: any): void;
|
|
2116
2116
|
deletePages(ids: Array<string>): void;
|
|
2117
|
-
groupElements(ids: Array<string
|
|
2117
|
+
groupElements(ids: Array<string>, attrs?: any): any;
|
|
2118
2118
|
ungroupElements(ids: Array<string>): void;
|
|
2119
2119
|
deleteElements(ids: Array<string>): void;
|
|
2120
2120
|
on(event: any, callback: any): import("mobx-state-tree").IDisposer;
|