polotno 4.16.1 → 4.18.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.
Files changed (51) hide show
  1. package/canvas/element.js +1 -1
  2. package/canvas/figure-element.js +1 -1
  3. package/canvas/gif-element.js +1 -1
  4. package/canvas/html-element.js +1 -1
  5. package/canvas/image-element.d.ts +15 -2
  6. package/canvas/image-element.js +1 -1
  7. package/canvas/line-element.js +1 -1
  8. package/canvas/page.js +1 -1
  9. package/canvas/placed-node.d.ts +22 -0
  10. package/canvas/placed-node.js +1 -0
  11. package/canvas/render-tag-element.js +1 -1
  12. package/canvas/rich-editor.js +2 -2
  13. package/canvas/table-element.js +1 -1
  14. package/canvas/text-element/auto-delete-empty-text.d.ts +15 -0
  15. package/canvas/text-element/auto-delete-empty-text.js +1 -0
  16. package/canvas/text-element/font-specs-loader.js +1 -1
  17. package/canvas/text-element.js +1 -1
  18. package/canvas/use-color.d.ts +2 -4
  19. package/canvas/use-color.js +1 -1
  20. package/canvas/use-image.js +1 -1
  21. package/canvas/video-element.js +1 -1
  22. package/canvas/workspace-canvas.js +1 -1
  23. package/model/group-model.d.ts +7 -0
  24. package/model/group-model.js +1 -1
  25. package/model/history.js +1 -1
  26. package/model/page-model.d.ts +15 -0
  27. package/model/page-model.js +1 -1
  28. package/model/store.d.ts +10 -7
  29. package/model/store.js +1 -1
  30. package/model/table-model.d.ts +3 -0
  31. package/model/table-model.js +1 -1
  32. package/package.json +20 -19
  33. package/pages-timeline/element-track.js +1 -1
  34. package/pages-timeline/page-preview.d.ts +9 -2
  35. package/pages-timeline/page-preview.js +1 -1
  36. package/polotno.bundle.js +171 -171
  37. package/side-panel/animations-panel.js +1 -1
  38. package/side-panel/text-panel.js +1 -1
  39. package/side-panel/text-template.js +1 -1
  40. package/utils/duplicate.js +1 -1
  41. package/utils/fonts.js +1 -1
  42. package/utils/from-svg.js +1 -1
  43. package/utils/image-dpi.js +1 -1
  44. package/utils/loader.js +1 -1
  45. package/utils/px.d.ts +1 -0
  46. package/utils/px.js +1 -1
  47. package/utils/ref-counted.d.ts +5 -0
  48. package/utils/ref-counted.js +1 -0
  49. package/utils/validate-key.js +1 -1
  50. package/utils/wait.d.ts +0 -1
  51. 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{PolotnoIcon as c}from"../icons/registry.js";import{t as u}from"../utils/l10n.js";import{cn as g}from"../lib/utils.js";import{PanelHeader as v}from"../primitives/panel-header.js";import{PanelScrollArea as h}from"../primitives/panel-scroll-area.js";export{o as NumberInput};const f=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:g("pn:flex-1",(null==l?void 0:l.enabled)&&!(null==r?void 0:r.enabled)&&"pn:bg-muted"),onClick:()=>{a.history.transaction(()=>{i.setAnimation("enter",{enabled:!0}),i.setAnimation("exit",{enabled:!1})})},children:"Enter"}),e(t,{variant:"outline",className:g("pn:flex-1",(null==l?void 0:l.enabled)&&(null==r?void 0:r.enabled)&&"pn:bg-muted"),onClick:()=>{a.history.transaction(()=>{i.setAnimation("enter",{enabled:!0}),i.setAnimation("exit",{enabled:!0})})},children:"Both"}),e(t,{variant:"outline",className:g("pn:flex-1",(null==r?void 0:r.enabled)&&!(null==l?void 0:l.enabled)&&"pn:bg-muted"),onClick:()=>{a.history.transaction(()=>{i.setAnimation("enter",{enabled:!1}),i.setAnimation("exit",{enabled:!0})})},children:"Exit"})]})]}):null}),b=["right","left","up","down","bottom-right","bottom-left","top-right","top-left"],x={right:e(c,{name:"animation.directionRight"}),left:e(c,{name:"animation.directionLeft"}),up:e(c,{name:"animation.directionUp"}),down:e(c,{name:"animation.directionDown"}),"bottom-right":e(c,{name:"animation.directionBottomRight"}),"bottom-left":e(c,{name:"animation.directionBottomLeft"}),"top-right":e(c,{name:"animation.directionTopRight"}),"top-left":e(c,{name:"animation.directionTopLeft"})},y=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:[x[i],e(s,{})]})}),e(r,{children:b.map(i=>e(d,{value:i,children:n("div",{className:"pn:flex pn:items-center pn:gap-2",children:[x[i],i]})},i))})]})]})),T=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"})]})]})]})),k=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=>{n.setAnimation("enter",{delay:1e3*e})},min:0,max:t/1e3,step:.01})})}),C=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=>{n.setAnimation("loop",{duration:500/e})},min:.1,max:3,step:.01,onCommit:()=>{const e=i.activePage;i.play({animatedElementsIds:[n.id],currentTime:n.page.startTime}),setTimeout(()=>{i.stop(),e&&i.selectPage(e.id)},1e3)}})})}),A=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=>{n.setAnimation("enter",{duration:1e3*e}),n.setAnimation("exit",{duration:1e3*e})},min:0,max:t/1e3,step:.01})})}),j=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=>{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})})}})});const a=i.activePage;(()=>{let e;return(...t)=>{e&&clearTimeout(e),e=setTimeout(()=>{(()=>{i.isPlaying||(i.play({animatedElementsIds:[n.id],currentTime:n.page.startTime}),setTimeout(()=>{i.stop(),a&&i.selectPage(a.id)},1e3))})(...t)},300)}})()()},s=Math.max(3,d);return e("div",{style:{padding:"10px"},children:e(a,{label:u("toolbar.strength"),value:parseFloat(d.toFixed(2)),onChange:e=>m(e),min:.1,sliderMax:s,step:.05})})}),N=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=>{n.setAnimation("exit",{delay:1e3*e})},min:0,max:t/1e3,step:.01})})}),P=[{key:"move",icon:"animation.typeMove",label:"toolbar.move"},{key:"fade",icon:"animation.typeFade",label:"toolbar.fade"},{key:"zoom",icon:"animation.typeZoom",label:"toolbar.zoom"}],E=[{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,b=m.map(e=>e.id).join(","),x="animation"===a.openedSidePanel;if(i.useEffect(()=>{x&&(s&&s.animations||a.restoreSidePanel())},[x,b]),!s||!s.animations){return null}const z=(e,n)=>{if(a.history.transaction(()=>{m.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){const e=a.activePage;a.play({animatedElementsIds:m.map(e=>e.id),currentTime:s.page.startTime}),setTimeout(()=>{a.stop(),e&&a.selectPage(e.id)},1e3)}},F=e=>{var n;return!!((e?null===(n=s.animations)||void 0===n?void 0:n.filter(n=>n.name===e||n.type===e):s.animations)||[]).find(e=>e.enabled)},w=F("move")||F("fade")||F("zoom"),B=F("rotate")||F("blink")||F("bounce");return n(h,{header:e(v,{title:u("sidePanel.animate"),onClose:()=>a.restoreSidePanel()}),children:[n("div",{style:{paddingTop:"10px",lineHeight:"35px"},children:["Animations"," ",e(t,{variant:"outline",style:{marginLeft:"10px",display:w?"inline-flex":"none"},onClick:()=>{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:P.map(({key:i,icon:a,label:o})=>e("div",{children:n(t,{variant:"outline",size:"lg",className:g("pn:flex pn:h-auto pn:w-full pn:flex-col pn:items-center pn:gap-2 pn:p-5",F(i)&&"pn:bg-muted"),onClick:()=>{z(i,{enabled:!F(i)})},children:[e(c,{name:a}),u(o)]})},i))}),n("div",{className:"pn:bg-black/5 pn:dark:bg-white/5",style:{display:w?"block":"none",padding:"10px"},children:[e(f,{element:s,store:a,enabled:F("enter")||F("exit")}),F("move")&&e(y,{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=>{z("move",{data:{direction:e},enabled:!0})}}),F("move")&&e(j,{store:a,element:p,animationName:"move"}),F("zoom")&&e(T,{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=>{z("zoom",{data:{direction:e},enabled:!0})}}),F("zoom")&&e(j,{store:a,element:p,animationName:"zoom"}),F("enter")&&e(k,{store:a,element:p}),F("enter")&&e(A,{store:a,element:p}),F("exit")&&e(N,{store:a,element:p})]}),n("div",{style:{paddingTop:"10px",lineHeight:"35px"},children:["Effects"," ",e(t,{variant:"outline",style:{marginLeft:"10px",display:B?"inline-flex":"none"},onClick:()=>{p.set({animations:[]})},children:"Remove All"})]}),e("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(100px, 1fr))",gap:"5px",paddingTop:"10px"},children:E.map(({key:i,icon:o,label:l})=>e("div",{children:n(t,{variant:"outline",size:"lg",className:g("pn:flex pn:h-auto pn:w-full pn:flex-col pn:items-center pn:gap-2 pn:p-5",F(i)&&"pn:bg-muted"),onClick:()=>{((e,n)=>{if(a.history.transaction(()=>{m.forEach(i=>{i.setAnimation("loop",Object.assign({name:e},n))})}),n.enabled){const e=a.activePage;a.play({animatedElementsIds:m.map(e=>e.id),currentTime:s.page.startTime}),setTimeout(()=>{a.stop(),e&&a.selectPage(e.id)},1e3)}})(i,{enabled:!F(i)})},children:[e(c,{name:o}),u(l)]})},i))}),B&&e(C,{store:a,element:p}),F("bounce")&&e(j,{store:a,element:p,animationName:"bounce"})]})]})});
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"})]})]})});
@@ -1 +1 @@
1
- var e=this&&this.__rest||function(e,t){var o={};for(var n in e){Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(o[n]=e[n])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i<n.length;i++){t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(o[n[i]]=e[n[i]])}}return o};import{jsx as t,jsxs as o}from"react/jsx-runtime";import*as n from"react";import{observer as i}from"mobx-react-lite";import l from"swr";import{PolotnoIcon as a}from"../icons/registry.js";import{t as r}from"../utils/l10n.js";import{isMobile as s}from"../utils/screen.js";import{textTemplateList as p}from"../utils/api.js";import{fetcher as c}from"../utils/use-api.js";import{localFileToURL as f}from"../utils/file.js";import{cssFontFamily as m}from"@polotno/core/fonts";import{registerNextDomDrop as d}from"../canvas/page.js";import{Button as h}from"../primitives/button.js";import{Tabs as y,TabsList as u,TabsTrigger as x}from"../primitives/tabs.js";import{ImagesGrid as g}from"./images-grid.js";import{loadTextTemplate as v}from"./text-template.js";import{PanelScrollArea as b}from"../primitives/panel-scroll-area.js";let j=async e=>f(e);export function setFontUploadFunc(e){j=e}const w=i(({onSelect:e,onRemove:n,font:i})=>o("div",{style:{fontFamily:m(i.fontFamily)},className:"polotno-font-item pn:relative pn:mb-2.5 pn:flex pn:h-[100px] pn:cursor-pointer pn:flex-col pn:justify-center pn:rounded-md pn:bg-black/40 pn:text-center pn:text-[25px] pn:text-white pn:shadow-[0_0_5px_rgba(16,22,26,0.3)]",onClick:e,children:[i.fontFamily," text",t(h,{style:{position:"absolute",right:0,bottom:0},variant:"ghost",size:"icon-sm",onClick:e=>{e.stopPropagation(),n()},children:t(a,{name:"action.remove"})})]})),S=o=>{var{onSelect:n}=o,i=e(o,["onSelect"]);return t(h,Object.assign({},i,{draggable:!0,className:"polotno-close-panel",onClick:()=>n(),onDragStart:()=>{d(({x:e,y:t})=>{n({x:e,y:t})})},onDragEnd:()=>{d(null)}}))},F=[{previewSize:"25px",fontSize:76,labelKey:"sidePanel.createHeader",textKey:"sidePanel.headerText"},{previewSize:"18px",fontSize:44,labelKey:"sidePanel.createSubHeader",textKey:"sidePanel.subHeaderText"},{previewSize:"14px",fontSize:30,labelKey:"sidePanel.createBody",textKey:"sidePanel.bodyText"}];export const TextPanel=i(({store:e})=>{n.useEffect(()=>{e.loadFont("Roboto")},[]);const i=t=>{var o;const n=t.width||e.width/2,i=((null==t?void 0:t.x)||e.width/2)-n/2,l=((null==t?void 0:t.y)||e.height/2)-t.fontSize/2,a=(e.width+e.height)/2160,r=null===(o=e.activePage)||void 0===o?void 0:o.addElement(Object.assign(Object.assign({type:"text",fontFamily:"Roboto"},t),{x:i,y:l,width:n,fontSize:t.fontSize*a}));s()||null==r||r.toggleEditMode(!0)};n.useEffect(()=>{e.fonts.forEach(t=>e.loadFont(t.fontFamily))},[e.fonts]);const{data:f,error:m}=l(p(),c),[d,P]=n.useState("text"),[z,O]=n.useState(null),E=n.useRef(null),C=e=>{E.current=e,O(e)};return o("div",{style:{height:"100%",display:"flex",flexDirection:"column"},children:[t(y,{value:d,onValueChange:e=>P(String(e)),className:"pn:mb-3",children:o(u,{className:"pn:w-full pn:h-10",children:[t(x,{value:"text",children:r("sidePanel.text")}),t(x,{value:"font",children:r("sidePanel.myFonts")})]})}),"text"===d&&o("div",{className:"polotno-text-panel-container pn:flex pn:flex-col",style:{height:"calc(100% - 52px)"},children:[F.map(({previewSize:e,fontSize:o,labelKey:n,textKey:l})=>t(S,{style:{fontSize:e},variant:"ghost",className:"pn:mb-[5px] pn:w-full pn:h-auto pn:min-h-[2.5rem] pn:py-1 pn:justify-start pn:font-['Roboto']",onSelect:e=>{i(Object.assign(Object.assign({},e),{fontSize:o,text:r(l),fontFamily:"Roboto"}))},children:r(n)},n)),t(g,{shadowEnabled:!1,images:null==f?void 0:f.items,getPreview:e=>e.preview,getImageClassName:e=>e.json.indexOf("plain")>=0?"polotno-text-preview-plain":"",isLoading:!f,error:m,getIsLoading:e=>e.json===z,onSelect:async(t,o)=>{if(E.current===t.json){return}C(t.json);const n=await v(e,t).finally(()=>{E.current===t.json&&C(null)});if(!e.activePage){return}const i=(e.width+e.height)/2160,l=o?o.x-n.width/2*i:e.width/2-n.width/2*i,a=o?o.y-n.height/2*i:e.height/2-n.height/2*i;e.history.transaction(()=>{const t=n.pages[0].children,o=[];t.forEach(t=>{delete t.id;const{id:n}=e.activePage.addElement(Object.assign(Object.assign({},t),{fontSize:t.fontSize*i,x:t.x*i+l,y:t.y*i+a,width:t.width*i,height:t.height*i}));o.push(n)}),e.selectElements(o)})}})]}),"font"===d&&o("div",{style:{display:"flex",flexDirection:"column",height:"calc(100% - 62px)"},children:[o("label",{htmlFor:"polotno-font-upload",children:[o(h,{style:{width:"100%"},onClick:()=>{var e;null===(e=document.querySelector("#polotno-font-upload"))||void 0===e||e.click()},children:[t(a,{name:"text.uploadFont"}),r("sidePanel.uploadFont")]}),t("input",{type:"file",accept:".ttf, .otf, .woff, .woff2, .eot",id:"polotno-font-upload",style:{display:"none"},onChange:async t=>{const{target:o}=t;for(const n of Array.from(o.files||[])){const t=await j(n),o=n.name.split(".")[0].replace(/,/g,"");e.addFont({fontFamily:o,url:t})}o.value=""}})]}),t(b,{className:"pn:mt-4",children:e.fonts.map((o,n)=>t(w,{font:o,onSelect:()=>{i({fontSize:80,text:"Cool text",fontFamily:o.fontFamily})},onRemove:()=>{e.find(e=>("text"===e.type&&e.fontFamily===o.fontFamily&&e.set({fontFamily:"Roboto"}),!1)),e.removeFont(o.fontFamily)}},n))})]})]})});
1
+ var e=this&&this.__rest||function(e,t){var o={};for(var n in e){Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(o[n]=e[n])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i<n.length;i++){t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(o[n[i]]=e[n[i]])}}return o};import{jsx as t,jsxs as o}from"react/jsx-runtime";import*as n from"react";import{observer as i}from"mobx-react-lite";import l from"swr";import{PolotnoIcon as a}from"../icons/registry.js";import{t as r}from"../utils/l10n.js";import{isMobile as s}from"../utils/screen.js";import{textTemplateList as p}from"../utils/api.js";import{fetcher as c}from"../utils/use-api.js";import{localFileToURL as f}from"../utils/file.js";import{cssFontFamily as m}from"@polotno/core/fonts";import{registerNextDomDrop as d}from"../canvas/page.js";import{Button as h}from"../primitives/button.js";import{Tabs as u,TabsList as y,TabsTrigger as x}from"../primitives/tabs.js";import{ImagesGrid as g}from"./images-grid.js";import{loadTextTemplate as v}from"./text-template.js";import{PanelScrollArea as b}from"../primitives/panel-scroll-area.js";let j=async e=>f(e);export function setFontUploadFunc(e){j=e}const w=i(({onSelect:e,onRemove:n,font:i})=>o("div",{style:{fontFamily:m(i.fontFamily)},className:"polotno-font-item pn:relative pn:mb-2.5 pn:flex pn:h-[100px] pn:cursor-pointer pn:flex-col pn:justify-center pn:rounded-md pn:bg-black/40 pn:text-center pn:text-[25px] pn:text-white pn:shadow-[0_0_5px_rgba(16,22,26,0.3)]",onClick:e,children:[i.fontFamily," text",t(h,{style:{position:"absolute",right:0,bottom:0},variant:"ghost",size:"icon-sm",onClick:e=>{e.stopPropagation(),n()},children:t(a,{name:"action.remove"})})]})),S=o=>{var{onSelect:n}=o,i=e(o,["onSelect"]);return t(h,Object.assign({},i,{draggable:!0,className:"polotno-close-panel",onClick:()=>n(),onDragStart:()=>{d(({x:e,y:t})=>{n({x:e,y:t})})},onDragEnd:()=>{d(null)}}))},F=[{previewSize:"25px",fontSize:76,labelKey:"sidePanel.createHeader",textKey:"sidePanel.headerText"},{previewSize:"18px",fontSize:44,labelKey:"sidePanel.createSubHeader",textKey:"sidePanel.subHeaderText"},{previewSize:"14px",fontSize:30,labelKey:"sidePanel.createBody",textKey:"sidePanel.bodyText"}];export const TextPanel=i(({store:e})=>{n.useEffect(()=>{e.loadFont("Roboto")},[]);const i=t=>{var o;const n=t.width||e.width/2,i=((null==t?void 0:t.x)||e.width/2)-n/2,l=((null==t?void 0:t.y)||e.height/2)-t.fontSize/2,a=(e.width+e.height)/2160,r=null===(o=e.activePage)||void 0===o?void 0:o.addElement(Object.assign(Object.assign({type:"text",fontFamily:"Roboto"},t),{x:i,y:l,width:n,fontSize:t.fontSize*a}));s()||null==r||r.toggleEditMode(!0)};n.useEffect(()=>{e.fonts.forEach(t=>e.loadFont(t.fontFamily))},[e.fonts]);const{data:f,error:m}=l(p(),c),[d,P]=n.useState("text"),[z,O]=n.useState(null),E=n.useRef(null),C=e=>{E.current=e,O(e)},[K,N]=n.useState(null);return o("div",{style:{height:"100%",display:"flex",flexDirection:"column"},children:[t(u,{value:d,onValueChange:e=>P(String(e)),className:"pn:mb-3",children:o(y,{className:"pn:w-full pn:h-10",children:[t(x,{value:"text",children:r("sidePanel.text")}),t(x,{value:"font",children:r("sidePanel.myFonts")})]})}),"text"===d&&o("div",{className:"polotno-text-panel-container pn:flex pn:flex-col",style:{height:"calc(100% - 52px)"},children:[F.map(({previewSize:e,fontSize:o,labelKey:n,textKey:l})=>t(S,{style:{fontSize:e},variant:"ghost",className:"pn:mb-[5px] pn:w-full pn:h-auto pn:min-h-[2.5rem] pn:py-1 pn:justify-start pn:font-['Roboto']",onSelect:e=>{i(Object.assign(Object.assign({},e),{fontSize:o,text:r(l),fontFamily:"Roboto"}))},children:r(n)},n)),t(g,{shadowEnabled:!1,images:null==f?void 0:f.items,getPreview:e=>e.preview,getImageClassName:e=>e.json.indexOf("plain")>=0?"polotno-text-preview-plain":"",isLoading:!f,error:m||K,getIsLoading:e=>e.json===z,onSelect:async(t,o)=>{if(E.current===t.json){return}let n;N(null),C(t.json);try{n=await v(e,t)}catch(r){return console.warn("polotno: failed to load the text template",r),void(E.current===t.json&&N(r))}finally{E.current===t.json&&C(null)}if(!e.activePage){return}const i=(e.width+e.height)/2160,l=o?o.x-n.width/2*i:e.width/2-n.width/2*i,a=o?o.y-n.height/2*i:e.height/2-n.height/2*i;e.history.transaction(()=>{const t=n.pages[0].children,o=[];t.forEach(t=>{delete t.id;const{id:n}=e.activePage.addElement(Object.assign(Object.assign({},t),{fontSize:t.fontSize*i,x:t.x*i+l,y:t.y*i+a,width:t.width*i,height:t.height*i}));o.push(n)}),e.selectElements(o)})}})]}),"font"===d&&o("div",{style:{display:"flex",flexDirection:"column",height:"calc(100% - 62px)"},children:[o("label",{htmlFor:"polotno-font-upload",children:[o(h,{style:{width:"100%"},onClick:()=>{var e;null===(e=document.querySelector("#polotno-font-upload"))||void 0===e||e.click()},children:[t(a,{name:"text.uploadFont"}),r("sidePanel.uploadFont")]}),t("input",{type:"file",accept:".ttf, .otf, .woff, .woff2, .eot",id:"polotno-font-upload",style:{display:"none"},onChange:async t=>{const{target:o}=t;for(const n of Array.from(o.files||[])){const t=await j(n),o=n.name.split(".")[0].replace(/,/g,"");e.addFont({fontFamily:o,url:t})}o.value=""}})]}),t(b,{className:"pn:mt-4",children:e.fonts.map((o,n)=>t(w,{font:o,onSelect:()=>{i({fontSize:80,text:"Cool text",fontFamily:o.fontFamily})},onRemove:()=>{e.find(e=>("text"===e.type&&e.fontFamily===o.fontFamily&&e.set({fontFamily:"Roboto"}),!1)),e.removeFont(o.fontFamily)}},n))})]})]})});
@@ -1 +1 @@
1
- import{extractFontSpecsFromHtml as t}from"../utils/rich-text-html.js";export async function loadTextTemplate(o,e){const a=Date.now(),l=((o=[])=>o.filter(t=>t.fontFamily).flatMap(o=>{var e,a;return t("",{fontFamily:o.fontFamily,fontWeight:null!==(e=o.fontWeight)&&void 0!==e?e:"normal",fontStyle:null!==(a=o.fontStyle)&&void 0!==a?a:"normal"})}))(e.fonts).map(t=>o.loadFont(t.family,t.style,t.weight).catch(()=>{})),n=await(await fetch(e.json)).json(),i=3e3-(Date.now()-a);if(i>0){let t;await Promise.race([Promise.all(l),new Promise(o=>{t=setTimeout(o,i)})]),clearTimeout(t)}return n}
1
+ import{extractFontSpecsFromHtml as t}from"../utils/rich-text-html.js";export async function loadTextTemplate(o,e){const a=Date.now(),l=((o=[])=>o.filter(t=>t.fontFamily).flatMap(o=>{var e,a;return t("",{fontFamily:o.fontFamily,fontWeight:null!==(e=o.fontWeight)&&void 0!==e?e:"normal",fontStyle:null!==(a=o.fontStyle)&&void 0!==a?a:"normal"})}))(e.fonts).map(t=>o.loadFont(t.family,t.style,t.weight).catch(()=>{})),n=await fetch(e.json);if(!n.ok){throw new Error(`polotno: text template request failed with ${n.status}`)}const i=await n.json(),r=3e3-(Date.now()-a);if(r>0){let t;await Promise.race([Promise.all(l),new Promise(o=>{t=setTimeout(o,r)})]),clearTimeout(t)}return i}
@@ -1 +1 @@
1
- import{forEveryChild as e}from"../model/group-model.js";const t={x:50,y:50},n=new WeakMap;function o(t){const n="group"===t.type?[]:[t];return e(t,e=>{"group"!==e.type&&n.push(e)}),n}export function duplicateElements(e,c){const s=function(e,c){const s=n.get(c),d=e.map(e=>e.id);if(!s||d.length!==s.copyIds.length||!s.copyIds.every(e=>d.includes(e))){return t}const r=c.getElementById(s.sourceId),p=c.getElementById(s.copyIds[0]),l=r&&o(r)[0],u=p&&o(p)[0];return l&&u?{x:u.x-l.x,y:u.y-l.y}:t}(e,c),d=e.filter(e=>!1!==e.removable).map(e=>{const t=e.clone();return o(t).forEach(e=>{e.set({x:e.x+s.x,y:e.y+s.y})}),{sourceId:e.id,copyId:t.id}}),r=d.map(e=>e.copyId);d.length&&n.set(c,{sourceId:d[0].sourceId,copyIds:r}),c.selectElements(r)}export function cloneBehind(e,t,o){const c=e.map(e=>{const n=e.clone({},{skipSelect:!0});return t.setElementZIndex(n.id,t.children.indexOf(e)),n.id});e.length&&n.set(o,{sourceId:c[0],copyIds:e.map(e=>e.id)})}
1
+ import{isAlive as e}from"mobx-state-tree";import{forEveryChild as t}from"../model/group-model.js";const n={x:50,y:50},o=new WeakMap;function c(e){const n="group"===e.type?[]:[e];return t(e,e=>{"group"!==e.type&&n.push(e)}),n}export function duplicateElements(t,r){const s=t.filter(t=>e(t));if(!s.length){return}const d=function(e,t){const r=o.get(t),s=e.map(e=>e.id);if(!r||s.length!==r.copyIds.length||!r.copyIds.every(e=>s.includes(e))){return n}const d=t.getElementById(r.sourceId),p=t.getElementById(r.copyIds[0]),l=d&&c(d)[0],i=p&&c(p)[0];return l&&i?{x:i.x-l.x,y:i.y-l.y}:n}(s,r),p=s.filter(e=>!1!==e.removable).map(e=>{const t=e.clone();return c(t).forEach(e=>{e.set({x:e.x+d.x,y:e.y+d.y})}),{sourceId:e.id,copyId:t.id}}),l=p.map(e=>e.copyId);p.length&&o.set(r,{sourceId:p[0].sourceId,copyIds:l}),r.selectElements(l)}export function cloneBehind(e,t,n){const c=e.map(e=>{const n=e.clone({},{skipSelect:!0});return t.setElementZIndex(n.id,t.children.indexOf(e)),n.id});e.length&&o.set(n,{sourceId:c[0],copyIds:e.map(e=>e.id)})}
package/utils/fonts.js CHANGED
@@ -1 +1 @@
1
- import*as t from"mobx";import{triggerLoadError as o,getFontLoadTimeout as n}from"./loader.js";import{polotnoError as e}from"@polotno/core/errors";import{removeTags as r}from"@polotno/core/text";import{DEFAULT_RETRIES as s,retryDelayMs as i}from"@polotno/core/retry";import{getGoogleFontsUrl as a,getGoogleFontsVariants as c}from"@polotno/core/google-fonts-url";import{resolveFontFaceStyles as l,googleFontVariantUrl as u,cssFontFamily as f}from"@polotno/core/fonts";export{setGoogleFontsVariants,getGoogleFontsVariants,getGoogleFontsUrl}from"@polotno/core/google-fonts-url";const d=["Roboto","Amatic SC","Press Start 2P","Marck Script","Rubik Mono One"];let m=t.observable([...d]),p=t.observable({value:!1});export function isGoogleFontChanged(){return p.value}export function setGoogleFonts(t){if("default"===t){return m.replace([...d]),void(p.value=!1)}p.value=!0,m.splice(0,m.length),m.push(...t)}export function getFontsList(){return m}export const globalFonts=t.observable([]);export function addGlobalFont(t){globalFonts.push(t)}export function removeGlobalFont(t){const o=globalFonts.findIndex(o=>o.fontFamily===t);-1!==o&&globalFonts.splice(o,1)}export function replaceGlobalFonts(t){globalFonts.replace(t)}const g="BESbswy 0123456789 Il1Ww",h=["sans-serif","serif","monospace"];function x(t){const o=function(t=""){const o=r(t).replace(/\s+/g," ").trim();return o?Array.from(o).slice(0,10).join(""):""}(t);return o?`${g} ${o}`:g}export function _getFontProbeTextForTesting(t){return x(t)}let F;function y(t){return{width:t.width,actualBoundingBoxLeft:t.actualBoundingBoxLeft||0,actualBoundingBoxRight:t.actualBoundingBoxRight||0,actualBoundingBoxAscent:t.actualBoundingBoxAscent||0,actualBoundingBoxDescent:t.actualBoundingBoxDescent||0}}function $(t="sans-serif",o="normal",n="normal",e=g){F||(F=document.createElement("canvas"));const r=F.getContext("2d");return r.font=`${o} ${n} 40px ${t}`,y(r.measureText(e))}function B(t,o,n,e,r){return h.some(s=>{const i=function(t,o="sans-serif",n="normal",e="normal",r=g){F||(F=document.createElement("canvas"));const s=F.getContext("2d");return s.font=`${n} ${e} 40px ${f(t)}, ${o}`,y(s.measureText(r))}(t,s,o,n,e);return function(t,o,n=.01){return Math.abs(t.width-o.width)>n||Math.abs(t.actualBoundingBoxLeft-o.actualBoundingBoxLeft)>n||Math.abs(t.actualBoundingBoxRight-o.actualBoundingBoxRight)>n||Math.abs(t.actualBoundingBoxAscent-o.actualBoundingBoxAscent)>n||Math.abs(t.actualBoundingBoxDescent-o.actualBoundingBoxDescent)>n}(i,r[s])})}export function measureFontDom(t,o="sans-serif",n="normal",e="normal",r=g){if("undefined"==typeof document||!document.body){return 0}const s=document.createElement("span");s.textContent=r,s.style.cssText=`\n position:absolute;\n visibility:hidden;\n white-space:nowrap;\n top:-9999px;\n left:-9999px;\n font:${n} ${e} 90px ${f(t)}, ${o};\n `,document.body.appendChild(s);const i=s.getBoundingClientRect().width;return s.remove(),i}const w={Arial:!0},b={};export const isFontLoaded=(t,o,n,e)=>{var r;if(o&&n){const i=`${t}_${o}_${n}`;if(!w[i]){return!1}const a=textChars(e),c=b[i];if([...a].every(t=>null==c?void 0:c.has(t))){return!0}try{return!!(null===(r=document.fonts)||void 0===r?void 0:r.check(v(t,o,n),a))}catch(s){return!1}}return Object.keys(w).some(o=>o.startsWith(t+"_"))||!!w[t]};export function _setFontLoadedForTesting(t,o){o?w[t]=!0:delete w[t]}export async function loadFont(t,o,e,r){var s;const i=performance.now()+n();await loadFontFace(t,o,e,r);const a=textChars(r),c=()=>{var n,r;const s=null!==(n=b[r=`${t}_${o}_${e}`])&&void 0!==n?n:b[r]=new Set;for(const t of a){s.add(t)}};if(!a||!(null===(s=document.fonts)||void 0===s?void 0:s.load)){return c()}let l;await Promise.race([document.fonts.load(v(t,o,e),a).catch(()=>{}).then(c),new Promise(t=>{l=setTimeout(t,Math.max(0,i-performance.now()))})]),clearTimeout(l)}const v=(t,o,n)=>`${o} ${n} 16px ${f(t)}`;export function textChars(t){return[...new Set(r(null!=t?t:"").replace(/\s/g,""))].join("")}export async function loadFontFace(t,r,s,a){var c;const l=`${t}_${r}_${s}`;if(injectGoogleFontVariant(t,r,s),w[l]&&!D(t,r,s)){return}const u=!!(null===(c=document.fonts)||void 0===c?void 0:c.load),f=x(a),d={"sans-serif":$("sans-serif",r,s,f),serif:$("serif",r,s,f),monospace:$("monospace",r,s,f)};if(u){try{const o=!D(t,r,s);if(await document.fonts.load(v(t,r,s),f),B(t,r,s,f,d)&&o){return void _(l,t)}}catch(p){}}const m=n()/60;for(let n=0;n<m;n++){const a=!D(t,r,s);if(u){try{await document.fonts.load(v(t,r,s),f)}catch(g){}}if(B(t,r,s,f,d)&&a){return void _(l,t)}if("missing"===C[t]){if(G(t)){const n=`Font "${t}" not found: not registered and no matching Google Font.`;console.error(n),o(e("FONT_FAILED",n,{family:t,reason:"not-found"}))}return}if(t in T&&!T[t]&&"errored"===C[t]&&injectGoogleFont(t),j[t]&&V(t)){const r=R(t);if("wait"===r){await new Promise(t=>setTimeout(t,60));continue}if("spent"!==r){P(t);const o=i(r);await new Promise(t=>setTimeout(t,o)),n+=Math.ceil(o/60);continue}if(G(t)){const n=`Failed to load font "${t}": its font file could not be fetched.`;console.error(n),o(e("FONT_FAILED",n,{family:t,reason:"fetch-failed"}))}return}await new Promise(t=>setTimeout(t,60))}console.warn(`Timeout for loading font "${t}". Looks like polotno can't load it. Is it a correct font family?`),o(e("FONT_FAILED",`Timeout for loading font "${t}"`,{family:t,reason:"timeout"}))}const T={},C={},E=new Set;function G(t){return!E.has(t)&&(E.add(t),setTimeout(()=>E.delete(t),n()),!0)}function _(t,o){w[t]=!0,delete C[o],delete L[o]}const L={};function R(t){const o=L[t],e=!o||Date.now()-o.at>n()?0:o.spent;return e>=s-1?"spent":o&&e>0&&Date.now()-o.at<i(e)?"wait":(L[t]={spent:e+1,at:Date.now()},e+1)}const A={};function D(t,o,n){return"loading"===T[t]||"loading"===A[`${t}|${"italic"===o?1:0}|${parseInt(n,10)}`]}export function injectGoogleFontVariant(t,o,n){const e=parseInt(n,10);if(!Number.isFinite(e)){return}if(function(t){const o=new Set;for(const n of c().split(",")){const e=n.trim().match(/^(\d+)(italic|i)?$/);e&&!!e[2]===t&&o.add(parseInt(e[1],10))}return o}("italic"===o).has(e)){return}if(!(t in T)){return}const r="italic"===o,s=`${t}|${r?1:0}|${e}`;if(A[s]){return}A[s]="loading";const i=document.createElement("link");i.type="text/css",i.href=u(t,r,e),i.rel="stylesheet",i.onload=()=>{A[s]=!0},i.onerror=()=>{A[s]=!0,i.remove()},document.getElementsByTagName("head")[0].appendChild(i)}export function injectGoogleFont(t){if(T[t]){return}const o=a(t),n=document.createElement("link");n.type="text/css",n.href=o,n.rel="stylesheet",n.onload=()=>{T[t]=!0},n.onerror=()=>{n.remove(),T[t]=!1,"errored"===C[t]?function(t){C[t]="probing",fetch(a(t),{mode:"no-cors"}).then(()=>{C[t]="missing"}).catch(()=>{delete C[t]})}(t):C[t]||(C[t]="errored")},document.getElementsByTagName("head")[0].appendChild(n),T[t]="loading"}const j={};let I;function S(){return I||(I=document.getElementById("polotno-font-style"),I||(I=document.createElement("style"),I.id="polotno-font-style",document.head.appendChild(I)),I)}function k(t){const o=t.fontFamily,n=l(t),e=S().sheet;return n.map(t=>{const n=e.insertRule(`\n @font-face{\n font-family:${f(o)};\n src:${t.src};\n font-style:${t.fontStyle};\n font-weight:${t.fontWeight};\n font-display:swap; /* optional but recommended */\n }`,e.cssRules.length);return e.cssRules[n]})}export function injectCustomFont(t){const o=t.fontFamily;if(!t.url&&!t.styles){return}const n=JSON.stringify(l(t)),e=j[o];if(e){if(e.src===n){return}M(e.rules),O(o)}delete C[o],j[o]={font:t,src:n,rules:k(t)}}function M(t){const o=S().sheet;for(const n of t){const t=Array.prototype.indexOf.call(o.cssRules,n);t>=0&&o.deleteRule(t)}}export function removeCustomFont(t){const o=j[t];o&&(M(o.rules),delete j[t],O(t))}function O(t){delete L[t];for(const o of Object.keys(w)){(o===t||o.startsWith(t+"_"))&&(delete w[o],delete b[o])}}function P(t){const o=j[t];o&&(M(o.rules),o.rules=k(o.font))}const N=t=>t.trim().replace(/^["']|["']$/g,"").toLowerCase();function V(t){const o=document.fonts;if(!o||"function"!=typeof o.forEach){return!1}const n=N(t);let e=!1;return o.forEach(t=>{"error"===t.status&&N(t.family)===n&&(e=!0)}),e}
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/from-svg.js CHANGED
@@ -1 +1 @@
1
- import t from"konva";import{getImageSize as e,getCrop as r}from"@polotno/core/image";import{resolveSvgSize as n}from"@polotno/core/svg";let o=0;const i=()=>(o+=1,o.toString());function a(t){const{width:e,height:r}=n({documentElement:t});return t.setAttribute("width",`${e}px`),t.setAttribute("height",`${r}px`),{width:e,height:r}}function s(e){const r=function(e){var r,n,o;const i=(null===(o=null===(n=null===(r=e.transform)||void 0===r?void 0:r.baseVal)||void 0===n?void 0:n.consolidate())||void 0===o?void 0:o.matrix)||new DOMMatrix;return new t.Transform([i.a,i.b,i.c,i.d,i.e,i.f])}(e);return e.parentNode&&"svg"!==e.parentNode.nodeName?s(e.parentNode).multiply(r):r}function l(t){return s(t).decompose()}function g(t){const{x:e,y:r}=t.getBoundingClientRect();if("svg"===t.nodeName){return{x:e,y:r}}const n=g(t.parentNode);return{x:e+n.x,y:r+n.y}}function u(t){return t.getElementsByTagName("text").length>0}function c(t){const e=Array.from(t.getElementsByTagName("rect")).find(t=>{const e=t.getAttribute("fill");return e&&e.indexOf("url")>=0});return t.getElementsByTagName("image").length>0||e}export function svgToURL(t){return"data:image/svg+xml;base64,"+window.btoa(unescape(encodeURIComponent(t)))}function h(t="url(#pattern)"){return t.replace(/url\(([^)]+)\)/,"$1").replace(/'/g,"")}function d(t){if(!t){return"Roboto"}if(t.includes("OpenSans")){return"Open Sans"}if(t.includes("Montserrat")){return"Montserrat"}const e=t.split(",").map(t=>t.trim());return e[1]||e[0]}function m(t){return t.parentNode&&"svg"===t.parentNode.nodeName?t.parentNode:t.parentElement?m(t.parentElement):null}async function f(t){if("defs"===t.nodeName){return[]}const n=t.getAttribute("id")||i();if("text"===t.nodeName){let e=Array.from(t.children).map(t=>t.textContent);0===e.length&&(e=[t.textContent]);const r=e.join("\n"),o=parseFloat(t.getAttribute("font-size")||t.style.fontSize||"20"),{x:i,y:a,rotation:s}=l(t),g=t.getAttribute("text-anchor")||"start";let u="left";return"middle"===g?u="center":"end"===g&&(u="right"),[{type:"text",text:r,id:n,x:i+t.getBBox().x,y:a+t.getBBox().y,fontSize:o,rotation:s,lineHeight:t.getBBox().height/e.length/o,width:t.getBBox().width,height:t.getBBox().height,fontFamily:d(t.getAttribute("font-family")||void 0),fontWeight:t.getAttribute("font-weight")||"normal",fontStyle:t.getAttribute("font-style")||"normal",align:u,fill:t.getAttribute("fill")||t.style.fill||"black"}]}if("image"===t.nodeName){const{x:o,y:i,rotation:a,scaleX:s,scaleY:g}=l(t),u=t.getBBox().width*s,c=t.getBBox().height*g,h=t.getAttribute("xlink:href")||"",d=await e(h),m=r({width:u,height:c},d);return[Object.assign({type:"image",id:n,x:o+t.getBBox().x,y:i+t.getBBox().y,width:u,height:c,src:h,rotation:a},m)]}if("rect"===t.nodeName){const{x:o,y:i,rotation:a}=l(t),s=parseFloat(t.getAttribute("width")||"0"),g=parseFloat(t.getAttribute("height")||"0"),u=t.getAttribute("fill")||"",c=u.indexOf("url")>=0,d=c?h(u):null,m=d?document.querySelector(d):null;if(c){const l=null==m?void 0:m.querySelector("use"),u=null==l?void 0:l.getAttribute("xlink:href"),c=u&&document.querySelector(u),h=c&&c.getAttribute("xlink:href");if(h){const l=await e(h),u=r({width:s,height:g},l);return[Object.assign({type:"image",id:n,x:o+t.getBBox().x,y:i+t.getBBox().y,width:s,height:g,src:h,rotation:a},u)]}}t.setAttribute("transform","");const f=t.getBBox();t.setAttribute("x","0"),t.setAttribute("y","0");const x=`<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${s}" height="${g}" viewBox="0 0 ${s} ${g}">${(null==m?void 0:m.outerHTML)||""}${t.outerHTML}</svg>`;return[{type:"svg",id:n,keepRatio:!1,x:o+f.x,y:i+f.y,width:s,height:g,src:svgToURL(x)}]}if("path"===t.nodeName||"polygon"===t.nodeName||"circle"===t.nodeName){const{x:e,y:r,rotation:o,scaleX:i,scaleY:a}=l(t),s=t.getBBox(),{width:g,height:u}=s;t.setAttribute("transform","");const c=t.getAttribute("fill")||"",d=c.indexOf("url")>=0?h(c):null,m=d?document.querySelector(d):null;let f=m?[m]:[];if(m&&m.getAttribute("xlink:href")){f=[m];const t=document.querySelector(m.getAttribute("xlink:href"));t&&f.push(t)}const x=`<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${g}" height="${u}" viewBox="0 0 ${g} ${u}"><defs>${f.map(t=>t.outerHTML).join("")}</defs><g transform="translate(${-s.x} ${-s.y})">${t.outerHTML}</g></svg>`;return[{type:"svg",id:n,keepRatio:!1,x:e+s.x*i,y:r+s.y*a,width:g*i,height:u*a,rotation:o,src:svgToURL(x)}]}if((t=>"g"===t.nodeName&&t.getBBox().width<450&&t.getBBox().height<450)(t)&&!u(t)&&!c(t)){const{x:e,y:r}=t.getBBox(),{width:o,height:i}=(g(t),t.getBBox()),s=Array.from(t.querySelectorAll("*"));let l=e,u=r;s.forEach(t=>{if("g"===t.nodeName){return}const e=t.getBBox();l=Math.min(l,e.x),u=Math.min(u,e.y)});const c=t.getBoundingClientRect(),h=m(t),d=null==h?void 0:h.getBoundingClientRect(),f=t.getAttribute("transform");t.setAttribute("transform","");const x=`<svg xmlns="http://www.w3.org/2000/svg" width="${o}" height="${i}" viewBox="0 0 ${o} ${i}"><g transform="translate(${-e} ${-r})">${t.outerHTML}</g></svg>`;t.setAttribute("transform",f||"");const p=a(h);return[{type:"svg",id:n,keepRatio:!1,x:(c.x-d.x)/d.width*p.width,y:(c.y-d.y)/d.height*p.height,width:o,height:i,name:t.getAttribute("id")||"",src:svgToURL(x)}]}if(!u(t)&&!c(t)){const e=[];for(const r of Array.from(t.children)){e.push(...await f(r))}return e}const o=[];for(const e of Array.from(t.children)){o.push(...await f(e))}return o}function x(t){t.querySelectorAll("script, foreignObject").forEach(t=>t.remove()),t.querySelectorAll("*").forEach(t=>{for(const e of Array.from(t.attributes)){e.name.startsWith("on")&&t.removeAttribute(e.name),"href"!==e.name&&"xlink:href"!==e.name||!e.value.trim().toLowerCase().startsWith("javascript:")||t.removeAttribute(e.name)}})}export async function svgToJson(t){const e=document.createElement("div");document.body.appendChild(e),e.innerHTML=function(t){const e=(new DOMParser).parseFromString(t,"image/svg+xml");if(e.querySelector("parsererror")){const e=(new DOMParser).parseFromString(t,"text/html").querySelector("svg");return e?(x(e),e.outerHTML):t}return x(e.documentElement),e.documentElement.outerHTML}(t);const r=e.querySelector("svg"),{width:n,height:o}=a(r),s=[];for(const i of Array.from(r.children)){s.push(...await f(i))}return e.parentElement.removeChild(e),{width:n,height:o,pages:[{id:i(),children:s}]}}
1
+ import t from"konva";import{getImageSize as e,getCrop as n}from"@polotno/core/image";import{parseSanitizedSvg as o,resolveSvgSize as r}from"@polotno/core/svg";let i=0;const s=()=>(i+=1,i.toString());function a(t){const{width:e,height:n}=r({documentElement:t});return t.setAttribute("width",`${e}px`),t.setAttribute("height",`${n}px`),{width:e,height:n}}function g(e){const n=function(e){var n,o,r;const i=(null===(r=null===(o=null===(n=e.transform)||void 0===n?void 0:n.baseVal)||void 0===o?void 0:o.consolidate())||void 0===r?void 0:r.matrix)||new DOMMatrix;return new t.Transform([i.a,i.b,i.c,i.d,i.e,i.f])}(e);return e.parentNode&&"svg"!==e.parentNode.nodeName?g(e.parentNode).multiply(n):n}function l(t){return g(t).decompose()}function u(t){const{x:e,y:n}=t.getBoundingClientRect();if("svg"===t.nodeName){return{x:e,y:n}}const o=u(t.parentNode);return{x:e+o.x,y:n+o.y}}function h(t){return t.getElementsByTagName("text").length>0}function d(t){const e=Array.from(t.getElementsByTagName("rect")).find(t=>{const e=t.getAttribute("fill");return e&&e.indexOf("url")>=0});return t.getElementsByTagName("image").length>0||e}export function svgToURL(t){return"data:image/svg+xml;base64,"+window.btoa(unescape(encodeURIComponent(t)))}function c(t="url(#pattern)"){return t.replace(/url\(([^)]+)\)/,"$1").replace(/'/g,"")}function f(t){if(!t){return"Roboto"}if(t.includes("OpenSans")){return"Open Sans"}if(t.includes("Montserrat")){return"Montserrat"}const e=t.split(",").map(t=>t.trim());return e[1]||e[0]}function m(t){return t.parentNode&&"svg"===t.parentNode.nodeName?t.parentNode:t.parentElement?m(t.parentElement):null}async function x(t){if("defs"===t.nodeName){return[]}const o=t.getAttribute("id")||s();if("text"===t.nodeName){let e=Array.from(t.children).map(t=>t.textContent);0===e.length&&(e=[t.textContent]);const n=e.join("\n"),r=parseFloat(t.getAttribute("font-size")||t.style.fontSize||"20"),{x:i,y:s,rotation:a}=l(t),g=t.getAttribute("text-anchor")||"start";let u="left";return"middle"===g?u="center":"end"===g&&(u="right"),[{type:"text",text:n,id:o,x:i+t.getBBox().x,y:s+t.getBBox().y,fontSize:r,rotation:a,lineHeight:t.getBBox().height/e.length/r,width:t.getBBox().width,height:t.getBBox().height,fontFamily:f(t.getAttribute("font-family")||void 0),fontWeight:t.getAttribute("font-weight")||"normal",fontStyle:t.getAttribute("font-style")||"normal",align:u,fill:t.getAttribute("fill")||t.style.fill||"black"}]}if("image"===t.nodeName){const{x:r,y:i,rotation:s,scaleX:a,scaleY:g}=l(t),u=t.getBBox().width*a,h=t.getBBox().height*g,d=t.getAttribute("xlink:href")||"",c=await e(d),f=n({width:u,height:h},c);return[Object.assign({type:"image",id:o,x:r+t.getBBox().x,y:i+t.getBBox().y,width:u,height:h,src:d,rotation:s},f)]}if("rect"===t.nodeName){const{x:r,y:i,rotation:s}=l(t),a=parseFloat(t.getAttribute("width")||"0"),g=parseFloat(t.getAttribute("height")||"0"),u=t.getAttribute("fill")||"",h=u.indexOf("url")>=0,d=h?c(u):null,f=d?document.querySelector(d):null;if(h){const l=null==f?void 0:f.querySelector("use"),u=null==l?void 0:l.getAttribute("xlink:href"),h=u&&document.querySelector(u),d=h&&h.getAttribute("xlink:href");if(d){const l=await e(d),u=n({width:a,height:g},l);return[Object.assign({type:"image",id:o,x:r+t.getBBox().x,y:i+t.getBBox().y,width:a,height:g,src:d,rotation:s},u)]}}t.setAttribute("transform","");const m=t.getBBox();t.setAttribute("x","0"),t.setAttribute("y","0");const x=`<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${a}" height="${g}" viewBox="0 0 ${a} ${g}">${(null==f?void 0:f.outerHTML)||""}${t.outerHTML}</svg>`;return[{type:"svg",id:o,keepRatio:!1,x:r+m.x,y:i+m.y,width:a,height:g,src:svgToURL(x)}]}if("path"===t.nodeName||"polygon"===t.nodeName||"circle"===t.nodeName){const{x:e,y:n,rotation:r,scaleX:i,scaleY:s}=l(t),a=t.getBBox(),{width:g,height:u}=a;t.setAttribute("transform","");const h=t.getAttribute("fill")||"",d=h.indexOf("url")>=0?c(h):null,f=d?document.querySelector(d):null;let m=f?[f]:[];if(f&&f.getAttribute("xlink:href")){m=[f];const t=document.querySelector(f.getAttribute("xlink:href"));t&&m.push(t)}const x=`<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${g}" height="${u}" viewBox="0 0 ${g} ${u}"><defs>${m.map(t=>t.outerHTML).join("")}</defs><g transform="translate(${-a.x} ${-a.y})">${t.outerHTML}</g></svg>`;return[{type:"svg",id:o,keepRatio:!1,x:e+a.x*i,y:n+a.y*s,width:g*i,height:u*s,rotation:r,src:svgToURL(x)}]}if((t=>"g"===t.nodeName&&t.getBBox().width<450&&t.getBBox().height<450)(t)&&!h(t)&&!d(t)){const{x:e,y:n}=t.getBBox(),{width:r,height:i}=(u(t),t.getBBox()),s=Array.from(t.querySelectorAll("*"));let g=e,l=n;s.forEach(t=>{if("g"===t.nodeName){return}const e=t.getBBox();g=Math.min(g,e.x),l=Math.min(l,e.y)});const h=t.getBoundingClientRect(),d=m(t),c=null==d?void 0:d.getBoundingClientRect(),f=t.getAttribute("transform");t.setAttribute("transform","");const x=`<svg xmlns="http://www.w3.org/2000/svg" width="${r}" height="${i}" viewBox="0 0 ${r} ${i}"><g transform="translate(${-e} ${-n})">${t.outerHTML}</g></svg>`;t.setAttribute("transform",f||"");const p=a(d);return[{type:"svg",id:o,keepRatio:!1,x:(h.x-c.x)/c.width*p.width,y:(h.y-c.y)/c.height*p.height,width:r,height:i,name:t.getAttribute("id")||"",src:svgToURL(x)}]}if(!h(t)&&!d(t)){const e=[];for(const n of Array.from(t.children)){e.push(...await x(n))}return e}const r=[];for(const e of Array.from(t.children)){r.push(...await x(e))}return r}export async function svgToJson(t){const e=o(t);if(!e){throw new Error("svgToJson: the markup contains no <svg> element")}const n=document.createElement("div");document.body.appendChild(n);const r=n.appendChild(document.importNode(e,!0)),{width:i,height:g}=a(r),l=[];for(const o of Array.from(r.children)){l.push(...await x(o))}return n.parentElement.removeChild(n),{width:i,height:g,pages:[{id:s(),children:l}]}}
@@ -1 +1 @@
1
- import{decodeBase64 as t,encodeBase64 as e}from"./base64.js";const n=[112,72,89,115],r=(()=>{const t=new Uint32Array(256);for(let e=0;e<256;e++){let n=e;for(let t=0;t<8;t++){n=1&n?3988292384^n>>>1:n>>>1}t[e]=n>>>0}return t})(),s=(t,e,n)=>{t[e]=n>>>24&255,t[e+1]=n>>>16&255,t[e+2]=n>>>8&255,t[e+3]=255&n};export const addDpiMetadataToImage=(o,l,a)=>{const i=o.indexOf(","),f=i>=0?o.slice(i+1):o,c=t(f),g="image/png"===l?((t,e)=>{const o=(t=>{const e=new Uint8Array(9),o=new DataView(e.buffer);o.setUint32(0,t,!1),o.setUint32(4,t,!1),e[8]=1;const l=new Uint8Array(8+e.length+4);s(l,0,e.length),l.set(n,4),l.set(e,8);const a=new Uint8Array(4+e.length);return a.set(n,0),a.set(e,4),s(l,8+e.length,(t=>{let e=4294967295;for(let n=0;n<t.length;n++){e=r[255&(e^t[n])]^e>>>8}return(4294967295^e)>>>0})(a)),l})(Math.round(e/.0254)),l=((t,e)=>{let n=8;for(;n+8<=t.length;){const r=t[n]<<24|t[n+1]<<16|t[n+2]<<8|t[n+3],s=n+4,o=t.subarray(s,s+4),l=8+r+4;if(e.every((t,e)=>o[e]===t)){return{offset:n,totalLength:l}}n+=l}return null})(t,n);if(l){const e=new Uint8Array(t.length-l.totalLength+o.length);return e.set(t.slice(0,l.offset),0),e.set(o,l.offset),e.set(t.slice(l.offset+l.totalLength),l.offset+o.length),e}const a=16+(t[8]<<24|t[9]<<16|t[10]<<8|t[11])+4;if(a>t.length){return t}const i=new Uint8Array(t.length+o.length);return i.set(t.slice(0,a),0),i.set(o,a),i.set(t.slice(a),a+o.length),i})(c,a):((t,e)=>{const n=(t=>{let e=2;for(;e+4<t.length;){if(255!==t[e]){return-1}const n=t[e+1];if(216===n||217===n){e+=2;continue}const r=t[e+2]<<8|t[e+3];if(r<2){return-1}if(224===n&&74===t[e+4]&&70===t[e+5]&&73===t[e+6]&&70===t[e+7]&&0===t[e+8]){return e}const s=e+2+r;if(s<=e||s>t.length){return-1}e=s}return-1})(t);if(n>=0){const r=new Uint8Array(t),s=n+11;return r[s]=1,r[s+1]=e>>8&255,r[s+2]=255&e,r[s+3]=e>>8&255,r[s+4]=255&e,r}const r=(t=>{const e=new Uint8Array(18);return e[0]=255,e[1]=224,e[2]=0,e[3]=16,e[4]=74,e[5]=70,e[6]=73,e[7]=70,e[8]=0,e[9]=1,e[10]=1,e[11]=1,e[12]=t>>8&255,e[13]=255&t,e[14]=t>>8&255,e[15]=255&t,e})(e),s=new Uint8Array(t.length+r.length);return s.set(t.subarray(0,2),0),s.set(r,2),s.set(t.subarray(2),2+r.length),s})(c,a);return`data:${l};base64,${e(g)}`};
1
+ import{decodeBase64 as t,encodeBase64 as e}from"./base64.js";const n=[137,80,78,71,13,10,26,10],r=n.length,s=[255,216],o=[112,72,89,115],l=(()=>{const t=new Uint32Array(256);for(let e=0;e<256;e++){let n=e;for(let t=0;t<8;t++){n=1&n?3988292384^n>>>1:n>>>1}t[e]=n>>>0}return t})(),i=(t,e,n)=>{t[e]=n>>>24&255,t[e+1]=n>>>16&255,t[e+2]=n>>>8&255,t[e+3]=255&n},a=(t,e)=>{const n=(t=>{const e=new Uint8Array(9),n=new DataView(e.buffer);n.setUint32(0,t,!1),n.setUint32(4,t,!1),e[8]=1;const r=new Uint8Array(8+e.length+4);i(r,0,e.length),r.set(o,4),r.set(e,8);const s=new Uint8Array(4+e.length);return s.set(o,0),s.set(e,4),i(r,8+e.length,(t=>{let e=4294967295;for(let n=0;n<t.length;n++){e=l[255&(e^t[n])]^e>>>8}return(4294967295^e)>>>0})(s)),r})(Math.round(e/.0254)),s=((t,e)=>{let n=r;for(;n+8<=t.length;){const r=t[n]<<24|t[n+1]<<16|t[n+2]<<8|t[n+3],s=n+4,o=t.subarray(s,s+4),l=8+r+4;if(e.every((t,e)=>o[e]===t)){return{offset:n,totalLength:l}}n+=l}return null})(t,o);if(s){const e=new Uint8Array(t.length-s.totalLength+n.length);return e.set(t.slice(0,s.offset),0),e.set(n,s.offset),e.set(t.slice(s.offset+s.totalLength),s.offset+n.length),e}const a=t[r]<<24|t[r+1]<<16|t[r+2]<<8|t[r+3],f=r+8+a+4;if(f>t.length){return t}const g=new Uint8Array(t.length+n.length);return g.set(t.slice(0,f),0),g.set(n,f),g.set(t.slice(f),f+n.length),g};export const addDpiMetadataToImage=(r,o,l)=>{const i=r.indexOf(","),f=i>=0?r.slice(i+1):r,g=t(f);if(!("image/png"===o?n:s).every((t,e)=>g[e]===t)){return r}const c="image/png"===o?a(g,l):((t,e)=>{const n=(t=>{let e=2;for(;e+4<t.length;){if(255!==t[e]){return-1}const n=t[e+1];if(216===n||217===n){e+=2;continue}const r=t[e+2]<<8|t[e+3];if(r<2){return-1}if(224===n&&74===t[e+4]&&70===t[e+5]&&73===t[e+6]&&70===t[e+7]&&0===t[e+8]){return e}const s=e+2+r;if(s<=e||s>t.length){return-1}e=s}return-1})(t);if(n>=0){const r=new Uint8Array(t),s=n+11;return r[s]=1,r[s+1]=e>>8&255,r[s+2]=255&e,r[s+3]=e>>8&255,r[s+4]=255&e,r}const r=(t=>{const e=new Uint8Array(18);return e[0]=255,e[1]=224,e[2]=0,e[3]=16,e[4]=74,e[5]=70,e[6]=73,e[7]=70,e[8]=0,e[9]=1,e[10]=1,e[11]=1,e[12]=t>>8&255,e[13]=255&t,e[14]=t>>8&255,e[15]=255&t,e})(e),s=new Uint8Array(t.length+r.length);return s.set(t.subarray(0,2),0),s.set(r,2),s.set(t.subarray(2),2+r.length),s})(g,l);return`data:${o};base64,${e(c)}`};
package/utils/loader.js CHANGED
@@ -1 +1 @@
1
- import{isAnimationUsed as e}from"../canvas/use-fadein.js";import{polotnoError as t}from"@polotno/core/errors";let o=0,r=[],n=3e4;export const setAssetLoadTimeout=e=>{n=e};export const getAssetLoadTimeout=()=>n;let i=6e3;export const setFontLoadTimeout=e=>{i=e};export const getFontLoadTimeout=()=>i;export function incrementLoader(e){o+=1;let r=!1,i=!1;const s=setTimeout(()=>{if(r){return}const o=String(e),i=o.startsWith("image")?"IMAGE_FAILED":o.startsWith("video")||o.startsWith("mediabunny")?"VIDEO_FAILED":"UNKNOWN";triggerLoadError(t(i,`Timeout loading asset ${e}`,{reason:"timeout",label:o,timeoutMs:n})),console.error("Timeout triggered for loader. Some assets may not have loaded.",e),r=!0,decrementLoader()},n);return()=>{i?console.error("Finish called twice! That is not expected. id: ",e):(i=!0,r||(clearTimeout(s),decrementLoader()))}}export function decrementLoader(){o-=1,0===o&&(r.forEach(e=>e()),r=[])}export function whenLoaded(){return new Promise(t=>{return n=()=>{e()?setTimeout(t,300):t(!0)},void(0===o?n():r.push(n));var n})}let s=[];export function onLoadError(e){s.push(e)}export function triggerLoadError(e){const o="string"==typeof e?t("UNKNOWN",e):e;s.forEach(e=>e(o))}
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,5 @@
1
+ export declare function refCountedCache<V>(): {
2
+ get: (key: string) => V | undefined;
3
+ remove(key: string, value: V): void;
4
+ acquire(key: string, create: () => V): [V, () => void];
5
+ };
@@ -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)}]}}}
@@ -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:"4.16.1"})});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()}
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:"4.18.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))}}