polotno 2.0.1 → 2.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/canvas/text-element.js +1 -1
- package/package.json +1 -1
- package/polotno.bundle.js +3 -3
- package/utils/fonts.d.ts +1 -1
- package/utils/fonts.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.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)})),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}))}));
|
package/package.json
CHANGED
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
|
|
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,8 +1219,8 @@ 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(
|
|
1223
|
-
|
|
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
1226
|
if(!e.a.height){let n=x();t.history.ignore(()=>{e.set({height:n})});return}// also do that check only while exporting
|
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) =>
|
|
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
|
|
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;
|