polotno 3.16.0 → 3.17.0
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/element.js +1 -1
- package/canvas/figure-element.js +1 -1
- package/canvas/gif-element.js +1 -1
- package/canvas/html-element.js +1 -1
- package/canvas/image-element.d.ts +15 -2
- package/canvas/image-element.js +1 -1
- package/canvas/line-element.js +1 -1
- package/canvas/page.js +1 -1
- package/canvas/placed-node.d.ts +22 -0
- package/canvas/placed-node.js +1 -0
- package/canvas/render-tag-element.js +1 -1
- package/canvas/rich-editor.js +2 -2
- package/canvas/table-element.js +1 -1
- package/canvas/text-element/auto-delete-empty-text.d.ts +15 -0
- package/canvas/text-element/auto-delete-empty-text.js +1 -0
- package/canvas/text-element/font-specs-loader.js +1 -1
- package/canvas/text-element.js +1 -1
- package/canvas/use-color.d.ts +2 -4
- package/canvas/use-color.js +1 -1
- package/canvas/use-image.js +1 -1
- package/canvas/video-element.js +1 -1
- package/canvas/workspace-canvas.js +1 -1
- package/model/group-model.d.ts +3 -0
- package/model/page-model.d.ts +12 -0
- package/model/page-model.js +1 -1
- package/model/store.d.ts +5 -6
- package/model/store.js +1 -1
- package/model/table-model.d.ts +3 -0
- package/model/table-model.js +1 -1
- package/package.json +15 -15
- package/pages-timeline/page-preview.d.ts +9 -2
- package/pages-timeline/page-preview.js +1 -1
- package/polotno.bundle.js +150 -150
- package/side-panel/animations-panel.js +1 -1
- package/toolbar/image-toolbar.js +1 -1
- package/utils/fonts.js +1 -1
- package/utils/l10n.js +1 -1
- package/utils/loader.js +1 -1
- package/utils/px.d.ts +1 -0
- package/utils/px.js +1 -1
- package/utils/ref-counted.d.ts +5 -0
- package/utils/ref-counted.js +1 -0
- package/utils/validate-key.js +1 -1
- package/utils/wait.d.ts +0 -1
- package/utils/wait.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as e,jsxs as n}from"react/jsx-runtime";import i from"react";import{Button as t}from"../primitives/button.js";import{SliderField as a}from"../primitives/slider-field.js";import{NumericInput as o}from"../primitives/numeric-input.js";import{Select as l,SelectContent as r,SelectItem as d,SelectTrigger as m,SelectValue as s}from"../primitives/select.js";import{observer as p}from"mobx-react-lite";import{
|
|
1
|
+
import{jsx as e,jsxs as n}from"react/jsx-runtime";import i from"react";import{Button as t}from"../primitives/button.js";import{SliderField as a}from"../primitives/slider-field.js";import{NumericInput as o}from"../primitives/numeric-input.js";import{Select as l,SelectContent as r,SelectItem as d,SelectTrigger as m,SelectValue as s}from"../primitives/select.js";import{observer as p}from"mobx-react-lite";import{isAlive as c}from"mobx-state-tree";import{PolotnoIcon as u}from"../icons/registry.js";import{t as v}from"../utils/l10n.js";import{cn as h}from"../lib/utils.js";import{PanelHeader as g}from"../primitives/panel-header.js";import{PanelScrollArea as f}from"../primitives/panel-scroll-area.js";export{o as NumberInput};const b=e=>!!e&&c(e),x=(e,n)=>{var i;const t=n.filter(b),a=null===(i=t[0])||void 0===i?void 0:i.page;if(!a){return}const o=e.activePage;e.play({animatedElementsIds:t.map(e=>e.id),currentTime:a.startTime}),setTimeout(()=>{e.stop(),o&&c(o)&&e.selectPage(o.id)},1e3)},y=p(({element:i,store:a,enabled:o})=>{const l=i.animations.find(e=>"enter"===e.type),r=i.animations.find(e=>"exit"===e.type);return o?n("div",{children:[e("div",{style:{padding:"10px 0px"},children:"Animate"}),n("div",{style:{display:"flex",gap:10},children:[e(t,{variant:"outline",className:h("pn:flex-1",(null==l?void 0:l.enabled)&&!(null==r?void 0:r.enabled)&&"pn:bg-muted"),onClick:()=>{b(i)&&a.history.transaction(()=>{i.setAnimation("enter",{enabled:!0}),i.setAnimation("exit",{enabled:!1})})},children:"Enter"}),e(t,{variant:"outline",className:h("pn:flex-1",(null==l?void 0:l.enabled)&&(null==r?void 0:r.enabled)&&"pn:bg-muted"),onClick:()=>{b(i)&&a.history.transaction(()=>{i.setAnimation("enter",{enabled:!0}),i.setAnimation("exit",{enabled:!0})})},children:"Both"}),e(t,{variant:"outline",className:h("pn:flex-1",(null==r?void 0:r.enabled)&&!(null==l?void 0:l.enabled)&&"pn:bg-muted"),onClick:()=>{b(i)&&a.history.transaction(()=>{i.setAnimation("enter",{enabled:!1}),i.setAnimation("exit",{enabled:!0})})},children:"Exit"})]})]}):null}),k=["right","left","up","down","bottom-right","bottom-left","top-right","top-left"],C={right:e(u,{name:"animation.directionRight"}),left:e(u,{name:"animation.directionLeft"}),up:e(u,{name:"animation.directionUp"}),down:e(u,{name:"animation.directionDown"}),"bottom-right":e(u,{name:"animation.directionBottomRight"}),"bottom-left":e(u,{name:"animation.directionBottomLeft"}),"top-right":e(u,{name:"animation.directionTopRight"}),"top-left":e(u,{name:"animation.directionTopLeft"})},A=p(({value:i,onChange:t})=>n("div",{style:{paddingTop:"10px"},children:[e("div",{style:{paddingBottom:"10px"},children:"Direction"}),n(l,{value:i,onValueChange:e=>{null!==e&&t(e)},children:[e(m,{className:"pn:w-full",children:n("div",{className:"pn:flex pn:items-center pn:gap-2",children:[C[i],e(s,{})]})}),e(r,{children:k.map(i=>e(d,{value:i,children:n("div",{className:"pn:flex pn:items-center pn:gap-2",children:[C[i],i]})},i))})]})]})),j=p(({value:i,onChange:t})=>n("div",{style:{paddingTop:"10px"},children:[e("div",{style:{paddingBottom:"10px"},children:"Direction"}),n(l,{value:i,onValueChange:e=>{null!==e&&t(e)},children:[e(m,{className:"pn:w-full",children:e(s,{children:"out"===i?"Zoom Out":"Zoom In"})}),n(r,{children:[e(d,{value:"in",children:"Zoom In"}),e(d,{value:"out",children:"Zoom Out"})]})]})]})),N=p(({element:n})=>{const i=n.animations.find(e=>"enter"===e.type);if(!i){return null}const t=n.page.duration;return e("div",{style:{padding:"10px"},children:e(a,{label:"Delay",value:parseFloat((i.delay/1e3).toFixed(2)),onChange:e=>{b(n)&&n.setAnimation("enter",{delay:1e3*e})},min:0,max:t/1e3,step:.01})})}),T=p(({element:n,store:i})=>{const t=n.animations.find(e=>"loop"===e.type&&e.enabled);if(!t){return null}const o=500/t.duration;return e("div",{style:{padding:"10px"},children:e(a,{label:"Speed",value:o,onChange:e=>{b(n)&&n.setAnimation("loop",{duration:500/e})},min:.1,max:3,step:.01,onCommit:()=>x(i,[n])})})}),E=p(({element:n})=>{const i=n.animations.find(e=>"enter"===e.type);if(!i){return null}const t=n.page.duration;return e("div",{style:{padding:"10px"},children:e(a,{label:"Duration",value:parseFloat((i.duration/1e3).toFixed(2)),onChange:e=>{b(n)&&(n.setAnimation("enter",{duration:1e3*e}),n.setAnimation("exit",{duration:1e3*e}))},min:0,max:t/1e3,step:.01})})}),z=p(({element:n,store:i,animationName:t})=>{var o,l;const r=n.animations.find(e=>e.name===t&&e.enabled);if(!r){return null}const d=null!==(l=null===(o=r.data)||void 0===o?void 0:o.strength)&&void 0!==l?l:1,m=e=>{b(n)&&(i.history.transaction(()=>{n.animations.forEach(i=>{if(i.name===t){const t=i.data||{};n.setAnimation(i.type,{data:Object.assign(Object.assign({},t),{strength:e})})}})}),(()=>{let e;return(...t)=>{e&&clearTimeout(e),e=setTimeout(()=>{(()=>{i.isPlaying||x(i,[n])})(...t)},300)}})()())},s=Math.max(3,d);return e("div",{style:{padding:"10px"},children:e(a,{label:v("toolbar.strength"),value:parseFloat(d.toFixed(2)),onChange:e=>m(e),min:.1,sliderMax:s,step:.05})})}),F=p(({element:n})=>{const i=n.animations.find(e=>"exit"===e.type);if(!i){return null}const t=n.page.duration;return e("div",{style:{padding:"10px"},children:e(a,{label:"End Delay",value:parseFloat((i.delay/1e3).toFixed(2)),onChange:e=>{b(n)&&n.setAnimation("exit",{delay:1e3*e})},min:0,max:t/1e3,step:.01})})}),w=[{key:"move",icon:"animation.typeMove",label:"toolbar.move"},{key:"fade",icon:"animation.typeFade",label:"toolbar.fade"},{key:"zoom",icon:"animation.typeZoom",label:"toolbar.zoom"}],B=[{key:"rotate",icon:"animation.typeRotate",label:"toolbar.rotate"},{key:"blink",icon:"animation.typeBlink",label:"toolbar.blink"},{key:"bounce",icon:"animation.typeBounce",label:"toolbar.bounce"}];export const AnimationsPanel=p(({store:a})=>{var o,l,r,d;const m=a.selectedElements,s=m[0],p=s,c=m.map(e=>e.id).join(","),k="animation"===a.openedSidePanel;if(i.useEffect(()=>{k&&(s&&s.animations||a.restoreSidePanel())},[k,c]),!s||!s.animations){return null}const C=()=>a.selectedElements.filter(b),O=(e,n)=>{const i=C();i.length&&(a.history.transaction(()=>{i.forEach(i=>{i.setAnimation("enter",Object.assign({name:e},n)),i.setAnimation("exit",Object.assign(Object.assign({name:e},n),{from:n.to,to:n.from}))})}),n.enabled&&x(a,i))},P=(e,n=s)=>{var i;return!!((e?null===(i=null==n?void 0:n.animations)||void 0===i?void 0:i.filter(n=>n.name===e||n.type===e):null==n?void 0:n.animations)||[]).find(e=>e.enabled)},D=P("move")||P("fade")||P("zoom"),R=P("rotate")||P("blink")||P("bounce");return n(f,{header:e(g,{title:v("sidePanel.animate"),onClose:()=>a.restoreSidePanel()}),children:[n("div",{style:{paddingTop:"10px",lineHeight:"35px"},children:["Animations"," ",e(t,{variant:"outline",style:{marginLeft:"10px",display:D?"inline-flex":"none"},onClick:()=>{b(p)&&p.set({animations:[]})},children:"Remove All"})]}),n("div",{style:{paddingTop:"25px"},children:[e("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(100px, 1fr))",gap:"5px",paddingBottom:"10px"},children:w.map(({key:i,icon:a,label:o})=>e("div",{children:n(t,{variant:"outline",size:"lg",className:h("pn:flex pn:h-auto pn:w-full pn:flex-col pn:items-center pn:gap-2 pn:p-5",P(i)&&"pn:bg-muted"),onClick:()=>{O(i,{enabled:!P(i,C()[0])})},children:[e(u,{name:a}),v(o)]})},i))}),n("div",{className:"pn:bg-black/5 pn:dark:bg-white/5",style:{display:D?"block":"none",padding:"10px"},children:[e(y,{element:s,store:a,enabled:P("enter")||P("exit")}),P("move")&&e(A,{value:(null===(l=null===(o=s.animations.find(e=>"move"===e.name))||void 0===o?void 0:o.data)||void 0===l?void 0:l.direction)||"right",onChange:e=>{O("move",{data:{direction:e},enabled:!0})}}),P("move")&&e(z,{store:a,element:p,animationName:"move"}),P("zoom")&&e(j,{value:(null===(d=null===(r=s.animations.find(e=>"zoom"===e.name))||void 0===r?void 0:r.data)||void 0===d?void 0:d.direction)||"in",onChange:e=>{O("zoom",{data:{direction:e},enabled:!0})}}),P("zoom")&&e(z,{store:a,element:p,animationName:"zoom"}),P("enter")&&e(N,{store:a,element:p}),P("enter")&&e(E,{store:a,element:p}),P("exit")&&e(F,{store:a,element:p})]}),n("div",{style:{paddingTop:"10px",lineHeight:"35px"},children:["Effects"," ",e(t,{variant:"outline",style:{marginLeft:"10px",display:R?"inline-flex":"none"},onClick:()=>{b(p)&&p.set({animations:[]})},children:"Remove All"})]}),e("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(100px, 1fr))",gap:"5px",paddingTop:"10px"},children:B.map(({key:i,icon:o,label:l})=>e("div",{children:n(t,{variant:"outline",size:"lg",className:h("pn:flex pn:h-auto pn:w-full pn:flex-col pn:items-center pn:gap-2 pn:p-5",P(i)&&"pn:bg-muted"),onClick:()=>{((e,n)=>{const i=C();i.length&&(a.history.transaction(()=>{i.forEach(i=>{i.setAnimation("loop",Object.assign({name:e},n))})}),n.enabled&&x(a,i))})(i,{enabled:!P(i,C()[0])})},children:[e(u,{name:o}),v(l)]})},i))}),R&&e(T,{store:a,element:p}),P("bounce")&&e(z,{store:a,element:p,animationName:"bounce"})]})]})});
|
package/toolbar/image-toolbar.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as e,jsxs as o}from"react/jsx-runtime";import{observer as t}from"mobx-react-lite";import{Button as r}from"../primitives/button.js";import{Tooltip as i,TooltipContent as a,TooltipTrigger as n}from"../primitives/tooltip.js";import{ElementContainer as m,extendToolbar as s}from"./element-container.js";import{PolotnoIcon as l}from"../icons/registry.js";import c from"./filters-picker.js";import{AnimationsPicker as p}from"./animations-picker.js";import g from"./flip-button.js";import{flags as d}from"../utils/flags.js";import{ImageRemoveBackground as u}from"./image-remove-background-button.js";export{ImageRemoveBackground}from"./image-remove-background-button.js";import{getCrop as h,getImageSize as f}from"@polotno/core/image";import{t as I}from"../utils/l10n.js";import{isImageLoadError as C}from"../utils/errors.js";import{FitToPageButton as b}from"./selection-size.js";import{ImageEdit as j}from"./image-tools.js";export{ImageEdit,ImageToolActions}from"./image-tools.js";export const ImageFitToBackground=({element:o,elements:t})=>t&&t.length>1?null:e(r,{variant:"ghost",size:"sm",onClick:async()=>{const{page:e}=o,t=e.computedBleed,r=e.computedWidth+t.left+t.right,i=e.computedHeight+t.top+t.bottom,a=await f(o.src).catch(e=>{if(!C(e)){throw e}return console.warn("polotno: failed to fit the image to the background",e),null});if(!a){return}const n=o.stretchEnabled?{cropX:0,cropY:0,cropWidth:1,cropHeight:1}:h({width:r,height:i},a);o.set(Object.assign({x:-t.left,y:-t.top,width:r,height:i,rotation:0},n))},children:I("toolbar.fitToBackground")});export const ImageClip=t(({element:o,store:t,elements:i})=>o.contentEditable?o.clipSrc?e(r,{variant:"ghost",size:"sm",onClickCapture:()=>{i.forEach(e=>{e.set({clipSrc:""})})},children:I("toolbar.removeClip")}):e(r,{variant:"ghost",size:"sm",onClickCapture:e=>{e.stopPropagation(),t.openSidePanel("image-clip")},children:I("toolbar.clip")}):null);export const ImageCrop=t(({element:t})=>t._cropEnabled?o(i,{children:[e(n,{render:e(r,{variant:"ghost",size:"icon-sm",onClickCapture:e=>{e.stopPropagation(),t.toggleCropMode(!0)},"aria-label":I("toolbar.crop"),children:e(l,{name:"toolbar.crop",className:"pn:size-4"})})}),e(a,{children:I("toolbar.crop")})]}):null);export const CropModeBar=t(({element:t})=>o("div",{className:"pn:flex pn:items-center",children:[o(r,{variant:"ghost",size:"sm",onClickCapture:()=>{t.toggleCropMode(!1)},children:[e(l,{name:"action.confirm",className:"pn:size-4"}),I("toolbar.cropDone")]}),o(r,{variant:"ghost",size:"sm",onClickCapture:()=>{t.cancelCropMode()},children:[e(l,{name:"action.close",className:"pn:size-4"}),I("toolbar.cropCancel")]})]}));export const ImageRemoveClip=t(({element:o})=>o.clipSrc?e(r,{variant:"ghost",size:"sm",onClickCapture:()=>{o.set({clipSrc:""})},children:I("toolbar.removeClip")}):null);const k={ImageFlip:g,ImageFilters:c,ImageFitToBackground,ImageFitToPage:b,ImageCrop,ImageEdit:j,ImageClip,ImageRemoveBackground:u,ImageAnimations:p};export const ImageToolbar=t(({store:o,components:t})=>{const r=o.selectedElements[0],i=["ImageCrop","ImageEdit","ImageFlip","ImageFilters","ImageFitToPage","ImageFitToBackground","ImageClip",d.animationsEnabled&&"ImageAnimations"],a=s({type:"image",usedItems:i,components:t});return e(m,{items:a,itemRender:i=>{const a=t[i]||k[i];return e(a,{element:r,store:o,elements:o.selectedElements,components:t},i)}})});export default ImageToolbar;
|
|
1
|
+
import{jsx as e,jsxs as o}from"react/jsx-runtime";import{observer as t}from"mobx-react-lite";import{Button as r}from"../primitives/button.js";import{Tooltip as i,TooltipContent as a,TooltipTrigger as n}from"../primitives/tooltip.js";import{ElementContainer as m,extendToolbar as s}from"./element-container.js";import{PolotnoIcon as l}from"../icons/registry.js";import c from"./filters-picker.js";import{AnimationsPicker as p}from"./animations-picker.js";import g from"./flip-button.js";import{flags as d}from"../utils/flags.js";import{ImageRemoveBackground as u}from"./image-remove-background-button.js";export{ImageRemoveBackground}from"./image-remove-background-button.js";import{getCrop as h,getImageSize as f}from"@polotno/core/image";import{t as I}from"../utils/l10n.js";import{isImageLoadError as C}from"../utils/errors.js";import{FitToPageButton as b}from"./selection-size.js";import{ImageEdit as j}from"./image-tools.js";export{ImageEdit,ImageToolActions}from"./image-tools.js";export const ImageFitToBackground=({element:o,elements:t})=>t&&t.length>1?null:e(r,{variant:"ghost",size:"sm",onClick:async()=>{const{page:e}=o,t=e.computedBleed,r=e.computedWidth+t.left+t.right,i=e.computedHeight+t.top+t.bottom,a=await f(o.src).catch(e=>{if(!C(e)){throw e}return console.warn("polotno: failed to fit the image to the background",e),null});if(!a){return}const n=o.stretchEnabled?{cropX:0,cropY:0,cropWidth:1,cropHeight:1}:h({width:r,height:i},a);o.set(Object.assign({x:-t.left,y:-t.top,width:r,height:i,rotation:0},n))},children:I("toolbar.fitToBackground")});export const ImageClip=t(({element:o,store:t,elements:i})=>o.contentEditable?o.clipSrc?e(r,{variant:"ghost",size:"sm",onClickCapture:()=>{i.forEach(e=>{e.set({clipSrc:""})})},children:I("toolbar.removeClip")}):e(r,{variant:"ghost",size:"sm",onClickCapture:e=>{e.stopPropagation(),t.openSidePanel("image-clip")},children:I("toolbar.clip")}):null);export const ImageCrop=t(({element:t})=>t._cropEnabled?o(i,{children:[e(n,{render:e(r,{variant:"ghost",size:"icon-sm",onClickCapture:e=>{e.stopPropagation(),t.toggleCropMode(!0)},"aria-label":I("toolbar.crop"),children:e(l,{name:"toolbar.crop",className:"pn:size-4"})})}),e(a,{children:I("toolbar.crop")})]}):null);export const CropModeBar=t(({element:t})=>o("div",{className:"pn:flex pn:items-center",children:[o(r,{variant:"ghost",size:"sm",onClickCapture:()=>{t.toggleCropMode(!1)},children:[e(l,{name:"action.confirm",className:"pn:size-4"}),I("toolbar.cropDone")]}),o(r,{variant:"ghost",size:"sm",onClickCapture:()=>{t.cancelCropMode()},children:[e(l,{name:"action.close",className:"pn:size-4"}),I("toolbar.cropCancel")]})]}));export const ImageRemoveClip=t(({element:o})=>o.clipSrc?e(r,{variant:"ghost",size:"sm",onClickCapture:()=>{o.set({clipSrc:""})},children:I("toolbar.removeClip")}):null);const k={ImageFlip:g,ImageFilters:c,ImageFitToBackground,ImageFitToPage:t(({store:o,elements:t})=>!t||t.length<=1?null:e(b,{store:o})),ImageCrop,ImageEdit:j,ImageClip,ImageRemoveBackground:u,ImageAnimations:p};export const ImageToolbar=t(({store:o,components:t})=>{const r=o.selectedElements[0],i=["ImageCrop","ImageEdit","ImageFlip","ImageFilters","ImageFitToPage","ImageFitToBackground","ImageClip",d.animationsEnabled&&"ImageAnimations"],a=s({type:"image",usedItems:i,components:t});return e(m,{items:a,itemRender:i=>{const a=t[i]||k[i];return e(a,{element:r,store:o,elements:o.selectedElements,components:t},i)}})});export default ImageToolbar;
|
package/utils/fonts.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as
|
|
1
|
+
import*as A from"mobx";import{triggerLoadError as t,getFontLoadTimeout as o}from"./loader.js";import{polotnoError as e}from"@polotno/core/errors";import{removeTags as n}from"@polotno/core/text";import{decodeBase64 as r}from"./base64.js";import{DEFAULT_RETRIES as s,retryDelayMs as i}from"@polotno/core/retry";import{getGoogleFontsUrl as c,getGoogleFontsVariants as a}from"@polotno/core/google-fonts-url";import{resolveFontFaceStyles as l,googleFontVariantUrl as u,cssFontFamily as f,parseUnicodeRange as d,rangesCover as m,toNumericWeight as p}from"@polotno/core/fonts";export{setGoogleFontsVariants,getGoogleFontsVariants,getGoogleFontsUrl}from"@polotno/core/google-fonts-url";const g=["Roboto","Amatic SC","Press Start 2P","Marck Script","Rubik Mono One"];let h=A.observable([...g]),F=A.observable({value:!1});export function isGoogleFontChanged(){return F.value}export function setGoogleFonts(A){if("default"===A){return h.replace([...g]),void(F.value=!1)}F.value=!0,h.splice(0,h.length),h.push(...A)}export function getFontsList(){return h}export const globalFonts=A.observable([]);export function addGlobalFont(A){globalFonts.push(A)}export function removeGlobalFont(A){const t=globalFonts.findIndex(t=>t.fontFamily===A);-1!==t&&globalFonts.splice(t,1)}export function replaceGlobalFonts(A){globalFonts.replace(A)}const y="BESbswy 0123456789 Il1Ww";function w(A){const t=function(A=""){const t=n(A).replace(/\s+/g," ").trim();return t?Array.from(t).slice(0,10).join(""):""}(A);return t?`${y} ${t}`:y}export function _getFontProbeTextForTesting(A){return w(A)}const b="PolotnoBlank";let x,B;function $(A,t,o,e){null!=B||(B=document.createElement("canvas"));const n=B.getContext("2d");if(!n){return!1}const r=(A,e)=>{n.font=`${t} ${o} 40px ${A}`;const r=n.measureText(e);return r.width>0||r.actualBoundingBoxLeft+r.actualBoundingBoxRight>0};if(r(b,y)){return!1}const s=`${f(A)}, ${b}`;return e.some(A=>r(s,A))}export function measureFontDom(A,t="sans-serif",o="normal",e="normal",n=y){if("undefined"==typeof document||!document.body){return 0}const r=document.createElement("span");r.textContent=n,r.style.cssText=`\n position:absolute;\n visibility:hidden;\n white-space:nowrap;\n top:-9999px;\n left:-9999px;\n font:${o} ${e} 90px ${f(A)}, ${t};\n `,document.body.appendChild(r);const s=r.getBoundingClientRect().width;return r.remove(),s}const E={Arial:!0},v={};export const isFontLoaded=(A,t,o,e)=>{if(t&&o){const n=`${A}_${t}_${o}`;if(!E[n]){return!1}const r=textChars(e),s=v[n];return!![...r].every(A=>null==s?void 0:s.has(A))||function(A,t,o,e){if("undefined"==typeof document||!document.fonts){return!1}const n="italic"===t?"italic":"normal",r=p(o),s=V(A),i=[...e].map(A=>A.codePointAt(0)),c=new Set;let a=!1;for(const u of document.fonts){if(V(u.family)!==s){continue}if(a=!0,u.style!==n){continue}const[A,t=A]=u.weight.split(/\s+/).map(p);if(r<A||r>t){continue}const o=d(u.unicodeRange),e=i.filter(A=>m(o,A));if(e.length){if("loaded"!==u.status){return!1}e.forEach(A=>c.add(A))}}if(a){return i.every(A=>c.has(A))}try{return document.fonts.check(G(A,t,o),e)}catch(l){return!1}}(A,t,o,r)}return Object.keys(E).some(t=>t.startsWith(A+"_"))||!!E[A]};export function _setFontLoadedForTesting(A,t){t?E[A]=!0:delete E[A]}export async function loadFont(A,t,e,n){var r;const s=performance.now()+o();await loadFontFace(A,t,e,n);const i=textChars(n),c=()=>{var o,n;const r=null!==(o=v[n=`${A}_${t}_${e}`])&&void 0!==o?o:v[n]=new Set;for(const A of i){r.add(A)}};if(!i||!(null===(r=document.fonts)||void 0===r?void 0:r.load)){return c()}let a;await Promise.race([document.fonts.load(G(A,t,e),i).catch(()=>{}).then(c),new Promise(A=>{a=setTimeout(A,Math.max(0,s-performance.now()))})]),clearTimeout(a)}const G=(A,t,o)=>`${t} ${o} 16px ${f(A)}`;export function textChars(A){return[...new Set(n(null!=A?A:"").replace(/\s/g,""))].join("")}export async function loadFontFace(A,n,s,c){var a;const l=`${A}_${n}_${s}`;if(injectGoogleFontVariant(A,n,s),E[l]&&!j(A,n,s)){return}const u=!!(null===(a=document.fonts)||void 0===a?void 0:a.load),f=w(c),d=[...textChars(c)];await(null!=x||(x=(async()=>{if("undefined"==typeof FontFace){return}const A=new FontFace(b,r("AAEAAAAKAIAAAwAgT1MvMlHNUusAAACsAAAAYGNtYXAAIQA0AAABDAAAAChnbHlmAAAAAAAAATQAAAAKaGVhZF8WQOUAAAFAAAAANmhoZWEDIf87AAABeAAAACRobXR4AAAAAAAAAZwAAAAIbG9jYQAFAAAAAAGkAAAABm1heHAAAwAAAAABrAAAACBuYW1lCUoZTgAAAcwAAACMcG9zdAADAAAAAAJYAAAAIAAEAAABkAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQT0xPAEAAAP//AyD/OAAAAyAAyAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAwAKAAAADAANAAAAAAAcAAAAAAAAAAEAAAAAABD//wAAAAEAAAAAAAAAAAAAAAAAAQAAAAEAAAAAAABfDzz1AAMD6AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAgAAAAAAAAABAAADIP84AAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAFAAAAAQAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQANgADAAEECQABABgAAAADAAEECQACAA4AGAADAAEECQAEABgAJgADAAEECQAGABgAPgBQAG8AbABvAHQAbgBvAEIAbABhAG4AawBSAGUAZwB1AGwAYQByAFAAbwBsAG8AdABuAG8AQgBsAGEAbgBrAFAAbwBsAG8AdABuAG8AQgBsAGEAbgBrAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="));document.fonts.add(A),await A.load()})().catch(A=>{console.error("Polotno could not load its blank probe font: no font can be verified as ready.",A)})),x);const m=o()/60;for(let o=0;o<m;o++){const r=!j(A,n,s);let c=[];if(u){try{c=await document.fonts.load(G(A,n,s),f)}catch(p){}}const a=t=>$(A,n,s,t),m=c.length>0&&c.every(A=>"loaded"===A.status);if(r&&(a([f])||m&&a(d))){return void Q(l,A)}if("missing"===T[A]){if(I(A)){const o=`Font "${A}" not found: not registered and no matching Google Font.`;console.error(o),t(e("FONT_FAILED",o,{family:A,reason:"not-found"}))}return}if(A in C&&!C[A]&&"errored"===T[A]&&injectGoogleFont(A),N[A]&&Y(A)){const n=k(A);if("wait"===n){await new Promise(A=>setTimeout(A,60));continue}if("spent"!==n){W(A);const t=i(n);await new Promise(A=>setTimeout(A,t)),o+=Math.ceil(t/60);continue}if(I(A)){const o=`Failed to load font "${A}": its font file could not be fetched.`;console.error(o),t(e("FONT_FAILED",o,{family:A,reason:"fetch-failed"}))}return}await new Promise(A=>setTimeout(A,60))}console.warn(`Timeout for loading font "${A}". Looks like polotno can't load it. Is it a correct font family?`),t(e("FONT_FAILED",`Timeout for loading font "${A}"`,{family:A,reason:"timeout"}))}const C={},T={},D=new Set;function I(A){return!D.has(A)&&(D.add(A),setTimeout(()=>D.delete(A),o()),!0)}function Q(A,t){E[A]=!0,delete T[t],delete P[t]}const P={};function k(A){const t=P[A],e=!t||Date.now()-t.at>o()?0:t.spent;return e>=s-1?"spent":t&&e>0&&Date.now()-t.at<i(e)?"wait":(P[A]={spent:e+1,at:Date.now()},e+1)}const _={};function j(A,t,o){return"loading"===C[A]||"loading"===_[`${A}|${"italic"===t?1:0}|${parseInt(o,10)}`]}export function injectGoogleFontVariant(A,t,o){const e=parseInt(o,10);if(!Number.isFinite(e)){return}if(function(A){const t=new Set;for(const o of a().split(",")){const e=o.trim().match(/^(\d+)(italic|i)?$/);e&&!!e[2]===A&&t.add(parseInt(e[1],10))}return t}("italic"===t).has(e)){return}if(!(A in C)){return}const n="italic"===t,r=`${A}|${n?1:0}|${e}`;if(_[r]){return}_[r]="loading";const s=document.createElement("link");s.type="text/css",s.href=u(A,n,e),s.rel="stylesheet",s.onload=()=>{_[r]=!0},s.onerror=()=>{_[r]=!0,s.remove()},document.getElementsByTagName("head")[0].appendChild(s)}export function injectGoogleFont(A){if(C[A]){return}const t=c(A),o=document.createElement("link");o.type="text/css",o.href=t,o.rel="stylesheet",o.onload=()=>{C[A]=!0},o.onerror=()=>{o.remove(),C[A]=!1,"errored"===T[A]?function(A){T[A]="probing",fetch(c(A),{mode:"no-cors"}).then(()=>{T[A]="missing"}).catch(()=>{delete T[A]})}(A):T[A]||(T[A]="errored")},document.getElementsByTagName("head")[0].appendChild(o),C[A]="loading"}const N={};let R;function S(){return R||(R=document.getElementById("polotno-font-style"),R||(R=document.createElement("style"),R.id="polotno-font-style",document.head.appendChild(R)),R)}function O(A){const t=A.fontFamily,o=l(A),e=S().sheet;return o.map(A=>{const o=e.insertRule(`\n @font-face{\n font-family:${f(t)};\n src:${A.src};\n font-style:${A.fontStyle};\n font-weight:${A.fontWeight};\n font-display:swap; /* optional but recommended */\n }`,e.cssRules.length);return e.cssRules[o]})}export function injectCustomFont(A){const t=A.fontFamily;if(!A.url&&!A.styles){return}const o=JSON.stringify(l(A)),e=N[t];if(e){if(e.src===o){return}L(e.rules),M(t)}delete T[t],N[t]={font:A,src:o,rules:O(A)}}function L(A){const t=S().sheet;for(const o of A){const A=Array.prototype.indexOf.call(t.cssRules,o);A>=0&&t.deleteRule(A)}}export function removeCustomFont(A){const t=N[A];t&&(L(t.rules),delete N[A],M(A))}function M(A){delete P[A];for(const t of Object.keys(E)){(t===A||t.startsWith(A+"_"))&&(delete E[t],delete v[t])}}function W(A){const t=N[A];t&&(L(t.rules),t.rules=O(t.font))}const V=A=>A.trim().replace(/^["']|["']$/g,"").toLowerCase();function Y(A){const t=document.fonts;if(!t||"function"!=typeof t.forEach){return!1}const o=V(A);let e=!1;return t.forEach(A=>{"error"===A.status&&V(A.family)===o&&(e=!0)}),e}
|
package/utils/l10n.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{observable as e,action as o,toJS as a}from"mobx";const r=e({imageEdit:{title:"AI edit",expand:"Expand",upscale:"Upscale",inpaint:"Generative fill",replace:"Replace",remove:"Remove",prompt:"Your prompt",promptPlaceholder:"Describe what should be there",expandPromptPlaceholder:"Describe the new area (optional)",replaceDescription:"Select an area on the image, then describe what you want to change.",replaceHint:"Describe what should replace the selection, such as “plain wall” or “open sky”.",removeDescription:"Select an object to remove. The surrounding image will fill the selected area.",expandDescription:"Drag the frame beyond the image edges to make room for new content.",cropDescription:"Drag the frame to crop the image.",upscaleDescription:"Increase the image resolution.",removeBackgroundDescription:"Remove the image background.",applyCrop:"Apply crop",generate:"Generate",clear:"Clear selection",resetFrame:"Reset frame",processing:"Generating…",loadingImage:"Loading image…",upscaling:"Upscaling…",removingBackground:"Removing background…",failed:"The image could not be edited. Please try again.",rasterFailed:"This device could not prepare the image. Try a smaller image.",selectRegion:"Drag on the image to select an area."},toolbar:{duration:"Duration",opacity:"Opacity",effects:"Effects",blur:"Blur",curvedText:"Curved text",curvePower:"Power",temperature:"Temperature",saturation:"Saturation",contrast:"Contrast",shadows:"Shadows",white:"White",black:"Black",vibrance:"Vibrance",textBackground:"Background",textBox:"Text box",backgroundCornerRadius:"Corner radius",backgroundOpacity:"Opacity",backgroundPadding:"Padding",brightness:"Brightness",filters:"Filters",sepia:"Sepia",grayscale:"Grayscale",cold:"Cold",natural:"Natural",warm:"Warm",textStroke:"Text Stroke",textEffect:{none:"None",shadow:"Shadow",lift:"Lift",glow:"Glow",outline:"Outline",sticker:"Sticker",pop:"Pop",background:"Background"},blendMode:"Blending",blend:{"pass-through":"Pass Through",normal:"Normal",multiply:"Multiply",screen:"Screen",overlay:"Overlay",darken:"Darken",lighten:"Lighten","color-dodge":"Color Dodge","color-burn":"Color Burn","hard-light":"Hard Light","soft-light":"Soft Light",difference:"Difference",exclusion:"Exclusion",hue:"Hue",saturation:"Saturation",color:"Color",luminosity:"Luminosity"},strokeLineJoin:"Corners",joinRound:"Round",joinMiter:"Miter",joinBevel:"Bevel",shadow:"Shadow",border:"Border",cornerRadius:"Corner Radius",copyStyle:"Copy style",uppercase:"Uppercase",position:"Position",layering:"Layering",toForward:"To Front",up:"Forward",down:"Backward",toBottom:"To back",alignLeft:"Align left",alignCenter:"Align center",alignRight:"Align right",alignTop:"Align top",alignMiddle:"Align middle",alignBottom:"Align bottom",flip:"Flip",flipHorizontally:"Flip horizontally",flipVertically:"Flip vertically",fitToBackground:"
|
|
1
|
+
import{observable as e,action as o,toJS as a}from"mobx";const r=e({imageEdit:{title:"AI edit",expand:"Expand",upscale:"Upscale",inpaint:"Generative fill",replace:"Replace",remove:"Remove",prompt:"Your prompt",promptPlaceholder:"Describe what should be there",expandPromptPlaceholder:"Describe the new area (optional)",replaceDescription:"Select an area on the image, then describe what you want to change.",replaceHint:"Describe what should replace the selection, such as “plain wall” or “open sky”.",removeDescription:"Select an object to remove. The surrounding image will fill the selected area.",expandDescription:"Drag the frame beyond the image edges to make room for new content.",cropDescription:"Drag the frame to crop the image.",upscaleDescription:"Increase the image resolution.",removeBackgroundDescription:"Remove the image background.",applyCrop:"Apply crop",generate:"Generate",clear:"Clear selection",resetFrame:"Reset frame",processing:"Generating…",loadingImage:"Loading image…",upscaling:"Upscaling…",removingBackground:"Removing background…",failed:"The image could not be edited. Please try again.",rasterFailed:"This device could not prepare the image. Try a smaller image.",selectRegion:"Drag on the image to select an area."},toolbar:{duration:"Duration",opacity:"Opacity",effects:"Effects",blur:"Blur",curvedText:"Curved text",curvePower:"Power",temperature:"Temperature",saturation:"Saturation",contrast:"Contrast",shadows:"Shadows",white:"White",black:"Black",vibrance:"Vibrance",textBackground:"Background",textBox:"Text box",backgroundCornerRadius:"Corner radius",backgroundOpacity:"Opacity",backgroundPadding:"Padding",brightness:"Brightness",filters:"Filters",sepia:"Sepia",grayscale:"Grayscale",cold:"Cold",natural:"Natural",warm:"Warm",textStroke:"Text Stroke",textEffect:{none:"None",shadow:"Shadow",lift:"Lift",glow:"Glow",outline:"Outline",sticker:"Sticker",pop:"Pop",background:"Background"},blendMode:"Blending",blend:{"pass-through":"Pass Through",normal:"Normal",multiply:"Multiply",screen:"Screen",overlay:"Overlay",darken:"Darken",lighten:"Lighten","color-dodge":"Color Dodge","color-burn":"Color Burn","hard-light":"Hard Light","soft-light":"Soft Light",difference:"Difference",exclusion:"Exclusion",hue:"Hue",saturation:"Saturation",color:"Color",luminosity:"Luminosity"},strokeLineJoin:"Corners",joinRound:"Round",joinMiter:"Miter",joinBevel:"Bevel",shadow:"Shadow",border:"Border",cornerRadius:"Corner Radius",copyStyle:"Copy style",uppercase:"Uppercase",position:"Position",layering:"Layering",toForward:"To Front",up:"Forward",down:"Backward",toBottom:"To back",alignLeft:"Align left",alignCenter:"Align center",alignRight:"Align right",alignTop:"Align top",alignMiddle:"Align middle",alignBottom:"Align bottom",flip:"Flip",flipHorizontally:"Flip horizontally",flipVertically:"Flip vertically",fitToBackground:"Fit to page",fitToPage:"Fit to page",widthShort:"W",heightShort:"H",removeBackground:"Remove background",removeBackgroundTitle:"Remove background from image",cancelRemoveBackground:"Cancel",confirmRemoveBackground:"Confirm",crop:"Crop",cropDone:"Done",cropCancel:"Cancel",clip:"Apply mask",removeClip:"Remove mask",removeMask:"Remove mask",transparency:"Transparency",lockedDescription:"Object is locked. Unlock it to allow changes from canvas.",unlockedDescription:"Object is unlocked. Lock it to prevent changes from canvas.",removeElements:"Remove elements",duplicateElements:"Duplicate elements",download:"Download",saveAsImage:"Save as image",saveAsPDF:"Save as PDF",lineHeight:"Line height",letterSpacing:"Letter spacing",offsetX:"Offset X",offsetY:"Offset Y",color:"Color",selectable:"Selectable",draggable:"Draggable",removable:"Removable",resizable:"Resizable",contentEditable:"Can change content",styleEditable:"Can change style",alwaysOnTop:"Always on top",showInExport:"Show in export",ungroupElements:"Ungroup",groupElements:"Group",lineSize:"Line size",fade:"Fade",move:"Move",zoom:"Zoom",animate:"Animate",rotate:"Rotate",none:"None",bounce:"Bounce",blink:"Blink",strength:"Strength",spaceEvenly:"Space evenly",horizontalDistribution:"Horizontally",verticalDistribution:"Vertically",strokeWidth:"Stroke Width",strokeSettings:"Stroke settings",spacing:"Spacing",volume:"Volume",speed:"Speed",seconds:"sec",lineStyle:"Line style",lineStartHead:"Line start",lineEndHead:"Line end",textDirection:"Text direction",fontSize:"Font size",fontFamily:"Font family",fontFamilyMixed:"Mixed",fontsInSelection:"Fonts in selection",textAlign:"Text align",verticalAlign:"Vertical align",bold:"Bold",italic:"Italic",underline:"Underline",strikethrough:"Strikethrough",cellBackground:"Cell background",tableBorderSettings:"Border settings",tableBorderColor:"Border color",tableBorderWidth:"Border width",tableBorderStyle:"Border style",borderModeAll:"All borders",borderModeOuter:"Outer borders",borderModeInner:"Inner borders",borderModeBottomOnly:"Bottom only",borderModeTopOnly:"Top only",borderModeLeftOnly:"Left only",borderModeRightOnly:"Right only",borderModeInnerHorizontal:"Inner horizontal",borderModeInnerVertical:"Inner vertical",tableStructure:"Table structure",tableRows:"Rows",tableColumns:"Columns",insertRowAbove:"Insert row above",insertRowBelow:"Insert row below",deleteRow:"Delete row",insertColumnLeft:"Insert column left",insertColumnRight:"Insert column right",deleteColumn:"Delete column",deleteRows:"Delete rows",deleteColumns:"Delete columns",distributeRowsEvenly:"Distribute rows evenly",distributeColumnsEvenly:"Distribute columns evenly",cellPadding:"Cell padding",listFormat:"List",colorPicker:{solid:"Solid",linear:"Linear",angle:"Angle",stops:"Gradient stops",stop:"Stop",addStop:"Add stop",removeStop:"Remove stop",reverse:"Reverse gradient",colors:"Colors",resetColors:"Reset",recolorAll:"Recolor all"},clipFade:{title:"Fade",preparing:"Preparing mask…",shape:"Shape",linear:"Linear",radial:"Radial",stopOpacity:"Stop opacity",stops:"Fade stops",stop:"Stop",start:"Fade start",end:"Fade end",center:"Fade center",radius:"Fade radius",reverse:"Reverse",removeStop:"Remove stop",addStop:"Add stop",reset:"Reset",hint:"Drag the handles on the image to position the fade."},aiText:{aiWrite:"AI write",rewrite:"Rewrite",shorten:"Shorten",continue:"Continue writing",proofread:"Proofread",tones:"Tones",friendly:"Friendly",professional:"Professional",humorous:"Humorous",formal:"Formal",customPrompt:"Custom prompt",generatedResult:"Generated result",cancel:"Cancel",generate:"Generate",back:"Back",tryAgain:"Try Again",insert:"Insert",promptPlaceholder:"Describe what you want to generate"}},workspace:{noPages:"There are no pages yet...",addPage:"Add page",removePage:"Remove page",duplicatePage:"Duplicate page",moveUp:"Move up",moveDown:"Move down",moveLeft:"Move left",moveRight:"Move right"},scale:{reset:"Reset"},error:{removeBackground:"Ops! Something went wrong. Background can not be removed."},sidePanel:{close:"Close",templates:"Templates",searchTemplatesWithSameSize:"Show templates with the same size",searchPlaceholder:"Search...",otherFormats:"Other formats",noResults:"No results",error:"Loading is failed...",text:"Text",uploadFont:"Upload font",myFonts:"My fonts",photos:"Photos",videos:"Videos",animations:"Animations",effects:"Effects",elements:"Elements",shapes:"Shapes",tables:"Tables",lines:"Lines",draw:"Draw",drawTool:"Tool",drawSelection:"Selection",drawBrush:"Brush",drawHighlighter:"Highlighter",upload:"Upload",uploadImage:"Add file",uploadTip:"Upload your assets",uploadUnsupported:"Skipped some files. You can add images, video and audio.",uploadFailed:"Upload failed. Please try again.",background:"Background",resize:"Resize",layers:"Layers",animate:"Animate",layerTypes:{image:"Image",text:"Text",svg:"SVG",line:"Line",figure:"Figure",group:"Group"},layersTip:"Elements on your active page:",noLayers:"No elements on the page...",namePlaceholder:"Type element name...",useMagicResize:"Use magic resize",advanced:"Advanced",bleed:"Bleed",showBleed:"Show bleed",clipImage:"Mask image",width:"Width",height:"Height",units:"Units",magicResizeDescription:"Magic resize will automatically resize and move all elements on the canvas",headerText:"Header",createHeader:"Create header",subHeaderText:"Sub Header",createSubHeader:"Create sub header",bodyText:"Body text",createBody:"Create body text"},pagesTimeline:{pages:"Pages",removePage:"Remove page",addPage:"Add page",duplicatePage:"Duplicate page",removeAudio:"Remove audio",duplicateAudio:"Duplicate audio",renameAudio:"Rename audio",muteAudio:"Mute",unmuteAudio:"Unmute",volume:"Volume",speed:"Speed",rewind:"Rewind to start",editAsVideo:"Edit as video",editAsVideoHint:"On: preview the frame at the playhead — timed elements hide outside their range. Off: show all elements while editing."},contextMenu:{duplicate:"Duplicate",split:"Split at playhead",rename:"Rename",remove:"Remove",lock:"Lock",unlock:"Unlock",copy:"Copy",paste:"Paste",copyStyle:"Copy style",moveUp:"Move up",moveDown:"Move down",moveBack:"Move back",moveForward:"Move forward"}}),n=e=>e&&"object"==typeof e;function i(e,o){Object.keys(o).forEach(a=>{const r=e[a],l=o[a];n(l)&&n(r)?i(r,l):e[a]=l})}function l(e,o,a=""){Object.keys(o).forEach(r=>{const i=o[r],s=a?`${a}.${r}`:r;n(i)?n(e[r])?l(e[r],i,s):console.warn(`Missing nested translation object at '${s}'`):void 0===e[r]&&console.warn(`Missing translation '${s}'`)})}export const setTranslations=o((e,{validate:o=!1}={})=>{o&&l(e,r),i(r,e)});export const getTranslations=()=>a(r);const s={};export const t=e=>{const o=function(e,o){var a,r=o.split("."),n=e;for(a=0;a<r.length;++a){if(null==n[r[a]]){return}n=n[r[a]]}return n}(r,e);if(void 0!==o){return o}s[e]||(s[e]=!0,console.warn(`Missing translation '${e}'`));const a=e.split("."),n=a[a.length-1]||" ";return n.charAt(0).toUpperCase()+n.slice(1)};
|
package/utils/loader.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isAnimationUsed as
|
|
1
|
+
import{isAnimationUsed as t}from"../canvas/use-fadein.js";import{polotnoError as e}from"@polotno/core/errors";let o=0,r=[],n=3e4;export const setAssetLoadTimeout=t=>{n=t};export const getAssetLoadTimeout=()=>n;let i=6e3;export const setFontLoadTimeout=t=>{i=t};export const getFontLoadTimeout=()=>i;export function incrementLoader(t){o+=1;let r=!1,i=!1;const s=setTimeout(()=>{if(r){return}const o=String(t),i=o.startsWith("image")?"IMAGE_FAILED":o.startsWith("font")?"FONT_FAILED":o.startsWith("video")||o.startsWith("mediabunny")?"VIDEO_FAILED":"UNKNOWN";triggerLoadError(e(i,`Timeout loading asset ${t}`,{reason:"FONT_FAILED"===i?"load-timeout":"timeout",label:o,timeoutMs:n})),console.error("Timeout triggered for loader. Some assets may not have loaded.",t),r=!0,decrementLoader()},n);return()=>{i?console.error("Finish called twice! That is not expected. id: ",t):(i=!0,r||(clearTimeout(s),decrementLoader()))}}export function decrementLoader(){o-=1,0===o&&s()}function s(){setTimeout(()=>{if(0!==o){return}const t=r;r=[],t.forEach(t=>t())})}export function whenLoaded(){return new Promise(e=>{return n=()=>{t()?setTimeout(e,300):e(!0)},r.push(n),void(0===o&&s());var n})}let a=[];export function onLoadError(t){a.push(t)}export function triggerLoadError(t){const o="string"==typeof t?e("UNKNOWN",t):t;a.forEach(t=>t(o))}
|
package/utils/px.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ export declare const roundEnabledPx: (value: number) => number;
|
|
|
3
3
|
export declare const MAIN_TRANSFORMER_NAME = "main-transformer";
|
|
4
4
|
export declare const activeAnchorOf: (node: Konva.Node) => string;
|
|
5
5
|
export declare const isCornerAnchor: (anchor: string) => boolean;
|
|
6
|
+
export declare const transformScale: (scale: number) => number;
|
|
6
7
|
export declare const textMinResizeWidth: (startWidth: number, fontSize: number) => number;
|
|
7
8
|
export declare const textMinWidthIsMeasured: (element: {
|
|
8
9
|
curveEnabled?: boolean;
|
package/utils/px.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var t=this&&this.__rest||function(t,e){var o={};for(var r in t){Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(o[r]=t[r])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(r=Object.getOwnPropertySymbols(t);n<r.length;n++){e.indexOf(r[n])<0&&Object.prototype.propertyIsEnumerable.call(t,r[n])&&(o[r[n]]=t[r[n]])}}return o};import{htmlInflatesMinContentWidth as e,scaleRichTextFontSizesInHtml as o}from"./rich-text-html.js";export const roundEnabledPx=t=>t>0?Math.max(1,Math.round(t)):0;export const MAIN_TRANSFORMER_NAME="main-transformer";export const activeAnchorOf=t=>{var e,o;const r=null===(e=t.getStage())||void 0===e?void 0:e.findOne(".main-transformer");return null!==(o=null==r?void 0:r.getActiveAnchor())&&void 0!==o?o:""};export const isCornerAnchor=t=>!(t.includes("middle")||t.includes("center"));export const textMinResizeWidth=(t,e)=>t<e?1:e;export const textMinWidthIsMeasured=t=>{var o;return!!t.curveEnabled||0!==(null!==(o=t.letterSpacing)&&void 0!==o?o:0)||e(t.text)};const r=(t,e)=>{var o;return{cornerRadius:(null!==(o=t.cornerRadius)&&void 0!==o?o:0)*e,shadowBlur:t.shadowBlur*e,shadowOffsetX:t.shadowOffsetX*e,shadowOffsetY:t.shadowOffsetY*e}},n=t=>{var e;return{cornerRadius:roundEnabledPx(null!==(e=t.cornerRadius)&&void 0!==e?e:0),shadowBlur:Math.round(t.shadowBlur),shadowOffsetX:Math.round(t.shadowOffsetX),shadowOffsetY:Math.round(t.shadowOffsetY)}};export const scaledFontSizeAttrs=(t,e)=>{const o=t.fontSize>0?e/t.fontSize:1;return{fontSize:e,strokeWidth:t.strokeWidth*o,borderSize:t.borderSize*o,shadowBlur:t.shadowBlur*o,shadowOffsetX:t.shadowOffsetX*o,shadowOffsetY:t.shadowOffsetY*o}};export const scaledFontSizeBounds=(t,e,o=!1)=>{const r=t=>{if(1===e){return t}const r=t*e;return o?Math.round(r):r},n={};return void 0!==t.minFontSize&&(n.minFontSize=r(t.minFontSize)),void 0!==t.maxFontSize&&(n.maxFontSize=r(t.maxFontSize)),n};export const roundedGeometryPx=t=>Math.round(1e6*t)/1e6+0;export const roundedCropFraction=t=>Math.round(1e9*t)/1e9+0;export const roundedPosition=t=>({x:roundedGeometryPx(t.x()),y:roundedGeometryPx(t.y())});export const roundedGeometryAttrs=t=>({x:roundedGeometryPx(t.x),y:roundedGeometryPx(t.y),width:roundedGeometryPx(t.width),height:roundedGeometryPx(t.height),rotation:roundedGeometryPx(t.rotation)});export const roundedFontSizeAttrs=(t,e)=>{const o=scaledFontSizeAttrs(t,e);return{fontSize:Math.round(o.fontSize),strokeWidth:roundEnabledPx(o.strokeWidth),borderSize:roundEnabledPx(o.borderSize),shadowBlur:Math.round(o.shadowBlur),shadowOffsetX:Math.round(o.shadowOffsetX),shadowOffsetY:Math.round(o.shadowOffsetY)}};const s=["image","svg","gif","video"];export const scaledStyleAttrs=(t,e)=>{const n=t;return"text"===n.type?Object.assign(Object.assign({},scaledFontSizeAttrs(n,n.fontSize*e)),{text:o(n.text,e)}):"figure"===n.type?Object.assign(Object.assign({},r(n,e)),{strokeWidth:n.strokeWidth*e}):s.includes(n.type)?Object.assign(Object.assign({},r(n,e)),{borderSize:n.borderSize*e}):{}};export const roundedStyleAttrs=t=>{const e=t;return"text"===e.type?roundedFontSizeAttrs(e,e.fontSize):"figure"===e.type?Object.assign(Object.assign({},n(e)),{strokeWidth:roundEnabledPx(e.strokeWidth)}):s.includes(e.type)?Object.assign(Object.assign({},n(e)),{borderSize:roundEnabledPx(e.borderSize)}):{}};export const roundedTextDecorationAttrs=e=>{const o=roundedFontSizeAttrs(e,e.fontSize),{fontSize:r}=o;return t(o,["fontSize"])};
|
|
1
|
+
var t=this&&this.__rest||function(t,e){var o={};for(var r in t){Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(o[r]=t[r])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(r=Object.getOwnPropertySymbols(t);n<r.length;n++){e.indexOf(r[n])<0&&Object.prototype.propertyIsEnumerable.call(t,r[n])&&(o[r[n]]=t[r[n]])}}return o};import{htmlInflatesMinContentWidth as e,scaleRichTextFontSizesInHtml as o}from"./rich-text-html.js";export const roundEnabledPx=t=>t>0?Math.max(1,Math.round(t)):0;export const MAIN_TRANSFORMER_NAME="main-transformer";export const activeAnchorOf=t=>{var e,o;const r=null===(e=t.getStage())||void 0===e?void 0:e.findOne(".main-transformer");return null!==(o=null==r?void 0:r.getActiveAnchor())&&void 0!==o?o:""};export const isCornerAnchor=t=>!(t.includes("middle")||t.includes("center"));export const transformScale=t=>Math.abs(t-1)<1e-7?1:t;export const textMinResizeWidth=(t,e)=>t<e?1:e;export const textMinWidthIsMeasured=t=>{var o;return!!t.curveEnabled||0!==(null!==(o=t.letterSpacing)&&void 0!==o?o:0)||e(t.text)};const r=(t,e)=>{var o;return{cornerRadius:(null!==(o=t.cornerRadius)&&void 0!==o?o:0)*e,shadowBlur:t.shadowBlur*e,shadowOffsetX:t.shadowOffsetX*e,shadowOffsetY:t.shadowOffsetY*e}},n=t=>{var e;return{cornerRadius:roundEnabledPx(null!==(e=t.cornerRadius)&&void 0!==e?e:0),shadowBlur:Math.round(t.shadowBlur),shadowOffsetX:Math.round(t.shadowOffsetX),shadowOffsetY:Math.round(t.shadowOffsetY)}};export const scaledFontSizeAttrs=(t,e)=>{const o=t.fontSize>0?e/t.fontSize:1;return{fontSize:e,strokeWidth:t.strokeWidth*o,borderSize:t.borderSize*o,shadowBlur:t.shadowBlur*o,shadowOffsetX:t.shadowOffsetX*o,shadowOffsetY:t.shadowOffsetY*o}};export const scaledFontSizeBounds=(t,e,o=!1)=>{const r=t=>{if(1===e){return t}const r=t*e;return o?Math.round(r):r},n={};return void 0!==t.minFontSize&&(n.minFontSize=r(t.minFontSize)),void 0!==t.maxFontSize&&(n.maxFontSize=r(t.maxFontSize)),n};export const roundedGeometryPx=t=>Math.round(1e6*t)/1e6+0;export const roundedCropFraction=t=>Math.round(1e9*t)/1e9+0;export const roundedPosition=t=>({x:roundedGeometryPx(t.x()),y:roundedGeometryPx(t.y())});export const roundedGeometryAttrs=t=>({x:roundedGeometryPx(t.x),y:roundedGeometryPx(t.y),width:roundedGeometryPx(t.width),height:roundedGeometryPx(t.height),rotation:roundedGeometryPx(t.rotation)});export const roundedFontSizeAttrs=(t,e)=>{const o=scaledFontSizeAttrs(t,e);return{fontSize:Math.round(o.fontSize),strokeWidth:roundEnabledPx(o.strokeWidth),borderSize:roundEnabledPx(o.borderSize),shadowBlur:Math.round(o.shadowBlur),shadowOffsetX:Math.round(o.shadowOffsetX),shadowOffsetY:Math.round(o.shadowOffsetY)}};const s=["image","svg","gif","video"];export const scaledStyleAttrs=(t,e)=>{const n=t;return"text"===n.type?Object.assign(Object.assign({},scaledFontSizeAttrs(n,n.fontSize*e)),{text:o(n.text,e)}):"figure"===n.type?Object.assign(Object.assign({},r(n,e)),{strokeWidth:n.strokeWidth*e}):s.includes(n.type)?Object.assign(Object.assign({},r(n,e)),{borderSize:n.borderSize*e}):{}};export const roundedStyleAttrs=t=>{const e=t;return"text"===e.type?roundedFontSizeAttrs(e,e.fontSize):"figure"===e.type?Object.assign(Object.assign({},n(e)),{strokeWidth:roundEnabledPx(e.strokeWidth)}):s.includes(e.type)?Object.assign(Object.assign({},n(e)),{borderSize:roundEnabledPx(e.borderSize)}):{}};export const roundedTextDecorationAttrs=e=>{const o=roundedFontSizeAttrs(e,e.fontSize),{fontSize:r}=o;return t(o,["fontSize"])};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export function refCountedCache(){const e=new Map;return{get:t=>{var r;return null===(r=e.get(t))||void 0===r?void 0:r.value},remove(t,r){var u;(null===(u=e.get(t))||void 0===u?void 0:u.value)===r&&e.delete(t)},acquire(t,r){let u=e.get(t);u||(u={value:r(),users:0},e.set(t,u));const l=u;return l.users++,[l.value,()=>{l.users--,l.users||e.get(t)!==l||e.delete(t)}]}}}
|
package/utils/validate-key.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as e from"mobx";import{getAPI as o}from"./api.js";import{removeBackgroundState as t}from"./flags.js";const n=e.observable({value:!1}),a=e.observable({value:"v1"});export const ___=()=>a.value;const i=e.observable({value:0});export const ____=()=>i.value;export const isCreditVisible=()=>n.value;const r=e.action(()=>{n.value=!0});let s="";export const getKey=()=>s||"";export const setKey=e=>{s=e||""};let l="undefined"!=typeof window?window.location.origin:"";const c="undefined"!=typeof navigator&&navigator.userAgent.indexOf("Headless")>-1,d="undefined"!=typeof navigator&&navigator.userAgent.indexOf("Electron")>-1;"file://"===l&&c&&(l="headless"),"file://"===l&&d&&(l="electron");const u=`%cPolotno error! Current domain is not allowed. It may lead to unexpected behavior and stop working. Please add "${l}" here: https://polotno.com/cabinet`;let p=fetch;export const __=e=>{p=e};export async function isKeyPaid(n){for(let s=0;s<5;s++){try{const r=await p(o()+"/validate-key",{method:"POST",body:JSON.stringify({key:n,site:location.host,skdVersion:"3.
|
|
1
|
+
import*as e from"mobx";import{getAPI as o}from"./api.js";import{removeBackgroundState as t}from"./flags.js";const n=e.observable({value:!1}),a=e.observable({value:"v1"});export const ___=()=>a.value;const i=e.observable({value:0});export const ____=()=>i.value;export const isCreditVisible=()=>n.value;const r=e.action(()=>{n.value=!0});let s="";export const getKey=()=>s||"";export const setKey=e=>{s=e||""};let l="undefined"!=typeof window?window.location.origin:"";const c="undefined"!=typeof navigator&&navigator.userAgent.indexOf("Headless")>-1,d="undefined"!=typeof navigator&&navigator.userAgent.indexOf("Electron")>-1;"file://"===l&&c&&(l="headless"),"file://"===l&&d&&(l="electron");const u=`%cPolotno error! Current domain is not allowed. It may lead to unexpected behavior and stop working. Please add "${l}" here: https://polotno.com/cabinet`;let p=fetch;export const __=e=>{p=e};export async function isKeyPaid(n){for(let s=0;s<5;s++){try{const r=await p(o()+"/validate-key",{method:"POST",body:JSON.stringify({key:n,site:location.host,skdVersion:"3.17.0"})});if(e.runInAction(()=>{a.value=r.headers.get("x-api-version")||""}),!n){return console.error("Polotno API is initialized without API key. It may lead to unexpected behavior and stop working. Please create API key here: https://polotno.com/cabinet"),e.runInAction(()=>{i.value=1}),!1}if(200!==r.status){await new Promise(e=>setTimeout(e,3e3));continue}const s=await r.json();return s.is_valid||(console.error("Polotno API key is not valid. Please get new API key here: https://polotno.com/cabinet"),e.runInAction(()=>{i.value=1})),s.is_paid||(console.log("%cPolotno Free Version. For development usage only. https://polotno.com/","background: rgb(0, 161, 255); color: white; padding: 5px; margin: 5px;"),e.runInAction(()=>{0===i.value&&(i.value=2)})),s.is_domain_valid||console.log(u,"background: rgba(247, 101, 68, 1); color: white; padding: 5px; margin: 5px;"),e.runInAction(()=>{t.defaultEnabled=s.remove_background_enabled}),s.is_paid||!1}catch(r){await new Promise(e=>setTimeout(e,3e3))}}return console.error("Can not validate Polotno API key. Please report to anton@polotno.com immediately."),!0}export async function validateKey(e){await isKeyPaid(s)&&!e||r()}
|
package/utils/wait.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare function waitTillAvailable<T>(func: () => T | Promise<T>): Promise<NonNullable<Awaited<T>> | undefined>;
|
package/utils/wait.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export async function waitTillAvailable(t){for(let i=0;i<30;i++){const i=await t();if(i){return i}await new Promise(t=>setTimeout(t,50))}}
|