polotno 2.0.1 → 2.0.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.
@@ -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.usePrevious=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.a.height-c)/2),"bottom"===t.verticalAlign&&(d=t.a.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.useReducer((e=>e+1),0),n=react_1.default.useRef(!!(0,fonts_1.isFontLoaded)(t));return react_1.default.useLayoutEffect((()=>{if(n.current)return;let r=!0;return(async()=>{n.current=!1,i();const o=(0,loader_1.incrementLoader)(`text ${t}`);await e.loadFont(t),konva_1.default.Util.requestAnimFrame(o),r&&(n.current=!0,i())})(),()=>{r=!1}}),[t]),[n.current]};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.useMemo((()=>{r.current=t.current,t.current=e}),[e]),r.current}function findFitFontSize(e,t){const r=e.fontSize(),i=e.height(),n=(0,text_1.removeTags)(t.text);let o=t.a.fontSize;e.height(void 0);const a=Math.round(2*t.a.fontSize)-1;for(let r=1;r<a;r++){const r=t.a.height&&e.height()>t.a.height,i=n.split("\n").join(" ").split(/[\s-]+/);let a=e.textArr.map((e=>e.text)).join(";");const l=i.find((e=>!a.includes(e)||(a=a.replace(e,""),!1)));if(!(r||l))break;o-=.5,e.fontSize(o)}return e.fontSize(r),e.height(i),o}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,exports.usePrevious=usePrevious;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.a.width/2,y:e.a.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.a.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.a.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.a.height)if("change-font-size"!==i||s){if("resize"===i){const i=y();f&&e.a.height<i&&t.history.ignore((()=>{e.set({height:i}),r.current.height(i)})),f||e.a.height===i||t.history.ignore((()=>{e.set({height:i}),r.current.height(i)}))}}else{const i=findFitFontSize(r.current,e);if(i!==e.a.fontSize)return void t.history.ignore((()=>{e.set({fontSize:i})}));const n=y();e.a.height===n||f||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.selectedShapes.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.a.fontSize,lineHeight:e.lineHeight}),E=e.selectable||"admin"===t.role,T=(0,exports.useTextColor)(e),L=react_1.default.useMemo((()=>e.backgroundEnabled?generateBackgroundShape({lines:JSON.parse(JSON.stringify(g)),cornerRadius:e.backgroundCornerRadius*(e.a.fontSize*b*.5),lineHeight:b*e.a.fontSize,padding:e.backgroundPadding*(e.a.fontSize*b*.5),width:e.a.width,align:e.align}):""),[e.backgroundEnabled,e.backgroundCornerRadius,e.a.fontSize,b,e.backgroundPadding,e.a.width,e.align,g]),M=(0,screen_1.useMobile)();let k=0;return"middle"===e.verticalAlign?k=(e.a.height-g.length*b*e.a.fontSize)/2:"bottom"===e.verticalAlign&&(k=e.a.height-g.length*b*e.a.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.a.width,height:e.a.height,text:x||e.placeholder},T,{stroke:e.stroke,lineJoin:"round",strokeWidth:e.strokeWidth,fillAfterStrokeEnabled:!0,fontSize:e.a.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.a.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.a.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.a.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;const o=r.target.scaleX();r.target.scaleX(1),r.target.scaleY(1),r.target.strokeWidth(e.strokeWidth),e.set({fontSize:Math.round(e.a.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}),null===(n=i.current)||void 0===n||n.setAttrs({scaleX:1,scaleY:1}),t.history.endTransaction(),d(!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.usePrevious=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.a.height-c)/2),"bottom"===t.verticalAlign&&(d=t.a.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.useReducer((e=>e+1),0),n=react_1.default.useRef((0,fonts_1.isFontLoaded)(t));return react_1.default.useLayoutEffect((()=>{if(n.current=(0,fonts_1.isFontLoaded)(t),n.current)return;let r=!0;return(async()=>{n.current=!1,i();const o=(0,loader_1.incrementLoader)(`text ${t}`);await e.loadFont(t),konva_1.default.Util.requestAnimFrame(o),r&&(n.current=!0,i())})(),()=>{r=!1}}),[t]),[n.current]};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.useMemo((()=>{r.current=t.current,t.current=e}),[e]),r.current}function findFitFontSize(e,t){const r=e.fontSize(),i=e.height(),n=(0,text_1.removeTags)(t.text);let o=t.a.fontSize;e.height(void 0);const a=Math.round(2*t.a.fontSize)-1;for(let r=1;r<a;r++){const r=t.a.height&&e.height()>t.a.height,i=n.split("\n").join(" ").split(/[\s-]+/);let a=e.textArr.map((e=>e.text)).join(";");const l=i.find((e=>!a.includes(e)||(a=a.replace(e,""),!1)));if(!(r||l))break;o-=.5,e.fontSize(o)}return e.fontSize(r),e.height(i),o}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,exports.usePrevious=usePrevious;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.a.width/2,y:e.a.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.a.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.a.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.a.height)if("change-font-size"!==i||s){if("resize"===i){const i=y();f&&e.a.height<i&&t.history.ignore((()=>{e.set({height:i}),r.current.height(i)}),!1,!0),f||e.a.height===i||t.history.ignore((()=>{e.set({height:i}),r.current.height(i)}),!1,!0)}}else{const i=findFitFontSize(r.current,e);if(i!==e.a.fontSize)return void t.history.ignore((()=>{e.set({fontSize:i})}),!1,!0);const n=y();e.a.height===n||f||t.history.ignore((()=>{e.set({height:n})}),!1,!0)}else{const r=y();t.history.ignore((()=>{e.set({height:r})}),!1,!0)}})),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.selectedShapes.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.a.fontSize,lineHeight:e.lineHeight}),E=e.selectable||"admin"===t.role,T=(0,exports.useTextColor)(e),L=react_1.default.useMemo((()=>e.backgroundEnabled?generateBackgroundShape({lines:JSON.parse(JSON.stringify(g)),cornerRadius:e.backgroundCornerRadius*(e.a.fontSize*b*.5),lineHeight:b*e.a.fontSize,padding:e.backgroundPadding*(e.a.fontSize*b*.5),width:e.a.width,align:e.align}):""),[e.backgroundEnabled,e.backgroundCornerRadius,e.a.fontSize,b,e.backgroundPadding,e.a.width,e.align,g]),M=(0,screen_1.useMobile)();let k=0;return"middle"===e.verticalAlign?k=(e.a.height-g.length*b*e.a.fontSize)/2:"bottom"===e.verticalAlign&&(k=e.a.height-g.length*b*e.a.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.a.width,height:e.a.height,text:x||e.placeholder},T,{stroke:e.stroke,lineJoin:"round",strokeWidth:e.strokeWidth,fillAfterStrokeEnabled:!0,fontSize:e.a.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.a.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.a.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.a.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;const o=r.target.scaleX();r.target.scaleX(1),r.target.scaleY(1),r.target.strokeWidth(e.strokeWidth),e.set({fontSize:Math.round(e.a.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}),null===(n=i.current)||void 0===n||n.setAttrs({scaleX:1,scaleY:1}),t.history.endTransaction(),d(!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}))}));
@@ -8,7 +8,7 @@ export declare const UndoManager: import("mobx-state-tree").IModelType<{
8
8
  } & {
9
9
  startTransaction(): void;
10
10
  endTransaction(skipSave?: boolean): void;
11
- ignore(func: any, skipStateReplacement?: boolean): Promise<void>;
11
+ ignore(func: any, skipStateReplacement?: boolean, delayed?: boolean): Promise<void>;
12
12
  transaction(func: any): Promise<void>;
13
13
  requestAddState(state: any): void;
14
14
  addUndoState(): void;
package/model/history.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.UndoManager=void 0;const mobx_state_tree_1=require("mobx-state-tree"),deep_equal_1=require("../utils/deep-equal");Object.assign(mobx_state_tree_1.types),exports.UndoManager=mobx_state_tree_1.types.model("UndoManager",{history:mobx_state_tree_1.types.array(mobx_state_tree_1.types.frozen()),undoIdx:-1,targetPath:""}).views((e=>({get canUndo(){return e.undoIdx>0},get canRedo(){return e.undoIdx<e.history.length-1}}))).actions((e=>{let t,o,a=!1,r=null,n=0,s=!1;function d(){const e=(0,mobx_state_tree_1.getSnapshot)(t);return{pages:e.pages,width:e.width,height:e.height}}function i(e){(0,mobx_state_tree_1.applySnapshot)(t.pages,e.pages),t.setSize(e.width,e.height)}return{startTransaction(){s=!0},endTransaction(e){s=!1,e||this.requestAddState(d())},async ignore(t,o=!1){n&&e.addUndoState();let a=s;a||e.startTransaction();try{await t()}catch(e){setTimeout((()=>{throw e}))}a||e.endTransaction(!0),o||a||e.replaceState(),clearTimeout(n),n=0},async transaction(t){await e.ignore(t,!0),this.addUndoState()},requestAddState(e){r=e,n||s||(a?a=!1:n=setTimeout((()=>{n=0,clearTimeout(n),s||this.addUndoState()}),100))},addUndoState(){if(a)return void(a=!1);const t=e.history[e.undoIdx];!(0,deep_equal_1.deepEqual)(r,t)&&(clearTimeout(n),n=0,e.history.splice(e.undoIdx+1),e.history.push(r),e.undoIdx=e.history.length-1)},afterCreate(){if(t=(0,mobx_state_tree_1.resolvePath)(e,".."),!t)throw new Error("Failed to find target store for UndoManager. Please provide `targetPath` property, or a `targetStore` in the environment");o=(0,mobx_state_tree_1.onSnapshot)(t,(()=>{this.requestAddState(d())})),0===e.history.length&&this.requestAddState(d())},clear(){clearTimeout(n),n=0,e.history.splice(0,e.history.length),e.undoIdx=-1,e.addUndoState(d())},beforeDestroy(){o()},undo(){n&&this.addUndoState(),e.canUndo?(e.undoIdx--,a=!0,i(e.history[e.undoIdx])):console.warn("No undo history. Please check `store.history.canUndo` before calling undo action.")},redo(){n&&this.addUndoState(),e.canRedo?(e.undoIdx++,a=!0,i(e.history[e.undoIdx])):console.warn("No redo history. Please check `store.history.canRedo` before calling redo action.")},replaceState(){e.history[e.undoIdx]=d()}}})),exports.default=exports.UndoManager;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.UndoManager=void 0;const mobx_state_tree_1=require("mobx-state-tree"),deep_equal_1=require("../utils/deep-equal");Object.assign(mobx_state_tree_1.types),exports.UndoManager=mobx_state_tree_1.types.model("UndoManager",{history:mobx_state_tree_1.types.array(mobx_state_tree_1.types.frozen()),undoIdx:-1,targetPath:""}).views((e=>({get canUndo(){return e.undoIdx>0},get canRedo(){return e.undoIdx<e.history.length-1}}))).actions((e=>{let t,o,a=!1,r=null,n=0,s=0;const d=()=>s>0;function i(){const e=(0,mobx_state_tree_1.getSnapshot)(t);return{pages:e.pages,width:e.width,height:e.height}}function h(e){(0,mobx_state_tree_1.applySnapshot)(t.pages,e.pages),t.setSize(e.width,e.height)}return{startTransaction(){s++},endTransaction(e){s--,e||this.requestAddState(i())},async ignore(t,o=!1,a=!1){n&&e.addUndoState(),a&&await new Promise((e=>setTimeout(e,60)));let r=d();e.startTransaction();let i=s;try{await t()}catch(e){setTimeout((()=>{throw e}))}const h=i!==s,u=!h;e.endTransaction(u),o||r||e.replaceState(),h||(clearTimeout(n),n=0)},async transaction(t){await e.ignore(t,!0),this.addUndoState()},requestAddState(e){r=e,n||d()||(a?a=!1:n=setTimeout((()=>{n=0,clearTimeout(n),d()||this.addUndoState()}),100))},addUndoState(){if(a)return void(a=!1);const t=e.history[e.undoIdx];!(0,deep_equal_1.deepEqual)(r,t)&&(clearTimeout(n),n=0,e.history.splice(e.undoIdx+1),e.history.push(r),e.undoIdx=e.history.length-1)},afterCreate(){if(t=(0,mobx_state_tree_1.resolvePath)(e,".."),!t)throw new Error("Failed to find target store for UndoManager. Please provide `targetPath` property, or a `targetStore` in the environment");o=(0,mobx_state_tree_1.onSnapshot)(t,(()=>{this.requestAddState(i())})),0===e.history.length&&this.requestAddState(i())},clear(){clearTimeout(n),n=0,e.history.splice(0,e.history.length),e.undoIdx=-1,e.addUndoState(i())},beforeDestroy(){o()},undo(){n&&this.addUndoState(),e.canUndo?(e.undoIdx--,a=!0,h(e.history[e.undoIdx])):console.warn("No undo history. Please check `store.history.canUndo` before calling undo action.")},redo(){n&&this.addUndoState(),e.canRedo?(e.undoIdx++,a=!0,h(e.history[e.undoIdx])):console.warn("No redo history. Please check `store.history.canRedo` before calling redo action.")},replaceState(){e.history[e.undoIdx]=i()}}})),exports.default=exports.UndoManager;
package/model/store.d.ts CHANGED
@@ -100,7 +100,7 @@ export declare const Store: import("mobx-state-tree").IModelType<{
100
100
  } & {
101
101
  startTransaction(): void;
102
102
  endTransaction(skipSave?: boolean): void;
103
- ignore(func: any, skipStateReplacement?: boolean): Promise<void>;
103
+ ignore(func: any, skipStateReplacement?: boolean, delayed?: boolean): Promise<void>;
104
104
  transaction(func: any): Promise<void>;
105
105
  requestAddState(state: any): void;
106
106
  addUndoState(): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "polotno",
3
- "version": "2.0.1",
3
+ "version": "2.0.3",
4
4
  "description": "Design Editor Framework",
5
5
  "author": "Anton Lavrenov",
6
6
  "keywords": [
package/polotno-app.d.ts CHANGED
@@ -141,7 +141,7 @@ export declare function createPolotnoApp({ container, key, showCredit }: {
141
141
  } & {
142
142
  startTransaction(): void;
143
143
  endTransaction(skipSave?: boolean): void;
144
- ignore(func: any, skipStateReplacement?: boolean): Promise<void>;
144
+ ignore(func: any, skipStateReplacement?: boolean, delayed?: boolean): Promise<void>;
145
145
  transaction(func: any): Promise<void>;
146
146
  requestAddState(state: any): void;
147
147
  addUndoState(): void;
@@ -161,7 +161,7 @@ export declare function createPolotnoApp({ container, key, showCredit }: {
161
161
  } & {
162
162
  startTransaction(): void;
163
163
  endTransaction(skipSave?: boolean): void;
164
- ignore(func: any, skipStateReplacement?: boolean): Promise<void>;
164
+ ignore(func: any, skipStateReplacement?: boolean, delayed?: boolean): Promise<void>;
165
165
  transaction(func: any): Promise<void>;
166
166
  requestAddState(state: any): void;
167
167
  addUndoState(): void;
@@ -626,7 +626,7 @@ export declare function createPolotnoApp({ container, key, showCredit }: {
626
626
  } & {
627
627
  startTransaction(): void;
628
628
  endTransaction(skipSave?: boolean): void;
629
- ignore(func: any, skipStateReplacement?: boolean): Promise<void>;
629
+ ignore(func: any, skipStateReplacement?: boolean, delayed?: boolean): Promise<void>;
630
630
  transaction(func: any): Promise<void>;
631
631
  requestAddState(state: any): void;
632
632
  addUndoState(): void;
package/polotno.bundle.js CHANGED
@@ -1178,7 +1178,7 @@ e.marker=e.marker.toUpperCase(),e.marker){case"M":case"L":case"A":case"T":e.valu
1178
1178
  function e(t,n){return"M"===t[n].marker?t[n]:e(t,n-1)}(n,t);e.values.x=r.values.x,e.values.y=r.values.y}return e}function lu(e,t,n){// Skip the first moveTo command and any other that's not a lineTo.
1179
1179
  if(0!==t&&"L"===e.marker){// It seems we have a lineTo here. Get the immediate previous command
1180
1180
  let r=n[t-1],i=["x","y"].every(t=>0===Math.round(Math.abs(r.values[t]-e.values[t])));i&&(e.overlap=!0)}return e}function lc(e,t){return Math.atan2(t.x-e.x,t.y-e.y)}function ld(e,t){let n=e.x-t.x,r=e.y-t.y;return Math.sqrt(Math.pow(n,2)+Math.pow(r,2))}function lh(e,t){let n=t/Math.tan(e);return n===1/0||n===-1/0||isNaN(n)?t:n}var v=h("8NFma");let lf=()=>!1;function lp(e,t){let n=/*@__PURE__*/l(v).useRef();/*@__PURE__*/l(v).useLayoutEffect(()=>{n.current&&n.current.destroy()},[t]),/*@__PURE__*/l(v).useLayoutEffect(()=>{},[])}let lg=0,lm=[];function lv(e){lg+=1;let t=!1,n=setTimeout(()=>{t||(lw(`Timeout loading image ${e}`),console.error("Timeout triggered for loader. Some assets may not have loaded.",e),t=!0,ly())},3e4);return()=>{t||(clearTimeout(n),ly())}}function ly(){0==(lg-=1)&&(lm.forEach(e=>e()),lm=[])}let lb=[];function lw(e){lb.forEach(t=>t(e))}let lx=eD(["Roboto","Amatic SC","Press Start 2P","Marck Script","Rubik Mono One"]),l_=eD({value:!1});function lE(){return l_.value}let lS=eD([]);var lO=document.createElement("canvas");function lC(e,t="Arial"){var n=lO.getContext("2d");return n.font=`normal 40px '${e}', ${t}`,n.measureText("Some test text;?#D-ПРИВЕТ!1230o9u8i7y6t5r4e3w2q1").width}let lk={// let us think Arial is already loaded
1181
- Arial:!0},lP=e=>lk[e];async function lT(e){if(lk[e])return;// try to use font load API
1181
+ Arial:!0},lP=e=>!!lk[e];async function lT(e){if(lk[e])return;// try to use font load API
1182
1182
  // it is better, because it is possible that the font is ALREADY loaded
1183
1183
  // so we don't need to wait for a manual check
1184
1184
  let t=!!document.fonts?.load,n=lC("Arial");if(t)try{await document.fonts.load(`16px '${e}'`);// when Chrome browser tell us the font is loaded, it is not really loaded yet, we still need to wait
@@ -1219,22 +1219,22 @@ let e=setTimeout(()=>{let e=u.current;if(!e)return;u.current?.focus();let t=i||e
1219
1219
  // select all when on mount (or very small time offset) we have flag on
1220
1220
  let[t,n]=/*@__PURE__*/l(v).useState(!1),r=/*@__PURE__*/l(v).useRef(!1);return /*@__PURE__*/l(v).useEffect(()=>{var t=!0;return(// to a timeout, because a user may toggle edit mode in a not batched by react transaction
1221
1221
  setTimeout(()=>{t&&(e._editModeEnabled&&(r.current=!0),n(!0),// remove select all flag
1222
- setTimeout(()=>{r.current=!1},50))},50),()=>{t=!1})},[]),{editorEnabled:t&&e._editModeEnabled,selectAll:r.current}},lX=(e,t)=>{let[n,r]=/*@__PURE__*/l(v).useReducer(e=>e+1,0),i=/*@__PURE__*/l(v).useRef(!!lP(t));return /*@__PURE__*/l(v).useLayoutEffect(()=>{// if font is already loaded after quick check, do nothing
1223
- if(i.current)return;let n=!0,o=async()=>{i.current=!1,r();let o=lv(`text ${t}`);await e.loadFont(t),/*@__PURE__*/l(nQ).Util.requestAnimFrame(o),n&&(i.current=!0,r())};return o(),()=>{n=!1}},[t]),[i.current]},lQ=({fontLoaded:e,fontFamily:t,fontSize:n,lineHeight:r})=>/*@__PURE__*/l(v).useMemo(()=>{if("number"==typeof r)return r;let e=document.createElement("div");e.style.fontFamily=t,e.style.fontSize=n+"px",e.style.lineHeight=r,e.innerText="Test text",document.body.appendChild(e);let i=e.offsetHeight;return document.body.removeChild(e),i/n},[e,t,n,r]);function lZ(e){let t=/*@__PURE__*/l(v).useRef(e),n=/*@__PURE__*/l(v).useRef(e);return /*@__PURE__*/l(v).useMemo(()=>{n.current=t.current,t.current=e},[e]),n.current;//in the end, return the current ref value.
1222
+ setTimeout(()=>{r.current=!1},50))},50),()=>{t=!1})},[]),{editorEnabled:t&&e._editModeEnabled,selectAll:r.current}},lX=(e,t)=>{let[n,r]=/*@__PURE__*/l(v).useReducer(e=>e+1,0),i=/*@__PURE__*/l(v).useRef(lP(t));return /*@__PURE__*/l(v).useLayoutEffect(()=>{if(// if font is already loaded after quick check, do nothing
1223
+ i.current=lP(t),i.current)return;let n=!0,o=async()=>{i.current=!1,r();let o=lv(`text ${t}`);await e.loadFont(t),/*@__PURE__*/l(nQ).Util.requestAnimFrame(o),n&&(i.current=!0,r())};return o(),()=>{n=!1}},[t]),[i.current]},lQ=({fontLoaded:e,fontFamily:t,fontSize:n,lineHeight:r})=>/*@__PURE__*/l(v).useMemo(()=>{if("number"==typeof r)return r;let e=document.createElement("div");e.style.fontFamily=t,e.style.fontSize=n+"px",e.style.lineHeight=r,e.innerText="Test text",document.body.appendChild(e);let i=e.offsetHeight;return document.body.removeChild(e),i/n},[e,t,n,r]);function lZ(e){let t=/*@__PURE__*/l(v).useRef(e),n=/*@__PURE__*/l(v).useRef(e);return /*@__PURE__*/l(v).useMemo(()=>{n.current=t.current,t.current=e},[e]),n.current;//in the end, return the current ref value.
1224
1224
  }let lJ=e=>/*@__PURE__*/l(v).useMemo(()=>{if(!lM(e.fill))return{fill:e.fill};let{stops:t,rotation:n}=lF(e.fill),r={x:e.a.width/2,y:e.a.height/2},i=Math.sqrt(Math.pow(r.x,2)+Math.pow(r.y,2)),o=/*@__PURE__*/l(nQ).Util.degToRad(n)-Math.PI/2,a=[];return t.forEach(({offset:e,color:t})=>{a.push(e,t)}),{fillLinearGradientStartPointX:r.x-i*Math.cos(o),fillLinearGradientStartPointY:r.y-i*Math.sin(o),fillLinearGradientColorStops:a,fillLinearGradientEndPointX:r.x+i*Math.cos(o),fillLinearGradientEndPointY:r.y+i*Math.sin(o),fill:t[1].color,fillPriority:"linear-gradient"}},[e.fill]),l0=nK(({element:e,store:t})=>{let n=/*@__PURE__*/l(v).useRef(null),r=/*@__PURE__*/l(v).useRef(null),{editorEnabled:i,selectAll:o}=lY(e),[a,s]=/*@__PURE__*/l(v).useState(!1),[u,c]=/*@__PURE__*/l(v).useState(!1),d=/*@__PURE__*/l(v).useRef(e.a.height),h=t.selectedElements.indexOf(e)>=0,{textVerticalResizeEnabled:f}=lj,g=lZ(e.fontFamily),[m,y]=/*@__PURE__*/l(v).useState([]);/*@__PURE__*/l(v).useEffect(()=>{let e=n.current?.textArr??[];JSON.stringify(e)!==JSON.stringify(m)&&y(e)}),/*@__PURE__*/l(v).useEffect(()=>{if(e.a.width)return;let t=n.current;t.width(600),e.set({width:1.4*t.getTextWidth()})},[]),/*@__PURE__*/l(v).useLayoutEffect(()=>{let t=tT(()=>{let t=n.current;lz(t,e)});return t});let[b]=lX(t,e.fontFamily),w=lR(e.text),x=()=>{let e=n.current,t=e.clone({height:void 0}),r=Math.ceil(t.fontSize()*t.lineHeight()*t.textArr.length+1// one extra pixel for fix possible rounding errors
1225
1225
  );return t.destroy(),r};/*@__PURE__*/l(v).useLayoutEffect(()=>{if(!b)return;let{textOverflow:r}=lj;// if no height, save it to element
1226
- if(!e.a.height){let n=x();t.history.ignore(()=>{e.set({height:n})});return}// also do that check only while exporting
1226
+ if(!e.a.height){let n=x();t.history.ignore(()=>{e.set({height:n})},!1,!0);return}// also do that check only while exporting
1227
1227
  if("change-font-size"!==r||u){if("resize"===r){// on other cases, we don't look into height from the element to render
1228
1228
  // but need to update it back
1229
1229
  let r=x();f&&e.a.height<r&&t.history.ignore(()=>{e.set({height:r}),// there are some issues with react updates, I can't find why it doesn't trigger update here
1230
- n.current.height(r)}),f||e.a.height===r||t.history.ignore(()=>{e.set({height:r}),n.current.height(r)})}}else{// ok, lets explain logic here
1230
+ n.current.height(r)},!1,!0),f||e.a.height===r||t.history.ignore(()=>{e.set({height:r}),n.current.height(r)},!1,!0)}}else{// ok, lets explain logic here
1231
1231
  // different OS have different font metrics
1232
1232
  // it is possible that on one OS design looks just fine
1233
1233
  // but on other OS, text a bit bigger
1234
1234
  // it may produce large shift it text layout
1235
1235
  // so a text may have a different number of lines
1236
1236
  // to avoid that, lets change font smaller
1237
- let r=n.current,i=function(e,t){let n=e.fontSize(),r=e.height(),i=lR(t.text),o=t.a.fontSize;e.height(void 0);let a=Math.round(2*t.a.fontSize)-1;for(let n=1;n<a;n++){let n=t.a.height&&e.height()>t.a.height,r=i.split("\n").join(" ").split(/[\s-]+/),a=e.textArr.map(e=>e.text).join(";"),l=r.find(e=>{let t=a.includes(e);return!t||(a=a.replace(e,""),!1)}),s=n||l;if(!s)break;o-=.5,e.fontSize(o)}return e.fontSize(n),e.height(r),o}(r,e);if(i!==e.a.fontSize){t.history.ignore(()=>{e.set({fontSize:i})});return}let o=x();e.a.height===o||f||t.history.ignore(()=>{e.set({height:o})})}}),/*@__PURE__*/l(v).useLayoutEffect(()=>{let t=n.current;t&&(// trigger width change to update transformer
1237
+ let r=n.current,i=function(e,t){let n=e.fontSize(),r=e.height(),i=lR(t.text),o=t.a.fontSize;e.height(void 0);let a=Math.round(2*t.a.fontSize)-1;for(let n=1;n<a;n++){let n=t.a.height&&e.height()>t.a.height,r=i.split("\n").join(" ").split(/[\s-]+/),a=e.textArr.map(e=>e.text).join(";"),l=r.find(e=>{let t=a.includes(e);return!t||(a=a.replace(e,""),!1)}),s=n||l;if(!s)break;o-=.5,e.fontSize(o)}return e.fontSize(n),e.height(r),o}(r,e);if(i!==e.a.fontSize){t.history.ignore(()=>{e.set({fontSize:i})},!1,!0);return}let o=x();e.a.height===o||f||t.history.ignore(()=>{e.set({height:o})},!1,!0)}}),/*@__PURE__*/l(v).useLayoutEffect(()=>{let t=n.current;t&&(// trigger width change to update transformer
1238
1238
  t.width(t.width()+1e-8),// recalculate text dimensions
1239
1239
  t._setTextData(),lz(t,e))},[b]);let _=/*@__PURE__*/l(v).useRef(null),E=/*@__PURE__*/l(v).useRef(0),S=n=>{n.evt.preventDefault();let r=t.selectedShapes.find(t=>t===e);r&&e.contentEditable&&(E.current=function(e){var t,n;let r=e.target,i=(// to detect relative position we need to invert transform
1240
1240
  (t=r.getAbsoluteTransform().copy()).invert(),n=r.getStage().getPointerPosition(),t.point(n)),o=r.textArr,a=Math.floor(i.y/(r.fontSize()*r.lineHeight())),l=o.slice(0,a).reduce((e,t)=>e+t.text.length,a),s=o[a]??o[0],u=0;"right"===r.align()?u=r.width()-s.width:"center"===r.align()&&(u=r.width()/2-s.width/2);let c=Math.round((i.x-u)/s.width*s.text.length);return l+c}(n),e.toggleEditMode())},O=!w&&e.placeholder,C=O?.6:e.a.opacity;lp(n,C);let k=lQ({fontLoaded:b,fontFamily:e.fontFamily,fontSize:e.a.fontSize,lineHeight:e.lineHeight}),P=e.selectable||"admin"===t.role,T=lJ(e),A=/*@__PURE__*/l(v).useMemo(()=>e.backgroundEnabled?// lets generate a background shape for the text
@@ -6192,13 +6192,13 @@ display:e.selectable?"auto":"none"},children:/*#__PURE__*/(0,p.jsxs)("div",{styl
6192
6192
  // somehow almost al types were removes, it was look like some tree-shaking issue
6193
6193
  // so I added this line to make sure that all types are included
6194
6194
  // and I really don't like this line
6195
- Object.assign(Nh);let Lx=Nh.model("UndoManager",{history:Nh.array(Nh.frozen()),undoIdx:-1,targetPath:""}).views(e=>({get canUndo(){return e.undoIdx>0},get canRedo(){return e.undoIdx<e.history.length-1}})).actions(e=>{let t,n;let r=!1,i=null,o=0,a=!1;function l(){let e=TC(t);return{pages:e.pages,width:e.width,height:e.height}}function s(e){TO(t.pages,e.pages),t.setSize(e.width,e.height)}return{startTransaction(){a=!0},endTransaction(e){a=!1,e||// for example when we drag end many elements at the same time
6196
- this.requestAddState(l())},async ignore(t,n=!1){o&&e.addUndoState();let r=a;r||e.startTransaction();try{await t()}catch(e){setTimeout(()=>{throw e})}r||e.endTransaction(!0),n||r||e.replaceState(),clearTimeout(o),o=0},async transaction(t){// ignore all changes
6195
+ Object.assign(Nh);let Lx=Nh.model("UndoManager",{history:Nh.array(Nh.frozen()),undoIdx:-1,targetPath:""}).views(e=>({get canUndo(){return e.undoIdx>0},get canRedo(){return e.undoIdx<e.history.length-1}})).actions(e=>{let t,n;let r=!1,i=null,o=0,a=0,l=()=>a>0;function s(){let e=TC(t);return{pages:e.pages,width:e.width,height:e.height}}function u(e){TO(t.pages,e.pages),t.setSize(e.width,e.height)}return{startTransaction(){a++},endTransaction(e){a--,e||// for example when we drag end many elements at the same time
6196
+ this.requestAddState(s())},async ignore(t,n=!1,r=!1){o&&e.addUndoState(),r&&await new Promise(e=>setTimeout(e,60));let i=l();e.startTransaction();let s=a;try{await t()}catch(e){setTimeout(()=>{throw e})}let u=s!==a;e.endTransaction(!u),n||i||e.replaceState(),u||(clearTimeout(o),o=0)},async transaction(t){// ignore all changes
6197
6197
  await e.ignore(t,!0),// then try to save
6198
- this.addUndoState()},requestAddState(e){if(i=e,!o&&!a){if(r){r=!1;return}o=setTimeout(()=>{clearTimeout(o=0),a||this.addUndoState()},100)}},addUndoState(){if(r){// skip recording if this state was caused by undo / redo
6199
- r=!1;return}let t=e.history[e.undoIdx],n=!Lw(i,t);n&&(clearTimeout(o),o=0,e.history.splice(e.undoIdx+1),e.history.push(i),e.undoIdx=e.history.length-1)},afterCreate(){var r,i,o;if(Ab("..",2),i=T5(e),void 0===o&&(o=!0),!(t=(r=T8(i,AE(".."),o))?r.value:void 0))throw Error("Failed to find target store for UndoManager. Please provide `targetPath` property, or a `targetStore` in the environment");n=TE(t,()=>{this.requestAddState(l())}),0===e.history.length&&this.requestAddState(l())},clear(){clearTimeout(o),o=0,e.history.splice(0,e.history.length),e.undoIdx=-1,e.addUndoState(l())},beforeDestroy(){n()},undo(){if(o&&this.addUndoState(),!e.canUndo){console.warn("No undo history. Please check `store.history.canUndo` before calling undo action.");return}e.undoIdx--,r=!0,s(e.history[e.undoIdx])},redo(){if(o&&this.addUndoState(),!e.canRedo){console.warn("No redo history. Please check `store.history.canRedo` before calling redo action.");return}e.undoIdx++,r=!0,s(e.history[e.undoIdx])},// overwrite current history point with the current state of the project
6198
+ this.addUndoState()},requestAddState(e){if(i=e,!o&&!l()){if(r){r=!1;return}o=setTimeout(()=>{clearTimeout(o=0),l()||this.addUndoState()},100)}},addUndoState(){if(r){// skip recording if this state was caused by undo / redo
6199
+ r=!1;return}let t=e.history[e.undoIdx],n=!Lw(i,t);n&&(clearTimeout(o),o=0,e.history.splice(e.undoIdx+1),e.history.push(i),e.undoIdx=e.history.length-1)},afterCreate(){var r,i,o;if(Ab("..",2),i=T5(e),void 0===o&&(o=!0),!(t=(r=T8(i,AE(".."),o))?r.value:void 0))throw Error("Failed to find target store for UndoManager. Please provide `targetPath` property, or a `targetStore` in the environment");n=TE(t,()=>{this.requestAddState(s())}),0===e.history.length&&this.requestAddState(s())},clear(){clearTimeout(o),o=0,e.history.splice(0,e.history.length),e.undoIdx=-1,e.addUndoState(s())},beforeDestroy(){n()},undo(){if(o&&this.addUndoState(),!e.canUndo){console.warn("No undo history. Please check `store.history.canUndo` before calling undo action.");return}e.undoIdx--,r=!0,u(e.history[e.undoIdx])},redo(){if(o&&this.addUndoState(),!e.canRedo){console.warn("No redo history. Please check `store.history.canRedo` before calling redo action.");return}e.undoIdx++,r=!0,u(e.history[e.undoIdx])},// overwrite current history point with the current state of the project
6200
6200
  // can be useful to insert current scheduled changes into the history point, without creating a new point
6201
- replaceState(){e.history[e.undoIdx]=l()}}});async function L_(e,t){let n=await (await fetch(e)).blob(),r=document.createElement("a"),i=URL.createObjectURL(n);r.href=i,r.download=t,document.body.appendChild(r),r.click(),setTimeout(function(){document.body.removeChild(r),window.URL.revokeObjectURL(i)},0)}async function LE({width:e,height:t}){let n=await (window.GIF?Promise.resolve(window.GIF):new Promise(e=>{var t=document.createElement("script");t.onload=function(){e(window.GIF)},t.src="https://cdnjs.cloudflare.com/ajax/libs/gif.js/0.2.0/gif.js",document.head.appendChild(t)}));return new n({workers:4,width:e,height:t,workerScript:URL.createObjectURL(new Blob([`// gif.worker.js 0.2.0 - https://github.com/jnordberg/gif.js
6201
+ replaceState(){e.history[e.undoIdx]=s()}}});async function L_(e,t){let n=await (await fetch(e)).blob(),r=document.createElement("a"),i=URL.createObjectURL(n);r.href=i,r.download=t,document.body.appendChild(r),r.click(),setTimeout(function(){document.body.removeChild(r),window.URL.revokeObjectURL(i)},0)}async function LE({width:e,height:t}){let n=await (window.GIF?Promise.resolve(window.GIF):new Promise(e=>{var t=document.createElement("script");t.onload=function(){e(window.GIF)},t.src="https://cdnjs.cloudflare.com/ajax/libs/gif.js/0.2.0/gif.js",document.head.appendChild(t)}));return new n({workers:4,width:e,height:t,workerScript:URL.createObjectURL(new Blob([`// gif.worker.js 0.2.0 - https://github.com/jnordberg/gif.js
6202
6202
  (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){var NeuQuant=require("./TypedNeuQuant.js");var LZWEncoder=require("./LZWEncoder.js");function ByteArray(){this.page=-1;this.pages=[];this.newPage()}ByteArray.pageSize=4096;ByteArray.charMap={};for(var i=0;i<256;i++)ByteArray.charMap[i]=String.fromCharCode(i);ByteArray.prototype.newPage=function(){this.pages[++this.page]=new Uint8Array(ByteArray.pageSize);this.cursor=0};ByteArray.prototype.getData=function(){var rv="";for(var p=0;p<this.pages.length;p++){for(var i=0;i<ByteArray.pageSize;i++){rv+=ByteArray.charMap[this.pages[p][i]]}}return rv};ByteArray.prototype.writeByte=function(val){if(this.cursor>=ByteArray.pageSize)this.newPage();this.pages[this.page][this.cursor++]=val};ByteArray.prototype.writeUTFBytes=function(string){for(var l=string.length,i=0;i<l;i++)this.writeByte(string.charCodeAt(i))};ByteArray.prototype.writeBytes=function(array,offset,length){for(var l=length||array.length,i=offset||0;i<l;i++)this.writeByte(array[i])};function GIFEncoder(width,height){this.width=~~width;this.height=~~height;this.transparent=null;this.transIndex=0;this.repeat=-1;this.delay=0;this.image=null;this.pixels=null;this.indexedPixels=null;this.colorDepth=null;this.colorTab=null;this.neuQuant=null;this.usedEntry=new Array;this.palSize=7;this.dispose=-1;this.firstFrame=true;this.sample=10;this.dither=false;this.globalPalette=false;this.out=new ByteArray}GIFEncoder.prototype.setDelay=function(milliseconds){this.delay=Math.round(milliseconds/10)};GIFEncoder.prototype.setFrameRate=function(fps){this.delay=Math.round(100/fps)};GIFEncoder.prototype.setDispose=function(disposalCode){if(disposalCode>=0)this.dispose=disposalCode};GIFEncoder.prototype.setRepeat=function(repeat){this.repeat=repeat};GIFEncoder.prototype.setTransparent=function(color){this.transparent=color};GIFEncoder.prototype.addFrame=function(imageData){this.image=imageData;this.colorTab=this.globalPalette&&this.globalPalette.slice?this.globalPalette:null;this.getImagePixels();this.analyzePixels();if(this.globalPalette===true)this.globalPalette=this.colorTab;if(this.firstFrame){this.writeLSD();this.writePalette();if(this.repeat>=0){this.writeNetscapeExt()}}this.writeGraphicCtrlExt();this.writeImageDesc();if(!this.firstFrame&&!this.globalPalette)this.writePalette();this.writePixels();this.firstFrame=false};GIFEncoder.prototype.finish=function(){this.out.writeByte(59)};GIFEncoder.prototype.setQuality=function(quality){if(quality<1)quality=1;this.sample=quality};GIFEncoder.prototype.setDither=function(dither){if(dither===true)dither="FloydSteinberg";this.dither=dither};GIFEncoder.prototype.setGlobalPalette=function(palette){this.globalPalette=palette};GIFEncoder.prototype.getGlobalPalette=function(){return this.globalPalette&&this.globalPalette.slice&&this.globalPalette.slice(0)||this.globalPalette};GIFEncoder.prototype.writeHeader=function(){this.out.writeUTFBytes("GIF89a")};GIFEncoder.prototype.analyzePixels=function(){if(!this.colorTab){this.neuQuant=new NeuQuant(this.pixels,this.sample);this.neuQuant.buildColormap();this.colorTab=this.neuQuant.getColormap()}if(this.dither){this.ditherPixels(this.dither.replace("-serpentine",""),this.dither.match(/-serpentine/)!==null)}else{this.indexPixels()}this.pixels=null;this.colorDepth=8;this.palSize=7;if(this.transparent!==null){this.transIndex=this.findClosest(this.transparent,true)}};GIFEncoder.prototype.indexPixels=function(imgq){var nPix=this.pixels.length/3;this.indexedPixels=new Uint8Array(nPix);var k=0;for(var j=0;j<nPix;j++){var index=this.findClosestRGB(this.pixels[k++]&255,this.pixels[k++]&255,this.pixels[k++]&255);this.usedEntry[index]=true;this.indexedPixels[j]=index}};GIFEncoder.prototype.ditherPixels=function(kernel,serpentine){var kernels={FalseFloydSteinberg:[[3/8,1,0],[3/8,0,1],[2/8,1,1]],FloydSteinberg:[[7/16,1,0],[3/16,-1,1],[5/16,0,1],[1/16,1,1]],Stucki:[[8/42,1,0],[4/42,2,0],[2/42,-2,1],[4/42,-1,1],[8/42,0,1],[4/42,1,1],[2/42,2,1],[1/42,-2,2],[2/42,-1,2],[4/42,0,2],[2/42,1,2],[1/42,2,2]],Atkinson:[[1/8,1,0],[1/8,2,0],[1/8,-1,1],[1/8,0,1],[1/8,1,1],[1/8,0,2]]};if(!kernel||!kernels[kernel]){throw"Unknown dithering kernel: "+kernel}var ds=kernels[kernel];var index=0,height=this.height,width=this.width,data=this.pixels;var direction=serpentine?-1:1;this.indexedPixels=new Uint8Array(this.pixels.length/3);for(var y=0;y<height;y++){if(serpentine)direction=direction*-1;for(var x=direction==1?0:width-1,xend=direction==1?width:0;x!==xend;x+=direction){index=y*width+x;var idx=index*3;var r1=data[idx];var g1=data[idx+1];var b1=data[idx+2];idx=this.findClosestRGB(r1,g1,b1);this.usedEntry[idx]=true;this.indexedPixels[index]=idx;idx*=3;var r2=this.colorTab[idx];var g2=this.colorTab[idx+1];var b2=this.colorTab[idx+2];var er=r1-r2;var eg=g1-g2;var eb=b1-b2;for(var i=direction==1?0:ds.length-1,end=direction==1?ds.length:0;i!==end;i+=direction){var x1=ds[i][1];var y1=ds[i][2];if(x1+x>=0&&x1+x<width&&y1+y>=0&&y1+y<height){var d=ds[i][0];idx=index+x1+y1*width;idx*=3;data[idx]=Math.max(0,Math.min(255,data[idx]+er*d));data[idx+1]=Math.max(0,Math.min(255,data[idx+1]+eg*d));data[idx+2]=Math.max(0,Math.min(255,data[idx+2]+eb*d))}}}}};GIFEncoder.prototype.findClosest=function(c,used){return this.findClosestRGB((c&16711680)>>16,(c&65280)>>8,c&255,used)};GIFEncoder.prototype.findClosestRGB=function(r,g,b,used){if(this.colorTab===null)return-1;if(this.neuQuant&&!used){return this.neuQuant.lookupRGB(r,g,b)}var c=b|g<<8|r<<16;var minpos=0;var dmin=256*256*256;var len=this.colorTab.length;for(var i=0,index=0;i<len;index++){var dr=r-(this.colorTab[i++]&255);var dg=g-(this.colorTab[i++]&255);var db=b-(this.colorTab[i++]&255);var d=dr*dr+dg*dg+db*db;if((!used||this.usedEntry[index])&&d<dmin){dmin=d;minpos=index}}return minpos};GIFEncoder.prototype.getImagePixels=function(){var w=this.width;var h=this.height;this.pixels=new Uint8Array(w*h*3);var data=this.image;var srcPos=0;var count=0;for(var i=0;i<h;i++){for(var j=0;j<w;j++){this.pixels[count++]=data[srcPos++];this.pixels[count++]=data[srcPos++];this.pixels[count++]=data[srcPos++];srcPos++}}};GIFEncoder.prototype.writeGraphicCtrlExt=function(){this.out.writeByte(33);this.out.writeByte(249);this.out.writeByte(4);var transp,disp;if(this.transparent===null){transp=0;disp=0}else{transp=1;disp=2}if(this.dispose>=0){disp=dispose&7}disp<<=2;this.out.writeByte(0|disp|0|transp);this.writeShort(this.delay);this.out.writeByte(this.transIndex);this.out.writeByte(0)};GIFEncoder.prototype.writeImageDesc=function(){this.out.writeByte(44);this.writeShort(0);this.writeShort(0);this.writeShort(this.width);this.writeShort(this.height);if(this.firstFrame||this.globalPalette){this.out.writeByte(0)}else{this.out.writeByte(128|0|0|0|this.palSize)}};GIFEncoder.prototype.writeLSD=function(){this.writeShort(this.width);this.writeShort(this.height);this.out.writeByte(128|112|0|this.palSize);this.out.writeByte(0);this.out.writeByte(0)};GIFEncoder.prototype.writeNetscapeExt=function(){this.out.writeByte(33);this.out.writeByte(255);this.out.writeByte(11);this.out.writeUTFBytes("NETSCAPE2.0");this.out.writeByte(3);this.out.writeByte(1);this.writeShort(this.repeat);this.out.writeByte(0)};GIFEncoder.prototype.writePalette=function(){this.out.writeBytes(this.colorTab);var n=3*256-this.colorTab.length;for(var i=0;i<n;i++)this.out.writeByte(0)};GIFEncoder.prototype.writeShort=function(pValue){this.out.writeByte(pValue&255);this.out.writeByte(pValue>>8&255)};GIFEncoder.prototype.writePixels=function(){var enc=new LZWEncoder(this.width,this.height,this.indexedPixels,this.colorDepth);enc.encode(this.out)};GIFEncoder.prototype.stream=function(){return this.out};module.exports=GIFEncoder},{"./LZWEncoder.js":2,"./TypedNeuQuant.js":3}],2:[function(require,module,exports){var EOF=-1;var BITS=12;var HSIZE=5003;var masks=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535];function LZWEncoder(width,height,pixels,colorDepth){var initCodeSize=Math.max(2,colorDepth);var accum=new Uint8Array(256);var htab=new Int32Array(HSIZE);var codetab=new Int32Array(HSIZE);var cur_accum,cur_bits=0;var a_count;var free_ent=0;var maxcode;var clear_flg=false;var g_init_bits,ClearCode,EOFCode;function char_out(c,outs){accum[a_count++]=c;if(a_count>=254)flush_char(outs)}function cl_block(outs){cl_hash(HSIZE);free_ent=ClearCode+2;clear_flg=true;output(ClearCode,outs)}function cl_hash(hsize){for(var i=0;i<hsize;++i)htab[i]=-1}function compress(init_bits,outs){var fcode,c,i,ent,disp,hsize_reg,hshift;g_init_bits=init_bits;clear_flg=false;n_bits=g_init_bits;maxcode=MAXCODE(n_bits);ClearCode=1<<init_bits-1;EOFCode=ClearCode+1;free_ent=ClearCode+2;a_count=0;ent=nextPixel();hshift=0;for(fcode=HSIZE;fcode<65536;fcode*=2)++hshift;hshift=8-hshift;hsize_reg=HSIZE;cl_hash(hsize_reg);output(ClearCode,outs);outer_loop:while((c=nextPixel())!=EOF){fcode=(c<<BITS)+ent;i=c<<hshift^ent;if(htab[i]===fcode){ent=codetab[i];continue}else if(htab[i]>=0){disp=hsize_reg-i;if(i===0)disp=1;do{if((i-=disp)<0)i+=hsize_reg;if(htab[i]===fcode){ent=codetab[i];continue outer_loop}}while(htab[i]>=0)}output(ent,outs);ent=c;if(free_ent<1<<BITS){codetab[i]=free_ent++;htab[i]=fcode}else{cl_block(outs)}}output(ent,outs);output(EOFCode,outs)}function encode(outs){outs.writeByte(initCodeSize);remaining=width*height;curPixel=0;compress(initCodeSize+1,outs);outs.writeByte(0)}function flush_char(outs){if(a_count>0){outs.writeByte(a_count);outs.writeBytes(accum,0,a_count);a_count=0}}function MAXCODE(n_bits){return(1<<n_bits)-1}function nextPixel(){if(remaining===0)return EOF;--remaining;var pix=pixels[curPixel++];return pix&255}function output(code,outs){cur_accum&=masks[cur_bits];if(cur_bits>0)cur_accum|=code<<cur_bits;else cur_accum=code;cur_bits+=n_bits;while(cur_bits>=8){char_out(cur_accum&255,outs);cur_accum>>=8;cur_bits-=8}if(free_ent>maxcode||clear_flg){if(clear_flg){maxcode=MAXCODE(n_bits=g_init_bits);clear_flg=false}else{++n_bits;if(n_bits==BITS)maxcode=1<<BITS;else maxcode=MAXCODE(n_bits)}}if(code==EOFCode){while(cur_bits>0){char_out(cur_accum&255,outs);cur_accum>>=8;cur_bits-=8}flush_char(outs)}}this.encode=encode}module.exports=LZWEncoder},{}],3:[function(require,module,exports){var ncycles=100;var netsize=256;var maxnetpos=netsize-1;var netbiasshift=4;var intbiasshift=16;var intbias=1<<intbiasshift;var gammashift=10;var gamma=1<<gammashift;var betashift=10;var beta=intbias>>betashift;var betagamma=intbias<<gammashift-betashift;var initrad=netsize>>3;var radiusbiasshift=6;var radiusbias=1<<radiusbiasshift;var initradius=initrad*radiusbias;var radiusdec=30;var alphabiasshift=10;var initalpha=1<<alphabiasshift;var alphadec;var radbiasshift=8;var radbias=1<<radbiasshift;var alpharadbshift=alphabiasshift+radbiasshift;var alpharadbias=1<<alpharadbshift;var prime1=499;var prime2=491;var prime3=487;var prime4=503;var minpicturebytes=3*prime4;function NeuQuant(pixels,samplefac){var network;var netindex;var bias;var freq;var radpower;function init(){network=[];netindex=new Int32Array(256);bias=new Int32Array(netsize);freq=new Int32Array(netsize);radpower=new Int32Array(netsize>>3);var i,v;for(i=0;i<netsize;i++){v=(i<<netbiasshift+8)/netsize;network[i]=new Float64Array([v,v,v,0]);freq[i]=intbias/netsize;bias[i]=0}}function unbiasnet(){for(var i=0;i<netsize;i++){network[i][0]>>=netbiasshift;network[i][1]>>=netbiasshift;network[i][2]>>=netbiasshift;network[i][3]=i}}function altersingle(alpha,i,b,g,r){network[i][0]-=alpha*(network[i][0]-b)/initalpha;network[i][1]-=alpha*(network[i][1]-g)/initalpha;network[i][2]-=alpha*(network[i][2]-r)/initalpha}function alterneigh(radius,i,b,g,r){var lo=Math.abs(i-radius);var hi=Math.min(i+radius,netsize);var j=i+1;var k=i-1;var m=1;var p,a;while(j<hi||k>lo){a=radpower[m++];if(j<hi){p=network[j++];p[0]-=a*(p[0]-b)/alpharadbias;p[1]-=a*(p[1]-g)/alpharadbias;p[2]-=a*(p[2]-r)/alpharadbias}if(k>lo){p=network[k--];p[0]-=a*(p[0]-b)/alpharadbias;p[1]-=a*(p[1]-g)/alpharadbias;p[2]-=a*(p[2]-r)/alpharadbias}}}function contest(b,g,r){var bestd=~(1<<31);var bestbiasd=bestd;var bestpos=-1;var bestbiaspos=bestpos;var i,n,dist,biasdist,betafreq;for(i=0;i<netsize;i++){n=network[i];dist=Math.abs(n[0]-b)+Math.abs(n[1]-g)+Math.abs(n[2]-r);if(dist<bestd){bestd=dist;bestpos=i}biasdist=dist-(bias[i]>>intbiasshift-netbiasshift);if(biasdist<bestbiasd){bestbiasd=biasdist;bestbiaspos=i}betafreq=freq[i]>>betashift;freq[i]-=betafreq;bias[i]+=betafreq<<gammashift}freq[bestpos]+=beta;bias[bestpos]-=betagamma;return bestbiaspos}function inxbuild(){var i,j,p,q,smallpos,smallval,previouscol=0,startpos=0;for(i=0;i<netsize;i++){p=network[i];smallpos=i;smallval=p[1];for(j=i+1;j<netsize;j++){q=network[j];if(q[1]<smallval){smallpos=j;smallval=q[1]}}q=network[smallpos];if(i!=smallpos){j=q[0];q[0]=p[0];p[0]=j;j=q[1];q[1]=p[1];p[1]=j;j=q[2];q[2]=p[2];p[2]=j;j=q[3];q[3]=p[3];p[3]=j}if(smallval!=previouscol){netindex[previouscol]=startpos+i>>1;for(j=previouscol+1;j<smallval;j++)netindex[j]=i;previouscol=smallval;startpos=i}}netindex[previouscol]=startpos+maxnetpos>>1;for(j=previouscol+1;j<256;j++)netindex[j]=maxnetpos}function inxsearch(b,g,r){var a,p,dist;var bestd=1e3;var best=-1;var i=netindex[g];var j=i-1;while(i<netsize||j>=0){if(i<netsize){p=network[i];dist=p[1]-g;if(dist>=bestd)i=netsize;else{i++;if(dist<0)dist=-dist;a=p[0]-b;if(a<0)a=-a;dist+=a;if(dist<bestd){a=p[2]-r;if(a<0)a=-a;dist+=a;if(dist<bestd){bestd=dist;best=p[3]}}}}if(j>=0){p=network[j];dist=g-p[1];if(dist>=bestd)j=-1;else{j--;if(dist<0)dist=-dist;a=p[0]-b;if(a<0)a=-a;dist+=a;if(dist<bestd){a=p[2]-r;if(a<0)a=-a;dist+=a;if(dist<bestd){bestd=dist;best=p[3]}}}}}return best}function learn(){var i;var lengthcount=pixels.length;var alphadec=30+(samplefac-1)/3;var samplepixels=lengthcount/(3*samplefac);var delta=~~(samplepixels/ncycles);var alpha=initalpha;var radius=initradius;var rad=radius>>radiusbiasshift;if(rad<=1)rad=0;for(i=0;i<rad;i++)radpower[i]=alpha*((rad*rad-i*i)*radbias/(rad*rad));var step;if(lengthcount<minpicturebytes){samplefac=1;step=3}else if(lengthcount%prime1!==0){step=3*prime1}else if(lengthcount%prime2!==0){step=3*prime2}else if(lengthcount%prime3!==0){step=3*prime3}else{step=3*prime4}var b,g,r,j;var pix=0;i=0;while(i<samplepixels){b=(pixels[pix]&255)<<netbiasshift;g=(pixels[pix+1]&255)<<netbiasshift;r=(pixels[pix+2]&255)<<netbiasshift;j=contest(b,g,r);altersingle(alpha,j,b,g,r);if(rad!==0)alterneigh(rad,j,b,g,r);pix+=step;if(pix>=lengthcount)pix-=lengthcount;i++;if(delta===0)delta=1;if(i%delta===0){alpha-=alpha/alphadec;radius-=radius/radiusdec;rad=radius>>radiusbiasshift;if(rad<=1)rad=0;for(j=0;j<rad;j++)radpower[j]=alpha*((rad*rad-j*j)*radbias/(rad*rad))}}}function buildColormap(){init();learn();unbiasnet();inxbuild()}this.buildColormap=buildColormap;function getColormap(){var map=[];var index=[];for(var i=0;i<netsize;i++)index[network[i][3]]=i;var k=0;for(var l=0;l<netsize;l++){var j=index[l];map[k++]=network[j][0];map[k++]=network[j][1];map[k++]=network[j][2]}return map}this.getColormap=getColormap;this.lookupRGB=inxsearch}module.exports=NeuQuant},{}],4:[function(require,module,exports){var GIFEncoder,renderFrame;GIFEncoder=require("./GIFEncoder.js");renderFrame=function(frame){var encoder,page,stream,transfer;encoder=new GIFEncoder(frame.width,frame.height);if(frame.index===0){encoder.writeHeader()}else{encoder.firstFrame=false}encoder.setTransparent(frame.transparent);encoder.setRepeat(frame.repeat);encoder.setDelay(frame.delay);encoder.setQuality(frame.quality);encoder.setDither(frame.dither);encoder.setGlobalPalette(frame.globalPalette);encoder.addFrame(frame.data);if(frame.last){encoder.finish()}if(frame.globalPalette===true){frame.globalPalette=encoder.getGlobalPalette()}stream=encoder.stream();frame.data=stream.pages;frame.cursor=stream.cursor;frame.pageSize=stream.constructor.pageSize;if(frame.canTransfer){transfer=function(){var i,len,ref,results;ref=frame.data;results=[];for(i=0,len=ref.length;i<len;i++){page=ref[i];results.push(page.buffer)}return results}();return self.postMessage(frame,transfer)}else{return self.postMessage(frame)}};self.onmessage=function(event){return renderFrame(event.data)}},{"./GIFEncoder.js":1}]},{},[4]);
6203
6203
  `],{type:"application/javascript"}))})}async function LS(e){for(let t=0;t<30;t++){let t=await e();if(t)return t;await new Promise(e=>setTimeout(e,50))}}let LO=(e,t,...n)=>({type:e,props:t,children:n||[]}),LC=async({element:e,page:t,store:n})=>{let r,i,{src:o}=e;if("svg"===e.type){let t=await l4(o);o=se(t,new Map(Object.entries(e.colorsReplace)))}// src = await cropImage(src, element);
6204
6204
  let a="";e.flipX&&(a+="scaleX(-1)"),e.flipY&&(a+="scaleY(-1)");let l={};if(e.clipSrc){let t=await l5(e.clipSrc);l["clip-path"]=`url(${t})`}let s=await PJ(o),u=s.width*e.cropWidth,c=s.height*e.cropHeight,d=e.width/e.height,h="svg"===e.type;h?(r=u,i=c):d>=u/c?(r=u,i=u/d):(r=c*d,i=c);let f=r/s.width,p=i/s.height,g=r/i,m=e.width/e.height,v=g>m?e.height/i:e.width/r,y=r*v/f,b=i*v/p,w=e.cropX*v*s.width,x=e.cropY*v*s.height;return LO("div",{src:o,style:{...l,width:"100%",height:"100%","border-radius":e.cornerRadius+"px",border:e.borderSize?`${e.borderSize}px solid ${e.borderColor}`:"none",background:`url(${o})`,transform:a,"background-size":`${Math.round(y)}px ${Math.round(b)}px`,"background-position-x":`${Math.round(w)}px`,"background-position-y":`${Math.round(x)}px`}})},Lk=async({element:e,page:t,store:n})=>{let r={};e.fill.indexOf("gradient")>=0&&(r={...r,"background-color":e.fill,"background-image":e.fill,"background-clip":"text","text-fill-color":"transparent","-webkit-background-clip":"text","-webkit-text-fill-color":"transparent"});let i=e.backgroundPadding*(e.fontSize*e.lineHeight),o=LO("div",{style:{position:"absolute",top:-i/2+"px",left:-i/2+"px",display:e.backgroundEnabled?"block":"none",width:e.width+i+"px",height:e.height+i+"px","background-color":e.backgroundColor,"border-radius":e.backgroundCornerRadius*(e.fontSize*e.lineHeight*.5)+"px"}}),a=LO("div",{style:{...r,position:"absolute",top:0,left:0,width:e.width+"px",color:e.fill,"white-space":"pre-wrap","font-size":e.fontSize+"px","text-align":e.align,"font-family":e.fontFamily,"text-decoration":e.textDecoration||"none","line-height":e.lineHeight,"letter-spacing":e.letterSpacing+"em","font-style":e.fontStyle,"font-weight":e.fontWeight,"-webkit-text-stroke":`${e.strokeWidth}px ${e.stroke}`,"text-stroke":`${e.strokeWidth}px ${e.stroke}`}},e.text.split("\n").join("<br />"));return LO("div",{style:{position:"relative"}},o,a)},LP=({element:e,type:t})=>{let n={"stroke-width":e.height,stroke:e.color,"line-cap":"round","stroke-linejoin":"round",// fill: element.color,
package/utils/fonts.d.ts CHANGED
@@ -10,7 +10,7 @@ export declare const globalFonts: mobx.IObservableArray<FontItem>;
10
10
  export declare function addGlobalFont(font: FontItem): void;
11
11
  export declare function removeGlobalFont(fontFamily: string): void;
12
12
  export declare function replaceGlobalFonts(fonts: Array<FontItem>): void;
13
- export declare const isFontLoaded: (fontName: string) => any;
13
+ export declare const isFontLoaded: (fontName: string) => boolean;
14
14
  export declare function loadFont(fontName: any): Promise<void>;
15
15
  export declare function setGoogleFontsVariants(variants: string): void;
16
16
  export declare function injectGoogleFont(fontName: string): void;
package/utils/fonts.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 s=Object.getOwnPropertyDescriptor(t,o);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,n,s)}: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};Object.defineProperty(exports,"__esModule",{value:!0}),exports.injectCustomFont=exports.injectGoogleFont=exports.setGoogleFontsVariants=exports.loadFont=exports.isFontLoaded=exports.replaceGlobalFonts=exports.removeGlobalFont=exports.addGlobalFont=exports.globalFonts=exports.getFontsList=exports.setGoogleFonts=exports.isGoogleFontChanged=void 0;const mobx=__importStar(require("mobx")),loader_1=require("./loader");let GOOGLE_FONTS=mobx.observable(["Roboto","Amatic SC","Press Start 2P","Marck Script","Rubik Mono One"]),googleFontsChanged=mobx.observable({value:!1});function isGoogleFontChanged(){return googleFontsChanged.value}function setGoogleFonts(e){"default"!==e?(googleFontsChanged.value=!0,GOOGLE_FONTS.splice(0,GOOGLE_FONTS.length),GOOGLE_FONTS.push(...e)):googleFontsChanged.value=!1}function getFontsList(){return GOOGLE_FONTS}function addGlobalFont(e){exports.globalFonts.push(e)}function removeGlobalFont(e){const t=exports.globalFonts.findIndex((t=>t.fontFamily===e));-1!==t&&exports.globalFonts.splice(t,1)}function replaceGlobalFonts(e){exports.globalFonts.replace(e)}exports.isGoogleFontChanged=isGoogleFontChanged,exports.setGoogleFonts=setGoogleFonts,exports.getFontsList=getFontsList,exports.globalFonts=mobx.observable([]),exports.addGlobalFont=addGlobalFont,exports.removeGlobalFont=removeGlobalFont,exports.replaceGlobalFonts=replaceGlobalFonts;var TEXT_TEXT="Some test text;?#D-ПРИВЕТ!1230o9u8i7y6t5r4e3w2q1",canvas=document.createElement("canvas");function measureArial(){return measureFont("Arial")}function measureTimes(){return measureFont("Times","Times")}function measureFont(e,t="Arial"){var o=canvas.getContext("2d");return o.font=`normal 40px '${e}', ${t}`,o.measureText(TEXT_TEXT).width}const MAX_ATTEMPTS=100,loadedFonts={Arial:!0},isFontLoaded=e=>loadedFonts[e];async function loadFont(e){var t;if(loadedFonts[e])return;const o=!!(null===(t=document.fonts)||void 0===t?void 0:t.load),n=measureArial();if(o)try{await document.fonts.load(`16px '${e}'`);const t=measureFont(e);if(n!==t)return void(loadedFonts[e]=!0)}catch(e){}const s=measureTimes(),r=measureFont(e);for(let t=0;t<100;t++){const t=measureFont(e,"Arial"),o=measureFont(e,"Times");if(t!==r||t!==n||o!==s)return void(loadedFonts[e]=!0);await new Promise((e=>setTimeout(e,60)))}console.warn(`Timeout for loading font "${e}". Looks like polotno can't load it. Is it a correct font family?`),(0,loader_1.triggerLoadError)(`Timeout for loading font "${e}"`)}exports.isFontLoaded=isFontLoaded,exports.loadFont=loadFont;const registeredGoogleFonts={};let googleFontsVariants="400,400italic,700,700italic";function setGoogleFontsVariants(e){googleFontsVariants=e}function injectGoogleFont(e){if(registeredGoogleFonts[e])return;const t=`https://fonts.googleapis.com/css?family=${e.replace(/ /g,"+")}:${googleFontsVariants}`,o=document.createElement("link");o.type="text/css",o.href=t,o.rel="stylesheet",document.getElementsByTagName("head")[0].appendChild(o),registeredGoogleFonts[e]=!0}exports.setGoogleFontsVariants=setGoogleFontsVariants,exports.injectGoogleFont=injectGoogleFont;const registeredCustomFonts={};function injectCustomFont(e){const t=e.fontFamily;if(registeredCustomFonts[t])return;if(!e.url&&!e.styles)return;const o=document.createElement("style");o.type="text/css";const n=e.styles||(e.url?[{src:`url("${e.url}")`}]:[]);let s="";n.forEach((e=>{s+=`\n @font-face {\n font-family: '${t}';\n src: ${e.src};\n font-style: ${e.fontStyle||"normal"};\n font-weight: ${e.fontWeight||"normal"};\n }\n `})),o.innerHTML=s,document.getElementsByTagName("head")[0].appendChild(o),registeredCustomFonts[e.fontFamily]=!0}exports.injectCustomFont=injectCustomFont;
1
+ "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,o,n){void 0===n&&(n=o);var s=Object.getOwnPropertyDescriptor(t,o);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,n,s)}: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};Object.defineProperty(exports,"__esModule",{value:!0}),exports.injectCustomFont=exports.injectGoogleFont=exports.setGoogleFontsVariants=exports.loadFont=exports.isFontLoaded=exports.replaceGlobalFonts=exports.removeGlobalFont=exports.addGlobalFont=exports.globalFonts=exports.getFontsList=exports.setGoogleFonts=exports.isGoogleFontChanged=void 0;const mobx=__importStar(require("mobx")),loader_1=require("./loader");let GOOGLE_FONTS=mobx.observable(["Roboto","Amatic SC","Press Start 2P","Marck Script","Rubik Mono One"]),googleFontsChanged=mobx.observable({value:!1});function isGoogleFontChanged(){return googleFontsChanged.value}function setGoogleFonts(e){"default"!==e?(googleFontsChanged.value=!0,GOOGLE_FONTS.splice(0,GOOGLE_FONTS.length),GOOGLE_FONTS.push(...e)):googleFontsChanged.value=!1}function getFontsList(){return GOOGLE_FONTS}function addGlobalFont(e){exports.globalFonts.push(e)}function removeGlobalFont(e){const t=exports.globalFonts.findIndex((t=>t.fontFamily===e));-1!==t&&exports.globalFonts.splice(t,1)}function replaceGlobalFonts(e){exports.globalFonts.replace(e)}exports.isGoogleFontChanged=isGoogleFontChanged,exports.setGoogleFonts=setGoogleFonts,exports.getFontsList=getFontsList,exports.globalFonts=mobx.observable([]),exports.addGlobalFont=addGlobalFont,exports.removeGlobalFont=removeGlobalFont,exports.replaceGlobalFonts=replaceGlobalFonts;var TEXT_TEXT="Some test text;?#D-ПРИВЕТ!1230o9u8i7y6t5r4e3w2q1",canvas=document.createElement("canvas");function measureArial(){return measureFont("Arial")}function measureTimes(){return measureFont("Times","Times")}function measureFont(e,t="Arial"){var o=canvas.getContext("2d");return o.font=`normal 40px '${e}', ${t}`,o.measureText(TEXT_TEXT).width}const MAX_ATTEMPTS=100,loadedFonts={Arial:!0},isFontLoaded=e=>!!loadedFonts[e];async function loadFont(e){var t;if(loadedFonts[e])return;const o=!!(null===(t=document.fonts)||void 0===t?void 0:t.load),n=measureArial();if(o)try{await document.fonts.load(`16px '${e}'`);const t=measureFont(e);if(n!==t)return void(loadedFonts[e]=!0)}catch(e){}const s=measureTimes(),r=measureFont(e);for(let t=0;t<100;t++){const t=measureFont(e,"Arial"),o=measureFont(e,"Times");if(t!==r||t!==n||o!==s)return void(loadedFonts[e]=!0);await new Promise((e=>setTimeout(e,60)))}console.warn(`Timeout for loading font "${e}". Looks like polotno can't load it. Is it a correct font family?`),(0,loader_1.triggerLoadError)(`Timeout for loading font "${e}"`)}exports.isFontLoaded=isFontLoaded,exports.loadFont=loadFont;const registeredGoogleFonts={};let googleFontsVariants="400,400italic,700,700italic";function setGoogleFontsVariants(e){googleFontsVariants=e}function injectGoogleFont(e){if(registeredGoogleFonts[e])return;const t=`https://fonts.googleapis.com/css?family=${e.replace(/ /g,"+")}:${googleFontsVariants}`,o=document.createElement("link");o.type="text/css",o.href=t,o.rel="stylesheet",document.getElementsByTagName("head")[0].appendChild(o),registeredGoogleFonts[e]=!0}exports.setGoogleFontsVariants=setGoogleFontsVariants,exports.injectGoogleFont=injectGoogleFont;const registeredCustomFonts={};function injectCustomFont(e){const t=e.fontFamily;if(registeredCustomFonts[t])return;if(!e.url&&!e.styles)return;const o=document.createElement("style");o.type="text/css";const n=e.styles||(e.url?[{src:`url("${e.url}")`}]:[]);let s="";n.forEach((e=>{s+=`\n @font-face {\n font-family: '${t}';\n src: ${e.src};\n font-style: ${e.fontStyle||"normal"};\n font-weight: ${e.fontWeight||"normal"};\n }\n `})),o.innerHTML=s,document.getElementsByTagName("head")[0].appendChild(o),registeredCustomFonts[e.fontFamily]=!0}exports.injectCustomFont=injectCustomFont;