polotno 1.8.0 → 1.8.3
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/text-element.js +1 -1
- package/model/store.d.ts +0 -1
- package/model/store.js +1 -1
- package/package.json +1 -3
- package/polotno-app.d.ts +0 -2
- package/polotno.bundle.js +29 -29
- package/utils/text.js +1 -1
package/canvas/text-element.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&__createBinding(t,e,r);return __setModuleDefault(t,e),t},__importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.TextElement=exports.useTextColor=exports.getLineHeight=exports.useFontLoader=exports.getDir=exports.isRTLText=void 0;const react_1=__importDefault(require("react")),mobx_react_lite_1=require("mobx-react-lite"),react_konva_1=require("react-konva"),react_konva_utils_1=require("react-konva-utils"),mobx_1=require("mobx"),konva_1=__importDefault(require("konva")),svg_round_corners_1=require("svg-round-corners"),loader_1=require("../utils/loader"),fonts_1=require("../utils/fonts"),flags_1=require("../utils/flags"),text_1=require("../utils/text"),gradient=__importStar(require("../utils/gradient")),apply_filters_1=require("./apply-filters"),use_fadein_1=require("./use-fadein"),highlighter_1=require("./highlighter"),screen_1=require("../utils/screen"),styleNode=document.createElement("style");styleNode.type="text/css",document.head.appendChild(styleNode);const initialStyles={border:"none",padding:"0px",overflow:"hidden",background:"none",outline:"none",resize:"none",overflowWrap:"break-word",whiteSpace:"pre-wrap",userSelect:"text",wordBreak:"normal"};function isRTL(e){var t="֑-߿יִ-﷽ﹰ-ﻼ";return new RegExp("^[^"+t+"]*?["+t+"]").test(e)}function isRTLText(e){e=e.replace(/\s/g,"");let t=0;for(var r=0;r<e.length;r++){isRTL(e[r])&&(t+=1)}return t>e.length/2}function getDir(e){return isRTLText(e)?"rtl":"ltr"}exports.isRTLText=isRTLText,exports.getDir=getDir;const TextInput=(0,mobx_react_lite_1.observer)((({textNodeRef:e,element:t,onBlur:r,selectAll:i,cursorPosition:n})=>{const[o,a]=react_1.default.useState(initialStyles),l=e.current;react_1.default.useLayoutEffect((()=>{const e={};e.width=l.width()-2*l.padding()+"px",e.height=l.height()-2*l.padding()+10+"px",e.fontSize=l.fontSize()+"px",e.lineHeight=l.lineHeight()+.01,e.fontFamily=l.fontFamily(),e.textAlign=l.align(),e.color=l.fill(),e.fontWeight=t.fontWeight,e.fontStyle=t.fontStyle,e.letterSpacing=t.letterSpacing+"em";const r=`\n .polotno-input::placeholder {\n color: ${o.color};\n opacity: 0.6;\n }\n `;styleNode.innerHTML="",styleNode.appendChild(document.createTextNode(r)),JSON.stringify(e)!==JSON.stringify(o)&&a(e)}));const s=react_1.default.useRef(null);react_1.default.useEffect((()=>{const e=setTimeout((()=>{var e;const t=s.current;if(!t)return;null===(e=s.current)||void 0===e||e.focus();const r=n||t.value.length;t.selectionStart=t.selectionEnd=r,i&&(null==t||t.select(),document.execCommand("selectAll",!1,null))}));return()=>{clearTimeout(e)}}),[]);let d=0;const c=l.textArr.length*l.lineHeight()*l.fontSize();return"middle"===t.verticalAlign&&(d=(t.height-c)/2),"bottom"===t.verticalAlign&&(d=t.height-c),react_1.default.createElement(react_konva_utils_1.Html,null,react_1.default.createElement("textarea",{className:"polotno-input",ref:s,dir:getDir(t.text),style:Object.assign(Object.assign(Object.assign({},initialStyles),o),{paddingTop:d+"px"}),value:t.text,onChange:e=>{t.set({text:e.target.value})},placeholder:t.placeholder,onBlur:r}))})),useEditor=e=>{const[t,r]=react_1.default.useState(!1),i=react_1.default.useRef(!1);return react_1.default.useEffect((()=>{var t=!0;return setTimeout((()=>{t&&(e._editModeEnabled&&(i.current=!0),r(!0),setTimeout((()=>{i.current=!1}),50))}),50),()=>{t=!1}}),[]),{editorEnabled:t&&e._editModeEnabled,selectAll:i.current}},useFontLoader=(e,t)=>{const[r,i]=react_1.default.useState((0,fonts_1.isFontLoaded)(t));return react_1.default.useLayoutEffect((()=>{if((0,fonts_1.isFontLoaded)(t))return void i(!0);let n=!0;return(async()=>{r&&i(!1);const o=(0,loader_1.incrementLoader)(`text ${t}`);await e.loadFont(t),konva_1.default.Util.requestAnimFrame(o),n&&i(!0)})(),()=>{n=!1}}),[t]),[r]};exports.useFontLoader=useFontLoader;const getLineHeight=({fontLoaded:e,fontFamily:t,fontSize:r,lineHeight:i})=>react_1.default.useMemo((()=>{if("number"==typeof i)return i;const e=document.createElement("div");e.style.fontFamily=t,e.style.fontSize=r+"px",e.style.lineHeight=i,e.innerText="Test text",document.body.appendChild(e);const n=e.offsetHeight;return document.body.removeChild(e),n/r}),[e,t,r,i]);function getRelativePointerPosition(e){var t=e.getAbsoluteTransform().copy();t.invert();var r=e.getStage().getPointerPosition();return t.point(r)}function getCursorPosition(e){var t;const r=e.target,i=getRelativePointerPosition(r),n=r.textArr,o=Math.floor(i.y/(r.fontSize()*r.lineHeight())),a=n.slice(0,o).reduce(((e,t)=>e+t.text.length),o),l=null!==(t=n[o])&&void 0!==t?t:n[0];let s=0;"right"===r.align()?s=r.width()-l.width:"center"===r.align()&&(s=r.width()/2-l.width/2);return a+Math.round((i.x-s)/l.width*l.text.length)}function usePrevious(e){const t=react_1.default.useRef(e),r=react_1.default.useRef(e);return react_1.default.useEffect((()=>{r.current=t.current,t.current=e}),[e]),r.current}function findFitFontSize(e,t){const r=e.getAttrs(),i=(0,text_1.removeTags)(t.text);let n=t.fontSize;const o=Math.round(2*t.fontSize)-1;for(let r=1;r<o;r++){const r=t.height&&e.height()>t.height,o=i.split("\n").join(" ").split(" ");let a=e.textArr.map((e=>e.text)).join(";");const l=o.find((e=>!a.includes(e)||(a=a.replace(e,""),!1)));if(!(r||l))break;n-=.5,e.fontSize(n)}return e.fontSize(r.fontSize),n}function generateBackgroundShape({lines:e,lineHeight:t,width:r,align:i="left",padding:n=0,cornerRadius:o=0}){var a;e.forEach(((e,t)=>{e.cx=r/2,"right"===i?e.cx=r-e.width/2:"left"===i&&(e.cx=e.width/2),"justify"!==i||e.lastInParagraph||(e.width=r),"justify"===i&&(e.cx=e.width/2)}));let l=`M ${null===(a=e[0])||void 0===a?void 0:a.cx} ${-n}`;e.forEach(((r,i)=>{const{cx:o}=r,a=e[i-1];a&&a.width>r.width?l+=` L ${o+r.width/2+n} ${i*t+n}`:l+=` L ${o+r.width/2+n} ${i*t-n}`;const s=e[i+1];s&&s.width>r.width?l+=` L ${o+r.width/2+n} ${(i+1)*t-n}`:l+=` L ${o+r.width/2+n} ${(i+1)*t+n}`}));for(var s=e.length-1;s>=0;s--){const r=e[s],{cx:i}=r,o=e[s+1];o&&o.width>r.width?l+=` L ${i-r.width/2-n} ${(s+1)*t-n}`:l+=` L ${i-r.width/2-n} ${(s+1)*t+n}`;const a=e[s-1];a&&a.width>r.width?l+=` L ${i-r.width/2-n} ${s*t+n}`:l+=` L ${i-r.width/2-n} ${s*t-n}`}l+=" Z";const d=(0,svg_round_corners_1.parsePath)(l);return(0,svg_round_corners_1.roundCommands)(d,o).path}exports.getLineHeight=getLineHeight;const useTextColor=e=>react_1.default.useMemo((()=>{if(!gradient.isGradient(e.fill))return{fill:e.fill};const{stops:t,rotation:r}=gradient.parseColor(e.fill),i={x:e.width/2,y:e.height/2},n=Math.sqrt(Math.pow(i.x,2)+Math.pow(i.y,2)),o=konva_1.default.Util.degToRad(r)-Math.PI/2,a=[];return t.forEach((({offset:e,color:t})=>{a.push(e,t)})),{fillLinearGradientStartPointX:i.x-n*Math.cos(o),fillLinearGradientStartPointY:i.y-n*Math.sin(o),fillLinearGradientColorStops:a,fillLinearGradientEndPointX:i.x+n*Math.cos(o),fillLinearGradientEndPointY:i.y+n*Math.sin(o),fill:t[1].color,fillPriority:"linear-gradient"}}),[e.fill]);exports.useTextColor=useTextColor,exports.TextElement=(0,mobx_react_lite_1.observer)((({element:e,store:t})=>{const r=react_1.default.useRef(null),i=react_1.default.useRef(null),{editorEnabled:n,selectAll:o}=useEditor(e),[a,l]=react_1.default.useState(!1),[s,d]=react_1.default.useState(!1),c=react_1.default.useRef(e.height),u=t.selectedElements.indexOf(e)>=0,{textVerticalResizeEnabled:f}=flags_1.flags,h=usePrevious(e.fontFamily),[g,_]=react_1.default.useState([]);react_1.default.useEffect((()=>{var e,t;const i=null!==(t=null===(e=r.current)||void 0===e?void 0:e.textArr)&&void 0!==t?t:[];JSON.stringify(i)!==JSON.stringify(g)&&_(i)})),react_1.default.useEffect((()=>{if(e.width)return;const t=r.current;t.width(600),e.set({width:1.4*t.getTextWidth()})}),[]),react_1.default.useLayoutEffect((()=>(0,mobx_1.autorun)((()=>{const t=r.current;(0,apply_filters_1.applyFilter)(t,e)}))));const[p]=(0,exports.useFontLoader)(t,e.fontFamily),x=(0,text_1.removeTags)(e.text),y=()=>{const e=r.current.clone({height:void 0}),t=Math.ceil(e.fontSize()*e.lineHeight()*e.textArr.length+1);return e.destroy(),t};react_1.default.useLayoutEffect((()=>{if(!p)return;const{textOverflow:i}=flags_1.flags;if(e.height)if("change-font-size"!==i||s){if("resize"===i){const i=y();f&&e.height<i&&t.history.ignore((()=>{e.set({height:i}),r.current.height(i)})),f||e.height===i||t.history.ignore((()=>{e.set({height:i}),r.current.height(i)}))}}else{const i=findFitFontSize(r.current,e);if(i!==e.fontSize)return void t.history.ignore((()=>{e.set({fontSize:i})}));const n=y();e.height!==n&&t.history.ignore((()=>{e.set({height:n})}))}else{const r=y();t.history.ignore((()=>{e.set({height:r})}))}})),react_1.default.useLayoutEffect((()=>{const t=r.current;t&&(t.width(t.width()+1e-8),t._setTextData(),(0,apply_filters_1.applyFilter)(t,e))}),[p]);const m=react_1.default.useRef(null),v=react_1.default.useRef(0),w=r=>{r.evt.preventDefault();const i=t.selectedElements.find((t=>t===e));i&&e.contentEditable&&(v.current=getCursorPosition(r),e.toggleEditMode())},S=!x&&e.placeholder?.6:e.a.opacity;(0,use_fadein_1.useFadeIn)(r,S);const b=(0,exports.getLineHeight)({fontLoaded:p,fontFamily:e.fontFamily,fontSize:e.fontSize,lineHeight:e.lineHeight}),E=e.selectable||"admin"===t.role,T=(0,exports.useTextColor)(e),L=react_1.default.useMemo((()=>e.backgroundEnabled?generateBackgroundShape({lines:g,cornerRadius:e.backgroundCornerRadius*(e.fontSize*b*.5),lineHeight:b*e.fontSize,padding:e.backgroundPadding*(e.fontSize*b*.5),width:e.width,align:e.align}):""),[e.backgroundEnabled,e.backgroundCornerRadius,e.fontSize,b,e.backgroundPadding,e.width,e.align,g]),M=(0,screen_1.useMobile)();let k=0;return"middle"===e.verticalAlign?k=(e.height-g.length*b*e.fontSize)/2:"bottom"===e.verticalAlign&&(k=e.height-g.length*b*e.fontSize),react_1.default.createElement(react_1.default.Fragment,null,react_1.default.createElement(react_konva_1.Path,{ref:i,x:e.a.x,y:e.a.y,rotation:e.a.rotation,hideInExport:!e.showInExport||!x,listening:!1,visible:e.backgroundEnabled,opacity:e.backgroundOpacity,data:L,fill:e.backgroundColor,offsetY:-k}),react_1.default.createElement(react_konva_1.Text,Object.assign({ref:r,id:e.id,name:"element",hideInExport:!e.showInExport||!x,editModeEnabled:e._editModeEnabled,x:e.a.x,y:e.a.y,rotation:e.a.rotation,width:e.width,height:e.height,text:x||e.placeholder},T,{stroke:e.stroke,strokeWidth:e.strokeWidth,fillAfterStrokeEnabled:!0,fontSize:e.fontSize,fontFamily:`"${e.fontFamily}", "${h}"`,fontStyle:e.fontStyle+" "+e.fontWeight,textDecoration:e.textDecoration,align:e.align,verticalAlign:e.verticalAlign,draggable:M?e.draggable&&u:e.draggable,preventDefault:!M||u,opacity:S,visible:!e._editModeEnabled,ellipsis:"ellipsis"===flags_1.flags.textOverflow,shadowEnabled:e.shadowEnabled,shadowBlur:e.shadowBlur,shadowOffsetX:e.shadowOffsetX,shadowOffsetY:e.shadowOffsetY,shadowColor:e.shadowColor,shadowOpacity:e.shadowOpacity,lineHeight:b,letterSpacing:e.letterSpacing*e.fontSize,listening:E,onDragStart:()=>{t.history.startTransaction()},onDragMove:t=>{e.set({x:t.target.x(),y:t.target.y()})},onDragEnd:r=>{e.set({x:r.target.x(),y:r.target.y()}),t.history.endTransaction()},onMouseEnter:()=>{l(!0)},onMouseLeave:()=>{l(!1)},onClick:w,onTap:w,onTransformStart:()=>{d(!0),t.history.startTransaction(),c.current=r.current.height()},onTransform:t=>{var r,n;const o=t.target;null===(r=i.current)||void 0===r||r.setAttrs({x:o.x(),y:o.y(),rotation:o.rotation(),scale:o.scale()});const a=(null===(n=o.getStage())||void 0===n?void 0:n.findOne("Transformer")).getActiveAnchor();if("middle-left"===a||"middle-right"===a){const t=o.scaleX(),r=o.width()*t,i=e.fontSize;let n=r;r<i&&(n=i,m.current&&o.position(m.current)),o.width(n),o.scaleX(1),o.scaleY(1);const a=y();if("ellipsis"!==flags_1.flags.textOverflow){const t=Math.max(a,c.current);o.height(t),e.set({height:o.height()})}e.set({x:o.x(),y:o.y(),width:o.width(),rotation:o.rotation()}),(0,apply_filters_1.applyFilter)(o,e)}if("top-center"===a||"bottom-center"===a){let r="resize"===flags_1.flags.textOverflow?y():b*e.fontSize;t.target.height(Math.max(r,t.target.height()*t.target.scaleY())),t.target.scaleY(1)}t.target.strokeWidth(e.strokeWidth/t.target.scaleX()),m.current=t.target.position()},onTransformEnd:r=>{var n;d(!1);const o=r.target.scaleX();r.target.scaleX(1),r.target.scaleY(1),r.target.strokeWidth(e.strokeWidth),e.set({fontSize:Math.round(e.fontSize*o),width:Math.ceil(r.target.width()*o),x:r.target.x(),y:r.target.y(),rotation:r.target.rotation(),height:r.target.height()*o}),t.history.endTransaction(),null===(n=i.current)||void 0===n||n.setAttrs({scaleX:1,scaleY:1})}})),n&&react_1.default.createElement(react_konva_1.Group,{x:e.a.x,y:e.a.y,rotation:e.a.rotation},react_1.default.createElement(TextInput,{textNodeRef:r,element:e,selectAll:o,cursorPosition:v.current,onBlur:()=>{e.toggleEditMode(!1)}})),!s&&(a||u)&&react_1.default.createElement(highlighter_1.Highlighter,{element:e}))}));
|
|
1
|
+
"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&__createBinding(t,e,r);return __setModuleDefault(t,e),t},__importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.TextElement=exports.useTextColor=exports.getLineHeight=exports.useFontLoader=exports.getDir=exports.isRTLText=void 0;const react_1=__importDefault(require("react")),mobx_react_lite_1=require("mobx-react-lite"),react_konva_1=require("react-konva"),react_konva_utils_1=require("react-konva-utils"),mobx_1=require("mobx"),konva_1=__importDefault(require("konva")),svg_round_corners_1=require("svg-round-corners"),loader_1=require("../utils/loader"),fonts_1=require("../utils/fonts"),flags_1=require("../utils/flags"),text_1=require("../utils/text"),gradient=__importStar(require("../utils/gradient")),apply_filters_1=require("./apply-filters"),use_fadein_1=require("./use-fadein"),highlighter_1=require("./highlighter"),screen_1=require("../utils/screen"),styleNode=document.createElement("style");styleNode.type="text/css",document.head.appendChild(styleNode);const initialStyles={border:"none",padding:"0px",overflow:"hidden",background:"none",outline:"none",resize:"none",overflowWrap:"break-word",whiteSpace:"pre-wrap",userSelect:"text",wordBreak:"normal"};function isRTL(e){var t="֑-߿יִ-﷽ﹰ-ﻼ";return new RegExp("^[^"+t+"]*?["+t+"]").test(e)}function isRTLText(e){e=e.replace(/\s/g,"");let t=0;for(var r=0;r<e.length;r++){isRTL(e[r])&&(t+=1)}return t>e.length/2}function getDir(e){return isRTLText(e)?"rtl":"ltr"}exports.isRTLText=isRTLText,exports.getDir=getDir;const TextInput=(0,mobx_react_lite_1.observer)((({textNodeRef:e,element:t,onBlur:r,selectAll:i,cursorPosition:n})=>{const[o,a]=react_1.default.useState(initialStyles),l=e.current;react_1.default.useLayoutEffect((()=>{const e={};e.width=l.width()-2*l.padding()+"px",e.height=l.height()-2*l.padding()+10+"px",e.fontSize=l.fontSize()+"px",e.lineHeight=l.lineHeight()+.01,e.fontFamily=l.fontFamily(),e.textAlign=l.align(),e.color=l.fill(),e.fontWeight=t.fontWeight,e.fontStyle=t.fontStyle,e.letterSpacing=t.letterSpacing+"em";const r=`\n .polotno-input::placeholder {\n color: ${o.color};\n opacity: 0.6;\n }\n `;styleNode.innerHTML="",styleNode.appendChild(document.createTextNode(r)),JSON.stringify(e)!==JSON.stringify(o)&&a(e)}));const s=react_1.default.useRef(null);react_1.default.useEffect((()=>{const e=setTimeout((()=>{var e;const t=s.current;if(!t)return;null===(e=s.current)||void 0===e||e.focus();const r=n||t.value.length;t.selectionStart=t.selectionEnd=r,i&&(null==t||t.select(),document.execCommand("selectAll",!1,null))}));return()=>{clearTimeout(e)}}),[]);let d=0;const c=l.textArr.length*l.lineHeight()*l.fontSize();"middle"===t.verticalAlign&&(d=(t.height-c)/2),"bottom"===t.verticalAlign&&(d=t.height-c);const u=(0,text_1.removeTags)(t.text);return react_1.default.createElement(react_konva_utils_1.Html,null,react_1.default.createElement("textarea",{className:"polotno-input",ref:s,dir:getDir(u),style:Object.assign(Object.assign(Object.assign({},initialStyles),o),{paddingTop:d+"px"}),value:u,onChange:e=>{t.set({text:e.target.value})},placeholder:t.placeholder,onBlur:r}))})),useEditor=e=>{const[t,r]=react_1.default.useState(!1),i=react_1.default.useRef(!1);return react_1.default.useEffect((()=>{var t=!0;return setTimeout((()=>{t&&(e._editModeEnabled&&(i.current=!0),r(!0),setTimeout((()=>{i.current=!1}),50))}),50),()=>{t=!1}}),[]),{editorEnabled:t&&e._editModeEnabled,selectAll:i.current}},useFontLoader=(e,t)=>{const[r,i]=react_1.default.useState((0,fonts_1.isFontLoaded)(t));return react_1.default.useLayoutEffect((()=>{if((0,fonts_1.isFontLoaded)(t))return void i(!0);let n=!0;return(async()=>{r&&i(!1);const o=(0,loader_1.incrementLoader)(`text ${t}`);await e.loadFont(t),konva_1.default.Util.requestAnimFrame(o),n&&i(!0)})(),()=>{n=!1}}),[t]),[r]};exports.useFontLoader=useFontLoader;const getLineHeight=({fontLoaded:e,fontFamily:t,fontSize:r,lineHeight:i})=>react_1.default.useMemo((()=>{if("number"==typeof i)return i;const e=document.createElement("div");e.style.fontFamily=t,e.style.fontSize=r+"px",e.style.lineHeight=i,e.innerText="Test text",document.body.appendChild(e);const n=e.offsetHeight;return document.body.removeChild(e),n/r}),[e,t,r,i]);function getRelativePointerPosition(e){var t=e.getAbsoluteTransform().copy();t.invert();var r=e.getStage().getPointerPosition();return t.point(r)}function getCursorPosition(e){var t;const r=e.target,i=getRelativePointerPosition(r),n=r.textArr,o=Math.floor(i.y/(r.fontSize()*r.lineHeight())),a=n.slice(0,o).reduce(((e,t)=>e+t.text.length),o),l=null!==(t=n[o])&&void 0!==t?t:n[0];let s=0;"right"===r.align()?s=r.width()-l.width:"center"===r.align()&&(s=r.width()/2-l.width/2);return a+Math.round((i.x-s)/l.width*l.text.length)}function usePrevious(e){const t=react_1.default.useRef(e),r=react_1.default.useRef(e);return react_1.default.useEffect((()=>{r.current=t.current,t.current=e}),[e]),r.current}function findFitFontSize(e,t){const r=e.getAttrs(),i=(0,text_1.removeTags)(t.text);let n=t.fontSize;const o=Math.round(2*t.fontSize)-1;for(let r=1;r<o;r++){const r=t.height&&e.height()>t.height,o=i.split("\n").join(" ").split(" ");let a=e.textArr.map((e=>e.text)).join(";");const l=o.find((e=>!a.includes(e)||(a=a.replace(e,""),!1)));if(!(r||l))break;n-=.5,e.fontSize(n)}return e.fontSize(r.fontSize),n}function generateBackgroundShape({lines:e,lineHeight:t,width:r,align:i="left",padding:n=0,cornerRadius:o=0}){var a;e.forEach(((e,t)=>{e.cx=r/2,"right"===i?e.cx=r-e.width/2:"left"===i&&(e.cx=e.width/2),"justify"!==i||e.lastInParagraph||(e.width=r),"justify"===i&&(e.cx=e.width/2)}));let l=`M ${null===(a=e[0])||void 0===a?void 0:a.cx} ${-n}`;e.forEach(((r,i)=>{const{cx:o}=r,a=e[i-1];a&&a.width>r.width?l+=` L ${o+r.width/2+n} ${i*t+n}`:l+=` L ${o+r.width/2+n} ${i*t-n}`;const s=e[i+1];s&&s.width>r.width?l+=` L ${o+r.width/2+n} ${(i+1)*t-n}`:l+=` L ${o+r.width/2+n} ${(i+1)*t+n}`}));for(var s=e.length-1;s>=0;s--){const r=e[s],{cx:i}=r,o=e[s+1];o&&o.width>r.width?l+=` L ${i-r.width/2-n} ${(s+1)*t-n}`:l+=` L ${i-r.width/2-n} ${(s+1)*t+n}`;const a=e[s-1];a&&a.width>r.width?l+=` L ${i-r.width/2-n} ${s*t+n}`:l+=` L ${i-r.width/2-n} ${s*t-n}`}l+=" Z";const d=(0,svg_round_corners_1.parsePath)(l);return(0,svg_round_corners_1.roundCommands)(d,o).path}exports.getLineHeight=getLineHeight;const useTextColor=e=>react_1.default.useMemo((()=>{if(!gradient.isGradient(e.fill))return{fill:e.fill};const{stops:t,rotation:r}=gradient.parseColor(e.fill),i={x:e.width/2,y:e.height/2},n=Math.sqrt(Math.pow(i.x,2)+Math.pow(i.y,2)),o=konva_1.default.Util.degToRad(r)-Math.PI/2,a=[];return t.forEach((({offset:e,color:t})=>{a.push(e,t)})),{fillLinearGradientStartPointX:i.x-n*Math.cos(o),fillLinearGradientStartPointY:i.y-n*Math.sin(o),fillLinearGradientColorStops:a,fillLinearGradientEndPointX:i.x+n*Math.cos(o),fillLinearGradientEndPointY:i.y+n*Math.sin(o),fill:t[1].color,fillPriority:"linear-gradient"}}),[e.fill]);exports.useTextColor=useTextColor,exports.TextElement=(0,mobx_react_lite_1.observer)((({element:e,store:t})=>{const r=react_1.default.useRef(null),i=react_1.default.useRef(null),{editorEnabled:n,selectAll:o}=useEditor(e),[a,l]=react_1.default.useState(!1),[s,d]=react_1.default.useState(!1),c=react_1.default.useRef(e.height),u=t.selectedElements.indexOf(e)>=0,{textVerticalResizeEnabled:f}=flags_1.flags,h=usePrevious(e.fontFamily),[g,_]=react_1.default.useState([]);react_1.default.useEffect((()=>{var e,t;const i=null!==(t=null===(e=r.current)||void 0===e?void 0:e.textArr)&&void 0!==t?t:[];JSON.stringify(i)!==JSON.stringify(g)&&_(i)})),react_1.default.useEffect((()=>{if(e.width)return;const t=r.current;t.width(600),e.set({width:1.4*t.getTextWidth()})}),[]),react_1.default.useLayoutEffect((()=>(0,mobx_1.autorun)((()=>{const t=r.current;(0,apply_filters_1.applyFilter)(t,e)}))));const[p]=(0,exports.useFontLoader)(t,e.fontFamily),x=(0,text_1.removeTags)(e.text),y=()=>{const e=r.current.clone({height:void 0}),t=Math.ceil(e.fontSize()*e.lineHeight()*e.textArr.length+1);return e.destroy(),t};react_1.default.useLayoutEffect((()=>{if(!p)return;const{textOverflow:i}=flags_1.flags;if(e.height)if("change-font-size"!==i||s){if("resize"===i){const i=y();f&&e.height<i&&t.history.ignore((()=>{e.set({height:i}),r.current.height(i)})),f||e.height===i||t.history.ignore((()=>{e.set({height:i}),r.current.height(i)}))}}else{const i=findFitFontSize(r.current,e);if(i!==e.fontSize)return void t.history.ignore((()=>{e.set({fontSize:i})}));const n=y();e.height!==n&&t.history.ignore((()=>{e.set({height:n})}))}else{const r=y();t.history.ignore((()=>{e.set({height:r})}))}})),react_1.default.useLayoutEffect((()=>{const t=r.current;t&&(t.width(t.width()+1e-8),t._setTextData(),(0,apply_filters_1.applyFilter)(t,e))}),[p]);const m=react_1.default.useRef(null),v=react_1.default.useRef(0),w=r=>{r.evt.preventDefault();const i=t.selectedElements.find((t=>t===e));i&&e.contentEditable&&(v.current=getCursorPosition(r),e.toggleEditMode())},S=!x&&e.placeholder?.6:e.a.opacity;(0,use_fadein_1.useFadeIn)(r,S);const b=(0,exports.getLineHeight)({fontLoaded:p,fontFamily:e.fontFamily,fontSize:e.fontSize,lineHeight:e.lineHeight}),E=e.selectable||"admin"===t.role,T=(0,exports.useTextColor)(e),L=react_1.default.useMemo((()=>e.backgroundEnabled?generateBackgroundShape({lines:g,cornerRadius:e.backgroundCornerRadius*(e.fontSize*b*.5),lineHeight:b*e.fontSize,padding:e.backgroundPadding*(e.fontSize*b*.5),width:e.width,align:e.align}):""),[e.backgroundEnabled,e.backgroundCornerRadius,e.fontSize,b,e.backgroundPadding,e.width,e.align,g]),M=(0,screen_1.useMobile)();let k=0;return"middle"===e.verticalAlign?k=(e.height-g.length*b*e.fontSize)/2:"bottom"===e.verticalAlign&&(k=e.height-g.length*b*e.fontSize),react_1.default.createElement(react_1.default.Fragment,null,react_1.default.createElement(react_konva_1.Path,{ref:i,x:e.a.x,y:e.a.y,rotation:e.a.rotation,hideInExport:!e.showInExport||!x,listening:!1,visible:e.backgroundEnabled,opacity:e.backgroundOpacity,data:L,fill:e.backgroundColor,offsetY:-k}),react_1.default.createElement(react_konva_1.Text,Object.assign({ref:r,id:e.id,name:"element",hideInExport:!e.showInExport||!x,editModeEnabled:e._editModeEnabled,x:e.a.x,y:e.a.y,rotation:e.a.rotation,width:e.width,height:e.height,text:x||e.placeholder},T,{stroke:e.stroke,strokeWidth:e.strokeWidth,fillAfterStrokeEnabled:!0,fontSize:e.fontSize,fontFamily:`"${e.fontFamily}", "${h}"`,fontStyle:e.fontStyle+" "+e.fontWeight,textDecoration:e.textDecoration,align:e.align,verticalAlign:e.verticalAlign,draggable:M?e.draggable&&u:e.draggable,preventDefault:!M||u,opacity:S,visible:!e._editModeEnabled,ellipsis:"ellipsis"===flags_1.flags.textOverflow,shadowEnabled:e.shadowEnabled,shadowBlur:e.shadowBlur,shadowOffsetX:e.shadowOffsetX,shadowOffsetY:e.shadowOffsetY,shadowColor:e.shadowColor,shadowOpacity:e.shadowOpacity,lineHeight:b,letterSpacing:e.letterSpacing*e.fontSize,listening:E,onDragStart:()=>{t.history.startTransaction()},onDragMove:t=>{e.set({x:t.target.x(),y:t.target.y()})},onDragEnd:r=>{e.set({x:r.target.x(),y:r.target.y()}),t.history.endTransaction()},onMouseEnter:()=>{l(!0)},onMouseLeave:()=>{l(!1)},onClick:w,onTap:w,onTransformStart:()=>{d(!0),t.history.startTransaction(),c.current=r.current.height()},onTransform:t=>{var r,n;const o=t.target;null===(r=i.current)||void 0===r||r.setAttrs({x:o.x(),y:o.y(),rotation:o.rotation(),scale:o.scale()});const a=(null===(n=o.getStage())||void 0===n?void 0:n.findOne("Transformer")).getActiveAnchor();if("middle-left"===a||"middle-right"===a){const t=o.scaleX(),r=o.width()*t,i=e.fontSize;let n=r;r<i&&(n=i,m.current&&o.position(m.current)),o.width(n),o.scaleX(1),o.scaleY(1);const a=y();if("ellipsis"!==flags_1.flags.textOverflow){const t=Math.max(a,c.current);o.height(t),e.set({height:o.height()})}e.set({x:o.x(),y:o.y(),width:o.width(),rotation:o.rotation()}),(0,apply_filters_1.applyFilter)(o,e)}if("top-center"===a||"bottom-center"===a){let r="resize"===flags_1.flags.textOverflow?y():b*e.fontSize;t.target.height(Math.max(r,t.target.height()*t.target.scaleY())),t.target.scaleY(1)}t.target.strokeWidth(e.strokeWidth/t.target.scaleX()),m.current=t.target.position()},onTransformEnd:r=>{var n;d(!1);const o=r.target.scaleX();r.target.scaleX(1),r.target.scaleY(1),r.target.strokeWidth(e.strokeWidth),e.set({fontSize:Math.round(e.fontSize*o),width:Math.ceil(r.target.width()*o),x:r.target.x(),y:r.target.y(),rotation:r.target.rotation(),height:r.target.height()*o}),t.history.endTransaction(),null===(n=i.current)||void 0===n||n.setAttrs({scaleX:1,scaleY:1})}})),n&&react_1.default.createElement(react_konva_1.Group,{x:e.a.x,y:e.a.y,rotation:e.a.rotation},react_1.default.createElement(TextInput,{textNodeRef:r,element:e,selectAll:o,cursorPosition:v.current,onBlur:()=>{e.toggleEditMode(!1)}})),!s&&(a||u)&&react_1.default.createElement(highlighter_1.Highlighter,{element:e}))}));
|
package/model/store.d.ts
CHANGED
|
@@ -488,7 +488,6 @@ export declare const Store: import("mobx-state-tree").IModelType<{
|
|
|
488
488
|
saveAsHTML({ filename }?: {
|
|
489
489
|
filename?: string | undefined;
|
|
490
490
|
}): Promise<void>;
|
|
491
|
-
saveAsGIF(): Promise<void>;
|
|
492
491
|
saveAsPDF({ fileName, ...exportProps }?: ExportOptions & {
|
|
493
492
|
fileName?: string | undefined;
|
|
494
493
|
dpi?: number | undefined;
|
package/model/store.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,o,n){void 0===n&&(n=o);var a=Object.getOwnPropertyDescriptor(t,o);a&&!("get"in a?!t.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,n,a)}:function(e,t,o,n){void 0===n&&(n=o),e[n]=t[o]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var o in e)"default"!==o&&Object.prototype.hasOwnProperty.call(e,o)&&__createBinding(t,e,o);return __setModuleDefault(t,e),t},__rest=this&&this.__rest||function(e,t){var o={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(o[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var a=0;for(n=Object.getOwnPropertySymbols(e);a<n.length;a++)t.indexOf(n[a])<0&&Object.prototype.propertyIsEnumerable.call(e,n[a])&&(o[n[a]]=e[n[a]])}return o},__importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.createStore=exports.Store=exports.Font=exports.Page=exports.GroupElement=exports.registerShapeModel=exports.SVGElement=exports.LineElement=exports.VideoElement=exports.ImageElement=exports.TextElement=exports.Element=exports.Node=void 0;const mobx_state_tree_1=require("mobx-state-tree"),history_1=require("./history"),nanoid_1=require("nanoid"),konva_1=__importDefault(require("konva")),AnimatedGIF_1=__importDefault(require("gifshot/src/modules/core/AnimatedGIF")),getBase64GIF_1=__importDefault(require("gifshot/src/modules/core/getBase64GIF")),download_1=require("../utils/download"),pdf_1=require("../utils/pdf"),validate_key_1=require("../utils/validate-key"),fonts=__importStar(require("../utils/fonts")),loader_1=require("../utils/loader"),unit_1=require("../utils/unit"),deep_equal_1=require("../utils/deep-equal"),wait_1=require("../utils/wait"),html_1=require("../utils/html");(0,mobx_state_tree_1.setLivelinessChecking)("ignore");const forEveryChild=(e,t)=>{e.children&&e.children.forEach((e=>{t(e),forEveryChild(e,t)}))};exports.Node=mobx_state_tree_1.types.model("Node",{id:mobx_state_tree_1.types.identifier,type:"none",name:"",opacity:1,animations:mobx_state_tree_1.types.array(mobx_state_tree_1.types.frozen()),custom:mobx_state_tree_1.types.frozen(),visible:!0,selectable:!0,removable:!0,alwaysOnTop:!1,showInExport:!0}).postProcessSnapshot((e=>{const t=Object.assign({},e),o={};for(var n in t)"_"!==n[0]&&(o[n]=e[n]);return o})).views((e=>({get locked(){return!(e.draggable||e.contentEditable||e.styleEditable||e.resizable)},get page(){return(0,mobx_state_tree_1.getParentOfType)(e,exports.Page)},get store(){return(0,mobx_state_tree_1.getParentOfType)(e,exports.Store)},get top(){let t=e;for(;;){if(!(0,mobx_state_tree_1.hasParentOfType)(t,exports.GroupElement))return t;t=(0,mobx_state_tree_1.getParentOfType)(t,exports.GroupElement)}},get parent(){return(0,mobx_state_tree_1.hasParentOfType)(e,exports.GroupElement)?(0,mobx_state_tree_1.getParentOfType)(e,exports.GroupElement):(0,mobx_state_tree_1.hasParentOfType)(e,exports.Page)?(0,mobx_state_tree_1.getParentOfType)(e,exports.Page):(0,mobx_state_tree_1.hasParentOfType)(e,exports.Store)?(0,mobx_state_tree_1.getParentOfType)(e,exports.Store):null}}))).actions((e=>({toJSON:()=>Object.assign({},(0,mobx_state_tree_1.getSnapshot)(e))}))).actions((e=>({clone(t={}){const o=e.toJSON();return t.id=t.id||(0,nanoid_1.nanoid)(10),forEveryChild(o,(e=>{e.id=(0,nanoid_1.nanoid)(10)})),Object.assign(o,t),e.page.addElement(o)},set(t){Object.assign(e,t)},moveUp(){e.page.moveElementsUp([e.id])},moveTop(){e.page.moveElementsTop([e.id])},moveDown(){e.page.moveElementsDown([e.id])},moveBottom(){e.page.moveElementsBottom([e.id])},beforeDestroy(){e.store.history.endTransaction()}}))),exports.Element=exports.Node.named("Element").props({x:0,y:0,width:100,height:100,rotation:0,opacity:1,blurEnabled:!1,blurRadius:10,brightnessEnabled:!1,brightness:0,sepiaEnabled:!1,grayscaleEnabled:!1,shadowEnabled:!1,shadowBlur:5,shadowOffsetX:0,shadowOffsetY:0,shadowColor:"black",shadowOpacity:1,visible:!0,draggable:!0,resizable:!0,selectable:!0,contentEditable:!0,styleEditable:!0,alwaysOnTop:!1,showInExport:!0}).preProcessSnapshot((e=>{const t=Object.assign(Object.assign({},e),{x:e.x||0,y:e.y||0});return"width"in e&&(t.width=t.width||1),"height"in e&&(t.height=t.height||1),e.locked&&(t.draggable=!1,t.contentEditable=!1,t.styleEditable=!1,t.resizable=!1),t})).views((e=>({get a(){return e},animated:t=>e[t]}))),exports.TextElement=exports.Element.named("Text").props({type:"text",text:"",placeholder:"",fontSize:14,fontFamily:"Roboto",fontStyle:"normal",fontWeight:"normal",textDecoration:"",fill:"black",align:"center",width:100,height:0,verticalAlign:"top",strokeWidth:0,stroke:"black",lineHeight:mobx_state_tree_1.types.optional(mobx_state_tree_1.types.union(mobx_state_tree_1.types.number,mobx_state_tree_1.types.string),1.2),letterSpacing:0,_editModeEnabled:!1,backgroundEnabled:!1,backgroundColor:"#7ED321",backgroundOpacity:1,backgroundCornerRadius:.5,backgroundPadding:.5}).preProcessSnapshot((e=>Object.assign({},e))).actions((e=>({toggleEditMode(t){e._editModeEnabled=null!=t?t:!e._editModeEnabled,e._editModeEnabled?e.store.history.startTransaction():e.store.history.endTransaction()}}))),exports.ImageElement=exports.Element.named("Image").props({type:"image",width:100,height:100,src:"",cropX:0,cropY:0,cropWidth:1,cropHeight:1,cornerRadius:0,flipX:!1,flipY:!1,clipSrc:"",borderColor:"black",borderSize:0,keepRatio:!1,_cropModeEnabled:!1}).actions((e=>({toggleCropMode(t){e._cropModeEnabled=null!=t?t:!e._cropModeEnabled,e._cropModeEnabled?e.store.history.startTransaction():e.store.history.endTransaction()}}))),exports.VideoElement=exports.ImageElement.named("Video").props({type:"video",duration:0}),exports.LineElement=exports.Element.named("Line").props({type:"line",width:400,height:10,color:"black",dash:mobx_state_tree_1.types.array(mobx_state_tree_1.types.number),startHead:"",endHead:""}).actions((e=>({}))),exports.SVGElement=exports.Element.named("SVG").props({type:"svg",src:"",maskSrc:"",cropX:0,cropY:0,cropWidth:1,cropHeight:1,keepRatio:!0,flipX:!1,flipY:!1,width:100,height:100,borderColor:"black",borderSize:0,cornerRadius:0,colorsReplace:mobx_state_tree_1.types.map(mobx_state_tree_1.types.string)}).preProcessSnapshot((e=>Object.assign(Object.assign({},e),{src:e.src||e.svgSource}))).actions((e=>({replaceColor(t,o){e.colorsReplace.set(t,o)}})));const ADDITIONAL_TYPES=[];function registerShapeModel(e){const t=e.type;if(!t)throw new Error('You must pass "type" attribute to custom model.');const o=exports.Element.named(t).props(e);TYPES_MAP[t]=o,ADDITIONAL_TYPES.push(o)}exports.registerShapeModel=registerShapeModel;const additionalTypesUnion=[...new Array(20)].map(((e,t)=>mobx_state_tree_1.types.late((()=>ADDITIONAL_TYPES[t])))),ElementTypes=mobx_state_tree_1.types.union({dispatcher:e=>{const t=TYPES_MAP[e.type];if(!t)throw new Error(`Unknown element type: "${e.type}"`);return t}},exports.SVGElement,exports.TextElement,exports.ImageElement,exports.LineElement,exports.VideoElement,mobx_state_tree_1.types.late((()=>exports.GroupElement)),...additionalTypesUnion);exports.GroupElement=exports.Node.named("Group").props({type:"group",children:mobx_state_tree_1.types.array(ElementTypes)}).views((e=>({get draggable(){let t=!0;return forEveryChild(e,(e=>{e.draggable||(t=!1)})),t},get resizable(){let t=!0;return forEveryChild(e,(e=>{e.resizable||(t=!1)})),t},get contentEditable(){let t=!0;return forEveryChild(e,(e=>{e.contentEditable||(t=!1)})),t},get styleEditable(){let t=!0;return forEveryChild(e,(e=>{e.styleEditable||(t=!1)})),t},get locked(){let t=!0;return forEveryChild(e,(e=>{e.locked||(t=!1)})),t}}))).actions((e=>({set(t){var{draggable:o,contentEditable:n,styleEditable:a,resizable:i}=t,s=__rest(t,["draggable","contentEditable","styleEditable","resizable"]);void 0!==o&&forEveryChild(e,(e=>{e.set({draggable:o})})),void 0!==n&&forEveryChild(e,(e=>{e.set({contentEditable:n})})),void 0!==a&&forEveryChild(e,(e=>{e.set({styleEditable:a})})),void 0!==i&&forEveryChild(e,(e=>{e.set({resizable:i})})),Object.assign(e,s)}})));const TYPES_MAP={svg:exports.SVGElement,text:exports.TextElement,image:exports.ImageElement,group:exports.GroupElement,line:exports.LineElement,video:exports.VideoElement};function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){const o=exports.Store.create();return(0,validate_key_1.validateKey)(e,t),o}exports.Page=mobx_state_tree_1.types.model("Page",{id:mobx_state_tree_1.types.identifier,children:mobx_state_tree_1.types.array(ElementTypes),width:mobx_state_tree_1.types.optional(mobx_state_tree_1.types.union(mobx_state_tree_1.types.number,mobx_state_tree_1.types.literal("auto")),"auto"),height:mobx_state_tree_1.types.optional(mobx_state_tree_1.types.union(mobx_state_tree_1.types.number,mobx_state_tree_1.types.literal("auto")),"auto"),background:"white",bleed:0,custom:mobx_state_tree_1.types.frozen(),_exporting:!1}).postProcessSnapshot((e=>{const t=Object.assign({},e),o={};for(var n in t)"_"!==n[0]&&(o[n]=e[n]);return o})).views((e=>({get store(){return(0,mobx_state_tree_1.getParentOfType)(e,exports.Store)},get animatedChildren(){}}))).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((e=>({toJSON:()=>JSON.parse(JSON.stringify((0,mobx_state_tree_1.getSnapshot)(e))),_forEachElementUp(t,o){const n=t.map((t=>({id:t,index:e.children.findIndex((e=>e.id===t))})));n.sort(((e,t)=>t.index-e.index));for(const{index:a}of n){if(-1==a)continue;const n=a<e.children.length-1&&e.children[a+1],i=t.indexOf(null==n?void 0:n.id)>=0;a===e.children.length-1||i||o(a)}},_forEachElementDown(t,o){const n=t.map((t=>({id:t,index:e.children.findIndex((e=>e.id===t))})));n.sort(((e,t)=>e.index-t.index));for(const{index:a}of n){if(-1==a)continue;const n=a>0&&e.children[a-1],i=t.indexOf(null==n?void 0:n.id)>=0;0===a||i||o(a)}return!1}}))).actions((e=>({clone(t={}){const o=e.toJSON();o.children.forEach((e=>{e.id=(0,nanoid_1.nanoid)(10),forEveryChild(e,(e=>{e.id=(0,nanoid_1.nanoid)(10)}))}));const n=Object.assign(Object.assign(Object.assign({},o),{id:(0,nanoid_1.nanoid)(10)}),t),a=e.store.addPage(n),i=e.store.pages.indexOf(e);a.setZIndex(i+1),a.select()},setZIndex(t){e.store.setPageZIndex(e.id,t)},set(t){Object.assign(e,t)},select(){e.store.selectPage(e.id)},addElement(t){const o=TYPES_MAP[t.type];if(!o)return void console.error("Can not find model with type "+t.type);t.children&&t.children.forEach((e=>{e.id=(0,nanoid_1.nanoid)(10)}));const n=o.create(Object.assign({id:(0,nanoid_1.nanoid)(10)},t));return e.children.push(n),n.selectable&&e.store.selectElements([n.id]),n},canMoveElementsUp(t){let o=!1;return e._forEachElementUp(t,(()=>{o=o||!0})),o},moveElementsUp(t){e._forEachElementUp(t,(t=>{const o=e.children[t];(0,mobx_state_tree_1.detach)(o),e.children.splice(t+1,0,o)}))},canMoveElementsTop(e){return this.canMoveElementsUp(e)},moveElementsTop(t){const o=[],n=[];e.children.forEach((e=>{t.indexOf(e.id)>=0?o.push(e):n.push(e)})),e.children.replace(n.concat(o))},canMoveElementsDown(t){let o=!1;return e._forEachElementDown(t,(()=>{o=o||!0})),o},moveElementsDown(t){e._forEachElementDown(t,(t=>{const o=e.children[t];(0,mobx_state_tree_1.detach)(o),e.children.splice(t-1,0,o)}))},canMoveElementsBottom(e){return this.canMoveElementsDown(e)},moveElementsBottom(t){const o=[],n=[];e.children.forEach((e=>{t.indexOf(e.id)>=0?o.push(e):n.push(e)})),e.children.replace(o.concat(n))},setElementZIndex(t,o){const n=e.children.find((e=>e.id===t));n&&((0,mobx_state_tree_1.detach)(n),e.children.remove(n),e.children.splice(o,0,n))},setSize({width:t,height:o,useMagic:n,softChange:a}){if(n){const n=t/e.computedWidth,a=o/e.computedHeight;for(const t of e.children)t.set({x:t.x*n,y:t.y*a}),"text"===t.type?t.set({fontSize:t.fontSize*n,width:Math.max(t.width*n,2)}):"image"===t.type?t.set({width:t.width*n,height:t.height*a}):"svg"===t.type&&t.set({width:Math.max(t.width*n,2),height:Math.max(t.height*n,2)})}"auto"!==e.width||a||(e.width=t),"auto"!==e.height||a||(e.height=o)}}))).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])}}))),exports.Font=mobx_state_tree_1.types.model("Font",{fontFamily:mobx_state_tree_1.types.string,url:mobx_state_tree_1.types.optional(mobx_state_tree_1.types.string,""),styles:mobx_state_tree_1.types.frozen()}).preProcessSnapshot((e=>Object.assign(Object.assign({},e),{fontFamily:e.fontFamily||e.name}))),exports.Store=mobx_state_tree_1.types.model("Store",{role:"",pages:mobx_state_tree_1.types.array(exports.Page),fonts:mobx_state_tree_1.types.array(exports.Font),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:"px",dpi:72,bleedVisible:!1,rulesVisible:!1,openedSidePanel:"",selectedElementsIds:mobx_state_tree_1.types.array(mobx_state_tree_1.types.string),history:mobx_state_tree_1.types.optional(history_1.UndoManager,{targetPath:"../pages"}),_elementsPixelRatio:2,_activePageId:""}).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 o of e.pages)for(const e of o.children)if(e.id===t)return e})).filter((e=>!!e))},get children(){return e.pages},get selectedShapes(){const t=[];return e.selectedElementsIds.forEach((o=>{for(const n of e.pages)for(const e of n.children)e.id===o&&"group"!==e.type&&t.push(e),"group"===e.type&&e.id===o&&t.push(...e.children)})),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 forEveryChild(e,(e=>{"video"===e.type&&(t=Math.max(t,e.duration))})),t}}))).actions((e=>({afterCreate(){e.history.canUndo},setCurrentTime(t){e.currentTime=t},play(){e.currentTime=0,e.isPlaying=!0,requestAnimationFrame(e.seek)},seek(){e.currentTime+=1e3/60,e.isPlaying&&e.currentTime<e.duration?requestAnimationFrame(e.seek):e.stop()},stop(){e.isPlaying=!1,e.currentTime=0},setUnit({unit:t,dpi:o}){e.unit=t||e.unit,e.dpi=o||e.dpi},setRole(t){e.role=t},find(t){let o;return forEveryChild({children:e.pages},(e=>{!o&&t(e)&&(o=e)})),o},getElementById:t=>e.find((e=>e.id===t)),addPage(t){const o=exports.Page.create(Object.assign({id:(0,nanoid_1.nanoid)(10)},t));return e.pages.push(o),e._activePageId=o.id,o},selectPage(t){e._activePageId=t},selectElements(t){const o=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,mobx_state_tree_1.cast)(o)},toggleBleed(t){e.bleedVisible=null!=t?t:!e.bleedVisible},toggleRulers(t){e.rulesVisible=null!=t?t:!e.rulesVisible},openSidePanel(t){e.openedSidePanel=t},setScale(t){e.scale=t},_setScaleToFit(t){e.scaleToFit=t},setElementsPixelRatio(t){e._elementsPixelRatio=t},setSize(t,o,n){e.pages.forEach((e=>{e.setSize({width:t,height:o,useMagic:n,softChange:!0})})),e.width=t,e.height=o},setPageZIndex(t,o){const n=e.pages.find((e=>e.id===t));n&&((0,mobx_state_tree_1.detach)(n),e.pages.remove(n),e.pages.splice(o,0,n))},deletePages(t){const o=e.pages.indexOf(e.activePage);t.forEach((t=>{const o=e.pages.find((e=>e.id===t));(0,mobx_state_tree_1.destroy)(o)}));const n=Math.min(e.pages.length-1,o),a=e.pages[n];a&&(e._activePageId=a.id),e.selectedElementsIds=(0,mobx_state_tree_1.cast)(e.selectedElementsIds.filter((t=>e.getElementById(t))))},groupElements(t){const o=t.map((t=>e.getElementById(t)));o.forEach((e=>{e&&(0,mobx_state_tree_1.detach)(e)}));const n=e.activePage,a=exports.GroupElement.create({id:(0,nanoid_1.nanoid)(10),children:(0,mobx_state_tree_1.cast)(o)});return n.children.push(a),e.selectedElementsIds=(0,mobx_state_tree_1.cast)([a.id]),a},ungroupElements(t){const o=t.map((t=>e.getElementById(t))),n=[];o.forEach((e=>{if(e&&"group"===e.type){const t=e.page,o=t.children.indexOf(e);e.children.forEach((e=>{n.push(e.id)})),e.children.forEach((e=>{(0,mobx_state_tree_1.detach)(e),t.children.push(e)})),t.children.splice(o,1)}})),e.selectedElementsIds=(0,mobx_state_tree_1.cast)(n)},deleteElements(t){t.forEach((t=>{e.pages.forEach((e=>{const o=e.children.find((e=>e.id===t));o&&(0,mobx_state_tree_1.destroy)(o)}))})),e.selectedElementsIds=(0,mobx_state_tree_1.cast)(e.selectedElementsIds.filter((t=>e.getElementById(t))))},on(t,o){if("change"===t){let t=e.toJSON();return(0,mobx_state_tree_1.onSnapshot)(e,(n=>{const a=e.toJSON();!(0,deep_equal_1.deepEqual)(t,a)&&(t=a,o(a))}))}},async _toCanvas({pixelRatio:t,ignoreBackground:o,pageId:n,mimeType:a,includeBleed:i}={}){var s;const r=t||1;n=n||(null===(s=e.pages[0])||void 0===s?void 0:s.id);const l=e.pages.find((e=>e.id===n));if(!l)throw new Error(`No page for export with id ${n}`);null==l||l.set({_exporting:!0});const d=await(0,wait_1.waitTillAvailable)((()=>konva_1.default.stages.find((e=>e.getAttr("pageId")===n))));if(!d)throw new Error(`Export is failed. Can not find stage for page ${n}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`);await e.waitLoading();const c=d.findOne(".page-container");d.find("Transformer").forEach((e=>e.visible(!1))),c.find(".page-background").forEach((e=>e.shadowEnabled(!1))),c.find(".page-background").forEach((e=>e.strokeEnabled(!1))),c.find(".highlighter").forEach((e=>e.visible(!1)));const p=c.findOne(".page-background-group"),m=p.clip();p.clip({x:null,y:null,width:null,height:null});const _=c.findOne(".elements-container"),g=_.clip();_.clip({x:null,y:null,width:null,height:null});const h=c.find((e=>e.getAttr("hideInExport")));h.forEach((e=>{e.setAttr("oldVisible",e.visible()),e.hide()}));const u=c.find((e=>!e.visible()&&e.getAttr("editModeEnabled")));u.forEach((e=>{e.setAttr("oldVisible",e.visible()),e.show()})),o&&c.find(".page-background").forEach((e=>e.hide()));const b=i?l.bleed:0;let f=b;e.bleedVisible&&i?f=0:e.bleedVisible&&!i&&(f=-l.bleed);const x=document.createElement("canvas");x.width=(l.computedWidth+2*b)*r,x.height=(l.computedHeight+2*b)*r;const y=x.getContext("2d");"image/jpeg"===a&&(y.fillStyle="white",y.fillRect(0,0,x.width,x.height));const E=c.toCanvas({x:c.x()-f*c.scaleX(),y:c.y()-f*c.scaleY(),width:(l.computedWidth+2*b)*c.scaleX(),height:(l.computedHeight+2*b)*c.scaleY(),pixelRatio:1/c.scaleX()*r});return y.drawImage(E,0,0),konva_1.default.Util.releaseCanvas(E),o&&c.find(".page-background").forEach((e=>e.show())),h.forEach((e=>{e.visible(e.getAttr("oldVisible"))})),u.forEach((e=>{e.visible(e.getAttr("oldVisible"))})),c.find(".page-background").forEach((e=>e.shadowEnabled(!0))),c.find(".page-background").forEach((e=>e.strokeEnabled(!0))),d.find("Transformer").forEach((e=>e.visible(!0))),c.find(".highlighter").forEach((e=>e.visible(!0))),p.clip(m),_.clip(g),null==l||l.set({_exporting:!1}),x},async toDataURL({pixelRatio:t,ignoreBackground:o,pageId:n,mimeType:a,includeBleed:i,quality:s}={}){const r=await e._toCanvas({pixelRatio:t,ignoreBackground:o,pageId:n,mimeType:a,includeBleed:i}),l=r.toDataURL(a,s);return konva_1.default.Util.releaseCanvas(r),l},async toBlob({pixelRatio:t,ignoreBackground:o,pageId:n,mimeType:a,includeBleed:i,quality:s}={}){const r=await e._toCanvas({pixelRatio:t,ignoreBackground:o,pageId:n,mimeType:a,includeBleed:i}),l=new Promise((e=>{r.toBlob(e,a,s)}));return konva_1.default.Util.releaseCanvas(r),l},async saveAsImage(t={}){var{fileName:o}=t,n=__rest(t,["fileName"]);const a=n.mimeType||"image/png",i=a.split("/")[1];(0,download_1.downloadFile)(await e.toDataURL(n),o||"polotno."+i,a)},async _toPDF(t){const o=t.dpi||e.dpi,n=t.parallel||1,a=t.unit||("px"===e.unit?"mm":e.unit),i=t.pixelRatio||1,s=t.pageIds||e.pages.map((e=>e.id)),r=e.pages.filter((e=>s.includes(e.id))),l=await(0,pdf_1.getJsPDF)(),d=e=>(0,unit_1.pxToUnit)({px:e,unit:a,dpi:o}),c=r[0]||{},p=t.includeBleed?c.bleed:0,m=d(c.computedWidth+2*p),_=d(c.computedHeight+2*p);var g=new l({unit:a,orientation:m>_?"landscape":"portrait",format:[m,_],compress:!0,putOnlyUsedFonts:!0});g.deletePage(1);const h=e._elementsPixelRatio;e.setElementsPixelRatio(i),await new Promise((e=>setTimeout(e)));const u=((e,t)=>{for(var o=[],n=0;n<e.length;n+=t)o.push(e.slice(n,n+t));return o})(r,n);for(const o of u){const n=o.map((async o=>{const n=t.includeBleed?o.bleed:0,a=d(o.computedWidth+2*n),s=d(o.computedHeight+2*n);let r=0,l=i;for(;r<10;){r+=1,2===r&&console.error("Polotno can not export PDF with current settings. Quality is automatically reduced.");const n=await e.toDataURL(Object.assign(Object.assign({},t),{pageId:o.id,pixelRatio:l}));if(n.length>20)return{url:n,width:a,height:s};l*=.8}}));(await Promise.all(n)).forEach((({url:e,width:t,height:o})=>{g.addPage([t,o],t>o?"landscape":"portrait"),g.addImage(e,0,0,t,o,void 0,"FAST")}))}return e.setElementsPixelRatio(h),g},toPDFDataURL:async t=>(await e._toPDF(Object.assign({mimeType:"image/jpeg"},t))).output("datauristring"),async toHTML(){const t=e.toJSON();return(0,html_1.jsonToHTML)({json:t})},async saveAsHTML({filename:t}={}){const o=await e.toHTML(),n="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(o)));(0,download_1.downloadFile)(n,t||"polotno.html")},async saveAsGIF(){const t=new AnimatedGIF_1.default({numWorkers:1,gifWidth:e.width,gifHeight:e.height});for(let o=0;o<3;o++){e.setCurrentTime(1*o);const n=await e._toCanvas();t.addFrame(n)}const o=await new Promise((e=>{console.log(1),(0,getBase64GIF_1.default)(t,(t=>{console.log(2),e(t)}))}));(0,download_1.downloadFile)(o,"polotno.gif")},async saveAsPDF(t={}){var{fileName:o}=t,n=__rest(t,["fileName"]);(await e._toPDF(Object.assign({mimeType:"image/jpeg"},n))).save(o||"polotno.pdf")},async waitLoading(){await new Promise((e=>setTimeout(e,50))),await(0,loader_1.whenLoaded)()},toJSON:()=>({width:e.width,height:e.height,fonts:(0,mobx_state_tree_1.getSnapshot)(e.fonts),pages:(0,mobx_state_tree_1.getSnapshot)(e.pages),unit:e.unit,dpi:e.dpi}),loadJSON(t,o=!1){var n;const a=Object.assign({},t),i=e.pages.indexOf(e.activePage);let s=null===(n=a.pages[i]||a.pages[0])||void 0===n?void 0:n.id;a._activePageId=s;const r=Object.assign({},(0,mobx_state_tree_1.getSnapshot)(e));Object.assign(r,a),r.history=o?e.history.toJSON():{history:[],undoIdx:-1},(0,mobx_state_tree_1.applySnapshot)(e,r)},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,mobx_state_tree_1.destroy)(e)))},async loadFont(t){const o=e.fonts.find((e=>e.fontFamily===t))||fonts.globalFonts.find((e=>e.fontFamily===t));o?fonts.injectCustomFont(o):fonts.injectGoogleFont(t),await fonts.loadFont(t)}}))),exports.createStore=createStore,exports.default=createStore;
|
|
1
|
+
"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,o,n){void 0===n&&(n=o);var a=Object.getOwnPropertyDescriptor(t,o);a&&!("get"in a?!t.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,n,a)}:function(e,t,o,n){void 0===n&&(n=o),e[n]=t[o]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var o in e)"default"!==o&&Object.prototype.hasOwnProperty.call(e,o)&&__createBinding(t,e,o);return __setModuleDefault(t,e),t},__rest=this&&this.__rest||function(e,t){var o={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(o[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var a=0;for(n=Object.getOwnPropertySymbols(e);a<n.length;a++)t.indexOf(n[a])<0&&Object.prototype.propertyIsEnumerable.call(e,n[a])&&(o[n[a]]=e[n[a]])}return o},__importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.createStore=exports.Store=exports.Font=exports.Page=exports.GroupElement=exports.registerShapeModel=exports.SVGElement=exports.LineElement=exports.VideoElement=exports.ImageElement=exports.TextElement=exports.Element=exports.Node=void 0;const mobx_state_tree_1=require("mobx-state-tree"),history_1=require("./history"),nanoid_1=require("nanoid"),konva_1=__importDefault(require("konva")),download_1=require("../utils/download"),pdf_1=require("../utils/pdf"),validate_key_1=require("../utils/validate-key"),fonts=__importStar(require("../utils/fonts")),loader_1=require("../utils/loader"),unit_1=require("../utils/unit"),deep_equal_1=require("../utils/deep-equal"),wait_1=require("../utils/wait"),html_1=require("../utils/html");(0,mobx_state_tree_1.setLivelinessChecking)("ignore");const forEveryChild=(e,t)=>{e.children&&e.children.forEach((e=>{t(e),forEveryChild(e,t)}))};exports.Node=mobx_state_tree_1.types.model("Node",{id:mobx_state_tree_1.types.identifier,type:"none",name:"",opacity:1,animations:mobx_state_tree_1.types.array(mobx_state_tree_1.types.frozen()),custom:mobx_state_tree_1.types.frozen(),visible:!0,selectable:!0,removable:!0,alwaysOnTop:!1,showInExport:!0}).postProcessSnapshot((e=>{const t=Object.assign({},e),o={};for(var n in t)"_"!==n[0]&&(o[n]=e[n]);return o})).views((e=>({get locked(){return!(e.draggable||e.contentEditable||e.styleEditable||e.resizable)},get page(){return(0,mobx_state_tree_1.getParentOfType)(e,exports.Page)},get store(){return(0,mobx_state_tree_1.getParentOfType)(e,exports.Store)},get top(){let t=e;for(;;){if(!(0,mobx_state_tree_1.hasParentOfType)(t,exports.GroupElement))return t;t=(0,mobx_state_tree_1.getParentOfType)(t,exports.GroupElement)}},get parent(){return(0,mobx_state_tree_1.hasParentOfType)(e,exports.GroupElement)?(0,mobx_state_tree_1.getParentOfType)(e,exports.GroupElement):(0,mobx_state_tree_1.hasParentOfType)(e,exports.Page)?(0,mobx_state_tree_1.getParentOfType)(e,exports.Page):(0,mobx_state_tree_1.hasParentOfType)(e,exports.Store)?(0,mobx_state_tree_1.getParentOfType)(e,exports.Store):null}}))).actions((e=>({toJSON:()=>Object.assign({},(0,mobx_state_tree_1.getSnapshot)(e))}))).actions((e=>({clone(t={}){const o=e.toJSON();return t.id=t.id||(0,nanoid_1.nanoid)(10),forEveryChild(o,(e=>{e.id=(0,nanoid_1.nanoid)(10)})),Object.assign(o,t),e.page.addElement(o)},set(t){Object.assign(e,t)},moveUp(){e.page.moveElementsUp([e.id])},moveTop(){e.page.moveElementsTop([e.id])},moveDown(){e.page.moveElementsDown([e.id])},moveBottom(){e.page.moveElementsBottom([e.id])},beforeDestroy(){e.store.history.endTransaction()}}))),exports.Element=exports.Node.named("Element").props({x:0,y:0,width:100,height:100,rotation:0,opacity:1,blurEnabled:!1,blurRadius:10,brightnessEnabled:!1,brightness:0,sepiaEnabled:!1,grayscaleEnabled:!1,shadowEnabled:!1,shadowBlur:5,shadowOffsetX:0,shadowOffsetY:0,shadowColor:"black",shadowOpacity:1,visible:!0,draggable:!0,resizable:!0,selectable:!0,contentEditable:!0,styleEditable:!0,alwaysOnTop:!1,showInExport:!0}).preProcessSnapshot((e=>{const t=Object.assign(Object.assign({},e),{x:e.x||0,y:e.y||0});return"width"in e&&(t.width=t.width||1),"height"in e&&(t.height=t.height||1),e.locked&&(t.draggable=!1,t.contentEditable=!1,t.styleEditable=!1,t.resizable=!1),t})).views((e=>({get a(){return e},animated:t=>e[t]}))),exports.TextElement=exports.Element.named("Text").props({type:"text",text:"",placeholder:"",fontSize:14,fontFamily:"Roboto",fontStyle:"normal",fontWeight:"normal",textDecoration:"",fill:"black",align:"center",width:100,height:0,verticalAlign:"top",strokeWidth:0,stroke:"black",lineHeight:mobx_state_tree_1.types.optional(mobx_state_tree_1.types.union(mobx_state_tree_1.types.number,mobx_state_tree_1.types.string),1.2),letterSpacing:0,_editModeEnabled:!1,backgroundEnabled:!1,backgroundColor:"#7ED321",backgroundOpacity:1,backgroundCornerRadius:.5,backgroundPadding:.5}).preProcessSnapshot((e=>Object.assign({},e))).actions((e=>({toggleEditMode(t){e._editModeEnabled=null!=t?t:!e._editModeEnabled,e._editModeEnabled?e.store.history.startTransaction():e.store.history.endTransaction()}}))),exports.ImageElement=exports.Element.named("Image").props({type:"image",width:100,height:100,src:"",cropX:0,cropY:0,cropWidth:1,cropHeight:1,cornerRadius:0,flipX:!1,flipY:!1,clipSrc:"",borderColor:"black",borderSize:0,keepRatio:!1,_cropModeEnabled:!1}).actions((e=>({toggleCropMode(t){e._cropModeEnabled=null!=t?t:!e._cropModeEnabled,e._cropModeEnabled?e.store.history.startTransaction():e.store.history.endTransaction()}}))),exports.VideoElement=exports.ImageElement.named("Video").props({type:"video",duration:0}),exports.LineElement=exports.Element.named("Line").props({type:"line",width:400,height:10,color:"black",dash:mobx_state_tree_1.types.array(mobx_state_tree_1.types.number),startHead:"",endHead:""}).actions((e=>({}))),exports.SVGElement=exports.Element.named("SVG").props({type:"svg",src:"",maskSrc:"",cropX:0,cropY:0,cropWidth:1,cropHeight:1,keepRatio:!0,flipX:!1,flipY:!1,width:100,height:100,borderColor:"black",borderSize:0,cornerRadius:0,colorsReplace:mobx_state_tree_1.types.map(mobx_state_tree_1.types.string)}).preProcessSnapshot((e=>Object.assign(Object.assign({},e),{src:e.src||e.svgSource}))).actions((e=>({replaceColor(t,o){e.colorsReplace.set(t,o)}})));const ADDITIONAL_TYPES=[];function registerShapeModel(e){const t=e.type;if(!t)throw new Error('You must pass "type" attribute to custom model.');const o=exports.Element.named(t).props(e);TYPES_MAP[t]=o,ADDITIONAL_TYPES.push(o)}exports.registerShapeModel=registerShapeModel;const additionalTypesUnion=[...new Array(20)].map(((e,t)=>mobx_state_tree_1.types.late((()=>ADDITIONAL_TYPES[t])))),ElementTypes=mobx_state_tree_1.types.union({dispatcher:e=>{const t=TYPES_MAP[e.type];if(!t)throw new Error(`Unknown element type: "${e.type}"`);return t}},exports.SVGElement,exports.TextElement,exports.ImageElement,exports.LineElement,exports.VideoElement,mobx_state_tree_1.types.late((()=>exports.GroupElement)),...additionalTypesUnion);exports.GroupElement=exports.Node.named("Group").props({type:"group",children:mobx_state_tree_1.types.array(ElementTypes)}).views((e=>({get draggable(){let t=!0;return forEveryChild(e,(e=>{e.draggable||(t=!1)})),t},get resizable(){let t=!0;return forEveryChild(e,(e=>{e.resizable||(t=!1)})),t},get contentEditable(){let t=!0;return forEveryChild(e,(e=>{e.contentEditable||(t=!1)})),t},get styleEditable(){let t=!0;return forEveryChild(e,(e=>{e.styleEditable||(t=!1)})),t},get locked(){let t=!0;return forEveryChild(e,(e=>{e.locked||(t=!1)})),t}}))).actions((e=>({set(t){var{draggable:o,contentEditable:n,styleEditable:a,resizable:i}=t,s=__rest(t,["draggable","contentEditable","styleEditable","resizable"]);void 0!==o&&forEveryChild(e,(e=>{e.set({draggable:o})})),void 0!==n&&forEveryChild(e,(e=>{e.set({contentEditable:n})})),void 0!==a&&forEveryChild(e,(e=>{e.set({styleEditable:a})})),void 0!==i&&forEveryChild(e,(e=>{e.set({resizable:i})})),Object.assign(e,s)}})));const TYPES_MAP={svg:exports.SVGElement,text:exports.TextElement,image:exports.ImageElement,group:exports.GroupElement,line:exports.LineElement,video:exports.VideoElement};function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){const o=exports.Store.create();return(0,validate_key_1.validateKey)(e,t),o}exports.Page=mobx_state_tree_1.types.model("Page",{id:mobx_state_tree_1.types.identifier,children:mobx_state_tree_1.types.array(ElementTypes),width:mobx_state_tree_1.types.optional(mobx_state_tree_1.types.union(mobx_state_tree_1.types.number,mobx_state_tree_1.types.literal("auto")),"auto"),height:mobx_state_tree_1.types.optional(mobx_state_tree_1.types.union(mobx_state_tree_1.types.number,mobx_state_tree_1.types.literal("auto")),"auto"),background:"white",bleed:0,custom:mobx_state_tree_1.types.frozen(),_exporting:!1}).postProcessSnapshot((e=>{const t=Object.assign({},e),o={};for(var n in t)"_"!==n[0]&&(o[n]=e[n]);return o})).views((e=>({get store(){return(0,mobx_state_tree_1.getParentOfType)(e,exports.Store)},get animatedChildren(){}}))).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((e=>({toJSON:()=>JSON.parse(JSON.stringify((0,mobx_state_tree_1.getSnapshot)(e))),_forEachElementUp(t,o){const n=t.map((t=>({id:t,index:e.children.findIndex((e=>e.id===t))})));n.sort(((e,t)=>t.index-e.index));for(const{index:a}of n){if(-1==a)continue;const n=a<e.children.length-1&&e.children[a+1],i=t.indexOf(null==n?void 0:n.id)>=0;a===e.children.length-1||i||o(a)}},_forEachElementDown(t,o){const n=t.map((t=>({id:t,index:e.children.findIndex((e=>e.id===t))})));n.sort(((e,t)=>e.index-t.index));for(const{index:a}of n){if(-1==a)continue;const n=a>0&&e.children[a-1],i=t.indexOf(null==n?void 0:n.id)>=0;0===a||i||o(a)}return!1}}))).actions((e=>({clone(t={}){const o=e.toJSON();o.children.forEach((e=>{e.id=(0,nanoid_1.nanoid)(10),forEveryChild(e,(e=>{e.id=(0,nanoid_1.nanoid)(10)}))}));const n=Object.assign(Object.assign(Object.assign({},o),{id:(0,nanoid_1.nanoid)(10)}),t),a=e.store.addPage(n),i=e.store.pages.indexOf(e);a.setZIndex(i+1),a.select()},setZIndex(t){e.store.setPageZIndex(e.id,t)},set(t){Object.assign(e,t)},select(){e.store.selectPage(e.id)},addElement(t){const o=TYPES_MAP[t.type];if(!o)return void console.error("Can not find model with type "+t.type);t.children&&t.children.forEach((e=>{e.id=(0,nanoid_1.nanoid)(10)}));const n=o.create(Object.assign({id:(0,nanoid_1.nanoid)(10)},t));return e.children.push(n),n.selectable&&e.store.selectElements([n.id]),n},canMoveElementsUp(t){let o=!1;return e._forEachElementUp(t,(()=>{o=o||!0})),o},moveElementsUp(t){e._forEachElementUp(t,(t=>{const o=e.children[t];(0,mobx_state_tree_1.detach)(o),e.children.splice(t+1,0,o)}))},canMoveElementsTop(e){return this.canMoveElementsUp(e)},moveElementsTop(t){const o=[],n=[];e.children.forEach((e=>{t.indexOf(e.id)>=0?o.push(e):n.push(e)})),e.children.replace(n.concat(o))},canMoveElementsDown(t){let o=!1;return e._forEachElementDown(t,(()=>{o=o||!0})),o},moveElementsDown(t){e._forEachElementDown(t,(t=>{const o=e.children[t];(0,mobx_state_tree_1.detach)(o),e.children.splice(t-1,0,o)}))},canMoveElementsBottom(e){return this.canMoveElementsDown(e)},moveElementsBottom(t){const o=[],n=[];e.children.forEach((e=>{t.indexOf(e.id)>=0?o.push(e):n.push(e)})),e.children.replace(o.concat(n))},setElementZIndex(t,o){const n=e.children.find((e=>e.id===t));n&&((0,mobx_state_tree_1.detach)(n),e.children.remove(n),e.children.splice(o,0,n))},setSize({width:t,height:o,useMagic:n,softChange:a}){if(n){const n=t/e.computedWidth,a=o/e.computedHeight;for(const t of e.children)t.set({x:t.x*n,y:t.y*a}),"text"===t.type?t.set({fontSize:t.fontSize*n,width:Math.max(t.width*n,2)}):"image"===t.type?t.set({width:t.width*n,height:t.height*a}):"svg"===t.type&&t.set({width:Math.max(t.width*n,2),height:Math.max(t.height*n,2)})}"auto"!==e.width||a||(e.width=t),"auto"!==e.height||a||(e.height=o)}}))).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])}}))),exports.Font=mobx_state_tree_1.types.model("Font",{fontFamily:mobx_state_tree_1.types.string,url:mobx_state_tree_1.types.optional(mobx_state_tree_1.types.string,""),styles:mobx_state_tree_1.types.frozen()}).preProcessSnapshot((e=>Object.assign(Object.assign({},e),{fontFamily:e.fontFamily||e.name}))),exports.Store=mobx_state_tree_1.types.model("Store",{role:"",pages:mobx_state_tree_1.types.array(exports.Page),fonts:mobx_state_tree_1.types.array(exports.Font),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:"px",dpi:72,bleedVisible:!1,rulesVisible:!1,openedSidePanel:"",selectedElementsIds:mobx_state_tree_1.types.array(mobx_state_tree_1.types.string),history:mobx_state_tree_1.types.optional(history_1.UndoManager,{targetPath:"../pages"}),_elementsPixelRatio:2,_activePageId:""}).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 o of e.pages)for(const e of o.children)if(e.id===t)return e})).filter((e=>!!e))},get children(){return e.pages},get selectedShapes(){const t=[];return e.selectedElementsIds.forEach((o=>{for(const n of e.pages)for(const e of n.children)e.id===o&&"group"!==e.type&&t.push(e),"group"===e.type&&e.id===o&&t.push(...e.children)})),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 forEveryChild(e,(e=>{"video"===e.type&&(t=Math.max(t,e.duration))})),t}}))).actions((e=>({afterCreate(){e.history.canUndo},setCurrentTime(t){e.currentTime=t},play(){e.currentTime=0,e.isPlaying=!0,requestAnimationFrame(e.seek)},seek(){e.currentTime+=1e3/60,e.isPlaying&&e.currentTime<e.duration?requestAnimationFrame(e.seek):e.stop()},stop(){e.isPlaying=!1,e.currentTime=0},setUnit({unit:t,dpi:o}){e.unit=t||e.unit,e.dpi=o||e.dpi},setRole(t){e.role=t},find(t){let o;return forEveryChild({children:e.pages},(e=>{!o&&t(e)&&(o=e)})),o},getElementById:t=>e.find((e=>e.id===t)),addPage(t){const o=exports.Page.create(Object.assign({id:(0,nanoid_1.nanoid)(10)},t));return e.pages.push(o),e._activePageId=o.id,o},selectPage(t){e._activePageId=t},selectElements(t){const o=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,mobx_state_tree_1.cast)(o)},toggleBleed(t){e.bleedVisible=null!=t?t:!e.bleedVisible},toggleRulers(t){e.rulesVisible=null!=t?t:!e.rulesVisible},openSidePanel(t){e.openedSidePanel=t},setScale(t){e.scale=t},_setScaleToFit(t){e.scaleToFit=t},setElementsPixelRatio(t){e._elementsPixelRatio=t},setSize(t,o,n){e.pages.forEach((e=>{e.setSize({width:t,height:o,useMagic:n,softChange:!0})})),e.width=t,e.height=o},setPageZIndex(t,o){const n=e.pages.find((e=>e.id===t));n&&((0,mobx_state_tree_1.detach)(n),e.pages.remove(n),e.pages.splice(o,0,n))},deletePages(t){const o=e.pages.indexOf(e.activePage);t.forEach((t=>{const o=e.pages.find((e=>e.id===t));(0,mobx_state_tree_1.destroy)(o)}));const n=Math.min(e.pages.length-1,o),a=e.pages[n];a&&(e._activePageId=a.id),e.selectedElementsIds=(0,mobx_state_tree_1.cast)(e.selectedElementsIds.filter((t=>e.getElementById(t))))},groupElements(t){const o=t.map((t=>e.getElementById(t)));o.forEach((e=>{e&&(0,mobx_state_tree_1.detach)(e)}));const n=e.activePage,a=exports.GroupElement.create({id:(0,nanoid_1.nanoid)(10),children:(0,mobx_state_tree_1.cast)(o)});return n.children.push(a),e.selectedElementsIds=(0,mobx_state_tree_1.cast)([a.id]),a},ungroupElements(t){const o=t.map((t=>e.getElementById(t))),n=[];o.forEach((e=>{if(e&&"group"===e.type){const t=e.page,o=t.children.indexOf(e);e.children.forEach((e=>{n.push(e.id)})),e.children.forEach((e=>{(0,mobx_state_tree_1.detach)(e),t.children.push(e)})),t.children.splice(o,1)}})),e.selectedElementsIds=(0,mobx_state_tree_1.cast)(n)},deleteElements(t){t.forEach((t=>{e.pages.forEach((e=>{const o=e.children.find((e=>e.id===t));o&&(0,mobx_state_tree_1.destroy)(o)}))})),e.selectedElementsIds=(0,mobx_state_tree_1.cast)(e.selectedElementsIds.filter((t=>e.getElementById(t))))},on(t,o){if("change"===t){let t=e.toJSON();return(0,mobx_state_tree_1.onSnapshot)(e,(n=>{const a=e.toJSON();!(0,deep_equal_1.deepEqual)(t,a)&&(t=a,o(a))}))}},async _toCanvas({pixelRatio:t,ignoreBackground:o,pageId:n,mimeType:a,includeBleed:i}={}){var s;const r=t||1;n=n||(null===(s=e.pages[0])||void 0===s?void 0:s.id);const l=e.pages.find((e=>e.id===n));if(!l)throw new Error(`No page for export with id ${n}`);null==l||l.set({_exporting:!0});const d=await(0,wait_1.waitTillAvailable)((()=>konva_1.default.stages.find((e=>e.getAttr("pageId")===n))));if(!d)throw new Error(`Export is failed. Can not find stage for page ${n}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`);await e.waitLoading();const p=d.findOne(".page-container");d.find("Transformer").forEach((e=>e.visible(!1))),p.find(".page-background").forEach((e=>e.shadowEnabled(!1))),p.find(".page-background").forEach((e=>e.strokeEnabled(!1))),p.find(".highlighter").forEach((e=>e.visible(!1)));const c=p.findOne(".page-background-group"),m=c.clip();c.clip({x:null,y:null,width:null,height:null});const _=p.findOne(".elements-container"),g=_.clip();_.clip({x:null,y:null,width:null,height:null});const h=p.find((e=>e.getAttr("hideInExport")));h.forEach((e=>{e.setAttr("oldVisible",e.visible()),e.hide()}));const u=p.find((e=>!e.visible()&&e.getAttr("editModeEnabled")));u.forEach((e=>{e.setAttr("oldVisible",e.visible()),e.show()})),o&&p.find(".page-background").forEach((e=>e.hide()));const b=i?l.bleed:0;let f=b;e.bleedVisible&&i?f=0:e.bleedVisible&&!i&&(f=-l.bleed);const x=document.createElement("canvas");x.width=(l.computedWidth+2*b)*r,x.height=(l.computedHeight+2*b)*r;const y=x.getContext("2d");"image/jpeg"===a&&(y.fillStyle="white",y.fillRect(0,0,x.width,x.height));const E=p.toCanvas({x:p.x()-f*p.scaleX(),y:p.y()-f*p.scaleY(),width:(l.computedWidth+2*b)*p.scaleX(),height:(l.computedHeight+2*b)*p.scaleY(),pixelRatio:1/p.scaleX()*r});return y.drawImage(E,0,0),konva_1.default.Util.releaseCanvas(E),o&&p.find(".page-background").forEach((e=>e.show())),h.forEach((e=>{e.visible(e.getAttr("oldVisible"))})),u.forEach((e=>{e.visible(e.getAttr("oldVisible"))})),p.find(".page-background").forEach((e=>e.shadowEnabled(!0))),p.find(".page-background").forEach((e=>e.strokeEnabled(!0))),d.find("Transformer").forEach((e=>e.visible(!0))),p.find(".highlighter").forEach((e=>e.visible(!0))),c.clip(m),_.clip(g),null==l||l.set({_exporting:!1}),x},async toDataURL({pixelRatio:t,ignoreBackground:o,pageId:n,mimeType:a,includeBleed:i,quality:s}={}){const r=await e._toCanvas({pixelRatio:t,ignoreBackground:o,pageId:n,mimeType:a,includeBleed:i}),l=r.toDataURL(a,s);return konva_1.default.Util.releaseCanvas(r),l},async toBlob({pixelRatio:t,ignoreBackground:o,pageId:n,mimeType:a,includeBleed:i,quality:s}={}){const r=await e._toCanvas({pixelRatio:t,ignoreBackground:o,pageId:n,mimeType:a,includeBleed:i}),l=new Promise((e=>{r.toBlob(e,a,s)}));return konva_1.default.Util.releaseCanvas(r),l},async saveAsImage(t={}){var{fileName:o}=t,n=__rest(t,["fileName"]);const a=n.mimeType||"image/png",i=a.split("/")[1];(0,download_1.downloadFile)(await e.toDataURL(n),o||"polotno."+i,a)},async _toPDF(t){const o=t.dpi||e.dpi,n=t.parallel||1,a=t.unit||("px"===e.unit?"mm":e.unit),i=t.pixelRatio||1,s=t.pageIds||e.pages.map((e=>e.id)),r=e.pages.filter((e=>s.includes(e.id))),l=await(0,pdf_1.getJsPDF)(),d=e=>(0,unit_1.pxToUnit)({px:e,unit:a,dpi:o}),p=r[0]||{},c=t.includeBleed?p.bleed:0,m=d(p.computedWidth+2*c),_=d(p.computedHeight+2*c);var g=new l({unit:a,orientation:m>_?"landscape":"portrait",format:[m,_],compress:!0,putOnlyUsedFonts:!0});g.deletePage(1);const h=e._elementsPixelRatio;e.setElementsPixelRatio(i),await new Promise((e=>setTimeout(e)));const u=((e,t)=>{for(var o=[],n=0;n<e.length;n+=t)o.push(e.slice(n,n+t));return o})(r,n);for(const o of u){const n=o.map((async o=>{const n=t.includeBleed?o.bleed:0,a=d(o.computedWidth+2*n),s=d(o.computedHeight+2*n);let r=0,l=i;for(;r<10;){r+=1,2===r&&console.error("Polotno can not export PDF with current settings. Quality is automatically reduced.");const n=await e.toDataURL(Object.assign(Object.assign({},t),{pageId:o.id,pixelRatio:l}));if(n.length>20)return{url:n,width:a,height:s};l*=.8}}));(await Promise.all(n)).forEach((({url:e,width:t,height:o})=>{g.addPage([t,o],t>o?"landscape":"portrait"),g.addImage(e,0,0,t,o,void 0,"FAST")}))}return e.setElementsPixelRatio(h),g},toPDFDataURL:async t=>(await e._toPDF(Object.assign({mimeType:"image/jpeg"},t))).output("datauristring"),async toHTML(){const t=e.toJSON();return(0,html_1.jsonToHTML)({json:t})},async saveAsHTML({filename:t}={}){const o=await e.toHTML(),n="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(o)));(0,download_1.downloadFile)(n,t||"polotno.html")},async saveAsPDF(t={}){var{fileName:o}=t,n=__rest(t,["fileName"]);(await e._toPDF(Object.assign({mimeType:"image/jpeg"},n))).save(o||"polotno.pdf")},async waitLoading(){await new Promise((e=>setTimeout(e,50))),await(0,loader_1.whenLoaded)()},toJSON:()=>({width:e.width,height:e.height,fonts:(0,mobx_state_tree_1.getSnapshot)(e.fonts),pages:(0,mobx_state_tree_1.getSnapshot)(e.pages),unit:e.unit,dpi:e.dpi}),loadJSON(t,o=!1){var n;const a=Object.assign({},t),i=e.pages.indexOf(e.activePage);let s=null===(n=a.pages[i]||a.pages[0])||void 0===n?void 0:n.id;a._activePageId=s;const r=Object.assign({},(0,mobx_state_tree_1.getSnapshot)(e));Object.assign(r,a),r.history=o?e.history.toJSON():{history:[],undoIdx:-1},(0,mobx_state_tree_1.applySnapshot)(e,r)},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,mobx_state_tree_1.destroy)(e)))},async loadFont(t){const o=e.fonts.find((e=>e.fontFamily===t))||fonts.globalFonts.find((e=>e.fontFamily===t));o?fonts.injectCustomFont(o):fonts.injectGoogleFont(t),await fonts.loadFont(t)}}))),exports.createStore=createStore,exports.default=createStore;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "polotno",
|
|
3
|
-
"version": "1.8.
|
|
3
|
+
"version": "1.8.3",
|
|
4
4
|
"description": "Design Editor Framework",
|
|
5
5
|
"author": "Anton Lavrenov",
|
|
6
6
|
"keywords": [
|
|
@@ -14,8 +14,6 @@
|
|
|
14
14
|
"@blueprintjs/popover2": "^1.13.3",
|
|
15
15
|
"@blueprintjs/select": "^4.9.3",
|
|
16
16
|
"@meronex/icons": "^4.0.0",
|
|
17
|
-
"gif.js": "^0.2.0",
|
|
18
|
-
"gifshot": "^0.4.5",
|
|
19
17
|
"gradient-parser": "^1.0.2",
|
|
20
18
|
"konva": "^8.4.2",
|
|
21
19
|
"mobx": "6.8.0",
|
package/polotno-app.d.ts
CHANGED
|
@@ -487,7 +487,6 @@ export declare function createPolotnoApp({ container, key, showCredit }: {
|
|
|
487
487
|
saveAsHTML({ filename }?: {
|
|
488
488
|
filename?: string | undefined;
|
|
489
489
|
}): Promise<void>;
|
|
490
|
-
saveAsGIF(): Promise<void>;
|
|
491
490
|
saveAsPDF({ fileName, ...exportProps }?: import("./model/store").ExportOptions & {
|
|
492
491
|
fileName?: string | undefined;
|
|
493
492
|
dpi?: number | undefined;
|
|
@@ -915,7 +914,6 @@ export declare function createPolotnoApp({ container, key, showCredit }: {
|
|
|
915
914
|
saveAsHTML({ filename }?: {
|
|
916
915
|
filename?: string | undefined;
|
|
917
916
|
}): Promise<void>;
|
|
918
|
-
saveAsGIF(): Promise<void>;
|
|
919
917
|
saveAsPDF({ fileName, ...exportProps }?: import("./model/store").ExportOptions & {
|
|
920
918
|
fileName?: string | undefined;
|
|
921
919
|
dpi?: number | undefined;
|