polotno 3.5.1 → 3.6.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 (114) hide show
  1. package/blueprint/toolbar/image-toolbar.d.ts +2 -2
  2. package/blueprint/toolbar/sketch.js +1 -1
  3. package/canvas/apply-filters.d.ts +1 -1
  4. package/canvas/audio.js +1 -1
  5. package/canvas/context-menu/context-menu.d.ts +2 -2
  6. package/canvas/figure-element.js +1 -1
  7. package/canvas/html-element.js +1 -1
  8. package/canvas/image-element.d.ts +11 -0
  9. package/canvas/image-element.js +1 -1
  10. package/canvas/page-controls.d.ts +1 -1
  11. package/canvas/render-tag-element.js +1 -1
  12. package/canvas/rich-editor.js +2 -2
  13. package/canvas/rules.d.ts +1 -1
  14. package/canvas/text-element.js +1 -1
  15. package/canvas/tooltip.d.ts +2 -2
  16. package/canvas/use-transformer-snap.js +1 -1
  17. package/canvas/video-element.js +1 -1
  18. package/hooks/use-event.js +1 -1
  19. package/icons/registry.d.ts +1 -0
  20. package/icons/registry.js +1 -1
  21. package/model/audio-model.d.ts +2 -0
  22. package/model/audio-model.js +1 -1
  23. package/model/group-model.d.ts +0 -1
  24. package/model/page-model.d.ts +0 -1
  25. package/model/store.d.ts +3 -9
  26. package/model/store.js +1 -1
  27. package/model/text-model.d.ts +0 -1
  28. package/model/text-model.js +1 -1
  29. package/package.json +7 -7
  30. package/pages-timeline/audio-track.d.ts +3 -2
  31. package/pages-timeline/audio-track.js +1 -1
  32. package/pages-timeline/audios.js +1 -1
  33. package/pages-timeline/element-track.js +1 -1
  34. package/pages-timeline/index.d.ts +1 -1
  35. package/pages-timeline/index.js +1 -1
  36. package/pages-timeline/play-button.d.ts +1 -1
  37. package/pages-timeline/track-styles.d.ts +9 -0
  38. package/pages-timeline/track-styles.js +1 -1
  39. package/polotno.bundle.js +201 -202
  40. package/primitives/button-group.d.ts +2 -2
  41. package/primitives/button.d.ts +2 -2
  42. package/primitives/dialog.d.ts +2 -2
  43. package/primitives/dropdown-menu.d.ts +2 -2
  44. package/primitives/field-group.d.ts +1 -1
  45. package/primitives/field-row.d.ts +1 -1
  46. package/primitives/floating-control.js +2 -2
  47. package/primitives/index.d.ts +27 -27
  48. package/primitives/input-group.d.ts +2 -2
  49. package/primitives/input.d.ts +1 -1
  50. package/primitives/navbar.d.ts +5 -5
  51. package/primitives/numeric-input.d.ts +1 -1
  52. package/primitives/overflow-list.d.ts +1 -1
  53. package/primitives/panel-header.d.ts +1 -1
  54. package/primitives/popover.d.ts +2 -2
  55. package/primitives/portal-scope.d.ts +3 -3
  56. package/primitives/search-input.d.ts +1 -1
  57. package/primitives/select.d.ts +2 -2
  58. package/primitives/separator.d.ts +1 -1
  59. package/primitives/slider-field.d.ts +1 -1
  60. package/primitives/slider.d.ts +2 -2
  61. package/primitives/spinner.d.ts +1 -1
  62. package/primitives/switch.d.ts +1 -1
  63. package/primitives/tabs.d.ts +2 -2
  64. package/primitives/textarea.d.ts +1 -1
  65. package/primitives/toggle-group.d.ts +4 -4
  66. package/primitives/toggle.d.ts +3 -3
  67. package/primitives/tooltip-icon-button.d.ts +4 -4
  68. package/primitives/tooltip.d.ts +2 -2
  69. package/side-panel/background-panel.d.ts +2 -2
  70. package/side-panel/draw-panel.d.ts +2 -2
  71. package/side-panel/elements-panel.d.ts +2 -2
  72. package/side-panel/images-grid.js +1 -1
  73. package/side-panel/index.d.ts +35 -35
  74. package/side-panel/photos-panel.d.ts +1 -1
  75. package/side-panel/select-gif.d.ts +1 -1
  76. package/side-panel/side-panel.d.ts +5 -5
  77. package/side-panel/size-panel.d.ts +3 -3
  78. package/side-panel/tab-button.d.ts +1 -1
  79. package/side-panel/tab-button.js +2 -2
  80. package/side-panel/templates-panel.d.ts +2 -2
  81. package/side-panel/unsplash-credit.d.ts +1 -1
  82. package/side-panel/upload-panel.d.ts +3 -3
  83. package/side-panel/upload-panel.js +1 -1
  84. package/side-panel/videos-grid.js +1 -1
  85. package/themes/blueprint.css +1 -1
  86. package/themes/carbon.css +127 -128
  87. package/toolbar/download-button.d.ts +2 -2
  88. package/toolbar/element-container.d.ts +1 -1
  89. package/toolbar/filters-picker.d.ts +1 -1
  90. package/toolbar/group-toolbar.d.ts +2 -2
  91. package/toolbar/history-buttons.d.ts +1 -1
  92. package/toolbar/image-remove-background-button.d.ts +1 -1
  93. package/toolbar/image-toolbar.d.ts +1 -1
  94. package/toolbar/index.d.ts +34 -34
  95. package/toolbar/many-toolbar.d.ts +2 -2
  96. package/toolbar/opacity-picker.d.ts +1 -1
  97. package/toolbar/page-toolbar.d.ts +3 -3
  98. package/toolbar/toolbar.d.ts +3 -3
  99. package/toolbar/zoom-buttons.d.ts +1 -1
  100. package/ui-types.d.ts +8 -8
  101. package/ui.css +1 -1
  102. package/utils/array.js +1 -1
  103. package/utils/clipboard.d.ts +0 -2
  104. package/utils/file.d.ts +3 -0
  105. package/utils/file.js +1 -1
  106. package/utils/fonts.js +1 -1
  107. package/utils/html-to-svg/svg-builder.d.ts +1 -1
  108. package/utils/insert-file.d.ts +3 -2
  109. package/utils/insert-file.js +1 -1
  110. package/utils/l10n.d.ts +4 -0
  111. package/utils/l10n.js +1 -1
  112. package/utils/media.d.ts +6 -0
  113. package/utils/media.js +1 -0
  114. package/utils/validate-key.js +1 -1
@@ -6,10 +6,10 @@ type Props = {
6
6
  store: StoreType;
7
7
  components?: any;
8
8
  };
9
- export declare const ImageFitToBackground: ({ element }: {
9
+ export declare const ImageFitToBackground: ({ element, }: {
10
10
  element: ImageElementType;
11
11
  }) => React.JSX.Element;
12
- export declare const ImageClip: (({ element, store, elements }: {
12
+ export declare const ImageClip: (({ element, store, elements, }: {
13
13
  element: ImageElementType;
14
14
  store: StoreType;
15
15
  elements: ImageElementType[];
@@ -1 +1 @@
1
- import{jsx as e,jsxs as t}from"react/jsx-runtime";import r from"react";import o from"../../utils/reactcss/index.js";import i from"lodash-es/merge.js";import{Button as n}from"@blueprintjs/core";import{CgColorPicker as s}from"../../icons/meronex.js";import a from"konva";import{ColorWrap as l,Saturation as c,Hue as d,Alpha as p,Checkboard as h}from"../../utils/react-color/components/common/index.js";import{SketchFields as u}from"../../utils/react-color/components/sketch/SketchFields.js";import{SketchPresetColors as g}from"../../utils/react-color/components/sketch/SketchPresetColors.js";const m=e=>{const t=r.useRef(e);return t.current=e,r.useCallback((...e)=>t.current(...e),[])};export const Sketch=({width:l=200,rgb:x,hex:f,hsv:v,hsl:b,onChange:w,onSwatchHover:y,disableAlpha:k=!1,presetColors:C=["#D0021B","#F5A623","#F8E71C","#8B572A","#7ED321","#417505","#BD10E0","#9013FE","#4A90E2","#50E3C2","#B8E986","#000000","#4A4A4A","#9B9B9B","#FFFFFF"],renderers:E,styles:A={},className:S=""})=>{const j=o(i({default:Object.assign({picker:{width:l,padding:"10px 10px 0",boxSizing:"initial",background:"#fff",borderRadius:"4px",boxShadow:"0 0 0 1px rgba(0,0,0,.15), 0 8px 16px rgba(0,0,0,.15)"},saturation:{width:"100%",paddingBottom:"75%",position:"relative",overflow:"hidden"},Saturation:{radius:"3px",shadow:"inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)"},controls:{display:"flex"},sliders:{padding:"4px 0",flex:"1"},color:{width:"24px",height:"24px",position:"relative",marginTop:"4px",marginLeft:"4px",borderRadius:"3px"},activeColor:{absolute:"0px 0px 0px 0px",borderRadius:"2px",background:`rgba(${x.r},${x.g},${x.b},${x.a})`,boxShadow:"inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)"},hue:{position:"relative",height:"10px",overflow:"hidden"},Hue:{radius:"2px",shadow:"inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)"},alpha:{position:"relative",height:"10px",marginTop:"4px",overflow:"hidden"},Alpha:{radius:"2px",shadow:"inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)"}},A),disableAlpha:{color:{height:"10px"},hue:{height:"10px"},alpha:{display:"none"}}},A),{disableAlpha:k}),[B,F]=r.useState(!1),R=r.useRef(null),L=m(e=>{var t;if(B){const r=null===(t=R.current)||void 0===t?void 0:t.fill();r&&w(a.Util.colorToRGBA(r)),P(),function(e){let t=e.target;for(;t;){if(t.classList.contains("color-picker-button")){return!0}t=t.parentElement}return!1}(e)||F(!1),e.stopPropagation(),e.stopImmediatePropagation()}}),N=m(e=>{if(!B){return}const t=a.stages.find(t=>{var r;const o=null===(r=t.getContent().parentElement)||void 0===r?void 0:r.parentElement;if(!o){return!1}const i=o.getBoundingClientRect();return i.left<e.clientX&&i.left+i.width>e.clientX&&i.top<e.clientY&&i.top+i.height>e.clientY});if(!t){return void P()}const r=t.getContent().getBoundingClientRect(),o=e.clientX-r.left,i=e.clientY-r.top,n=t.children[0],s=n.getNativeCanvasElement(),l=n.getCanvas().getPixelRatio(),{data:c}=s.getContext("2d").getImageData(o*l,i*l,1,1),d=t.findOne(".line-guides");d.findOne(".picker")||(R.current&&R.current.destroy(),R.current=new a.Circle({name:"picker",radius:14,stroke:"black",strokeWidth:1}),d.add(R.current)),R.current.setAbsolutePosition({x:o-15,y:i-15}),R.current.fill("rgb("+c[0]+","+c[1]+","+c[2]+")")});r.useEffect(()=>(window.addEventListener("mousemove",N),window.addEventListener("mousedown",L,!0),window.addEventListener("touchstart",L,!0),()=>{window.removeEventListener("mousemove",N),window.removeEventListener("mousedown",L,!0),window.removeEventListener("touchstart",L,!0),P()}),[]),r.useEffect(()=>{B||P()},[B]),r.useEffect(()=>(B&&(document.body.style.cursor="crosshair"),()=>{document.body.style.cursor="default"}),[B]);const P=m(()=>{R.current&&(R.current.destroy(),R.current=null)});return t("div",{style:j.picker,className:`sketch-picker ${S}`,children:[e("div",{style:j.saturation,children:e(c,{style:j.Saturation,hsl:b,hsv:v,onChange:w})}),t("div",{style:j.controls,className:"flexbox-fix",children:[t("div",{style:j.sliders,children:[e("div",{style:j.hue,children:e(d,{style:j.Hue,hsl:b,onChange:w})}),e("div",{style:j.alpha,children:e(p,{style:j.Alpha,rgb:x,hsl:b,renderers:E,onChange:w})})]}),t("div",{style:j.color,children:[e(h,{size:8,white:"transparent",grey:"rgba(0,0,0,.08)"}),e("div",{style:j.activeColor})]}),e("div",{style:j.color,children:e(n,{icon:e(s,{className:"bp6-icon"}),className:"color-picker-button",minimal:!0,style:{width:"24px",height:"24px",minWidth:"24px",minHeight:"24px",padding:0,margin:0},active:B,onClickCapture:e=>{F(e=>!e),e.stopPropagation()}})})]}),e(u,{rgb:x,hsl:b,hex:f,onChange:w,disableAlpha:k}),e(g,{colors:C,onClick:w,onSwatchHover:y})]})};export default l(Sketch);
1
+ import{jsx as e,jsxs as t}from"react/jsx-runtime";import r from"react";import o from"../../utils/reactcss/index.js";import i from"lodash-es/merge.js";import{Button as n}from"@blueprintjs/core";import{CgColorPicker as s}from"../../icons/meronex.js";import a from"konva";import{ColorWrap as l,Saturation as c,Hue as d,Alpha as p,Checkboard as h}from"../../utils/react-color/components/common/index.js";import{SketchFields as u}from"../../utils/react-color/components/sketch/SketchFields.js";import{SketchPresetColors as g}from"../../utils/react-color/components/sketch/SketchPresetColors.js";const m=e=>{const t=r.useRef(e);return t.current=e,r.useCallback((...e)=>t.current(...e),[])};export const Sketch=({width:l=200,rgb:x,hex:v,hsv:f,hsl:b,onChange:w,onSwatchHover:y,disableAlpha:k=!1,presetColors:C=["#D0021B","#F5A623","#F8E71C","#8B572A","#7ED321","#417505","#BD10E0","#9013FE","#4A90E2","#50E3C2","#B8E986","#000000","#4A4A4A","#9B9B9B","#FFFFFF"],renderers:E,styles:A={},className:S=""})=>{const j=o(i({default:Object.assign({picker:{width:l,padding:"10px 10px 0",boxSizing:"initial",background:"#fff",borderRadius:"4px",boxShadow:"0 0 0 1px rgba(0,0,0,.15), 0 8px 16px rgba(0,0,0,.15)"},saturation:{width:"100%",paddingBottom:"75%",position:"relative",overflow:"hidden"},Saturation:{radius:"3px",shadow:"inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)"},controls:{display:"flex"},sliders:{padding:"4px 0",flex:"1"},color:{width:"24px",height:"24px",position:"relative",marginTop:"4px",marginLeft:"4px",borderRadius:"3px"},activeColor:{absolute:"0px 0px 0px 0px",borderRadius:"2px",background:`rgba(${x.r},${x.g},${x.b},${x.a})`,boxShadow:"inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)"},hue:{position:"relative",height:"10px",overflow:"hidden"},Hue:{radius:"2px",shadow:"inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)"},alpha:{position:"relative",height:"10px",marginTop:"4px",overflow:"hidden"},Alpha:{radius:"2px",shadow:"inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)"}},A),disableAlpha:{color:{height:"10px"},hue:{height:"10px"},alpha:{display:"none"}}},A),{disableAlpha:k}),[B,F]=r.useState(!1),R=r.useRef(null),L=m(e=>{var t;if(B){const r=null===(t=R.current)||void 0===t?void 0:t.fill();r&&w(a.Util.colorToRGBA(r)),P(),function(e){var t;let r=e.target;for(;r;){if(null===(t=r.classList)||void 0===t?void 0:t.contains("color-picker-button")){return!0}r=r.parentElement}return!1}(e)||F(!1),e.stopPropagation(),e.stopImmediatePropagation()}}),N=m(e=>{if(!B){return}const t=a.stages.find(t=>{var r;const o=null===(r=t.getContent().parentElement)||void 0===r?void 0:r.parentElement;if(!o){return!1}const i=o.getBoundingClientRect();return i.left<e.clientX&&i.left+i.width>e.clientX&&i.top<e.clientY&&i.top+i.height>e.clientY});if(!t){return void P()}const r=t.getContent().getBoundingClientRect(),o=e.clientX-r.left,i=e.clientY-r.top,n=t.children[0],s=n.getNativeCanvasElement(),l=n.getCanvas().getPixelRatio(),{data:c}=s.getContext("2d").getImageData(o*l,i*l,1,1),d=t.findOne(".line-guides");d.findOne(".picker")||(R.current&&R.current.destroy(),R.current=new a.Circle({name:"picker",radius:14,stroke:"black",strokeWidth:1}),d.add(R.current)),R.current.setAbsolutePosition({x:o-15,y:i-15}),R.current.fill("rgb("+c[0]+","+c[1]+","+c[2]+")")});r.useEffect(()=>(window.addEventListener("mousemove",N),window.addEventListener("mousedown",L,!0),window.addEventListener("touchstart",L,!0),()=>{window.removeEventListener("mousemove",N),window.removeEventListener("mousedown",L,!0),window.removeEventListener("touchstart",L,!0),P()}),[]),r.useEffect(()=>{B||P()},[B]),r.useEffect(()=>(B&&(document.body.style.cursor="crosshair"),()=>{document.body.style.cursor="default"}),[B]);const P=m(()=>{R.current&&(R.current.destroy(),R.current=null)});return t("div",{style:j.picker,className:`sketch-picker ${S}`,children:[e("div",{style:j.saturation,children:e(c,{style:j.Saturation,hsl:b,hsv:f,onChange:w})}),t("div",{style:j.controls,className:"flexbox-fix",children:[t("div",{style:j.sliders,children:[e("div",{style:j.hue,children:e(d,{style:j.Hue,hsl:b,onChange:w})}),e("div",{style:j.alpha,children:e(p,{style:j.Alpha,rgb:x,hsl:b,renderers:E,onChange:w})})]}),t("div",{style:j.color,children:[e(h,{size:8,white:"transparent",grey:"rgba(0,0,0,.08)"}),e("div",{style:j.activeColor})]}),e("div",{style:j.color,children:e(n,{icon:e(s,{className:"bp6-icon"}),className:"color-picker-button",minimal:!0,style:{width:"24px",height:"24px",minWidth:"24px",minHeight:"24px",padding:0,margin:0},active:B,onClickCapture:e=>{F(e=>!e),e.stopPropagation()}})})]}),e(u,{rgb:x,hsl:b,hex:v,onChange:w,disableAlpha:k}),e(g,{colors:C,onClick:w,onSwatchHover:y})]})};export default l(Sketch);
@@ -1,7 +1,7 @@
1
1
  import Konva from 'konva';
2
2
  import { ShapeType } from '../model/shape-model.js';
3
3
  import { Filter } from 'konva/lib/Node';
4
- export { getEffectiveBlurRadius, getElementBlurRadius } from '@polotno/core/filters';
4
+ export { getEffectiveBlurRadius, getElementBlurRadius, } from '@polotno/core/filters';
5
5
  export declare function getFilterAttrs(element: ShapeType): {
6
6
  filters: Filter[];
7
7
  brightness?: number;
package/canvas/audio.js CHANGED
@@ -1 +1 @@
1
- import e from"react";import{observer as t}from"mobx-react-lite";import{nodeAutorun as r}from"../utils/mobx.js";export const AudioElement=t(({audio:t,store:n})=>{const[i,s]=function(t){const[r,n]=e.useState(null),[i,s]=e.useState("loading");return e.useEffect(()=>{const e=new Audio(t),r=()=>{s("loaded"),n(e)},i=()=>{s("failed"),n(null)};return e.addEventListener("canplay",r),e.addEventListener("error",i),()=>{e.removeEventListener("canplay",r),e.removeEventListener("error",i)}},[t]),[r,i]}(t.src);return e.useEffect(()=>{i&&n.history.ignore(()=>{t.set({duration:1e3*i.duration})})},[i,t,n.history]),e.useEffect(()=>{if(!i){return}const e=()=>{i.currentTime=t.startTime*t.duration/1e3},s=()=>{const e=t.endTime*t.duration/1e3;i.currentTime>=e&&(i.pause(),i.currentTime=t.startTime*t.duration/1e3)};i.addEventListener("ended",e),i.addEventListener("timeupdate",s);const a=r(t,()=>{const e=n.animatedElementsIds;if(e.length&&!e.includes(t.id)){return}const r=n.currentTime-t.delay,s=t.speed,a=t.duration*(t.endTime-t.startTime),o=r>=0&&r<t.visibleDuration;if(!n.isPlaying||0!==n.animatedElementsIds.length||!o){return void i.pause()}i.volume=t.volume,i.playbackRate=s,i.preservesPitch=!1,i.paused&&i.play();const u=r*s%a/1e3+t.startTime*t.duration/1e3,d=i.currentTime;Math.abs(d-u)>.5&&u!==d&&(i.currentTime=u)});return()=>{i.pause(),i.removeEventListener("ended",e),i.removeEventListener("timeupdate",s),a()}},[n.isPlaying,t.startTime,t.endTime,t.volume,t.speed,i]),null});
1
+ import e from"react";import{observer as t}from"mobx-react-lite";import{nodeAutorun as r}from"../utils/mobx.js";import{createPlayGate as n}from"../utils/media.js";export const AudioElement=t(({audio:t,store:i})=>{const[s,o]=function(t){const[r,n]=e.useState(null),[i,s]=e.useState("loading");return e.useEffect(()=>{const e=new Audio(t),r=()=>{s("loaded"),n(e)},i=()=>{s("failed"),n(null)};return e.addEventListener("canplay",r),e.addEventListener("error",i),()=>{e.removeEventListener("canplay",r),e.removeEventListener("error",i)}},[t]),[r,i]}(t.src),a=e.useMemo(n,[s]);return e.useEffect(()=>{s&&i.history.ignore(()=>{t.set({duration:1e3*s.duration})})},[s,t,i.history]),e.useEffect(()=>{if(!s){return}const e=()=>{s.currentTime=t.startTime*t.duration/1e3},n=()=>{const e=t.endTime*t.duration/1e3;s.currentTime>=e&&(s.pause(),s.currentTime=t.startTime*t.duration/1e3)};s.addEventListener("ended",e),s.addEventListener("timeupdate",n);const o=r(t,()=>{const e=i.animatedElementsIds;if(e.length&&!e.includes(t.id)){return}const r=i.currentTime-t.delay,n=t.speed,o=t.duration*(t.endTime-t.startTime),u=r>=0&&r<t.visibleDuration;if(!i.isPlaying||0!==i.animatedElementsIds.length||!u){return a.reset(),void s.pause()}s.volume=t.volume,s.playbackRate=n,s.preservesPitch=!1,s.paused&&a.play(s);const d=r*n%o/1e3+t.startTime*t.duration/1e3,m=s.currentTime;Math.abs(m-d)>.5&&d!==m&&(s.currentTime=d)});return()=>{s.pause(),s.removeEventListener("ended",e),s.removeEventListener("timeupdate",n),o()}},[i.isPlaying,t.startTime,t.endTime,t.volume,t.speed,s]),null});
@@ -1,5 +1,5 @@
1
- import type { StoreType } from "../../model/store.js";
2
- import type { ShapeType } from "../../ui-types.js";
1
+ import type { StoreType } from '../../model/store.js';
2
+ import type { ShapeType } from '../../ui-types.js';
3
3
  type ContextMenuProps = {
4
4
  store: StoreType;
5
5
  element: ShapeType;
@@ -1 +1 @@
1
- import{jsx as t,Fragment as e,jsxs as a}from"react/jsx-runtime";import r from"react";import{observer as s}from"mobx-react-lite";import{Group as o,Rect as i,Path as n}from"react-konva";import{ROLES as h}from"../model/store.js";import{subTypeToPathDataFunc as d}from"@polotno/core/figure-to-svg";import{isTouchDevice as c}from"../utils/screen.js";import{roundEnabledPx as l,isCornerAnchor as g,scaledBoxStyleAttrs as m,roundedBoxStyleAttrs as f}from"../utils/px.js";import{useColor as p}from"./use-color.js";const u={};export const FigureElement=s(({element:w,store:b})=>{const x=r.useRef(null),k=r.useRef(!1),v=w.selectable||b.role===h.ADMIN,y=c(),j=w.isSelected,O=Math.min(w.strokeWidth,w.width/2,w.height/2),W=Math.max(0,Math.min(w.width/2,w.height/2,w.cornerRadius)),M=p(w,w.a.fill,"fill"),E=Object.assign(Object.assign({width:w.a.width,height:w.a.height},M),{cornerRadius:W,shadowEnabled:w.shadowEnabled,shadowBlur:w.shadowBlur,shadowOffsetX:w.shadowOffsetX,shadowOffsetY:w.shadowOffsetY,shadowColor:w.shadowColor,shadowOpacity:w.shadowOpacity,preventDefault:!y||j,hideInExport:!w.showInExport}),T=p(w,w.stroke,"stroke"),R=Object.assign(Object.assign({visible:O>0,x:O/2,y:O/2,width:w.a.width-O,height:w.a.height-O},T),{strokeWidth:O,cornerRadius:Math.max(0,W-O),dash:w.dash.map(t=>t*O),hideInExport:!w.showInExport,listening:!1}),P=Math.max(0,10-Math.min(w.a.width,w.a.height)),S=(X=w.subType,u[X]||(u[X]=(Y=d(X),s(({element:s,fillProps:h,strokeProps:d,hitStrokeWidth:c})=>{let l=Y({width:s.a.width,height:s.a.height,cornerRadius:s.cornerRadius}),g=1,m=1;"string"!=typeof l&&(g=l.scaleX,m=l.scaleY,l=l.path);const f=r.useRef(null);return a(e,{children:[t(i,{width:s.a.width,height:s.a.height,fill:"transparent",hitStrokeWidth:c}),t(n,Object.assign({},h,{ref:f,data:l,scaleX:g,scaleY:m})),t(o,{clipFunc:t=>{const e=f.current;if(e){var a=e.dataArray;t.beginPath();for(var r=0;r<a.length;r++){var s=a[r].command,o=a[r].points;switch(s){case"L":t.lineTo(o[0],o[1]);break;case"M":t.moveTo(o[0],o[1]);break;case"C":t.bezierCurveTo(o[0],o[1],o[2],o[3],o[4],o[5]);break;case"Q":t.quadraticCurveTo(o[0],o[1],o[2],o[3]);break;case"A":var i=o[0],n=o[1],h=o[2],d=o[3],c=o[4],l=o[5],g=o[6],m=o[7],p=h>d?h:d,u=h>d?1:h/d,w=h>d?d/h:1;t.translate(i,n),t.rotate(g),t.scale(u,w),t.arc(0,0,p,c,c+l,!m),t.scale(1/u,1/w),t.rotate(-g),t.translate(-i,-n);break;case"z":t.closePath()}}}},scaleX:g,scaleY:m,children:t(n,Object.assign({},d,{x:0,y:0,data:l,strokeWidth:2*d.strokeWidth,dash:d.dash.map(t=>t)}))})]})}))),u[X]||o);var X,Y;return t(e,{children:t(o,{ref:x,id:w.id,x:w.a.x,y:w.a.y,rotation:w.a.rotation,opacity:w.a.opacity,listening:v,draggable:y?w.draggable&&j:w.draggable,name:"element",onDragMove:t=>{w.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{w.set({x:t.target.x(),y:t.target.y()})},onTransformStart:t=>{var e,a;const r=null===(e=t.target.getStage())||void 0===e?void 0:e.findOne("Transformer");k.current=g(null!==(a=null==r?void 0:r.getActiveAnchor())&&void 0!==a?a:"")},onTransform:t=>{const e=t.target.scale();t.target.scaleX(1),t.target.scaleY(1);const a=k.current?Math.min(e.x,e.y):1;w.set(Object.assign({width:w.width*e.x,height:w.height*e.y,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation()},1!==a&&Object.assign(Object.assign({},m(w,a)),{strokeWidth:w.strokeWidth*a})))},onTransformEnd:()=>{w.set(Object.assign(Object.assign({},f(w)),{strokeWidth:l(w.strokeWidth)}))},children:t(S,{element:w,fillProps:E,strokeProps:R,hitStrokeWidth:P})})})});
1
+ import{jsx as t,Fragment as e,jsxs as a}from"react/jsx-runtime";import r from"react";import{observer as s}from"mobx-react-lite";import{Group as o,Rect as i,Path as n}from"react-konva";import{ROLES as h}from"../model/store.js";import{subTypeToPathDataFunc as d}from"@polotno/core/figure-to-svg";import{isTouchDevice as c}from"../utils/screen.js";import{roundEnabledPx as l,isCornerAnchor as g,scaledBoxStyleAttrs as m,roundedBoxStyleAttrs as f}from"../utils/px.js";import{useColor as u}from"./use-color.js";const p={};export const FigureElement=s(({element:w,store:b})=>{const x=r.useRef(null),k=r.useRef(!1),v=w.selectable||b.role===h.ADMIN,j=c(),y=w.isSelected,O=Math.min(w.strokeWidth,w.width/2,w.height/2),W=Math.max(0,Math.min(w.width/2,w.height/2,w.cornerRadius)),M=u(w,w.a.fill,"fill"),E=Object.assign(Object.assign({width:w.a.width,height:w.a.height},M),{cornerRadius:W,shadowEnabled:w.shadowEnabled,shadowBlur:w.shadowBlur,shadowOffsetX:w.shadowOffsetX,shadowOffsetY:w.shadowOffsetY,shadowColor:w.shadowColor,shadowOpacity:w.shadowOpacity,preventDefault:!j||y,hideInExport:!w.showInExport}),T=u(w,w.stroke,"stroke"),R=Object.assign(Object.assign({visible:O>0,x:O/2,y:O/2,width:w.a.width-O,height:w.a.height-O},T),{strokeWidth:O,cornerRadius:Math.max(0,W-O),dash:w.dash.map(t=>t*O),hideInExport:!w.showInExport,listening:!1}),P=Math.max(0,10-Math.min(w.a.width,w.a.height)),S=(A=w.subType,p[A]||(p[A]=(C=d(A),s(({element:s,fillProps:h,strokeProps:d,hitStrokeWidth:c})=>{const l=C({width:s.a.width,height:s.a.height,cornerRadius:s.cornerRadius}),g=r.useRef(null);return a(e,{children:[t(i,{width:s.a.width,height:s.a.height,fill:"transparent",hitStrokeWidth:c}),t(n,Object.assign({},h,{ref:g,data:l})),t(o,{clipFunc:t=>{const e=g.current;if(e){var a=e.dataArray;t.beginPath();for(var r=0;r<a.length;r++){var s=a[r].command,o=a[r].points;switch(s){case"L":t.lineTo(o[0],o[1]);break;case"M":t.moveTo(o[0],o[1]);break;case"C":t.bezierCurveTo(o[0],o[1],o[2],o[3],o[4],o[5]);break;case"Q":t.quadraticCurveTo(o[0],o[1],o[2],o[3]);break;case"A":var i=o[0],n=o[1],h=o[2],d=o[3],c=o[4],l=o[5],m=o[6],f=o[7],u=h>d?h:d,p=h>d?1:h/d,w=h>d?d/h:1;t.translate(i,n),t.rotate(m),t.scale(p,w),t.arc(0,0,u,c,c+l,!f),t.scale(1/p,1/w),t.rotate(-m),t.translate(-i,-n);break;case"z":t.closePath()}}}},children:t(n,Object.assign({},d,{x:0,y:0,data:l,strokeWidth:2*d.strokeWidth,dash:d.dash.map(t=>t)}))})]})}))),p[A]||o);var A,C;return t(e,{children:t(o,{ref:x,id:w.id,x:w.a.x,y:w.a.y,rotation:w.a.rotation,opacity:w.a.opacity,listening:v,draggable:j?w.draggable&&y:w.draggable,name:"element",onDragMove:t=>{w.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{w.set({x:t.target.x(),y:t.target.y()})},onTransformStart:t=>{var e,a;const r=null===(e=t.target.getStage())||void 0===e?void 0:e.findOne("Transformer");k.current=g(null!==(a=null==r?void 0:r.getActiveAnchor())&&void 0!==a?a:"")},onTransform:t=>{const e=t.target.scale();t.target.scaleX(1),t.target.scaleY(1);const a=k.current?Math.min(e.x,e.y):1;w.set(Object.assign({width:w.width*e.x,height:w.height*e.y,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation()},1!==a&&Object.assign(Object.assign({},m(w,a)),{strokeWidth:w.strokeWidth*a})))},onTransformEnd:()=>{w.set(Object.assign(Object.assign({},f(w)),{strokeWidth:l(w.strokeWidth)}))},children:t(S,{element:w,fillProps:E,strokeProps:R,hitStrokeWidth:P})})})});
@@ -1 +1 @@
1
- import{jsx as t,Fragment as e,jsxs as o}from"react/jsx-runtime";import r from"react";import{observer as n}from"mobx-react-lite";import{Group as i,Image as a,Path as s,Rect as l}from"react-konva";import{scaledFontSizeAttrs as c,roundedFontSizeAttrs as f,roundedTextDecorationAttrs as h,textMinResizeWidth as d}from"../utils/px.js";import u from"konva";import{isAlive as g}from"mobx-state-tree";import{nodeAutorun as m}from"../utils/mobx.js";import{flags as x}from"../utils/flags.js";import{applyFilter as p}from"./apply-filters.js";import{getLineHeight as y,useFontFamiliesLoader as w,usePrevious as v}from"./text-element.js";import{getCurvePath as b}from"@polotno/core/text-html";import{useColor as E}from"./use-color.js";import{useWorkspaceStyle as S}from"./workspace-style.js";import{detectSize as O,detectLineRects as k,htmlToCanvas as z}from"../utils/html2canvas.js";import{generateBackgroundShapeFromRects as F}from"@polotno/core/background-shape";import{useFadeIn as j}from"./use-fadein.js";import{Html as M}from"react-konva-utils";import{incrementLoader as R,triggerLoadError as X}from"../utils/loader.js";import{removeTags as Y}from"@polotno/core/text";import*as I from"../utils/fonts.js";import{isTouchDevice as C}from"../utils/screen.js";import{getLimitedFontSize as T}from"./text-element/max-font-size.js";import{visiblePlaceholder as A}from"./text-element/placeholder.js";import{useDelayer as P}from"./use-delayer.js";import{getHtml as B}from"@polotno/core/text-html";import{normalizeRichTextHtml as W,extractFontFamiliesFromHtml as $,scaleRichTextFontSizesInHtml as D}from"../utils/rich-text-html.js";import{findFitFontSize as H}from"./text-element/fit-font-size.js";import{RichEditor as _,RichTextContainer as L,applyOpacityToColor as J,quillRef as N,createQuill as q,setQuillContent as V,setQuillFormats as G,syncQuillFormatState as K,setCursorFromCoords as Q}from"./rich-editor.js";export{N as quillRef,q as createQuill,V as setQuillContent,G as setQuillFormats,K as syncQuillFormatState,Q as setCursorFromCoords};function U(t){const e=document.createElement("canvas"),o=e.getContext("2d");return null==o||o.drawImage(t,0,0,e.width,e.height),function(t){return!function(t){const e=t.getContext("2d").getImageData(0,0,t.width,t.height).data;for(let o=0;o<e.length;o+=4){if(0!==e[o+3]){return!0}}return!1}(t)}(e)}const Z=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),tt=navigator.userAgent.includes("Firefox");export const HTMLElement=n(({element:n,store:N})=>{var q,V;const{textOverflowIndicatorStyle:G}=S(),K=r.useRef(null),[Q,et]=r.useState(),[ot,rt]=r.useState(!1),[nt,it]=r.useState(!1),at=r.useRef(n.height),st=n.isSelected,lt=v(st),ct=n.fontSize/3,{textVerticalResizeEnabled:ft}=x,ht=x.autoDeleteEmptyText,dt=v(n.fontFamily),ut=r.useMemo(()=>W(n.text,{fontSize:n.fontSize,fontFamily:n.fontFamily}),[n.text,n.fontSize,n.fontFamily]),gt=r.useMemo(()=>[...new Set([n.fontFamily,...$(ut)])].filter(Boolean),[n.fontFamily,ut]),[mt]=w(N,gt,n.fontStyle,n.fontWeight,n.text||n.placeholder),xt=n._editModeEnabled;j(K);const pt=mt?n.fontFamily:dt!==n.fontFamily?dt:"Arial",yt=E(n).fill,wt=B(n,{fontFamily:pt,color:yt,textOverflow:x.textOverflow}),vt=r.useRef([]),bt=r.useRef(!0),[,Et]=r.useReducer(t=>t+1,0);r.useEffect(()=>{const t=vt.current;t.length>0&&(vt.current=[],t.forEach(t=>t()))}),r.useEffect(()=>()=>{bt.current=!1;const t=vt.current;t.length>0&&(vt.current=[],t.forEach(t=>t()))},[]);let{width:St,height:Ot}=function(t,e,o){return r.useMemo(()=>O(t),[t,e.width,o])}(wt,n,mt);r.useEffect(()=>{if(!mt){return}const t=(t,e,o,r)=>{const i=R(`text ${n.id}`),a=()=>{N.history.ignore(t,e,o).then(()=>{bt.current?(vt.current.push(i),Et()):i()})};r?queueMicrotask(a):a()};if(n.curveEnabled&&Math.abs(St-n.width)>1&&!ot&&t(()=>{if(g(n)&&Math.abs(St-n.width)>1){const t=n.x+n.width/2;n.set({width:St,x:t-St/2})}},!1,!0),!n.height){return void t(()=>{g(n)&&(n.height||n.set({height:Ot}))},void 0,void 0,!0)}const{textOverflow:e}=x;if("change-font-size"!==e||ot||xt||n.curveEnabled){"resize"===e&&(ft&&n.height<Ot&&!ot&&t(()=>{g(n)&&n.set({height:Ot})},!1,!0),ft||n.height===Ot||ot||t(()=>{g(n)&&n.set({height:Ot})},!1,!0))}else{const e=H(n,{fontFamily:n.fontFamily,textOverflow:x.textOverflow});e.fontSize!==n.fontSize?t(()=>{if(!g(n)){return}const t=c(n,e.fontSize);void 0!==e.text&&e.text!==n.text&&(t.text=e.text),n.set(t)},!1,!0):n.height!==Ot&&(ft&&n.height<Ot?t(()=>{g(n)&&n.set({height:Ot})},!1,!0):ft||t(()=>{g(n)&&n.set({height:Ot})},!1,!0))}});const kt=r.useMemo(()=>{const t={lastArgs:null,lastResult:null};return async function(e){return t.lastArgs&&t.lastResult&&(o=t.lastArgs,r=e,JSON.stringify(o)===JSON.stringify(r))||(t.lastResult=await z(e),t.lastArgs=Object.assign({},e)),t.lastResult;var o,r}},[]),zt=r.useRef(0),Ft=r.useRef(null);r.useEffect(()=>{ot||xt||(async()=>{zt.current++;const t=zt.current;let e=R(`text ${n.id} ${t}`);Ft.current&&Ft.current(),Ft.current=e,it(!0);let o=null;const r=Z?5:1;for(let a=0;a<r;a++){const e=a>0?kt:z;try{if(o=await e({skipCache:a>0,html:wt,width:St||n.width||1,height:n.height||Ot||1,fontFamily:pt,fontFamilies:$(wt),resolveFont:t=>N.fonts.find(e=>e.fontFamily===t)||I.globalFonts.find(e=>e.fontFamily===t),padding:ct,pixelRatio:N._elementsPixelRatio,font:N.fonts.find(t=>t.fontFamily===pt)||I.globalFonts.find(t=>t.fontFamily===pt)}),t!==zt.current){return}if((Z||tt)&&o&&U(o)){await new Promise(t=>setTimeout(t,50*(a+1)));continue}break}catch(i){console.error(i),X(`Error rendering rich text with id ${n.id}`);break}}o?et(o):e?(e(),e=null):console.error("Finish function is called twice!"),it(!1)})()},[wt,ot,Ot,xt,pt,n.height,N._elementsPixelRatio,mt]);const[jt,Mt]=P(nt,300),[Rt]=P(ot,300,!0),Xt=Rt||jt;r.useEffect(()=>{var t;if(!Xt){return m(n,()=>{const t=K.current;p(t,n)})}null===(t=K.current)||void 0===t||t.clearCache()},[Q,Xt,n.shadowColor,n.shadowOffsetX,n.shadowOffsetY,n.shadowOpacity]),r.useEffect(()=>{Q&&!nt&&Ft.current&&(Ft.current(),Ft.current=null)},[Q,nt]),r.useLayoutEffect(()=>{if(!mt){return}if(!n.curveEnabled){return}const t=new u.TextPath({data:b(n.a.width,n.a.height,n.curvePower,n.a.fontSize),text:Y(n.text),letterSpacing:n.letterSpacing*n.a.fontSize,fontSize:n.a.fontSize,fontFamily:n.fontFamily,fontWeight:n.fontWeight,fontStyle:n.fontStyle,align:"center",textBaseline:"middle",fill:n.fill}),e=t.getSelfRect().width;if(e){const t=e-n.a.width,o=n.a.rotation*Math.PI/180,r=-t/2*Math.cos(o),i=-t/2*Math.sin(o);queueMicrotask(()=>{g(n)&&n.set({width:e,x:n.a.x+r,y:n.a.y+i})})}t.destroy()},[mt,n.curveEnabled,n.curvePower,n.text,n.fontSize,n.fontFamily,n.fontWeight,n.fontStyle,n.letterSpacing]),r.useEffect(()=>()=>{Ft.current&&Ft.current()},[]),r.useEffect(()=>{lt&&!st&&ht&&""===Y(n.text)&&n.removable&&!A(n.placeholder)&&N.deleteElements([n.id])},[ht,n.placeholder,n.removable,n.text,st,lt]);let Yt=0;"middle"===n.verticalAlign&&(Yt=(n.height-Ot)/2),"bottom"===n.verticalAlign&&(Yt=n.height-Ot);const It=y({fontLoaded:mt,fontFamily:n.fontFamily,fontSize:n.fontSize,lineHeight:n.lineHeight}),Ct=n.backgroundPadding*(n.fontSize*It*.5),Tt=n.backgroundCornerRadius*(n.fontSize*It*.5),At=r.useMemo(()=>{if(!n.backgroundEnabled||n.curveEnabled||n.legacyBackground){return""}const t=k(wt);if(0===t.length){return""}const e=t.map(t=>({left:t.left+ct,right:t.right+ct,top:t.top+ct,bottom:t.bottom+ct}));return F({rects:e,padding:Ct,cornerRadius:Tt})},[n.backgroundEnabled,n.curveEnabled,n.legacyBackground,wt,mt,Ct,Tt,ct]),Pt=C(),Bt=b(n.a.width,Ot,n.curvePower,n.fontSize),Wt=r.useRef(null),$t=r.useRef(n.width),Dt=r.useRef(null),Ht=r.useRef(0),_t=r.useRef(0),Lt=r.useRef(null),Jt=xt&&n.strokeWidth>0&&!n.curveEnabled,Nt=St>0?(n.a.width+2*ct)/(St+2*ct):1;return o(e,{children:[n.curveEnabled||n.legacyBackground?t(l,{x:n.a.x,y:n.a.y,offsetX:Ct/Nt,offsetY:Ct/Nt,rotation:n.a.rotation,scaleX:Nt,scaleY:Nt,hideInExport:!n.showInExport,listening:!1,visible:n.backgroundEnabled,opacity:n.backgroundOpacity*n.a.opacity,fill:n.backgroundColor,width:n.width+2*Ct,height:n.height+2*Ct,cornerRadius:Tt}):t(s,{name:"html-background",x:n.a.x,y:n.a.y,offsetX:ct/Nt,offsetY:(ct-Yt)/Nt,rotation:n.a.rotation,scaleX:Nt,scaleY:Nt,hideInExport:!n.showInExport,listening:!1,visible:n.backgroundEnabled&&At.length>0,opacity:n.backgroundOpacity*n.a.opacity,fill:n.backgroundColor,data:At}),t(s,{x:n.a.x,y:n.a.y,rotation:n.a.rotation,data:Bt,stroke:G.stroke,strokeWidth:1,visible:!1}),t(l,{ref:K,name:"element",x:n.a.x,y:n.a.y,listening:n.selectable,rotation:n.a.rotation,width:n.a.width,height:n.a.height,visible:!Xt,draggable:Pt?n.draggable&&st:n.draggable,preventDefault:!Pt||st,opacity:xt?0:n.a.opacity,hideInExport:!n.showInExport,onDragMove:t=>{n.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{n.set({x:t.target.x(),y:t.target.y()})},id:n.id,onDblClick:t=>{n.contentEditable&&(Lt.current={x:t.evt.clientX,y:t.evt.clientY},n.toggleEditMode(!0))},onDblTap:t=>{var e;if(n.contentEditable){const o=null===(e=t.evt.changedTouches)||void 0===e?void 0:e[0];Lt.current=o?{x:o.clientX,y:o.clientY}:null,n.toggleEditMode(!0)}},onTransformStart:t=>{var e,o;rt(!0),at.current=n.height,$t.current=n.width,Wt.current=t.target.position();const r=null===(e=t.target.getStage())||void 0===e?void 0:e.findOne("Transformer");Dt.current=null!==(o=null==r?void 0:r.getActiveAnchor())&&void 0!==o?o:null,Ht.current=n.a.rotation,_t.current=n.height},onTransform:t=>{var e;const o=t.target,r=(null===(e=o.getStage())||void 0===e?void 0:e.findOne("Transformer")).getActiveAnchor(),i="middle-left"===r||"middle-right"===r,a="top-center"===r||"bottom-center"===r,s=o.scaleX();if(i){const t=o.scaleX(),e=o.width()*t,r=d($t.current,n.fontSize);let i=e;e<r&&(i=r,Wt.current&&o.position(Wt.current)),o.width(i),o.scaleX(1),o.scaleY(1);const a=B(Object.assign(Object.assign({},n.toJSON()),{width:i}),{fontFamily:pt,color:yt,textOverflow:x.textOverflow}),s=O(a).height,l=x.textVerticalResizeEnabled?Math.max(s,at.current):s;o.height(l),n.set({width:o.width(),height:l,x:o.x(),y:o.y()})}else if(a){const t="resize"===x.textOverflow,e="number"==typeof n.lineHeight?n.lineHeight:1,r=t?Ot:e*n.fontSize,i=o.height()*o.scaleY();if(i<r){if(o.height(r),Wt.current){if("top-center"===Dt.current){const t=Ht.current*Math.PI/180,e=_t.current-r;o.x(Wt.current.x-e*Math.sin(t)),o.y(Wt.current.y+e*Math.cos(t))}else{o.position(Wt.current)}}}else{o.height(i)}o.scaleY(1),o.scaleX(1),_t.current=Math.max(r,i),n.set({x:o.x(),y:o.y(),height:o.height(),rotation:o.rotation()})}else{o.scaleX(1),o.scaleY(1),n.set({fontSize:n.fontSize*s,letterSpacing:n.letterSpacing,width:o.width()*s,x:o.x(),y:o.y(),rotation:o.rotation(),height:o.height()*s,shadowBlur:n.shadowBlur*s,shadowOffsetX:n.shadowOffsetX*s,shadowOffsetY:n.shadowOffsetY*s,strokeWidth:n.strokeWidth*s,text:D(n.text,s)})}Wt.current=t.target.position()},onTransformEnd:t=>{rt(!1),it(!0);const e=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),n.set(Object.assign(Object.assign({},f(n,n.fontSize*e)),{width:t.target.width()*e,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),text:D(n.text,e)}))}}),t(a,{ref:K,image:Q,x:n.a.x,y:n.a.y,offsetX:ct,offsetY:ct-Yt,listening:!1,rotation:n.a.rotation,width:n.a.width+2*ct,height:(n.a.width+2*ct)*((null!==(q=null==Q?void 0:Q.height)&&void 0!==q?q:0)/((null==Q?void 0:Q.width)||1)||1),visible:!Xt&&!xt,opacity:n.a.opacity,shadowEnabled:n.shadowEnabled,shadowBlur:n.shadowBlur,shadowOffsetX:n.shadowOffsetX,shadowOffsetY:n.shadowOffsetY,shadowColor:n.shadowColor,shadowOpacity:n.shadowOpacity,hideInExport:!n.showInExport,editModeEnabled:n._editModeEnabled||ot||Xt}),(Xt&&!xt||Jt)&&t(i,{x:n.a.x,y:n.a.y,rotation:n.a.rotation,offsetY:-Yt,children:t(M,{divProps:{style:{pointerEvents:"none"}},children:t(L,{dangerouslySetInnerHTML:{__html:wt},style:{pointerEvents:"none",opacity:n.a.opacity,textShadow:n.shadowEnabled?`${n.shadowOffsetX}px ${n.shadowOffsetY}px ${n.shadowBlur}px ${J(n.shadowColor,null!==(V=n.shadowOpacity)&&void 0!==V?V:1)}`:void 0}})})}),xt&&t(i,{x:n.a.x,y:n.a.y,rotation:n.a.rotation,offsetY:-Yt,children:t(M,{divProps:{style:{zIndex:20}},children:t(_,{element:n,onChange:t=>{const e=T({oldText:Y(n.text),newText:Y(t),element:n});n.set(Object.assign({text:t},c(n,e)))},onBlur:t=>{g(n)&&(n.set(h(n)),n.toggleEditMode(!1),Mt(!0))},clickCoords:Lt.current})})})]})});
1
+ import{jsx as t,Fragment as e,jsxs as o}from"react/jsx-runtime";import r from"react";import{observer as n}from"mobx-react-lite";import{Group as i,Image as a,Path as s,Rect as l}from"react-konva";import{scaledFontSizeAttrs as c,roundedFontSizeAttrs as f,roundedTextDecorationAttrs as d,textMinResizeWidth as h}from"../utils/px.js";import u from"konva";import{isAlive as g}from"mobx-state-tree";import{nodeAutorun as m}from"../utils/mobx.js";import{flags as x}from"../utils/flags.js";import{applyFilter as p}from"./apply-filters.js";import{getLineHeight as y,useFontFamiliesLoader as w,usePrevious as v}from"./text-element.js";import{getCurvePath as b}from"@polotno/core/text-html";import{useColor as E}from"./use-color.js";import{useWorkspaceStyle as S}from"./workspace-style.js";import{detectSize as O,detectLineRects as k,htmlToCanvas as z}from"../utils/html2canvas.js";import{generateBackgroundShapeFromRects as F}from"@polotno/core/background-shape";import{useFadeIn as j}from"./use-fadein.js";import{Html as M}from"react-konva-utils";import{incrementLoader as R,triggerLoadError as X}from"../utils/loader.js";import{removeTags as Y}from"@polotno/core/text";import*as I from"../utils/fonts.js";import{isTouchDevice as C}from"../utils/screen.js";import{getLimitedFontSize as T}from"./text-element/max-font-size.js";import{visiblePlaceholder as A}from"./text-element/placeholder.js";import{useDelayer as P}from"./use-delayer.js";import{getHtml as B}from"@polotno/core/text-html";import{hasMeasuredHeight as W,resolveTextBoxHeight as $}from"@polotno/core/text-types";import{normalizeRichTextHtml as D,extractFontFamiliesFromHtml as H,scaleRichTextFontSizesInHtml as _}from"../utils/rich-text-html.js";import{findFitFontSize as L}from"./text-element/fit-font-size.js";import{RichEditor as J,RichTextContainer as N,applyOpacityToColor as q,quillRef as V,createQuill as G,setQuillContent as K,setQuillFormats as Q,syncQuillFormatState as U,setCursorFromCoords as Z}from"./rich-editor.js";export{V as quillRef,G as createQuill,K as setQuillContent,Q as setQuillFormats,U as syncQuillFormatState,Z as setCursorFromCoords};function tt(t){const e=document.createElement("canvas"),o=e.getContext("2d");return null==o||o.drawImage(t,0,0,e.width,e.height),function(t){return!function(t){const e=t.getContext("2d").getImageData(0,0,t.width,t.height).data;for(let o=0;o<e.length;o+=4){if(0!==e[o+3]){return!0}}return!1}(t)}(e)}const et=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),ot=navigator.userAgent.includes("Firefox");export const HTMLElement=n(({element:n,store:V})=>{var G,K;const{textOverflowIndicatorStyle:Q}=S(),U=r.useRef(null),[Z,rt]=r.useState(),[nt,it]=r.useState(!1),[at,st]=r.useState(!1),lt=r.useRef(n.height),ct=n.isSelected,ft=v(ct),dt=n.fontSize/3,{textVerticalResizeEnabled:ht}=x,ut=x.autoDeleteEmptyText,gt=v(n.fontFamily),mt=r.useMemo(()=>D(n.text,{fontSize:n.fontSize,fontFamily:n.fontFamily}),[n.text,n.fontSize,n.fontFamily]),xt=r.useMemo(()=>[...new Set([n.fontFamily,...H(mt)])].filter(Boolean),[n.fontFamily,mt]),[pt]=w(V,xt,n.fontStyle,n.fontWeight,n.text||n.placeholder),yt=n._editModeEnabled;j(U);const wt=pt?n.fontFamily:gt!==n.fontFamily?gt:"Arial",vt=E(n).fill,bt=B(n,{fontFamily:wt,color:vt,textOverflow:x.textOverflow}),Et=r.useRef([]),St=r.useRef(!0),[,Ot]=r.useReducer(t=>t+1,0);r.useEffect(()=>{const t=Et.current;t.length>0&&(Et.current=[],t.forEach(t=>t()))}),r.useEffect(()=>()=>{St.current=!1;const t=Et.current;t.length>0&&(Et.current=[],t.forEach(t=>t()))},[]);let{width:kt,height:zt}=function(t,e,o){return r.useMemo(()=>O(t),[t,e.width,o])}(bt,n,pt);r.useEffect(()=>{if(!pt){return}const t=(t,e,o,r)=>{const i=R(`text ${n.id}`),a=()=>{V.history.ignore(t,e,o).then(()=>{St.current?(Et.current.push(i),Ot()):i()})};r?queueMicrotask(a):a()};if(n.curveEnabled&&Math.abs(kt-n.width)>1&&!nt&&t(()=>{if(g(n)&&Math.abs(kt-n.width)>1){const t=n.x+n.width/2;n.set({width:kt,x:t-kt/2})}},!1,!0),!W(n)){return void t(()=>{g(n)&&(W(n)||n.set({height:zt}))},void 0,void 0,!0)}const{textOverflow:e}=x;if("change-font-size"!==e||nt||yt||n.curveEnabled){"resize"===e&&(ht&&n.height<zt&&!nt&&t(()=>{g(n)&&n.set({height:zt})},!1,!0),ht||n.height===zt||nt||t(()=>{g(n)&&n.set({height:zt})},!1,!0))}else{const e=L(n,{fontFamily:n.fontFamily,textOverflow:x.textOverflow});e.fontSize!==n.fontSize?t(()=>{if(!g(n)){return}const t=c(n,e.fontSize);void 0!==e.text&&e.text!==n.text&&(t.text=e.text),n.set(t)},!1,!0):n.height!==zt&&(ht&&n.height<zt?t(()=>{g(n)&&n.set({height:zt})},!1,!0):ht||t(()=>{g(n)&&n.set({height:zt})},!1,!0))}});const Ft=r.useMemo(()=>{const t={lastArgs:null,lastResult:null};return async function(e){return t.lastArgs&&t.lastResult&&(o=t.lastArgs,r=e,JSON.stringify(o)===JSON.stringify(r))||(t.lastResult=await z(e),t.lastArgs=Object.assign({},e)),t.lastResult;var o,r}},[]),jt=r.useRef(0),Mt=r.useRef(null);r.useEffect(()=>{nt||yt||(async()=>{jt.current++;const t=jt.current;let e=R(`text ${n.id} ${t}`);Mt.current&&Mt.current(),Mt.current=e,st(!0);let o=null;const r=et?5:1;for(let a=0;a<r;a++){const e=a>0?Ft:z;try{if(o=await e({skipCache:a>0,html:bt,width:kt||n.width||1,height:$(n,zt)||1,fontFamily:wt,fontFamilies:H(bt),resolveFont:t=>V.fonts.find(e=>e.fontFamily===t)||I.globalFonts.find(e=>e.fontFamily===t),padding:dt,pixelRatio:V._elementsPixelRatio,font:V.fonts.find(t=>t.fontFamily===wt)||I.globalFonts.find(t=>t.fontFamily===wt)}),t!==jt.current){return}if((et||ot)&&o&&tt(o)){await new Promise(t=>setTimeout(t,50*(a+1)));continue}break}catch(i){console.error(i),X(`Error rendering rich text with id ${n.id}`);break}}o?rt(o):e?(e(),e=null):console.error("Finish function is called twice!"),st(!1)})()},[bt,nt,zt,yt,wt,n.height,V._elementsPixelRatio,pt]);const[Rt,Xt]=P(at,300),[Yt]=P(nt,300,!0),It=Yt||Rt;r.useEffect(()=>{var t;if(!It){return m(n,()=>{const t=U.current;p(t,n)})}null===(t=U.current)||void 0===t||t.clearCache()},[Z,It,n.shadowColor,n.shadowOffsetX,n.shadowOffsetY,n.shadowOpacity]),r.useEffect(()=>{Z&&!at&&Mt.current&&(Mt.current(),Mt.current=null)},[Z,at]),r.useLayoutEffect(()=>{if(!pt){return}if(!n.curveEnabled){return}const t=new u.TextPath({data:b(n.a.width,n.a.height,n.curvePower,n.a.fontSize),text:Y(n.text),letterSpacing:n.letterSpacing*n.a.fontSize,fontSize:n.a.fontSize,fontFamily:n.fontFamily,fontWeight:n.fontWeight,fontStyle:n.fontStyle,align:"center",textBaseline:"middle",fill:n.fill}),e=t.getSelfRect().width;if(e){const t=e-n.a.width,o=n.a.rotation*Math.PI/180,r=-t/2*Math.cos(o),i=-t/2*Math.sin(o);queueMicrotask(()=>{g(n)&&n.set({width:e,x:n.a.x+r,y:n.a.y+i})})}t.destroy()},[pt,n.curveEnabled,n.curvePower,n.text,n.fontSize,n.fontFamily,n.fontWeight,n.fontStyle,n.letterSpacing]),r.useEffect(()=>()=>{Mt.current&&Mt.current()},[]),r.useEffect(()=>{ft&&!ct&&ut&&""===Y(n.text)&&n.removable&&!A(n.placeholder)&&V.deleteElements([n.id])},[ut,n.placeholder,n.removable,n.text,ct,ft]);const Ct=$(n,zt);let Tt=0;"middle"===n.verticalAlign&&(Tt=(Ct-zt)/2),"bottom"===n.verticalAlign&&(Tt=Ct-zt);const At=y({fontLoaded:pt,fontFamily:n.fontFamily,fontSize:n.fontSize,lineHeight:n.lineHeight}),Pt=n.backgroundPadding*(n.fontSize*At*.5),Bt=n.backgroundCornerRadius*(n.fontSize*At*.5),Wt=r.useMemo(()=>{if(!n.backgroundEnabled||n.curveEnabled||n.legacyBackground){return""}const t=k(bt);if(0===t.length){return""}const e=t.map(t=>({left:t.left+dt,right:t.right+dt,top:t.top+dt,bottom:t.bottom+dt}));return F({rects:e,padding:Pt,cornerRadius:Bt})},[n.backgroundEnabled,n.curveEnabled,n.legacyBackground,bt,pt,Pt,Bt,dt]),$t=C(),Dt=b(n.a.width,zt,n.curvePower,n.fontSize),Ht=r.useRef(null),_t=r.useRef(n.width),Lt=r.useRef(null),Jt=r.useRef(0),Nt=r.useRef(0),qt=r.useRef(null),Vt=yt&&n.strokeWidth>0&&!n.curveEnabled,Gt=kt>0?(n.a.width+2*dt)/(kt+2*dt):1;return o(e,{children:[n.curveEnabled||n.legacyBackground?t(l,{x:n.a.x,y:n.a.y,offsetX:Pt/Gt,offsetY:Pt/Gt,rotation:n.a.rotation,scaleX:Gt,scaleY:Gt,hideInExport:!n.showInExport,listening:!1,visible:n.backgroundEnabled,opacity:n.backgroundOpacity*n.a.opacity,fill:n.backgroundColor,width:n.width+2*Pt,height:Ct+2*Pt,cornerRadius:Bt}):t(s,{name:"html-background",x:n.a.x,y:n.a.y,offsetX:dt/Gt,offsetY:(dt-Tt)/Gt,rotation:n.a.rotation,scaleX:Gt,scaleY:Gt,hideInExport:!n.showInExport,listening:!1,visible:n.backgroundEnabled&&Wt.length>0,opacity:n.backgroundOpacity*n.a.opacity,fill:n.backgroundColor,data:Wt}),t(s,{x:n.a.x,y:n.a.y,rotation:n.a.rotation,data:Dt,stroke:Q.stroke,strokeWidth:1,visible:!1}),t(l,{ref:U,name:"element",x:n.a.x,y:n.a.y,listening:n.selectable,rotation:n.a.rotation,width:n.a.width,height:n.a.height,visible:!It,draggable:$t?n.draggable&&ct:n.draggable,preventDefault:!$t||ct,opacity:yt?0:n.a.opacity,hideInExport:!n.showInExport,onDragMove:t=>{n.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{n.set({x:t.target.x(),y:t.target.y()})},id:n.id,onDblClick:t=>{n.contentEditable&&(qt.current={x:t.evt.clientX,y:t.evt.clientY},n.toggleEditMode(!0))},onDblTap:t=>{var e;if(n.contentEditable){const o=null===(e=t.evt.changedTouches)||void 0===e?void 0:e[0];qt.current=o?{x:o.clientX,y:o.clientY}:null,n.toggleEditMode(!0)}},onTransformStart:t=>{var e,o;it(!0),lt.current=n.height,_t.current=n.width,Ht.current=t.target.position();const r=null===(e=t.target.getStage())||void 0===e?void 0:e.findOne("Transformer");Lt.current=null!==(o=null==r?void 0:r.getActiveAnchor())&&void 0!==o?o:null,Jt.current=n.a.rotation,Nt.current=n.height},onTransform:t=>{var e;const o=t.target,r=(null===(e=o.getStage())||void 0===e?void 0:e.findOne("Transformer")).getActiveAnchor(),i="middle-left"===r||"middle-right"===r,a="top-center"===r||"bottom-center"===r,s=o.scaleX();if(i){const t=o.scaleX(),e=o.width()*t,r=h(_t.current,n.fontSize);let i=e;e<r&&(i=r,Ht.current&&o.position(Ht.current)),o.width(i),o.scaleX(1),o.scaleY(1);const a=B(Object.assign(Object.assign({},n.toJSON()),{width:i}),{fontFamily:wt,color:vt,textOverflow:x.textOverflow}),s=O(a).height,l=x.textVerticalResizeEnabled?Math.max(s,lt.current):s;o.height(l),n.set({width:o.width(),height:l,x:o.x(),y:o.y()})}else if(a){const t="resize"===x.textOverflow,e="number"==typeof n.lineHeight?n.lineHeight:1,r=t?zt:e*n.fontSize,i=o.height()*o.scaleY();if(i<r){if(o.height(r),Ht.current){if("top-center"===Lt.current){const t=Jt.current*Math.PI/180,e=Nt.current-r;o.x(Ht.current.x-e*Math.sin(t)),o.y(Ht.current.y+e*Math.cos(t))}else{o.position(Ht.current)}}}else{o.height(i)}o.scaleY(1),o.scaleX(1),Nt.current=Math.max(r,i),n.set({x:o.x(),y:o.y(),height:o.height(),rotation:o.rotation()})}else{o.scaleX(1),o.scaleY(1),n.set({fontSize:n.fontSize*s,letterSpacing:n.letterSpacing,width:o.width()*s,x:o.x(),y:o.y(),rotation:o.rotation(),height:o.height()*s,shadowBlur:n.shadowBlur*s,shadowOffsetX:n.shadowOffsetX*s,shadowOffsetY:n.shadowOffsetY*s,strokeWidth:n.strokeWidth*s,text:_(n.text,s)})}Ht.current=t.target.position()},onTransformEnd:t=>{it(!1),st(!0);const e=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),n.set(Object.assign(Object.assign({},f(n,n.fontSize*e)),{width:t.target.width()*e,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),text:_(n.text,e)}))}}),t(a,{ref:U,image:Z,x:n.a.x,y:n.a.y,offsetX:dt,offsetY:dt-Tt,listening:!1,rotation:n.a.rotation,width:n.a.width+2*dt,height:(n.a.width+2*dt)*((null!==(G=null==Z?void 0:Z.height)&&void 0!==G?G:0)/((null==Z?void 0:Z.width)||1)||1),visible:!It&&!yt,opacity:n.a.opacity,shadowEnabled:n.shadowEnabled,shadowBlur:n.shadowBlur,shadowOffsetX:n.shadowOffsetX,shadowOffsetY:n.shadowOffsetY,shadowColor:n.shadowColor,shadowOpacity:n.shadowOpacity,hideInExport:!n.showInExport,editModeEnabled:n._editModeEnabled||nt||It}),(It&&!yt||Vt)&&t(i,{x:n.a.x,y:n.a.y,rotation:n.a.rotation,offsetY:-Tt,children:t(M,{divProps:{style:{pointerEvents:"none"}},children:t(N,{dangerouslySetInnerHTML:{__html:bt},style:{pointerEvents:"none",opacity:n.a.opacity,textShadow:n.shadowEnabled?`${n.shadowOffsetX}px ${n.shadowOffsetY}px ${n.shadowBlur}px ${q(n.shadowColor,null!==(K=n.shadowOpacity)&&void 0!==K?K:1)}`:void 0}})})}),yt&&t(i,{x:n.a.x,y:n.a.y,rotation:n.a.rotation,offsetY:-Tt,children:t(M,{divProps:{style:{zIndex:20}},children:t(J,{element:n,onChange:t=>{const e=T({oldText:Y(n.text),newText:Y(t),element:n});n.set(Object.assign({text:t},c(n,e)))},onBlur:t=>{g(n)&&(n.set(d(n)),n.toggleEditMode(!1),Xt(!0))},clickCoords:qt.current})})})]})});
@@ -2,6 +2,17 @@ import React from 'react';
2
2
  import { StoreType } from '../model/store.js';
3
3
  import { ImageElementType } from '../model/image-model.js';
4
4
  export declare const useSizeFixer: (src: string) => string;
5
+ export declare function maskCompositeSize(shapeRaster: {
6
+ width: number;
7
+ height: number;
8
+ }, element: {
9
+ width: number;
10
+ height: number;
11
+ stretchEnabled?: boolean;
12
+ }): {
13
+ width: number;
14
+ height: number;
15
+ };
5
16
  export declare const useCornerRadiusAndCrop: (element: ImageElementType, image: HTMLImageElement | HTMLCanvasElement | undefined, crop: {
6
17
  x: number;
7
18
  y: number;
@@ -1 +1 @@
1
- import{jsx as t,jsxs as e,Fragment as r}from"react/jsx-runtime";import o from"react";import{observer as i}from"mobx-react-lite";import{Arc as a,Group as n,Image as h,Rect as s,Text as d,Transformer as c}from"react-konva";import{ROLES as g}from"../model/store.js";import l from"use-image";import u from"konva";import{Portal as p}from"react-konva-utils";import{useWorkspaceStyle as m}from"./workspace-style.js";import{incrementLoader as f,triggerLoadError as w}from"../utils/loader.js";import{polotnoError as x}from"@polotno/core/errors";import{getCropRect as y}from"@polotno/core/image";import*as M from"@polotno/core/svg";import{flags as v}from"../utils/flags.js";import{trySetCanvasSize as b}from"../utils/canvas.js";import{roundEnabledPx as E,isCornerAnchor as S,scaledBoxStyleAttrs as I,roundedBoxStyleAttrs as R}from"../utils/px.js";import{useFilteredSource as C}from"./use-filtered-source.js";import{useFadeIn as X}from"./use-fadein.js";import{isTouchDevice as Y}from"../utils/screen.js";import{useDelayer as O}from"./use-delayer.js";import{useColor as T}from"./use-color.js";function j(){return document.createElement("canvas")}const A=t=>t.indexOf("data:image/svg+xml")>=0||t.indexOf(".svg")>=0;export const useSizeFixer=t=>{const[e,r]=o.useState(t);return o.useEffect(()=>{(async()=>{const o=await async function(t){if(!A(t)){return t}const e=await M.urlToString(t),r=M.fixSize(e);return M.svgToURL(r)}(t);o!==e&&r(o)})()},[t]),e};function D(t,e){return{x:(t.x+e.x)/2,y:(t.y+e.y)/2}}const W=(t,e)=>e.width<5||e.height<5?t:e,z={keepRatio:!1,rotateEnabled:!1,boundBoxFunc:W},L={enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],rotateEnabled:!1,borderEnabled:!1,boundBoxFunc:W};const k=(t,e,r)=>Math.max(e,Math.min(r,t));export const useCornerRadiusAndCrop=(t,e,r,i,a=0,n=!1,h=!0)=>{var s,d;const c=Math.floor(k(t.a.width*i,1,1e4)),g=Math.floor(k(t.a.height*i,1,1e4)),l=Math.min(a*i,c/2,g/2),p=Math.max(t.a.width/r.width,t.a.height/r.height)*i,m=(null===(s=t.page)||void 0===s?void 0:s._exportingOrRendering)&&v.imageDownScalingEnabled&&p<1&&!n,f=0===r.x&&0===r.y&&r.width===(null==e?void 0:e.width)&&r.height===(null==e?void 0:e.height),w=o.useMemo(()=>{if(e&&e.width&&e.height){return f&&0===l&&!m?void 0:j()}},[e,l,m,f]);return o.useLayoutEffect(()=>{if(!w||!e){return}b(w,c,g);const t=w.getContext("2d");if(!t){return}l&&(t.beginPath(),t.moveTo(l,0),t.lineTo(c-l,0),t.arc(c-l,l,l,3*Math.PI/2,0,!1),t.lineTo(c,g-l),t.arc(c-l,g-l,l,0,Math.PI/2,!1),t.lineTo(l,g),t.arc(l,g-l,l,Math.PI/2,Math.PI,!1),t.lineTo(0,l),t.arc(l,l,l,Math.PI,3*Math.PI/2,!1),t.clip());const o=m?function(t,e){var r,o;const i=j();i.width=t.width,i.height=t.height;const a=Math.max(1,Math.floor(i.width*e)),n=Math.max(1,Math.floor(i.height*e));null===(r=i.getContext("2d"))||void 0===r||r.drawImage(t,0,0,i.width,i.height);const h=function(t,e,r,o,i,a,n){for(var h=new ImageData(e,r),s=new Int32Array(t.data.buffer),d=t.width,c=new Int32Array(h.data.buffer),g=h.width,l=e/a,u=r/n,p=Math.round(1/l),m=Math.round(1/u),f=p*m,w=0;w<h.height;w++){for(var x=0;x<g;x++){for(var y=0+Math.round(x/l)+(0+Math.round(w/u))*d,M=0,v=0,b=0,E=0,S=0;S<m;S++){for(var I=0;I<p;I++){var R=s[y+I+S*d];M+=R<<24>>>24,v+=R<<16>>>24,b+=R<<8>>>24,E+=R>>>24}}M=Math.round(M/f),v=Math.round(v/f),b=Math.round(b/f),E=Math.round(E/f),c[x+w*g]=E<<24|b<<16|v<<8|M}}return h}(i.getContext("2d").getImageData(0,0,i.width,i.height),a,n,0,0,i.width,i.height);return i.width=a,i.height=n,null===(o=i.getContext("2d"))||void 0===o||o.putImageData(h,0,0),i}(e,p):e,i=m?{x:Math.floor(r.x*p),y:Math.floor(r.y*p),width:Math.floor(r.width*p),height:Math.floor(r.height*p)}:r;t.drawImage(o,i.x,i.y,i.width,i.height,0,0,w.width,w.height)},[w,t.a.width,t.a.height,r.x,r.y,r.width,r.height,a,i,n,null===(d=t.page)||void 0===d?void 0:d._exportingOrRendering,m]),o.useEffect(()=>()=>{w&&"CANVAS"===w.nodeName&&u.Util.releaseCanvas(w)},[w]),w||e};const H=j(),_=i(({element:r})=>{const i=Math.min(30,r.a.width/4,r.a.height/4),h=o.useRef(null);o.useEffect(()=>{const t=h.current;if(!t){return}const e=new u.Animation(e=>{t.rotate(((null==e?void 0:e.timeDiff)||0)/2)},t.getLayer());return e.start(),()=>{e.stop()}});const{mediaLoadingStyle:d}=m();return e(n,{x:r.x,y:r.y,rotation:r.rotation,listening:!1,opacity:r.a.opacity,hideInExport:!r.showInExport,children:[t(s,{width:r.a.width,height:r.a.height,fill:d.fill}),t(a,{ref:h,x:r.a.width/2,y:r.a.height/2,fill:d.textFill,outerRadius:Math.abs(i),innerRadius:Math.max(1,i-5),angle:270})]})}),P=i(({element:r})=>{const{mediaErrorStyle:o}=m(),i=Math.max(10,Math.min(30,r.a.width/25));return e(n,{x:r.x,y:r.y,rotation:r.rotation,listening:!1,opacity:r.a.opacity,hideInExport:!r.showInExport,children:[t(s,{width:r.a.width,height:r.a.height,fill:o.fill}),t(d,{text:"Can not load the image...",fontSize:i,width:r.a.width,height:r.a.height,align:"center",fill:o.textFill,verticalAlign:"middle",padding:5})]})});let F=l;export const setImageLoaderHook=t=>{F=t};export const useImageLoader=(t,e="",r="")=>{const i=o.useRef(void 0),a=()=>{var t;null===(t=i.current)||void 0===t||t.call(i),i.current=void 0};o.useEffect(()=>a,[]),o.useLayoutEffect(()=>{const o=e.slice(0,200),n=`image with id ${r} url: ${o}`;"loading"!==t||i.current||(i.current=f(n)),"loading"!==t&&a(),"failed"===t&&w(x("IMAGE_FAILED",n,{src:o,elementId:r,reason:"load"}))},[t])};export const ImageElement=i(({element:i,store:a})=>{var d,l,f;const w=m(),[x,v]=o.useState(!1),W=o.useRef(null),k=o.useRef(null),N=i.isSelected,[B,U]=(t=>{const[e,r]=o.useReducer(t=>t+1,0),i=o.useRef("loading"),a=o.useRef(t.src),n=o.useRef(t.src);n.current!==t.src&&(n.current=t.src,i.current="loading");const h=o.useMemo(()=>A(t.src)||"svg"===t.type,[t.src,t.type]);return o.useEffect(()=>{if(!h){return}if(!t.src){return}let e=!1;return(async()=>{i.current="loading",r();const o=await M.urlToString(t.src),n=M.fixSize(o);let h;h=t.colorsReplace?M.replaceColors(n,t.colorsReplace||new Map):M.svgToURL(n),e||(a.current=h,i.current="loaded",r())})(),()=>{e=!0}},[t.src,JSON.stringify(t.colorsReplace)]),h?[a.current,i.current]:[t.src,"loaded"]})(i),[V,$]=F(B,"anonymous"),q="svg"!==i.type||"loaded"===U?$:"loading";useImageLoader(q,i.src,i.id);const G=(null===(d=i.page)||void 0===d?void 0:d._exportingOrRendering)?1:Math.max(1,a.scale),J=a._elementsPixelRatio*G,K=(({image:t,status:e,type:r})=>{const i=o.useRef(void 0);return o.useEffect(()=>{i.current=t||i.current},[t]),"failed"!==e||"failed"!==e&&"svg"===r?i.current:void 0})({image:V,status:$,type:i.type}),Q=((t,e,r)=>{const i=o.useMemo(()=>{var o,i;const{flipX:a,flipY:n}=t,h="svg"===t.type||t.src.indexOf("data:image/svg+xml")>=0||t.src.indexOf(".svg")>=0,s=navigator.userAgent.toLowerCase().indexOf("firefox")>-1,d=(/^((?!chrome|android).)*safari/i.test(navigator.userAgent)||s)&&h||t.maskSrc;if(!a&&!n&&!d){return e}if(!e||!e.width||!e.height){return null}const c=j();let g=1;"svg"===t.type&&(g=Math.max(t.a.width/e.width*r,t.a.height/e.height*r)),b(c,Math.max(e.width*g,1),Math.max(e.height*g,1));let l=a?-c.width:0,u=n?-c.height:0;return null===(o=c.getContext("2d"))||void 0===o||o.scale(a?-1:1,n?-1:1),null===(i=c.getContext("2d"))||void 0===i||i.drawImage(e,l,u,c.width,c.height),c},[t.maskSrc,t.flipX,t.flipY,e,t.a.width,t.a.height,r]);return o.useEffect(()=>()=>{i&&"CANVAS"===i.nodeName&&u.Util.releaseCanvas(i)},[i]),i})(i,V||K,J),Z=((t,e)=>{const r=useSizeFixer(t.maskSrc||""),[i,a]=F(r,"anonymous");return useImageLoader(r?a:"loaded",r||"",t.id),o.useMemo(()=>{if(!i){return e}if(!e||!e.width||!e.height){return e}const r=j();r.width=Math.max(e.width,1),r.height=Math.max(e.height,1);const o=r.getContext("2d");if(!o){return e}o.drawImage(e,0,0),o.globalCompositeOperation="source-in";const a=function(t,e){const r=e.width/e.height;let o,i;return r>=t.width/t.height?(o=t.width,i=t.width/r):(o=t.height*r,i=t.height),{x:(t.width-o)/2,y:(t.height-i)/2,width:o,height:i}}(i,t);return o.drawImage(i,a.x,a.y,a.width,a.height,0,0,e.width,e.height),r},[e,i,t.a.width,t.a.height])})(i,Q)||H,[tt=H]=C(i,Z);let{cropX:et,cropY:rt,cropWidth:ot,cropHeight:it}=i.a;"loaded"!==$&&(et=rt=0,ot=it=1);const at=y({stretchEnabled:i.stretchEnabled,cropX:et,cropY:rt,cropWidth:ot,cropHeight:it,width:i.a.width,height:i.a.height},tt),nt=at.width,ht=at.height,st=i.stretchEnabled,dt=null!==(l=i.cornerRadius)&&void 0!==l?l:0,ct=(null===(f=i.page)||void 0===f?void 0:f._exportingOrRendering)?1:Math.min(2,a.scale),gt=a._elementsPixelRatio*ct;let lt=((t,e,r,i)=>{const a=useSizeFixer(t.clipSrc||""),[n,h]=F(a,"anonymous"),s=t.clipSrc?h:"loaded";useImageLoader(s,t.clipSrc,t.id);const d=o.useMemo(()=>{if(e&&n){return j()}},[e,n]);return o.useLayoutEffect(()=>{var o;if(!n){return}if(!e||!e.width||!e.height){return}if(!n||!n.width||!n.height){return}if(!d){return}const i=j(),a=Math.max(t.a.width/n.width*r,t.a.height/n.height*r);i.width=Math.max(n.width*a,1),i.height=Math.max(n.height*a,1),null===(o=i.getContext("2d"))||void 0===o||o.drawImage(n,0,0,i.width,i.height),d.width=Math.max(e.width,1),d.height=Math.max(e.height,1);const h=d.getContext("2d");h&&(h.save(),h.drawImage(i,0,0,e.width,e.height),u.Util.releaseCanvas(i),h.globalCompositeOperation="source-in",h.drawImage(e,0,0,d.width,d.height),h.restore())},[d,e,n,t.a.width,t.a.height,r,...i]),t.clipSrc&&n?d:e})(i,useCornerRadiusAndCrop(i,tt,at,gt,dt,x||i._cropModeEnabled||"svg"===i.type,!0),gt,[at,dt,gt]);const ut=Math.max(i.a.width/nt,i.a.height/ht);o.useEffect(()=>{var t;if(!i._cropModeEnabled){return}const e=null===(t=W.current)||void 0===t?void 0:t.getStage();function r(t){i._cropModeEnabled&&t.target!==k.current&&i.toggleCropMode(!1)}function o(t){i._cropModeEnabled&&t.target.parentNode!==(null==e?void 0:e.content)&&i.toggleCropMode(!1)}return document.body.addEventListener("click",o),null==e||e.on("click",r),null==e||e.on("tap",r),()=>{document.body.removeEventListener("click",o),document.body.removeEventListener("touchstart",o),null==e||e.off("click",r),null==e||e.off("click",r)}},[i._cropModeEnabled]);const pt=o.useRef(null),mt=o.useRef(null),ft=o.useRef(null);o.useLayoutEffect(()=>{i._cropModeEnabled&&(mt.current.nodes([pt.current]),ft.current.nodes([k.current]))},[i._cropModeEnabled]);var wt=o.useRef(null),xt=o.useRef(0),yt=o.useRef(!1);const Mt=t=>{var e;(null===(e=t.evt.touches)||void 0===e?void 0:e.length)>2&&t.target.stopDrag(),Math.round(t.target.x())>0&&(t.target.x(0),t.target.scaleX(1)),Math.round(t.target.y())>0&&(t.target.y(0),t.target.scaleY(1));const r=t.target.width()*t.target.scaleX(),o=t.target.height()*t.target.scaleY(),a=Math.min(1,nt/r),n=Math.min(1,ht/o),h=1-a,s=Math.min(h,Math.max(0,Math.round(-t.target.x())/r)),d=1-n,c=Math.min(d,Math.max(0,Math.round(-t.target.y())/o));t.target.setAttrs({x:-s*tt.width,y:-c*tt.height,scaleX:1,scaleY:1}),i.set({cropX:s,cropY:c,cropWidth:a,cropHeight:n})},vt=()=>{"svg"!==i.type&&i.contentEditable&&(i.stretchEnabled||setTimeout(()=>{i.toggleCropMode(!0)}))},bt="svg"===i.type&&K,Et="loading"===$&&!bt,[St]=O(Et,100,!1,!1),It="failed"===$,Rt=!St&&!It,Ct=o.useRef({cropX:0,cropY:0,cropWidth:0,cropHeight:0}),Xt=Rt?i.a.opacity:0;X(W,Xt);const Yt=i.selectable||a.role===g.ADMIN,Ot=Y(),Tt=T(i,i.borderColor,"stroke");return e(r,{children:[St&&t(_,{element:i}),It&&t(P,{element:i}),t(h,{ref:W,name:"element",id:i.id,image:lt,x:i.a.x,y:i.a.y,width:i.a.width||1,height:i.a.height||1,rotation:i.a.rotation,opacity:Xt,shadowEnabled:i.shadowEnabled,shadowBlur:i.shadowBlur,shadowOffsetX:i.shadowOffsetX,shadowOffsetY:i.shadowOffsetY,shadowColor:i.shadowColor,shadowOpacity:i.shadowOpacity,customCrop:at,listening:Yt,draggable:Ot?i.draggable&&N:i.draggable,preventDefault:!Ot||N,hideInExport:!i.showInExport,onDragMove:t=>{i.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{i.set({x:t.target.x(),y:t.target.y()})},onDblClick:vt,onDblTap:vt,onTransformStart:()=>{v(!0),Ct.current={cropX:i.cropX,cropY:i.cropY,cropWidth:i.cropWidth,cropHeight:i.cropHeight}},onTransform:t=>{var e,r;const o=t.currentTarget,a=Math.abs(o.scaleX()-1)<1e-7?1:o.scaleX(),n=Math.abs(o.scaleY()-1)<1e-7?1:o.scaleY();o.scaleX(1),o.scaleY(1);const h=null===(e=t.target.getStage())||void 0===e?void 0:e.findOne("Transformer"),s=1-nt/tt.width,d=Math.min(s,Math.max(0,i.cropX)),c=1-ht/tt.height,g=Math.min(c,Math.max(0,i.cropY)),l=S(null!==(r=h.getActiveAnchor())&&void 0!==r?r:""),u=!l&&a<1&&Ct.current.cropHeight>ht/tt.height;let p=l?i.cropWidth:i.cropWidth*a;u&&(p=i.cropWidth);const m=!l&&n<1&&Ct.current.cropWidth>nt/tt.width;let f=l?i.cropHeight:i.cropHeight*n;m&&(f=i.cropHeight),st&&(p=i.cropWidth,f=i.cropHeight);const w=l?Math.min(a,n):1;i.set(Object.assign({cropX:d,cropY:g,x:o.x(),y:o.y(),width:o.width()*a,height:o.height()*n,rotation:t.target.rotation(),cropWidth:Math.min(p,1-d),cropHeight:Math.min(f,1-g)},1!==w&&Object.assign(Object.assign({},I(i,w)),{borderSize:i.borderSize*w})))},onTransformEnd:t=>{const e=t.currentTarget;i.set(Object.assign(Object.assign({width:e.width(),height:e.height(),x:e.x(),y:e.y(),rotation:t.target.rotation(),cropWidth:nt/tt.width,cropHeight:ht/tt.height},R(i)),{borderSize:E(i.borderSize)})),v(!1)}}),t(s,Object.assign({x:i.x,y:i.y,width:Math.max(i.a.width-i.borderSize,0),height:Math.max(i.a.height-i.borderSize,0),opacity:Xt,offsetX:-i.borderSize/2,offsetY:-i.borderSize/2},Tt,{strokeWidth:i.borderSize,listening:!1,visible:!!i.borderSize,rotation:i.rotation,cornerRadius:Math.max(0,dt-i.borderSize),hideInExport:!i.showInExport})),i._cropModeEnabled&&e(p,{selector:".page-abs-container",enabled:!0,children:[t(s,{x:-window.innerWidth/a.scale,y:-window.innerWidth/a.scale,width:window.innerWidth/a.scale*3,height:window.innerWidth/a.scale*3,fill:w.cropOverlayFill}),t(h,{listening:!1,image:lt,x:i.x,y:i.y,width:i.a.width,height:i.a.height,rotation:i.rotation,shadowEnabled:i.shadowEnabled,shadowBlur:i.shadowBlur}),e(n,{x:i.x,y:i.y,rotation:i.rotation,scaleX:ut,scaleY:ut,children:[t(h,{image:tt,ref:k,opacity:.4,draggable:!0,x:-i.cropX*tt.width,y:-i.cropY*tt.height,onDragMove:Mt,onTransform:Mt,onTouchMove:t=>{t.evt.preventDefault();const e=t.target.getStage().getPointersPositions();var r=e[0],o=e[1];const i=t.target;if(r&&!o&&!i.isDragging()&&yt.current&&(i.startDrag(),yt.current=!1),r&&o){u.hitOnDragEnabled=!0,i.isDragging()&&(yt.current=!0,i.stopDrag());const e=t.target.getAbsoluteTransform().copy();e.invert();var a={x:r.x,y:r.y},n={x:o.x,y:o.y};if(!wt.current){return void(wt.current=D(a,n))}var h=D(a,n),s=function(t,e){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}(a,n);xt.current||(xt.current=s);const m=i.position();var d={x:h.x-m.x,y:h.y-m.y},c=s/xt.current;i.scaleX(c),i.scaleY(c);const f=e.point(h),w=e.point(wt.current);var g=f.x-w.x,l=f.y-w.y,p={x:Math.min(0,h.x-d.x*c+g),y:Math.min(0,h.y-d.y*c+l)};i.position(p),xt.current=s,wt.current=h,Mt(t)}},onTouchEnd:t=>{xt.current=0,wt.current=null,u.hitOnDragEnabled=!1}}),t(c,Object.assign({ref:ft},L,w.outerImageCropTransformerStyle)),t(s,{width:nt,height:ht,ref:pt,listening:!1,onTransform:t=>{if(i.cropX<Math.abs(t.target.x()/tt.width)&&t.target.x()<0&&i.cropX>0){const e=(i.cropWidth+i.cropX)*tt.width;t.target.scaleX(1),t.target.width(e)}if(i.cropY<Math.abs(t.target.y()/tt.height)&&t.target.y()<0&&i.cropY>0){const e=(i.cropHeight+i.cropY)*tt.height;t.target.scaleY(1),t.target.height(e)}t.target.x()<-i.cropX*tt.width-1e-9&&(t.target.x(-i.cropX*tt.width),t.target.scaleX(1)),t.target.y()<-i.cropY*tt.height-1e-9&&(t.target.y(-i.cropY*tt.height),t.target.scaleY(1));const e=Math.min(1,Math.max(0,i.cropX+t.target.x()/tt.width)),r=Math.min(1,Math.max(0,t.target.y()/tt.height+i.cropY)),o=t.target.width()*t.target.scaleX(),a=t.target.height()*t.target.scaleY(),n=Math.min(1-e,o/tt.width),h=Math.min(1-r,a/tt.height),s=t.target.getAbsolutePosition(t.target.getParent().getParent());t.target.scale({x:1,y:1}),t.target.position({x:0,y:0}),i.set({x:s.x,y:s.y,cropX:e,cropY:r,cropWidth:n,cropHeight:h,width:Math.min(o*ut,tt.width*(1-e)*ut),height:Math.min(a*ut,tt.height*(1-r)*ut)})}}),t(c,Object.assign({ref:mt},z,w.innerImageCropTransformerStyle,{visible:i.resizable}))]})]})]})});
1
+ import{jsx as t,jsxs as e,Fragment as r}from"react/jsx-runtime";import o from"react";import{observer as i}from"mobx-react-lite";import{Arc as a,Group as n,Image as h,Rect as s,Text as d,Transformer as c}from"react-konva";import{ROLES as g}from"../model/store.js";import l from"use-image";import u from"konva";import{Portal as p}from"react-konva-utils";import{useWorkspaceStyle as m}from"./workspace-style.js";import{incrementLoader as f,triggerLoadError as w}from"../utils/loader.js";import{polotnoError as x}from"@polotno/core/errors";import{getCropRect as M}from"@polotno/core/image";import*as y from"@polotno/core/svg";import{flags as v}from"../utils/flags.js";import{trySetCanvasSize as b}from"../utils/canvas.js";import{roundEnabledPx as E,isCornerAnchor as S,scaledBoxStyleAttrs as I,roundedBoxStyleAttrs as C}from"../utils/px.js";import{useFilteredSource as R}from"./use-filtered-source.js";import{useFadeIn as X}from"./use-fadein.js";import{isTouchDevice as Y}from"../utils/screen.js";import{useDelayer as O}from"./use-delayer.js";import{useColor as T}from"./use-color.js";function j(){return document.createElement("canvas")}const A=t=>t.indexOf("data:image/svg+xml")>=0||t.indexOf(".svg")>=0;export const useSizeFixer=t=>{const[e,r]=o.useState(t);return o.useEffect(()=>{(async()=>{const o=await async function(t){if(!A(t)){return t}const e=await y.urlToString(t),r=y.fixSize(e);return y.svgToURL(r)}(t);o!==e&&r(o)})()},[t]),e};function D(t,e){return{x:(t.x+e.x)/2,y:(t.y+e.y)/2}}const W=(t,e)=>e.width<5||e.height<5?t:e,z={keepRatio:!1,rotateEnabled:!1,boundBoxFunc:W},k={enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],rotateEnabled:!1,borderEnabled:!1,boundBoxFunc:W};export function maskCompositeSize(t,e){const r=M({stretchEnabled:e.stretchEnabled,cropX:0,cropY:0,cropWidth:1,cropHeight:1,width:Math.max(e.width,1),height:Math.max(e.height,1)},t);return{width:Math.max(Math.round(r.width),1),height:Math.max(Math.round(r.height),1)}}const L=(t,e,r)=>Math.max(e,Math.min(r,t));export const useCornerRadiusAndCrop=(t,e,r,i,a=0,n=!1,h=!0)=>{var s,d;const c=Math.floor(L(t.a.width*i,1,1e4)),g=Math.floor(L(t.a.height*i,1,1e4)),l=Math.min(a*i,c/2,g/2),p=Math.max(t.a.width/r.width,t.a.height/r.height)*i,m=(null===(s=t.page)||void 0===s?void 0:s._exportingOrRendering)&&v.imageDownScalingEnabled&&p<1&&!n,f=0===r.x&&0===r.y&&r.width===(null==e?void 0:e.width)&&r.height===(null==e?void 0:e.height),w=o.useMemo(()=>{if(e&&e.width&&e.height){return f&&0===l&&!m?void 0:j()}},[e,l,m,f]);return o.useLayoutEffect(()=>{if(!w||!e){return}b(w,c,g);const t=w.getContext("2d");if(!t){return}l&&(t.beginPath(),t.moveTo(l,0),t.lineTo(c-l,0),t.arc(c-l,l,l,3*Math.PI/2,0,!1),t.lineTo(c,g-l),t.arc(c-l,g-l,l,0,Math.PI/2,!1),t.lineTo(l,g),t.arc(l,g-l,l,Math.PI/2,Math.PI,!1),t.lineTo(0,l),t.arc(l,l,l,Math.PI,3*Math.PI/2,!1),t.clip());const o=m?function(t,e){var r,o;const i=j();i.width=t.width,i.height=t.height;const a=Math.max(1,Math.floor(i.width*e)),n=Math.max(1,Math.floor(i.height*e));null===(r=i.getContext("2d"))||void 0===r||r.drawImage(t,0,0,i.width,i.height);const h=function(t,e,r,o,i,a,n){for(var h=new ImageData(e,r),s=new Int32Array(t.data.buffer),d=t.width,c=new Int32Array(h.data.buffer),g=h.width,l=e/a,u=r/n,p=Math.round(1/l),m=Math.round(1/u),f=p*m,w=0;w<h.height;w++){for(var x=0;x<g;x++){for(var M=0+Math.round(x/l)+(0+Math.round(w/u))*d,y=0,v=0,b=0,E=0,S=0;S<m;S++){for(var I=0;I<p;I++){var C=s[M+I+S*d];y+=C<<24>>>24,v+=C<<16>>>24,b+=C<<8>>>24,E+=C>>>24}}y=Math.round(y/f),v=Math.round(v/f),b=Math.round(b/f),E=Math.round(E/f),c[x+w*g]=E<<24|b<<16|v<<8|y}}return h}(i.getContext("2d").getImageData(0,0,i.width,i.height),a,n,0,0,i.width,i.height);return i.width=a,i.height=n,null===(o=i.getContext("2d"))||void 0===o||o.putImageData(h,0,0),i}(e,p):e,i=m?{x:Math.floor(r.x*p),y:Math.floor(r.y*p),width:Math.floor(r.width*p),height:Math.floor(r.height*p)}:r;t.drawImage(o,i.x,i.y,i.width,i.height,0,0,w.width,w.height)},[w,t.a.width,t.a.height,r.x,r.y,r.width,r.height,a,i,n,null===(d=t.page)||void 0===d?void 0:d._exportingOrRendering,m]),o.useEffect(()=>()=>{w&&"CANVAS"===w.nodeName&&u.Util.releaseCanvas(w)},[w]),w||e};const H=j(),_=i(({element:r})=>{const i=Math.min(30,r.a.width/4,r.a.height/4),h=o.useRef(null);o.useEffect(()=>{const t=h.current;if(!t){return}const e=new u.Animation(e=>{t.rotate(((null==e?void 0:e.timeDiff)||0)/2)},t.getLayer());return e.start(),()=>{e.stop()}});const{mediaLoadingStyle:d}=m();return e(n,{x:r.x,y:r.y,rotation:r.rotation,listening:!1,opacity:r.a.opacity,hideInExport:!r.showInExport,children:[t(s,{width:r.a.width,height:r.a.height,fill:d.fill}),t(a,{ref:h,x:r.a.width/2,y:r.a.height/2,fill:d.textFill,outerRadius:Math.abs(i),innerRadius:Math.max(1,i-5),angle:270})]})}),P=i(({element:r})=>{const{mediaErrorStyle:o}=m(),i=Math.max(10,Math.min(30,r.a.width/25));return e(n,{x:r.x,y:r.y,rotation:r.rotation,listening:!1,opacity:r.a.opacity,hideInExport:!r.showInExport,children:[t(s,{width:r.a.width,height:r.a.height,fill:o.fill}),t(d,{text:"Can not load the image...",fontSize:i,width:r.a.width,height:r.a.height,align:"center",fill:o.textFill,verticalAlign:"middle",padding:5})]})});let F=l;export const setImageLoaderHook=t=>{F=t};export const useImageLoader=(t,e="",r="")=>{const i=o.useRef(void 0),a=()=>{var t;null===(t=i.current)||void 0===t||t.call(i),i.current=void 0};o.useEffect(()=>a,[]),o.useLayoutEffect(()=>{const o=e.slice(0,200),n=`image with id ${r} url: ${o}`;"loading"!==t||i.current||(i.current=f(n)),"loading"!==t&&a(),"failed"===t&&w(x("IMAGE_FAILED",n,{src:o,elementId:r,reason:"load"}))},[t])};export const ImageElement=i(({element:i,store:a})=>{var d,l,f;const w=m(),[x,v]=o.useState(!1),W=o.useRef(null),L=o.useRef(null),N=i.isSelected,[B,U]=(t=>{const[e,r]=o.useReducer(t=>t+1,0),i=o.useRef("loading"),a=o.useRef(t.src),n=o.useRef(t.src);n.current!==t.src&&(n.current=t.src,i.current="loading");const h=o.useMemo(()=>A(t.src)||"svg"===t.type,[t.src,t.type]);return o.useEffect(()=>{if(!h){return}if(!t.src){return}let e=!1;return(async()=>{i.current="loading",r();const o=await y.urlToString(t.src),n=y.fixSize(o);let h;h=t.colorsReplace?y.replaceColors(n,t.colorsReplace||new Map):y.svgToURL(n),e||(a.current=h,i.current="loaded",r())})(),()=>{e=!0}},[t.src,JSON.stringify(t.colorsReplace)]),h?[a.current,i.current]:[t.src,"loaded"]})(i),[V,$]=F(B,"anonymous"),q="svg"!==i.type||"loaded"===U?$:"loading";useImageLoader(q,i.src,i.id);const G=(null===(d=i.page)||void 0===d?void 0:d._exportingOrRendering)?1:Math.max(1,a.scale),J=a._elementsPixelRatio*G,K=(({image:t,status:e,type:r})=>{const i=o.useRef(void 0);return o.useEffect(()=>{i.current=t||i.current},[t]),"failed"!==e||"failed"!==e&&"svg"===r?i.current:void 0})({image:V,status:$,type:i.type}),Q=((t,e,r)=>{const i=o.useMemo(()=>{var o,i;const{flipX:a,flipY:n}=t,h="svg"===t.type||t.src.indexOf("data:image/svg+xml")>=0||t.src.indexOf(".svg")>=0,s=navigator.userAgent.toLowerCase().indexOf("firefox")>-1,d=(/^((?!chrome|android).)*safari/i.test(navigator.userAgent)||s)&&h||t.maskSrc;if(!a&&!n&&!d){return e}if(!e||!e.width||!e.height){return null}const c=j();let g=1;"svg"===t.type&&(g=Math.max(t.a.width/e.width*r,t.a.height/e.height*r)),b(c,Math.max(e.width*g,1),Math.max(e.height*g,1));let l=a?-c.width:0,u=n?-c.height:0;return null===(o=c.getContext("2d"))||void 0===o||o.scale(a?-1:1,n?-1:1),null===(i=c.getContext("2d"))||void 0===i||i.drawImage(e,l,u,c.width,c.height),c},[t.maskSrc,t.flipX,t.flipY,e,t.a.width,t.a.height,r]);return o.useEffect(()=>()=>{i&&"CANVAS"===i.nodeName&&u.Util.releaseCanvas(i)},[i]),i})(i,V||K,J),Z=((t,e)=>{const r=useSizeFixer(t.maskSrc||""),[i,a]=F(r,"anonymous");return useImageLoader(r?a:"loaded",r||"",t.id),o.useMemo(()=>{if(!i){return e}if(!e||!e.width||!e.height){return e}const{width:r,height:o}=maskCompositeSize(e,{width:t.a.width,height:t.a.height,stretchEnabled:t.stretchEnabled}),a=j();a.width=r,a.height=o;const n=a.getContext("2d");if(!n){return e}n.drawImage(e,0,0,r,o,0,0,r,o),n.globalCompositeOperation="source-in";const h=function(t,e){const r=e.width/e.height;let o,i;return r>=t.width/t.height?(o=t.width,i=t.width/r):(o=t.height*r,i=t.height),{x:(t.width-o)/2,y:(t.height-i)/2,width:o,height:i}}(i,t);return n.drawImage(i,h.x,h.y,h.width,h.height,0,0,r,o),a},[e,i,t.a.width,t.a.height,t.stretchEnabled])})(i,Q)||H,[tt=H]=R(i,Z);let{cropX:et,cropY:rt,cropWidth:ot,cropHeight:it}=i.a;"loaded"!==$&&(et=rt=0,ot=it=1);const at=M({stretchEnabled:i.stretchEnabled,cropX:et,cropY:rt,cropWidth:ot,cropHeight:it,width:i.a.width,height:i.a.height},tt),nt=at.width,ht=at.height,st=i.stretchEnabled,dt=null!==(l=i.cornerRadius)&&void 0!==l?l:0,ct=(null===(f=i.page)||void 0===f?void 0:f._exportingOrRendering)?1:Math.min(2,a.scale),gt=a._elementsPixelRatio*ct;let lt=((t,e,r,i)=>{const a=useSizeFixer(t.clipSrc||""),[n,h]=F(a,"anonymous"),s=t.clipSrc?h:"loaded";useImageLoader(s,t.clipSrc,t.id);const d=o.useMemo(()=>{if(e&&n){return j()}},[e,n]);return o.useLayoutEffect(()=>{var o;if(!n){return}if(!e||!e.width||!e.height){return}if(!n||!n.width||!n.height){return}if(!d){return}const i=j(),a=Math.max(t.a.width/n.width*r,t.a.height/n.height*r);i.width=Math.max(n.width*a,1),i.height=Math.max(n.height*a,1),null===(o=i.getContext("2d"))||void 0===o||o.drawImage(n,0,0,i.width,i.height),d.width=Math.max(e.width,1),d.height=Math.max(e.height,1);const h=d.getContext("2d");h&&(h.save(),h.drawImage(i,0,0,e.width,e.height),u.Util.releaseCanvas(i),h.globalCompositeOperation="source-in",h.drawImage(e,0,0,d.width,d.height),h.restore())},[d,e,n,t.a.width,t.a.height,r,...i]),t.clipSrc&&n?d:e})(i,useCornerRadiusAndCrop(i,tt,at,gt,dt,x||i._cropModeEnabled||"svg"===i.type,!0),gt,[at,dt,gt]);const ut=Math.max(i.a.width/nt,i.a.height/ht);o.useEffect(()=>{var t;if(!i._cropModeEnabled){return}const e=null===(t=W.current)||void 0===t?void 0:t.getStage();function r(t){i._cropModeEnabled&&t.target!==L.current&&i.toggleCropMode(!1)}function o(t){i._cropModeEnabled&&t.target.parentNode!==(null==e?void 0:e.content)&&i.toggleCropMode(!1)}return document.body.addEventListener("click",o),null==e||e.on("click",r),null==e||e.on("tap",r),()=>{document.body.removeEventListener("click",o),document.body.removeEventListener("touchstart",o),null==e||e.off("click",r),null==e||e.off("click",r)}},[i._cropModeEnabled]);const pt=o.useRef(null),mt=o.useRef(null),ft=o.useRef(null);o.useLayoutEffect(()=>{i._cropModeEnabled&&(mt.current.nodes([pt.current]),ft.current.nodes([L.current]))},[i._cropModeEnabled]);var wt=o.useRef(null),xt=o.useRef(0),Mt=o.useRef(!1);const yt=t=>{var e;(null===(e=t.evt.touches)||void 0===e?void 0:e.length)>2&&t.target.stopDrag(),Math.round(t.target.x())>0&&(t.target.x(0),t.target.scaleX(1)),Math.round(t.target.y())>0&&(t.target.y(0),t.target.scaleY(1));const r=t.target.width()*t.target.scaleX(),o=t.target.height()*t.target.scaleY(),a=Math.min(1,nt/r),n=Math.min(1,ht/o),h=1-a,s=Math.min(h,Math.max(0,Math.round(-t.target.x())/r)),d=1-n,c=Math.min(d,Math.max(0,Math.round(-t.target.y())/o));t.target.setAttrs({x:-s*tt.width,y:-c*tt.height,scaleX:1,scaleY:1}),i.set({cropX:s,cropY:c,cropWidth:a,cropHeight:n})},vt=()=>{"svg"!==i.type&&i.contentEditable&&(i.stretchEnabled||setTimeout(()=>{i.toggleCropMode(!0)}))},bt="svg"===i.type&&K,Et="loading"===$&&!bt,[St]=O(Et,100,!1,!1),It="failed"===$,Ct=!St&&!It,Rt=o.useRef({cropX:0,cropY:0,cropWidth:0,cropHeight:0}),Xt=Ct?i.a.opacity:0;X(W,Xt);const Yt=i.selectable||a.role===g.ADMIN,Ot=Y(),Tt=T(i,i.borderColor,"stroke");return e(r,{children:[St&&t(_,{element:i}),It&&t(P,{element:i}),t(h,{ref:W,name:"element",id:i.id,image:lt,x:i.a.x,y:i.a.y,width:i.a.width||1,height:i.a.height||1,rotation:i.a.rotation,opacity:Xt,shadowEnabled:i.shadowEnabled,shadowBlur:i.shadowBlur,shadowOffsetX:i.shadowOffsetX,shadowOffsetY:i.shadowOffsetY,shadowColor:i.shadowColor,shadowOpacity:i.shadowOpacity,customCrop:at,listening:Yt,draggable:Ot?i.draggable&&N:i.draggable,preventDefault:!Ot||N,hideInExport:!i.showInExport,onDragMove:t=>{i.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{i.set({x:t.target.x(),y:t.target.y()})},onDblClick:vt,onDblTap:vt,onTransformStart:()=>{v(!0),Rt.current={cropX:i.cropX,cropY:i.cropY,cropWidth:i.cropWidth,cropHeight:i.cropHeight}},onTransform:t=>{var e,r;const o=t.currentTarget,a=Math.abs(o.scaleX()-1)<1e-7?1:o.scaleX(),n=Math.abs(o.scaleY()-1)<1e-7?1:o.scaleY();o.scaleX(1),o.scaleY(1);const h=null===(e=t.target.getStage())||void 0===e?void 0:e.findOne("Transformer"),s=1-nt/tt.width,d=Math.min(s,Math.max(0,i.cropX)),c=1-ht/tt.height,g=Math.min(c,Math.max(0,i.cropY)),l=S(null!==(r=h.getActiveAnchor())&&void 0!==r?r:""),u=!l&&a<1&&Rt.current.cropHeight>ht/tt.height;let p=l?i.cropWidth:i.cropWidth*a;u&&(p=i.cropWidth);const m=!l&&n<1&&Rt.current.cropWidth>nt/tt.width;let f=l?i.cropHeight:i.cropHeight*n;m&&(f=i.cropHeight),st&&(p=i.cropWidth,f=i.cropHeight);const w=l?Math.min(a,n):1;i.set(Object.assign({cropX:d,cropY:g,x:o.x(),y:o.y(),width:o.width()*a,height:o.height()*n,rotation:t.target.rotation(),cropWidth:Math.min(p,1-d),cropHeight:Math.min(f,1-g)},1!==w&&Object.assign(Object.assign({},I(i,w)),{borderSize:i.borderSize*w})))},onTransformEnd:t=>{const e=t.currentTarget;i.set(Object.assign(Object.assign({width:e.width(),height:e.height(),x:e.x(),y:e.y(),rotation:t.target.rotation(),cropWidth:nt/tt.width,cropHeight:ht/tt.height},C(i)),{borderSize:E(i.borderSize)})),v(!1)}}),t(s,Object.assign({x:i.x,y:i.y,width:Math.max(i.a.width-i.borderSize,0),height:Math.max(i.a.height-i.borderSize,0),opacity:Xt,offsetX:-i.borderSize/2,offsetY:-i.borderSize/2},Tt,{strokeWidth:i.borderSize,listening:!1,visible:!!i.borderSize,rotation:i.rotation,cornerRadius:Math.max(0,dt-i.borderSize),hideInExport:!i.showInExport})),i._cropModeEnabled&&e(p,{selector:".page-abs-container",enabled:!0,children:[t(s,{x:-window.innerWidth/a.scale,y:-window.innerWidth/a.scale,width:window.innerWidth/a.scale*3,height:window.innerWidth/a.scale*3,fill:w.cropOverlayFill}),t(h,{listening:!1,image:lt,x:i.x,y:i.y,width:i.a.width,height:i.a.height,rotation:i.rotation,shadowEnabled:i.shadowEnabled,shadowBlur:i.shadowBlur}),e(n,{x:i.x,y:i.y,rotation:i.rotation,scaleX:ut,scaleY:ut,children:[t(h,{image:tt,ref:L,opacity:.4,draggable:!0,x:-i.cropX*tt.width,y:-i.cropY*tt.height,onDragMove:yt,onTransform:yt,onTouchMove:t=>{t.evt.preventDefault();const e=t.target.getStage().getPointersPositions();var r=e[0],o=e[1];const i=t.target;if(r&&!o&&!i.isDragging()&&Mt.current&&(i.startDrag(),Mt.current=!1),r&&o){u.hitOnDragEnabled=!0,i.isDragging()&&(Mt.current=!0,i.stopDrag());const e=t.target.getAbsoluteTransform().copy();e.invert();var a={x:r.x,y:r.y},n={x:o.x,y:o.y};if(!wt.current){return void(wt.current=D(a,n))}var h=D(a,n),s=function(t,e){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}(a,n);xt.current||(xt.current=s);const m=i.position();var d={x:h.x-m.x,y:h.y-m.y},c=s/xt.current;i.scaleX(c),i.scaleY(c);const f=e.point(h),w=e.point(wt.current);var g=f.x-w.x,l=f.y-w.y,p={x:Math.min(0,h.x-d.x*c+g),y:Math.min(0,h.y-d.y*c+l)};i.position(p),xt.current=s,wt.current=h,yt(t)}},onTouchEnd:t=>{xt.current=0,wt.current=null,u.hitOnDragEnabled=!1}}),t(c,Object.assign({ref:ft},k,w.outerImageCropTransformerStyle)),t(s,{width:nt,height:ht,ref:pt,listening:!1,onTransform:t=>{if(i.cropX<Math.abs(t.target.x()/tt.width)&&t.target.x()<0&&i.cropX>0){const e=(i.cropWidth+i.cropX)*tt.width;t.target.scaleX(1),t.target.width(e)}if(i.cropY<Math.abs(t.target.y()/tt.height)&&t.target.y()<0&&i.cropY>0){const e=(i.cropHeight+i.cropY)*tt.height;t.target.scaleY(1),t.target.height(e)}t.target.x()<-i.cropX*tt.width-1e-9&&(t.target.x(-i.cropX*tt.width),t.target.scaleX(1)),t.target.y()<-i.cropY*tt.height-1e-9&&(t.target.y(-i.cropY*tt.height),t.target.scaleY(1));const e=Math.min(1,Math.max(0,i.cropX+t.target.x()/tt.width)),r=Math.min(1,Math.max(0,t.target.y()/tt.height+i.cropY)),o=t.target.width()*t.target.scaleX(),a=t.target.height()*t.target.scaleY(),n=Math.min(1-e,o/tt.width),h=Math.min(1-r,a/tt.height),s=t.target.getAbsolutePosition(t.target.getParent().getParent());t.target.scale({x:1,y:1}),t.target.position({x:0,y:0}),i.set({x:s.x,y:s.y,cropX:e,cropY:r,cropWidth:n,cropHeight:h,width:Math.min(o*ut,tt.width*(1-e)*ut),height:Math.min(a*ut,tt.height*(1-r)*ut)})}}),t(c,Object.assign({ref:mt},z,w.innerImageCropTransformerStyle,{visible:i.resizable}))]})]})]})});
@@ -1,4 +1,4 @@
1
- import type { StoreType, PageType } from "../ui-types.js";
1
+ import type { StoreType, PageType } from '../ui-types.js';
2
2
  export declare const PageControls: (({ store, page, xPadding, yPadding, layout, }: {
3
3
  store: StoreType;
4
4
  page: PageType;
@@ -1 +1 @@
1
- var t=this&&this.__rest||function(t,e){var r={};for(var o in t){Object.prototype.hasOwnProperty.call(t,o)&&e.indexOf(o)<0&&(r[o]=t[o])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(t);n<o.length;n++){e.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(t,o[n])&&(r[o[n]]=t[o[n]])}}return r};import{jsx as e,Fragment as r,jsxs as o}from"react/jsx-runtime";import n from"react";import{observer as i}from"mobx-react-lite";import{Group as a,Path as s,Rect as l,Shape as c}from"react-konva";import{nodeAutorun as h}from"../utils/mobx.js";import{isAlive as d}from"mobx-state-tree";import{Html as f}from"react-konva-utils";import{layout as u,drawLayout as g}from"render-tag";import{layoutTextOnPath as m,drawTextOnPathLayout as x}from"render-tag/path";import{scaledFontSizeAttrs as p,roundedFontSizeAttrs as y,roundedTextDecorationAttrs as b,textMinResizeWidth as w}from"../utils/px.js";import{flags as v}from"../utils/flags.js";import{applyFilter as O}from"./apply-filters.js";import{getLineHeight as E,usePrevious as S}from"./text-element.js";import{useFontSpecsLoader as j}from"./text-element/font-specs-loader.js";import{getHtml as M,getCurvePath as z,getCurveTextHeight as k}from"@polotno/core/text-html";import{useColor as R}from"./use-color.js";import{isGradient as Y}from"@polotno/core/gradient";import{detectSize as X}from"@polotno/core/measure-html";import{generateBackgroundShapeFromRects as F}from"@polotno/core/background-shape";import{useFadeIn as T}from"./use-fadein.js";import{incrementLoader as I}from"../utils/loader.js";import{removeTags as P}from"@polotno/core/text";import{isTouchDevice as C}from"../utils/screen.js";import{getLimitedFontSize as B}from"./text-element/max-font-size.js";import{normalizeRichTextHtml as A,extractFontSpecsFromHtml as W,scaleRichTextFontSizesInHtml as D}from"../utils/rich-text-html.js";import{RichEditor as J}from"./rich-editor.js";import{findFitFontSize as N}from"./text-element/fit-font-size.js";import{visiblePlaceholder as $}from"./text-element/placeholder.js";import{wrapHtmlForRenderTag as _}from"@polotno/core/reset-style";import{xmlEscape as L}from"@polotno/core/xml";export{_ as wrapHtmlForRenderTag};export const RenderTagElement=i(({element:i,store:H})=>{var V;const q=n.useRef(null),G=n.useRef(null),[K,Q]=n.useState(!1),U=n.useRef(i.height),Z=i.isSelected,tt=S(Z),{textVerticalResizeEnabled:et}=v,rt=v.autoDeleteEmptyText,ot=S(i.fontFamily),nt=n.useMemo(()=>A(i.text,{fontSize:i.fontSize,fontFamily:i.fontFamily}),[i.text,i.fontSize,i.fontFamily]),it=n.useMemo(()=>W(nt,{fontFamily:i.fontFamily,fontWeight:i.fontWeight,fontStyle:i.fontStyle}),[nt,i.fontFamily,i.fontWeight,i.fontStyle]),[at]=j(H,it,i.text||i.placeholder),st=i._editModeEnabled;T(q);const lt=at?i.fontFamily:ot&&ot!==i.fontFamily?ot:"Arial",ct=R(i).fill,ht=Y(i.fill),dt=Y(i.stroke)&&!!i.strokeWidth,ft=!!i.strokeWidth&&(dt||ht),ut="ellipsis"===v.textOverflow&&!i.curveEnabled&&!!i.height&&!ft,gt=$(i.placeholder),mt=!P(i.text)&&!!gt,xt=mt?L(gt):i.text,pt=mt?.6:i.a.opacity,yt=M(mt?Object.assign(Object.assign({},i.toJSON()),{text:xt}):i,{fontFamily:lt,color:ct,forEditor:!ut,textOverflow:v.textOverflow}),bt=i.width||1,wt=i.curveEnabled,vt=function(t,e,r,o){return n.useMemo(()=>{if(o){return null}try{return u({html:_(t),width:Math.max(1,e),accuracy:"performance"})}catch(r){return console.error("render-tag layout failed:",r),null}},[t,e,r,o])}(yt,bt,at,wt),Ot=function(t,e,r){return n.useMemo(()=>{if(!e.curveEnabled){return null}const r=e.width||1,o=k(e),n=z(r,o,e.curvePower,e.fontSize);try{return m({html:_(t),path:n,align:"center",textBaseline:"middle"})}catch(i){return console.error("render-tag/path layoutTextOnPath failed:",i),null}},[r,e.curveEnabled,e.curvePower,e.fontSize,e.width,e.height,t])}(yt,i,at),Et=E({fontLoaded:at,fontFamily:i.fontFamily,fontSize:i.fontSize,lineHeight:i.lineHeight}),St=wt?0:Math.max(null!==(V=null==vt?void 0:vt.height)&&void 0!==V?V:0,i.fontSize*Et),jt=Ot?Ot.bounds:null,Mt=n.useMemo(()=>vt?vt.lines.map(t=>({left:t.bounds.x,right:t.bounds.x+t.bounds.width,top:t.bounds.y,bottom:t.bounds.y+t.bounds.height})):[],[vt]),zt=n.useRef([]),kt=n.useRef(!0),[,Rt]=n.useReducer(t=>t+1,0);n.useEffect(()=>{const t=zt.current;t.length>0&&(zt.current=[],t.forEach(t=>t()))});const Yt=n.useCallback((t,e,r,o)=>{const n=I(`text ${i.id}`),a=()=>{H.history.ignore(t,e,r).then(()=>{kt.current?(zt.current.push(n),Rt()):n()})};o?queueMicrotask(a):a()},[i.id,H]);n.useEffect(()=>{if(!at){return}if(!vt){return}if(!i.height){return void Yt(()=>{d(i)&&(i.height||i.set({height:St}))},void 0,void 0,!0)}if(H.isPlaying){return}const{textOverflow:t}=v,e=i.height!==St&&(!et||i.height<St),r=()=>Yt(()=>{d(i)&&i.set({height:St})},!1,!0);if("change-font-size"!==t||K||st||i.curveEnabled){"resize"===t&&e&&!K&&r()}else{const t=N(mt?Object.assign(Object.assign({},i.toJSON()),{text:xt,toJSON:()=>Object.assign(Object.assign({},i.toJSON()),{text:xt})}):i,{fontFamily:lt,color:ct,forEditor:!0},t=>{try{return u({html:_(t),width:bt,accuracy:"performance"}).height}catch(V){return X(t).height}});t.fontSize!==i.fontSize?Yt(()=>{if(!d(i)){return}const e=p(i,t.fontSize);void 0!==t.text&&t.text!==i.text&&(e.text=t.text),i.set(e)},!1,!0):e&&r()}}),n.useEffect(()=>()=>{kt.current=!1;const t=zt.current;t.length>0&&(zt.current=[],t.forEach(t=>t()))},[]),n.useLayoutEffect(()=>{if(!at||!i.curveEnabled||K){return}if(!jt||!jt.width){return}const t=t=>t&&et?Math.max(t,jt.height):jt.height;Math.abs(jt.width-i.width)<1&&Math.abs(t(i.height)-i.height)<1||Yt(()=>{if(!d(i)){return}const e=jt.width-i.width,r=t(i.height),o=r-i.height;if(Math.abs(e)<1&&Math.abs(o)<1){return}const n=i.a.rotation*Math.PI/180,a=-e/2*Math.cos(n),s=-e/2*Math.sin(n);i.set({width:jt.width,height:r,x:i.a.x+a,y:i.a.y+s})},!1,!0,!0)},[at,i.curveEnabled,jt,K,et,Yt]),n.useEffect(()=>{tt&&!Z&&rt&&""===P(i.text)&&i.removable&&!$(i.placeholder)&&H.deleteElements([i.id])},[rt,i.placeholder,i.removable,i.text,Z,tt]),n.useEffect(()=>h(i,()=>{const t=q.current;t&&O(t,i)}),[vt,Ot,i.a.width,i.a.height,i.shadowColor,i.shadowOffsetX,i.shadowOffsetY,i.shadowOpacity]);let Xt=0;wt||"middle"!==i.verticalAlign?wt||"bottom"!==i.verticalAlign||(Xt=i.height-St):Xt=(i.height-St)/2;const Ft=i.backgroundPadding*(i.fontSize*Et*.5),Tt=i.backgroundCornerRadius*(i.fontSize*Et*.5),It=n.useMemo(()=>!i.backgroundEnabled||i.curveEnabled||i.legacyBackground||0===Mt.length?"":F({rects:Mt,padding:Ft,cornerRadius:Tt}),[i.backgroundEnabled,i.curveEnabled,i.legacyBackground,Mt,Ft,Tt]),Pt=C(),Ct=n.useRef(null),Bt=n.useRef(i.width),At=n.useRef(null),Wt=n.useRef(null),Dt=n.useRef(null),Jt=n.useRef(0),Nt=n.useRef(0),$t=i.width>0?i.a.width/i.width:1;return o(r,{children:[i.curveEnabled||i.legacyBackground?e(l,{x:i.a.x,y:i.a.y,offsetX:Ft/$t,offsetY:Ft/$t,rotation:i.a.rotation,scaleX:$t,scaleY:$t,hideInExport:!i.showInExport,listening:!1,visible:i.backgroundEnabled,opacity:i.backgroundOpacity*pt,fill:i.backgroundColor,width:i.width+2*Ft,height:i.height+2*Ft,cornerRadius:Tt}):e(s,{name:"rendertag-background",x:i.a.x,y:i.a.y,offsetY:-Xt/$t,rotation:i.a.rotation,scaleX:$t,scaleY:$t,hideInExport:!i.showInExport,listening:!1,visible:i.backgroundEnabled&&It.length>0,opacity:i.backgroundOpacity*pt,fill:i.backgroundColor,data:It}),e(c,{ref:q,name:"rendertag-text",x:i.a.x,y:i.a.y,rotation:i.a.rotation,scaleX:$t,scaleY:$t,offsetY:$t>0?-Xt/$t:0,width:i.width,height:Math.max(i.height,St),listening:!1,visible:!st&&!!(wt?Ot:vt),opacity:pt,shadowEnabled:i.shadowEnabled,shadowBlur:i.shadowBlur,shadowOffsetX:i.shadowOffsetX,shadowOffsetY:i.shadowOffsetY,shadowColor:i.shadowColor,shadowOpacity:i.shadowOpacity,hideInExport:!i.showInExport,sceneFunc:(t,e)=>{const r=t._context;if(r){try{if(wt){if(!Ot||!jt){return}const t=(i.width-jt.width)/2-jt.x;r.save(),r.translate(t,-jt.y),x({layout:Ot,ctx:r}),r.restore()}else{if(!vt){return}g({layout:vt,width:bt,ctx:r,pixelRatio:1})}}catch(o){console.error("render-tag draw failed:",o)}}}}),e(l,{ref:G,name:"element",x:i.a.x,y:i.a.y,listening:i.selectable,rotation:i.a.rotation,width:i.a.width,height:i.a.height,visible:!st,draggable:Pt?i.draggable&&Z:i.draggable,preventDefault:!Pt||Z,opacity:0,hideInExport:!0,id:i.id,onDragMove:t=>{i.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{i.set({x:t.target.x(),y:t.target.y()})},onDblClick:t=>{i.contentEditable&&(Wt.current={x:t.evt.clientX,y:t.evt.clientY},i.toggleEditMode(!0))},onDblTap:t=>{var e;if(i.contentEditable){const r=null===(e=t.evt.changedTouches)||void 0===e?void 0:e[0];Wt.current=r?{x:r.clientX,y:r.clientY}:null,i.toggleEditMode(!0)}},onTransformStart:t=>{var e,r;Q(!0),U.current=i.height,Bt.current=i.width,At.current=null,Ct.current=t.target.position();const o=null===(e=t.target.getStage())||void 0===e?void 0:e.findOne("Transformer");Dt.current=null!==(r=null==o?void 0:o.getActiveAnchor())&&void 0!==r?r:null,Jt.current=i.a.rotation,Nt.current=i.height},onTransform:e=>{var r;const o=e.target,n=(null===(r=o.getStage())||void 0===r?void 0:r.findOne("Transformer")).getActiveAnchor(),a="middle-left"===n||"middle-right"===n,s="top-center"===n||"bottom-center"===n,l=o.scaleX();if(a){const e=o.scaleX(),n=o.width()*e;let a=Math.max(n,w(Bt.current,i.fontSize));const s=i.toJSON();let l=0;if(i.curveEnabled){l=k(Object.assign(Object.assign({},s),{width:a}))}else{const{x:e,y:o,width:n,height:i}=s,c=t(s,["x","y","width","height"]),h=`${JSON.stringify(c)}|${lt}|${at}|${ct}`;if(At.current&&At.current.signature===h&&a<=At.current.width){a=At.current.width,l=At.current.height}else{const t=t=>{const e=M(Object.assign(Object.assign({},s),{text:xt,width:t}),{fontFamily:lt,color:ct,forEditor:!0});try{return u({html:_(e),width:t,accuracy:"performance"})}catch(r){return{height:X(e).height,lines:[]}}};let e=t(a);const o=Math.max(0,...e.lines.map(t=>t.bounds.x+t.bounds.width));o>a+.5&&o<=Bt.current+.5&&(a=Math.min(Math.ceil(o),Bt.current),e=t(a),At.current={signature:h,width:a,height:e.height}),l=e.height}}a>n&&Ct.current&&o.position(Ct.current),o.width(a),o.scaleX(1),o.scaleY(1);let c=v.textVerticalResizeEnabled?Math.max(l,U.current):l;"ellipsis"===v.textOverflow&&(c=U.current),o.height(c),i.set({width:o.width(),height:c,x:o.x(),y:o.y()})}else if(s){const t="resize"===v.textOverflow?wt?(null==jt?void 0:jt.height)||i.fontSize:St:Et*i.fontSize,e=o.height()*o.scaleY();if(e<t){if(o.height(t),Ct.current){if("top-center"===Dt.current){const e=Jt.current*Math.PI/180,r=Nt.current-t;o.x(Ct.current.x-r*Math.sin(e)),o.y(Ct.current.y+r*Math.cos(e))}else{o.position(Ct.current)}}}else{o.height(e)}o.scaleY(1),o.scaleX(1),Nt.current=Math.max(t,e),i.set({x:o.x(),y:o.y(),height:o.height(),rotation:o.rotation()})}else{o.scaleX(1),o.scaleY(1),i.set({fontSize:i.fontSize*l,letterSpacing:i.letterSpacing,width:o.width()*l,x:o.x(),y:o.y(),rotation:o.rotation(),height:o.height()*l,shadowBlur:i.shadowBlur*l,shadowOffsetX:i.shadowOffsetX*l,shadowOffsetY:i.shadowOffsetY*l,strokeWidth:i.strokeWidth*l,text:D(i.text,l)})}Ct.current=e.target.position()},onTransformEnd:t=>{Q(!1);const e=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),i.set(Object.assign(Object.assign({},y(i,i.fontSize*e)),{width:t.target.width()*e,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),text:D(i.text,e)}))}}),st&&e(a,{x:i.a.x,y:i.a.y,rotation:i.a.rotation,offsetY:-Xt,children:e(f,{divProps:{style:{zIndex:20}},children:e(J,{element:i,onChange:t=>{const e=B({oldText:P(i.text),newText:P(t),element:i});i.set(Object.assign({text:t},p(i,e)))},onBlur:()=>{d(i)&&(i.set(b(i)),i.toggleEditMode(!1))},clickCoords:Wt.current})})})]})});
1
+ var t=this&&this.__rest||function(t,e){var r={};for(var o in t){Object.prototype.hasOwnProperty.call(t,o)&&e.indexOf(o)<0&&(r[o]=t[o])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(t);n<o.length;n++){e.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(t,o[n])&&(r[o[n]]=t[o[n]])}}return r};import{jsx as e,Fragment as r,jsxs as o}from"react/jsx-runtime";import n from"react";import{observer as i}from"mobx-react-lite";import{Group as a,Path as s,Rect as l,Shape as c}from"react-konva";import{nodeAutorun as h}from"../utils/mobx.js";import{isAlive as d}from"mobx-state-tree";import{Html as f}from"react-konva-utils";import{layout as u,drawLayout as g}from"render-tag";import{layoutTextOnPath as m,drawTextOnPathLayout as x}from"render-tag/path";import{scaledFontSizeAttrs as p,roundedFontSizeAttrs as y,roundedTextDecorationAttrs as b,textMinResizeWidth as w}from"../utils/px.js";import{flags as v}from"../utils/flags.js";import{applyFilter as O}from"./apply-filters.js";import{getLineHeight as E,usePrevious as S}from"./text-element.js";import{useFontSpecsLoader as j}from"./text-element/font-specs-loader.js";import{getHtml as M,getCurvePath as z,getCurveTextHeight as k}from"@polotno/core/text-html";import{useColor as R}from"./use-color.js";import{isGradient as Y}from"@polotno/core/gradient";import{detectSize as X}from"@polotno/core/measure-html";import{generateBackgroundShapeFromRects as F}from"@polotno/core/background-shape";import{useFadeIn as T}from"./use-fadein.js";import{incrementLoader as I}from"../utils/loader.js";import{removeTags as P}from"@polotno/core/text";import{isTouchDevice as C}from"../utils/screen.js";import{getLimitedFontSize as B}from"./text-element/max-font-size.js";import{normalizeRichTextHtml as A,extractFontSpecsFromHtml as W,scaleRichTextFontSizesInHtml as D}from"../utils/rich-text-html.js";import{RichEditor as J}from"./rich-editor.js";import{findFitFontSize as N}from"./text-element/fit-font-size.js";import{visiblePlaceholder as $}from"./text-element/placeholder.js";import{wrapHtmlForRenderTag as _}from"@polotno/core/reset-style";import{xmlEscape as L}from"@polotno/core/xml";import{hasMeasuredHeight as H,resolveTextBoxHeight as V}from"@polotno/core/text-types";export{_ as wrapHtmlForRenderTag};export const RenderTagElement=i(({element:i,store:q})=>{var G;const K=n.useRef(null),Q=n.useRef(null),[U,Z]=n.useState(!1),tt=n.useRef(i.height),et=i.isSelected,rt=S(et),{textVerticalResizeEnabled:ot}=v,nt=v.autoDeleteEmptyText,it=S(i.fontFamily),at=n.useMemo(()=>A(i.text,{fontSize:i.fontSize,fontFamily:i.fontFamily}),[i.text,i.fontSize,i.fontFamily]),st=n.useMemo(()=>W(at,{fontFamily:i.fontFamily,fontWeight:i.fontWeight,fontStyle:i.fontStyle}),[at,i.fontFamily,i.fontWeight,i.fontStyle]),[lt]=j(q,st,i.text||i.placeholder),ct=i._editModeEnabled;T(K);const ht=lt?i.fontFamily:it&&it!==i.fontFamily?it:"Arial",dt=R(i).fill,ft=Y(i.fill),ut=Y(i.stroke)&&!!i.strokeWidth,gt=!!i.strokeWidth&&(ut||ft),mt="ellipsis"===v.textOverflow&&!i.curveEnabled&&H(i)&&!gt,xt=$(i.placeholder),pt=!P(i.text)&&!!xt,yt=pt?L(xt):i.text,bt=pt?.6:i.a.opacity,wt=M(pt?Object.assign(Object.assign({},i.toJSON()),{text:yt}):i,{fontFamily:ht,color:dt,forEditor:!mt,textOverflow:v.textOverflow}),vt=i.width||1,Ot=i.curveEnabled,Et=function(t,e,r,o){return n.useMemo(()=>{if(o){return null}try{return u({html:_(t),width:Math.max(1,e),accuracy:"performance"})}catch(r){return console.error("render-tag layout failed:",r),null}},[t,e,r,o])}(wt,vt,lt,Ot),St=function(t,e,r){return n.useMemo(()=>{if(!e.curveEnabled){return null}const r=e.width||1,o=k(e),n=z(r,o,e.curvePower,e.fontSize);try{return m({html:_(t),path:n,align:"center",textBaseline:"middle"})}catch(i){return console.error("render-tag/path layoutTextOnPath failed:",i),null}},[r,e.curveEnabled,e.curvePower,e.fontSize,e.width,e.height,t])}(wt,i,lt),jt=E({fontLoaded:lt,fontFamily:i.fontFamily,fontSize:i.fontSize,lineHeight:i.lineHeight}),Mt=Ot?0:Math.max(null!==(G=null==Et?void 0:Et.height)&&void 0!==G?G:0,i.fontSize*jt),zt=St?St.bounds:null,kt=n.useMemo(()=>Et?Et.lines.map(t=>({left:t.bounds.x,right:t.bounds.x+t.bounds.width,top:t.bounds.y,bottom:t.bounds.y+t.bounds.height})):[],[Et]),Rt=n.useRef([]),Yt=n.useRef(!0),[,Xt]=n.useReducer(t=>t+1,0);n.useEffect(()=>{const t=Rt.current;t.length>0&&(Rt.current=[],t.forEach(t=>t()))});const Ft=n.useCallback((t,e,r,o)=>{const n=I(`text ${i.id}`),a=()=>{q.history.ignore(t,e,r).then(()=>{Yt.current?(Rt.current.push(n),Xt()):n()})};o?queueMicrotask(a):a()},[i.id,q]);n.useEffect(()=>{if(!lt){return}if(!Et){return}if(!H(i)){return void Ft(()=>{d(i)&&(H(i)||i.set({height:Mt}))},void 0,void 0,!0)}if(q.isPlaying){return}const{textOverflow:t}=v,e=i.height!==Mt&&(!ot||i.height<Mt),r=()=>Ft(()=>{d(i)&&i.set({height:Mt})},!1,!0);if("change-font-size"!==t||U||ct||i.curveEnabled){"resize"===t&&e&&!U&&r()}else{const t=N(pt?Object.assign(Object.assign({},i.toJSON()),{text:yt,toJSON:()=>Object.assign(Object.assign({},i.toJSON()),{text:yt})}):i,{fontFamily:ht,color:dt,forEditor:!0},t=>{try{return u({html:_(t),width:vt,accuracy:"performance"}).height}catch(G){return X(t).height}});t.fontSize!==i.fontSize?Ft(()=>{if(!d(i)){return}const e=p(i,t.fontSize);void 0!==t.text&&t.text!==i.text&&(e.text=t.text),i.set(e)},!1,!0):e&&r()}}),n.useEffect(()=>()=>{Yt.current=!1;const t=Rt.current;t.length>0&&(Rt.current=[],t.forEach(t=>t()))},[]),n.useLayoutEffect(()=>{if(!lt||!i.curveEnabled||U){return}if(!zt||!zt.width){return}const t=t=>t&&ot?Math.max(t,zt.height):zt.height;Math.abs(zt.width-i.width)<1&&Math.abs(t(i.height)-i.height)<1||Ft(()=>{if(!d(i)){return}const e=zt.width-i.width,r=t(i.height),o=r-i.height;if(Math.abs(e)<1&&Math.abs(o)<1){return}const n=i.a.rotation*Math.PI/180,a=-e/2*Math.cos(n),s=-e/2*Math.sin(n);i.set({width:zt.width,height:r,x:i.a.x+a,y:i.a.y+s})},!1,!0,!0)},[lt,i.curveEnabled,zt,U,ot,Ft]),n.useEffect(()=>{rt&&!et&&nt&&""===P(i.text)&&i.removable&&!$(i.placeholder)&&q.deleteElements([i.id])},[nt,i.placeholder,i.removable,i.text,et,rt]),n.useEffect(()=>h(i,()=>{const t=K.current;t&&O(t,i)}),[Et,St,i.a.width,i.a.height,i.shadowColor,i.shadowOffsetX,i.shadowOffsetY,i.shadowOpacity]);const Tt=V(i,Mt);let It=0;Ot||"middle"!==i.verticalAlign?Ot||"bottom"!==i.verticalAlign||(It=Tt-Mt):It=(Tt-Mt)/2;const Pt=i.backgroundPadding*(i.fontSize*jt*.5),Ct=i.backgroundCornerRadius*(i.fontSize*jt*.5),Bt=n.useMemo(()=>!i.backgroundEnabled||i.curveEnabled||i.legacyBackground||0===kt.length?"":F({rects:kt,padding:Pt,cornerRadius:Ct}),[i.backgroundEnabled,i.curveEnabled,i.legacyBackground,kt,Pt,Ct]),At=C(),Wt=n.useRef(null),Dt=n.useRef(i.width),Jt=n.useRef(null),Nt=n.useRef(null),$t=n.useRef(null),_t=n.useRef(0),Lt=n.useRef(0),Ht=i.width>0?i.a.width/i.width:1;return o(r,{children:[i.curveEnabled||i.legacyBackground?e(l,{x:i.a.x,y:i.a.y,offsetX:Pt/Ht,offsetY:Pt/Ht,rotation:i.a.rotation,scaleX:Ht,scaleY:Ht,hideInExport:!i.showInExport,listening:!1,visible:i.backgroundEnabled,opacity:i.backgroundOpacity*bt,fill:i.backgroundColor,width:i.width+2*Pt,height:Tt+2*Pt,cornerRadius:Ct}):e(s,{name:"rendertag-background",x:i.a.x,y:i.a.y,offsetY:-It/Ht,rotation:i.a.rotation,scaleX:Ht,scaleY:Ht,hideInExport:!i.showInExport,listening:!1,visible:i.backgroundEnabled&&Bt.length>0,opacity:i.backgroundOpacity*bt,fill:i.backgroundColor,data:Bt}),e(c,{ref:K,name:"rendertag-text",x:i.a.x,y:i.a.y,rotation:i.a.rotation,scaleX:Ht,scaleY:Ht,offsetY:Ht>0?-It/Ht:0,width:i.width,height:Math.max(i.height,Mt),listening:!1,visible:!ct&&!!(Ot?St:Et),opacity:bt,shadowEnabled:i.shadowEnabled,shadowBlur:i.shadowBlur,shadowOffsetX:i.shadowOffsetX,shadowOffsetY:i.shadowOffsetY,shadowColor:i.shadowColor,shadowOpacity:i.shadowOpacity,hideInExport:!i.showInExport,sceneFunc:(t,e)=>{const r=t._context;if(r){try{if(Ot){if(!St||!zt){return}const t=(i.width-zt.width)/2-zt.x;r.save(),r.translate(t,-zt.y),x({layout:St,ctx:r}),r.restore()}else{if(!Et){return}g({layout:Et,width:vt,ctx:r,pixelRatio:1})}}catch(o){console.error("render-tag draw failed:",o)}}}}),e(l,{ref:Q,name:"element",x:i.a.x,y:i.a.y,listening:i.selectable,rotation:i.a.rotation,width:i.a.width,height:i.a.height,visible:!ct,draggable:At?i.draggable&&et:i.draggable,preventDefault:!At||et,opacity:0,hideInExport:!0,id:i.id,onDragMove:t=>{i.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{i.set({x:t.target.x(),y:t.target.y()})},onDblClick:t=>{i.contentEditable&&(Nt.current={x:t.evt.clientX,y:t.evt.clientY},i.toggleEditMode(!0))},onDblTap:t=>{var e;if(i.contentEditable){const r=null===(e=t.evt.changedTouches)||void 0===e?void 0:e[0];Nt.current=r?{x:r.clientX,y:r.clientY}:null,i.toggleEditMode(!0)}},onTransformStart:t=>{var e,r;Z(!0),tt.current=i.height,Dt.current=i.width,Jt.current=null,Wt.current=t.target.position();const o=null===(e=t.target.getStage())||void 0===e?void 0:e.findOne("Transformer");$t.current=null!==(r=null==o?void 0:o.getActiveAnchor())&&void 0!==r?r:null,_t.current=i.a.rotation,Lt.current=i.height},onTransform:e=>{var r;const o=e.target,n=(null===(r=o.getStage())||void 0===r?void 0:r.findOne("Transformer")).getActiveAnchor(),a="middle-left"===n||"middle-right"===n,s="top-center"===n||"bottom-center"===n,l=o.scaleX();if(a){const e=o.scaleX(),n=o.width()*e;let a=Math.max(n,w(Dt.current,i.fontSize));const s=i.toJSON();let l=0;if(i.curveEnabled){l=k(Object.assign(Object.assign({},s),{width:a}))}else{const{x:e,y:o,width:n,height:i}=s,c=t(s,["x","y","width","height"]),h=`${JSON.stringify(c)}|${ht}|${lt}|${dt}`;if(Jt.current&&Jt.current.signature===h&&a<=Jt.current.width){a=Jt.current.width,l=Jt.current.height}else{const t=t=>{const e=M(Object.assign(Object.assign({},s),{text:yt,width:t}),{fontFamily:ht,color:dt,forEditor:!0});try{return u({html:_(e),width:t,accuracy:"performance"})}catch(r){return{height:X(e).height,lines:[]}}};let e=t(a);const o=Math.max(0,...e.lines.map(t=>t.bounds.x+t.bounds.width));o>a+.5&&o<=Dt.current+.5&&(a=Math.min(Math.ceil(o),Dt.current),e=t(a),Jt.current={signature:h,width:a,height:e.height}),l=e.height}}a>n&&Wt.current&&o.position(Wt.current),o.width(a),o.scaleX(1),o.scaleY(1);let c=v.textVerticalResizeEnabled?Math.max(l,tt.current):l;"ellipsis"===v.textOverflow&&(c=tt.current),o.height(c),i.set({width:o.width(),height:c,x:o.x(),y:o.y()})}else if(s){const t="resize"===v.textOverflow?Ot?(null==zt?void 0:zt.height)||i.fontSize:Mt:jt*i.fontSize,e=o.height()*o.scaleY();if(e<t){if(o.height(t),Wt.current){if("top-center"===$t.current){const e=_t.current*Math.PI/180,r=Lt.current-t;o.x(Wt.current.x-r*Math.sin(e)),o.y(Wt.current.y+r*Math.cos(e))}else{o.position(Wt.current)}}}else{o.height(e)}o.scaleY(1),o.scaleX(1),Lt.current=Math.max(t,e),i.set({x:o.x(),y:o.y(),height:o.height(),rotation:o.rotation()})}else{o.scaleX(1),o.scaleY(1),i.set({fontSize:i.fontSize*l,letterSpacing:i.letterSpacing,width:o.width()*l,x:o.x(),y:o.y(),rotation:o.rotation(),height:o.height()*l,shadowBlur:i.shadowBlur*l,shadowOffsetX:i.shadowOffsetX*l,shadowOffsetY:i.shadowOffsetY*l,strokeWidth:i.strokeWidth*l,text:D(i.text,l)})}Wt.current=e.target.position()},onTransformEnd:t=>{Z(!1);const e=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),i.set(Object.assign(Object.assign({},y(i,i.fontSize*e)),{width:t.target.width()*e,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),text:D(i.text,e)}))}}),ct&&e(a,{x:i.a.x,y:i.a.y,rotation:i.a.rotation,offsetY:-It,children:e(f,{divProps:{style:{zIndex:20}},children:e(J,{element:i,onChange:t=>{const e=B({oldText:P(i.text),newText:P(t),element:i});i.set(Object.assign({text:t},p(i,e)))},onBlur:()=>{d(i)&&(i.set(b(i)),i.toggleEditMode(!1))},clickCoords:Nt.current})})})]})});
@@ -1,4 +1,4 @@
1
- var t=this&&this.__rest||function(t,e){var o={};for(var n in t){Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(o[n]=t[n])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(t);r<n.length;r++){e.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(t,n[r])&&(o[n[r]]=t[n[r]])}}return o};import{jsx as e}from"react/jsx-runtime";import o from"react";import n from"quill";import*as r from"mobx";import{nodeReaction as i}from"../utils/mobx.js";import{isAlive as l}from"mobx-state-tree";import{getQuillEditorHtml as a,getDir as s}from"@polotno/core/text-html";import{quillHtmlToModelText as d,isQuillFormatMixed as c,isBoldWeight as u}from"../utils/rich-text-html.js";import{resetStyleContent as f,wrapHtmlForRenderTag as p}from"@polotno/core/reset-style";import{layout as h}from"render-tag";import{removeTags as m}from"@polotno/core/text";import{isGradient as g,firstStopColor as b}from"@polotno/core/gradient";import{getOptimalCaretColor as x}from"./text-element/caret-color.js";import{visiblePlaceholder as v}from"./text-element/placeholder.js";import{registerQuillUnrestrictedFontFormats as y}from"./quill-font-formats.js";import{ALL_QUILL_MIXED_KEYS as w,setActiveTextEditor as S,updateActiveTextFormat as k,clearActiveTextEditor as q}from"../utils/text-format-state.js";import T from"../utils/styled.js";import{applyOpacityToColor as E}from"@polotno/core/svg";export{E as applyOpacityToColor};export const quillRef=r.observable({enabled:!1,currentFormat:{},lastSelection:null,pendingToolbarInteraction:!1,editor:r.observable.object({instance:null},{},{deep:!1})});const C=w;export function syncQuillFormatState(t,e){const o=e?t.getFormat(e):{},n=function(t,e){const o={};if(!e||e.length<=0){return o}const n=t.getContents(e.index,e.length);for(const r of C){c(n,r)&&(o[r]=!0)}return o}(t,e);r.runInAction(()=>{quillRef.currentFormat=o}),k(o,n,e)}const F="polotno-saved-selection";function R(){const t=window.getSelection();if(!t||0===t.rangeCount||t.isCollapsed){return}if("undefined"==typeof Highlight||!CSS.highlights){return}const e=t.getRangeAt(0).cloneRange();CSS.highlights.set(F,new Highlight(e)),$()}function L(){"undefined"!=typeof CSS&&CSS.highlights&&CSS.highlights.delete(F)}function $(){setTimeout(()=>{"undefined"!=typeof CSS&&CSS.highlights&&CSS.highlights.has(F)&&(document.querySelector(".polotno-portal")||A(document.activeElement)?$():L())},300)}if("undefined"!=typeof document&&"undefined"!=typeof CSS&&CSS.highlights&&!document.querySelector("[data-polotno-highlight]")){const I=document.createElement("style");I.setAttribute("data-polotno-highlight",""),I.textContent=`::highlight(${F}) { background-color: Highlight; }`,document.head.appendChild(I)}let O=null;function M(t,e){"text"===t.type&&e.push(t);for(const o of t.children||[]){M(o,e)}}export function computeMarkerVars(t){var e,o,n;const r=t.fontSize;if(!r||r<=0){return null}const i=/\s/.test(t.fontFamily)?`'${t.fontFamily}'`:t.fontFamily,l=u(t.fontWeight)?700:400,a="italic"===t.fontStyle?"italic":"normal",s=null!=O?O:O=document.createElement("canvas").getContext("2d");s.fontKerning="normal",s.font=`${r}px ${i}`;const d=s.measureText("M"),c=(null!==(e=d.fontBoundingBoxAscent)&&void 0!==e?e:0)/r,f=(null!==(o=d.fontBoundingBoxDescent)&&void 0!==o?o:0)/r,m=`font-family:${i};font-size:${r}px;font-weight:${l};font-style:${a};line-height:${t.lineHeight};letter-spacing:${t.letterSpacing}em`,g=p(`<div style="${m}"><ul><li>x</li></ul><ol><li>x</li></ol></div>`);let b;try{b=h({html:g,width:Math.max(12*r,600)})}catch(q){return null}const x=[];M(b.layoutRoot,x);const v=x.find(t=>"•"===t.text),y=x.find(t=>/^\d/.test(t.text));if(!v){return null}const w=v.style.fontSize,S=w*(1+c-f)/2,k=2.1*r;return{bulletLeft:v.x,bulletTop:v.y-S,bulletFontSize:w,numberGap:y?Math.max(0,k-y.x-(null!==(n=y.width)&&void 0!==n?n:0)):0}}export const RichTextContainer=T("div",o.forwardRef)`
1
+ var t=this&&this.__rest||function(t,e){var o={};for(var n in t){Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(o[n]=t[n])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(t);r<n.length;r++){e.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(t,n[r])&&(o[n[r]]=t[n[r]])}}return o};import{jsx as e}from"react/jsx-runtime";import o from"react";import n from"quill";import*as r from"mobx";import{nodeReaction as i}from"../utils/mobx.js";import{isAlive as l}from"mobx-state-tree";import{getQuillEditorHtml as a,getDir as s}from"@polotno/core/text-html";import{quillHtmlToModelText as d,isQuillFormatMixed as c,isBoldWeight as u}from"../utils/rich-text-html.js";import{resetStyleContent as f,wrapHtmlForRenderTag as p}from"@polotno/core/reset-style";import{layout as m}from"render-tag";import{removeTags as h}from"@polotno/core/text";import{isGradient as g,firstStopColor as b}from"@polotno/core/gradient";import{getOptimalCaretColor as v}from"./text-element/caret-color.js";import{visiblePlaceholder as x}from"./text-element/placeholder.js";import{registerQuillUnrestrictedFontFormats as y}from"./quill-font-formats.js";import{ALL_QUILL_MIXED_KEYS as w,setActiveTextEditor as S,updateActiveTextFormat as k,clearActiveTextEditor as q}from"../utils/text-format-state.js";import T from"../utils/styled.js";import{applyOpacityToColor as E}from"@polotno/core/svg";export{E as applyOpacityToColor};export const quillRef=r.observable({enabled:!1,currentFormat:{},lastSelection:null,pendingToolbarInteraction:!1,editor:r.observable.object({instance:null},{},{deep:!1})});const C=w;export function syncQuillFormatState(t,e){const o=e?t.getFormat(e):{},n=function(t,e){const o={};if(!e||e.length<=0){return o}const n=t.getContents(e.index,e.length);for(const r of C){c(n,r)&&(o[r]=!0)}return o}(t,e);r.runInAction(()=>{quillRef.currentFormat=o}),k(o,n,e)}const F="polotno-saved-selection";function R(){const t=window.getSelection();if(!t||0===t.rangeCount||t.isCollapsed){return}if("undefined"==typeof Highlight||!CSS.highlights){return}const e=t.getRangeAt(0).cloneRange();CSS.highlights.set(F,new Highlight(e)),$()}function L(){"undefined"!=typeof CSS&&CSS.highlights&&CSS.highlights.delete(F)}function $(){setTimeout(()=>{"undefined"!=typeof CSS&&CSS.highlights&&CSS.highlights.has(F)&&(document.querySelector(".polotno-portal")||A(document.activeElement)?$():L())},300)}if("undefined"!=typeof document&&"undefined"!=typeof CSS&&CSS.highlights&&!document.querySelector("[data-polotno-highlight]")){const I=document.createElement("style");I.setAttribute("data-polotno-highlight",""),I.textContent=`::highlight(${F}) { background-color: Highlight; }`,document.head.appendChild(I)}let O=null;function M(t,e){"text"===t.type&&e.push(t);for(const o of t.children||[]){M(o,e)}}export function computeMarkerVars(t){var e,o,n;const r=t.fontSize;if(!r||r<=0){return null}const i=/\s/.test(t.fontFamily)?`'${t.fontFamily}'`:t.fontFamily,l=u(t.fontWeight)?700:400,a="italic"===t.fontStyle?"italic":"normal",s=null!=O?O:O=document.createElement("canvas").getContext("2d");s.fontKerning="normal",s.font=`${r}px ${i}`;const d=s.measureText("M"),c=(null!==(e=d.fontBoundingBoxAscent)&&void 0!==e?e:0)/r,f=(null!==(o=d.fontBoundingBoxDescent)&&void 0!==o?o:0)/r,h=`font-family:${i};font-size:${r}px;font-weight:${l};font-style:${a};line-height:${t.lineHeight};letter-spacing:${t.letterSpacing}em`,g=p(`<div style="${h}"><ul><li>x</li></ul><ol><li>x</li></ol></div>`);let b;try{b=m({html:g,width:Math.max(12*r,600)})}catch(q){return null}const v=[];M(b.layoutRoot,v);const x=v.find(t=>"•"===t.text),y=v.find(t=>/^\d/.test(t.text));if(!x){return null}const w=x.style.fontSize,S=w*(1+c-f)/2,k=2.1*r;return{bulletLeft:x.x,bulletTop:x.y-S,bulletFontSize:w,numberGap:y?Math.max(0,k-y.x-(null!==(n=y.width)&&void 0!==n?n:0)):0}}export const RichTextContainer=T("div",o.forwardRef)`
2
2
  .ql-editor {
3
3
  outline: none;
4
4
  /* anchor for the absolutely-positioned ::before placeholder below */
@@ -152,4 +152,4 @@ var t=this&&this.__rest||function(t,e){var o={};for(var n in t){Object.prototype
152
152
  &[style*='--polotno-gradient'] .ql-editor [style*='color:'] {
153
153
  -webkit-text-fill-color: currentColor;
154
154
  }
155
- `;let j=["background","font-weight","color","gradient","font","italic","size","script","strike","underline","indent","list","direction"];export const setQuillFormats=t=>{j=t};let N=!1;function z(){N||(N=!0,console.warn("[polotno] The Quill 'bold' format is deprecated. Use the numeric 'font-weight' format instead, e.g. quill.format('font-weight', '700') or applyTextFormat({ fontWeight: 700 })."))}function P(t){return t?"700":"400"}export const createQuill=(e,o)=>{y();const r=new n(e,{toolbar:!1,keyboard:!1,placeholder:(null==o?void 0:o.placeholder)||void 0,clipboard:{matchVisual:!1},formats:j});!function(e){const o=e.format.bind(e),n=e.formatText.bind(e),r=e.getFormat.bind(e);e.format=(t,e,n)=>"bold"===t?(z(),o("font-weight",P(e),n)):o(t,e,n),e.formatText=(e,o,r,i,l)=>{if(r&&"object"==typeof r){if("bold"in r){z();const{bold:l}=r,a=t(r,["bold"]);return n(e,o,Object.assign(Object.assign({},a),{"font-weight":P(l)}),i)}return n(e,o,r,i)}return"bold"===r?(z(),n(e,o,"font-weight",P(i),l)):n(e,o,r,i,l)},e.getFormat=(...t)=>{const e=r(...t);return e&&null!=e["font-weight"]&&!("bold"in e)&&(e.bold=u(e["font-weight"])),e}}(r);const i=n.import("delta"),l=(t,e)=>e.compose((new i).retain(e.length(),{"font-weight":"700"}));return r.clipboard.addMatcher("STRONG",l),r.clipboard.addMatcher("B",l),r};export const setQuillContent=(t,e)=>{var o=t.clipboard.convert({html:"<div class='ql-editor' style='outline: none;'>"+e.replace(/\t/g,"")+"<p><br></p></div>",text:""});o.ops.forEach(t=>{"string"==typeof t.insert&&t.insert.includes("")&&(t.insert=t.insert.split("").join("\t"))}),t.setContents(o),t.history.clear()};export const RichEditor=({onBlur:t,onChange:n,element:c,clickCoords:u})=>{var f;const p=o.useRef(null),h=o.useRef(!1);o.useLayoutEffect(()=>{let e,o=!1,i=null,s=null,f=null,m=null,g=null;const b=()=>{if(!o&&p.current){try{e=createQuill(p.current,{placeholder:v(c.placeholder)}),r.runInAction(()=>{quillRef.editor.instance=e}),quillRef.pendingToolbarInteraction=!1,window.__polotnoQuill=e,S({instance:e,store:c.store,element:c}),e.on("text-change",()=>{const t=e.getSelection();t&&(syncQuillFormatState(e,t),r.runInAction(()=>{quillRef.lastSelection={index:t.index,length:t.length}})),setTimeout(()=>{var t,o;const r=e.root;if(!r||!r.isConnected){return}if(!l(c)){return}const i=r.innerHTML;h.current=!0,n(d(i,{fontSize:c.fontSize,fontFamily:c.fontFamily}));const a=e.getContents(),s=c.fill;let u=null,f=!0;for(const e of a.ops){if("string"!=typeof e.insert||"\n"===e.insert){continue}if(null===(t=e.attributes)||void 0===t?void 0:t.gradient){f=!1;break}const n=(null===(o=e.attributes)||void 0===o?void 0:o.color)||s;if(null===u){u=n}else if(n!==u){f=!1;break}}f&&u&&c.set({fill:u})},10)});const o=a(c,c.fontFamily);setQuillContent(e,o),h.current=!0;const b=p.current.closest(".polotno-workspace-inner"),x=null==b?void 0:b.scrollLeft,y=null==b?void 0:b.scrollTop;u?setCursorFromCoords(e,u):e.setSelection(0,0,"api"),b&&void 0!==x&&void 0!==y&&(b.scrollLeft=x,b.scrollTop=y),e.on("selection-change",(t,o,n)=>{t&&(syncQuillFormatState(e,t),r.runInAction(()=>{quillRef.lastSelection={index:t.index,length:t.length}}))});const w=e.root;m=e=>{const o=e.relatedTarget;(null==o?void 0:o.classList.contains("ql-clipboard"))||(A(o)||quillRef.pendingToolbarInteraction?R():setTimeout(()=>{quillRef.pendingToolbarInteraction||A(document.activeElement)?R():(L(),t())},0))},g=()=>{L()},w.addEventListener("blur",m),w.addEventListener("focus",g),i=w,s=t=>{var o,n;const r=e.getSelection();if(!r||0===r.length){return}const i=e.getText(r.index,r.length).replace(/\n$/,""),l=window.getSelection();let a="";if(l&&l.rangeCount>0){const t=l.getRangeAt(0);let e=t.cloneContents(),o=t.startContainer;o&&o.nodeType===Node.TEXT_NODE&&(o=o.parentNode);let n=t.endContainer;if(n&&n.nodeType===Node.TEXT_NODE&&(n=n.parentNode),o&&o===n){let t=o;for(;t&&t!==w&&t.nodeType===Node.ELEMENT_NODE;){const o=t.tagName;if("SPAN"!==o&&"EM"!==o&&"STRONG"!==o&&"U"!==o&&"S"!==o&&"A"!==o){break}const n=t.cloneNode(!1);n.appendChild(e),e=n,t=t.parentNode}}const r=document.createElement("div");r.appendChild(e),a=r.innerHTML}if(null===(o=t.clipboardData)||void 0===o||o.setData("text/plain",i),a){const e='<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>\x3c!--StartFragment--\x3e<div style="white-space: pre-wrap; overflow-wrap: break-word;">'+a+"</div>\x3c!--EndFragment--\x3e</body></html>";null===(n=t.clipboardData)||void 0===n||n.setData("text/html",e)}t.preventDefault()},f=t=>{s&&s(t);const o=e.getSelection();o&&o.length>0&&e.deleteText(o.index,o.length)},i.addEventListener("copy",s),i.addEventListener("cut",f)}catch(b){console.error("RichEditor init failed:",b)}}};return p.current?b():queueMicrotask(b),()=>{o=!0,i&&m&&i.removeEventListener("blur",m),i&&g&&i.removeEventListener("focus",g),L(),i&&s&&f&&(i.removeEventListener("copy",s),i.removeEventListener("cut",f)),r.runInAction(()=>{quillRef.editor.instance=null,quillRef.currentFormat={},quillRef.lastSelection=null}),q(e),delete window.__polotnoQuill}},[]),o.useEffect(()=>i(c,()=>`${c.text}\0${c.fontSize}\0${c.fontFamily}`,()=>{const t=quillRef.editor.instance;if(!t){return}if(h.current){return void(h.current=!1)}const e=t.getSelection();setQuillContent(t,a(c,c.fontFamily)),h.current=!0,e&&(t.setSelection(e.index,e.length),syncQuillFormatState(t,t.getSelection()))},{fireImmediately:!0}),[]),o.useEffect(()=>i(c,()=>`${c.fontFamily}\0${c.fontSize}\0${c.fontWeight}\0${c.fontStyle}\0${c.lineHeight}\0${c.letterSpacing}\0${s(m(c.text))}`,()=>{const t=p.current;if(!t){return}const e="ltr"===s(m(c.text)),o=computeMarkerVars(c);o&&t.style.setProperty("--rt-number-gap",`${o.numberGap}px`),o&&e?(t.style.setProperty("--rt-bullet-left",`${o.bulletLeft}px`),t.style.setProperty("--rt-bullet-top",`${o.bulletTop}px`),t.style.setProperty("--rt-bullet-fs",`${o.bulletFontSize}px`),t.classList.add("rt-marker-geom")):t.classList.remove("rt-marker-geom")},{fireImmediately:!0}),[]),o.useEffect(()=>{window.addEventListener("blur",t);const e=e=>{var o;(null===(o=p.current)||void 0===o?void 0:o.contains(e.target))||A(e.target)||quillRef.pendingToolbarInteraction||(L(),t())};return window.addEventListener("mousedown",e),window.addEventListener("touchstart",e),()=>{window.removeEventListener("blur",t),window.removeEventListener("mousedown",e),window.removeEventListener("touchstart",e)}},[]);const y={color:c.fill};c.fill.indexOf("gradient")>=0&&(y["--polotno-gradient"]=c.fill,y.color="transparent"),c.strokeWidth>0&&(y.WebkitTextStroke=`${c.strokeWidth}px ${b(c.stroke)}`,y.paintOrder="stroke fill");const w=g(c.fill)?b(c.fill):x(c),k=c.a.rotation*Math.PI/180,T=c.shadowOffsetX*Math.cos(k)+c.shadowOffsetY*Math.sin(k),C=-c.shadowOffsetX*Math.sin(k)+c.shadowOffsetY*Math.cos(k);return e(RichTextContainer,{ref:p,style:Object.assign(Object.assign({},y),{fontSize:c.fontSize,fontFamily:c.fontFamily,fontWeight:c.fontWeight,fontStyle:c.fontStyle,"--polotno-text-decoration":c.textDecoration||"none",textTransform:c.textTransform,width:c.a.width,lineHeight:c.lineHeight,letterSpacing:c.letterSpacing*c.fontSize+"px",textAlign:c.align,opacity:Math.max(c.a.opacity,.2),textShadow:c.shadowEnabled?`${T}px ${C}px ${c.shadowBlur}px ${E(c.shadowColor,null!==(f=c.shadowOpacity)&&void 0!==f?f:1)}`:void 0,caretColor:w}),dir:s(m(c.text))})};function A(t){return!(!t||!t.closest(".sketch-picker")&&!t.closest("[data-polotno-keep-focus]")&&!t.closest(".polotno-portal")&&!t.closest(".polotno-toolbar"))}export function setCursorFromCoords(t,e){if(!t||!e){return}const{x:o,y:r}=e;try{let e=null;if(document.caretRangeFromPoint){e=document.caretRangeFromPoint(o,r)}else if(document.caretPositionFromPoint){const t=document.caretPositionFromPoint(o,r);t&&(e=document.createRange(),e.setStart(t.offsetNode,t.offset))}if(e){const o=n.find(e.startContainer,!0);if(o){const n=o.offset(t.scroll)+e.startOffset;return void t.setSelection(n,0,"api")}}}catch(i){}t.setSelection(0,0,"api")}
155
+ `;let j=["background","font-weight","color","gradient","font","italic","size","script","strike","underline","indent","list","direction"];export const setQuillFormats=t=>{j=t};let N=!1;function z(){N||(N=!0,console.warn("[polotno] The Quill 'bold' format is deprecated. Use the numeric 'font-weight' format instead, e.g. quill.format('font-weight', '700') or applyTextFormat({ fontWeight: 700 })."))}function P(t){return t?"700":"400"}export const createQuill=(e,o)=>{y();const r=new n(e,{toolbar:!1,keyboard:!1,placeholder:(null==o?void 0:o.placeholder)||void 0,clipboard:{matchVisual:!1},formats:j});!function(e){const o=e.format.bind(e),n=e.formatText.bind(e),r=e.getFormat.bind(e);e.format=(t,e,n)=>"bold"===t?(z(),o("font-weight",P(e),n)):o(t,e,n),e.formatText=(e,o,r,i,l)=>{if(r&&"object"==typeof r){if("bold"in r){z();const{bold:l}=r,a=t(r,["bold"]);return n(e,o,Object.assign(Object.assign({},a),{"font-weight":P(l)}),i)}return n(e,o,r,i)}return"bold"===r?(z(),n(e,o,"font-weight",P(i),l)):n(e,o,r,i,l)},e.getFormat=(...t)=>{const e=r(...t);return e&&null!=e["font-weight"]&&!("bold"in e)&&(e.bold=u(e["font-weight"])),e}}(r);const i=n.import("delta"),l=(t,e)=>e.compose((new i).retain(e.length(),{"font-weight":"700"}));return r.clipboard.addMatcher("STRONG",l),r.clipboard.addMatcher("B",l),r};export const setQuillContent=(t,e)=>{var o=t.clipboard.convert({html:"<div class='ql-editor' style='outline: none;'>"+e.replace(/\t/g,"")+"<p><br></p></div>",text:""});o.ops.forEach(t=>{"string"==typeof t.insert&&t.insert.includes("")&&(t.insert=t.insert.split("").join("\t"))}),t.setContents(o),t.history.clear()};export const RichEditor=({onBlur:t,onChange:n,element:c,clickCoords:u})=>{var f;const p=o.useRef(null),m=o.useRef(!1);o.useLayoutEffect(()=>{let e,o=!1,i=null,s=null,f=null,h=null,g=null;const b=()=>{if(!o&&p.current){try{e=createQuill(p.current,{placeholder:x(c.placeholder)}),r.runInAction(()=>{quillRef.editor.instance=e}),quillRef.pendingToolbarInteraction=!1,window.__polotnoQuill=e,S({instance:e,store:c.store,element:c}),e.on("text-change",()=>{const t=e.getSelection();t&&(syncQuillFormatState(e,t),r.runInAction(()=>{quillRef.lastSelection={index:t.index,length:t.length}})),setTimeout(()=>{var t,o;const r=e.root;if(!r||!r.isConnected){return}if(!l(c)){return}const i=r.innerHTML;m.current=!0,n(d(i,{fontSize:c.fontSize,fontFamily:c.fontFamily}));const a=e.getContents(),s=c.fill;let u=null,f=!0;for(const e of a.ops){if("string"!=typeof e.insert||"\n"===e.insert){continue}if(null===(t=e.attributes)||void 0===t?void 0:t.gradient){f=!1;break}const n=(null===(o=e.attributes)||void 0===o?void 0:o.color)||s;if(null===u){u=n}else if(n!==u){f=!1;break}}f&&u&&c.set({fill:u})},10)});const o=a(c,c.fontFamily);setQuillContent(e,o),m.current=!0;const b=p.current.closest(".polotno-workspace-inner"),v=null==b?void 0:b.scrollLeft,y=null==b?void 0:b.scrollTop;u?setCursorFromCoords(e,u):e.setSelection(0,0,"api"),b&&void 0!==v&&void 0!==y&&(b.scrollLeft=v,b.scrollTop=y),e.on("selection-change",(t,o,n)=>{t&&(syncQuillFormatState(e,t),r.runInAction(()=>{quillRef.lastSelection={index:t.index,length:t.length}}))});const w=e.root;h=e=>{const o=e.relatedTarget;(null==o?void 0:o.classList.contains("ql-clipboard"))||(A(o)||quillRef.pendingToolbarInteraction?R():setTimeout(()=>{quillRef.pendingToolbarInteraction||A(document.activeElement)?R():(L(),t())},0))},g=()=>{L()},w.addEventListener("blur",h),w.addEventListener("focus",g),i=w,s=t=>{var o,n;const r=e.getSelection();if(!r||0===r.length){return}const i=e.getText(r.index,r.length).replace(/\n$/,""),l=window.getSelection();let a="";if(l&&l.rangeCount>0){const t=l.getRangeAt(0);let e=t.cloneContents(),o=t.startContainer;o&&o.nodeType===Node.TEXT_NODE&&(o=o.parentNode);let n=t.endContainer;if(n&&n.nodeType===Node.TEXT_NODE&&(n=n.parentNode),o&&o===n){let t=o;for(;t&&t!==w&&t.nodeType===Node.ELEMENT_NODE;){const o=t.tagName;if("SPAN"!==o&&"EM"!==o&&"STRONG"!==o&&"U"!==o&&"S"!==o&&"A"!==o){break}const n=t.cloneNode(!1);n.appendChild(e),e=n,t=t.parentNode}}const r=document.createElement("div");r.appendChild(e),a=r.innerHTML}if(null===(o=t.clipboardData)||void 0===o||o.setData("text/plain",i),a){const e='<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>\x3c!--StartFragment--\x3e<div style="white-space: pre-wrap; overflow-wrap: break-word;">'+a+"</div>\x3c!--EndFragment--\x3e</body></html>";null===(n=t.clipboardData)||void 0===n||n.setData("text/html",e)}t.preventDefault()},f=t=>{s&&s(t);const o=e.getSelection();o&&o.length>0&&e.deleteText(o.index,o.length)},i.addEventListener("copy",s),i.addEventListener("cut",f)}catch(b){console.error("RichEditor init failed:",b)}}};return p.current?b():queueMicrotask(b),()=>{o=!0,i&&h&&i.removeEventListener("blur",h),i&&g&&i.removeEventListener("focus",g),L(),i&&s&&f&&(i.removeEventListener("copy",s),i.removeEventListener("cut",f)),r.runInAction(()=>{quillRef.editor.instance=null,quillRef.currentFormat={},quillRef.lastSelection=null}),q(e),delete window.__polotnoQuill}},[]),o.useEffect(()=>i(c,()=>`${c.text}\0${c.fontSize}\0${c.fontFamily}`,()=>{const t=quillRef.editor.instance;if(!t){return}if(m.current){return void(m.current=!1)}const e=t.getSelection();setQuillContent(t,a(c,c.fontFamily)),m.current=!0,e&&(t.setSelection(e.index,e.length),syncQuillFormatState(t,t.getSelection()))},{fireImmediately:!0}),[]),o.useEffect(()=>i(c,()=>`${c.fontFamily}\0${c.fontSize}\0${c.fontWeight}\0${c.fontStyle}\0${c.lineHeight}\0${c.letterSpacing}\0${s(h(c.text))}`,()=>{const t=p.current;if(!t){return}const e="ltr"===s(h(c.text)),o=computeMarkerVars(c);o&&t.style.setProperty("--rt-number-gap",`${o.numberGap}px`),o&&e?(t.style.setProperty("--rt-bullet-left",`${o.bulletLeft}px`),t.style.setProperty("--rt-bullet-top",`${o.bulletTop}px`),t.style.setProperty("--rt-bullet-fs",`${o.bulletFontSize}px`),t.classList.add("rt-marker-geom")):t.classList.remove("rt-marker-geom")},{fireImmediately:!0}),[]),o.useEffect(()=>{window.addEventListener("blur",t);const e=e=>{var o;const n=e.target;"number"==typeof(null==n?void 0:n.nodeType)&&(null===(o=p.current)||void 0===o?void 0:o.contains(n))||A(n)||quillRef.pendingToolbarInteraction||(L(),t())};return window.addEventListener("mousedown",e),window.addEventListener("touchstart",e),()=>{window.removeEventListener("blur",t),window.removeEventListener("mousedown",e),window.removeEventListener("touchstart",e)}},[]);const y={color:c.fill};c.fill.indexOf("gradient")>=0&&(y["--polotno-gradient"]=c.fill,y.color="transparent"),c.strokeWidth>0&&(y.WebkitTextStroke=`${c.strokeWidth}px ${b(c.stroke)}`,y.paintOrder="stroke fill");const w=g(c.fill)?b(c.fill):v(c),k=c.a.rotation*Math.PI/180,T=c.shadowOffsetX*Math.cos(k)+c.shadowOffsetY*Math.sin(k),C=-c.shadowOffsetX*Math.sin(k)+c.shadowOffsetY*Math.cos(k);return e(RichTextContainer,{ref:p,style:Object.assign(Object.assign({},y),{fontSize:c.fontSize,fontFamily:c.fontFamily,fontWeight:c.fontWeight,fontStyle:c.fontStyle,"--polotno-text-decoration":c.textDecoration||"none",textTransform:c.textTransform,width:c.a.width,lineHeight:c.lineHeight,letterSpacing:c.letterSpacing*c.fontSize+"px",textAlign:c.align,opacity:Math.max(c.a.opacity,.2),textShadow:c.shadowEnabled?`${T}px ${C}px ${c.shadowBlur}px ${E(c.shadowColor,null!==(f=c.shadowOpacity)&&void 0!==f?f:1)}`:void 0,caretColor:w}),dir:s(h(c.text))})};function A(t){const e=t;return!("function"!=typeof(null==e?void 0:e.closest)||!e.closest(".sketch-picker")&&!e.closest("[data-polotno-keep-focus]")&&!e.closest(".polotno-portal")&&!e.closest(".polotno-toolbar"))}export function setCursorFromCoords(t,e){if(!t||!e){return}const{x:o,y:r}=e;try{let e=null;if(document.caretRangeFromPoint){e=document.caretRangeFromPoint(o,r)}else if(document.caretPositionFromPoint){const t=document.caretPositionFromPoint(o,r);t&&(e=document.createRange(),e.setStart(t.offsetNode,t.offset))}if(e){const o=n.find(e.startContainer,!0);if(o){const n=o.offset(t.scroll)+e.startOffset;return void t.setSelection(n,0,"api")}}}catch(i){}t.setSelection(0,0,"api")}
package/canvas/rules.d.ts CHANGED
@@ -10,7 +10,7 @@ type TopRulesProps = {
10
10
  layout?: 'vertical' | 'horizontal';
11
11
  renderOnlyActivePage?: boolean;
12
12
  };
13
- export declare const TopRules: (({ store, width, height, pageSizes, layout, renderOnlyActivePage }: TopRulesProps) => React.JSX.Element | null) & {
13
+ export declare const TopRules: (({ store, width, height, pageSizes, layout, renderOnlyActivePage, }: TopRulesProps) => React.JSX.Element | null) & {
14
14
  displayName: string;
15
15
  };
16
16
  export {};
@@ -1 +1 @@
1
- import{jsx as t,Fragment as e,jsxs as r}from"react/jsx-runtime";import n from"react";import{observer as o}from"mobx-react-lite";import{Group as i,Path as a,Text as l,TextPath as s}from"react-konva";import{Html as c}from"react-konva-utils";import{nodeAutorun as u}from"../utils/mobx.js";import d from"konva";import{parsePath as f,roundCommands as h}from"svg-round-corners/lib/index.js";import{generateBackgroundShapeFromRects as g,textLinesToRects as m}from"@polotno/core/background-shape";import{useColor as p}from"./use-color.js";import{useWorkspaceStyle as x}from"./workspace-style.js";import{ROLES as w}from"../model/store.js";import{incrementLoader as v}from"../utils/loader.js";import{scaledFontSizeAttrs as y,roundedFontSizeAttrs as S,roundedTextDecorationAttrs as b,textMinResizeWidth as E}from"../utils/px.js";import{isFontLoaded as z}from"../utils/fonts.js";import{flags as k}from"../utils/flags.js";import{removeTags as O}from"@polotno/core/text";import{getDir as R,getCurvePath as A,resolveLineHeight as F,normalizeStrokeLineJoin as M}from"@polotno/core/text-html";import{applyFilter as j}from"./apply-filters.js";import{useFadeIn as L}from"./use-fadein.js";import{isTouchDevice as T}from"../utils/screen.js";import{isAlive as C,getParent as H}from"mobx-state-tree";import{getLimitedFontSize as P}from"./text-element/max-font-size.js";import{getOptimalCaretColor as X}from"./text-element/caret-color.js";import{visiblePlaceholder as Y}from"./text-element/placeholder.js";let W;function D(){return W||(W=document.getElementById("polotno-text-style"),W||(W=document.createElement("style"),W.id="polotno-text-style",document.head.appendChild(W)),W)}d._fixTextRendering=!0;const $={border:"none",padding:"0px",overflow:"hidden",background:"none",outline:"none",resize:"none",overflowWrap:"break-word",whiteSpace:"pre-wrap",userSelect:"text",wordBreak:"normal",textTransform:"none"};export{getDir}from"@polotno/core/text-html";const B=o(({textNodeRef:e,element:r,onBlur:o,selectAll:i,cursorPosition:a})=>{const[l,s]=n.useState($),c=e.current;n.useLayoutEffect(()=>{if(!c){return}const t={};t.width=c.width()-2*c.padding()+"px",t.height=c.height()-2*c.padding()+c.fontSize()*c.lineHeight()+"px",t.fontSize=c.fontSize()+"px",t.lineHeight=c.lineHeight()+.01,t.fontFamily=c.fontFamily(),t.textAlign=c.align(),t.color=c.fill(),t.fontWeight=r.fontWeight,t.fontStyle=r.fontStyle,t.letterSpacing=r.letterSpacing+"em",t.opacity=Math.max(r.a.opacity,.2),t.textTransform=r.textTransform,t.caretColor=X(r);const e=`\n .polotno-input::placeholder {\n color: ${l.color};\n opacity: 0.6;\n }\n `,n=D();n.innerHTML="",n.appendChild(document.createTextNode(e)),JSON.stringify(t)!==JSON.stringify(l)&&s(t)});const u=n.useRef(null);if(n.useLayoutEffect(()=>{var t;const e=u.current;if(!e){return}null===(t=u.current)||void 0===t||t.focus({preventScroll:!0});const r=a||e.value.length;e.selectionStart=e.selectionEnd=r,i&&(null==e||e.select(),document.execCommand("selectAll",!1,void 0))},[]),n.useEffect(()=>{window.addEventListener("blur",o);const t=t=>{var e;(null===(e=u.current)||void 0===e?void 0:e.contains(t.target))||o()};return window.addEventListener("touchstart",t),()=>{window.removeEventListener("blur",o),window.removeEventListener("touchstart",t)}},[]),!c){return null}let d=0;const f=c.textArr.length*c.lineHeight()*c.fontSize();"middle"===r.verticalAlign&&(d=(r.a.height-f)/2),"bottom"===r.verticalAlign&&(d=r.a.height-f);const h=O(r.text);return t("textarea",{className:"polotno-input",ref:u,dir:R(h),style:Object.assign(Object.assign(Object.assign({},$),l),{paddingTop:d+"px"}),value:h,onChange:t=>{const e=P({oldText:r.text,newText:t.target.value,element:r});r.set(Object.assign({text:t.target.value},y(r,e)))},placeholder:Y(r.placeholder),onBlur:o})}),I=e=>t(c,{children:t(B,Object.assign({},e))});export const useFontLoader=(t,e,r,o,i)=>{const[a,l]=n.useReducer(t=>t+1,0),s=n.useRef(z(e,r,o)),c=n.useRef(null);return n.useLayoutEffect(()=>{if(s.current=z(e,r,o),s.current){return}let n=!0;return(async()=>{s.current=!1,l();const a=v(`text ${e}`);await t.loadFont(e,r,o,i),n?(c.current=a,s.current=!0,l()):a()})(),()=>{c.current&&(c.current(),c.current=null),n=!1}},[e,r,o]),n.useEffect(()=>{s.current&&setTimeout(()=>{c.current&&(c.current(),c.current=null)})},[s.current]),[s.current]};export const useFontFamiliesLoader=(t,e,r,o,i)=>{const[a,l]=n.useReducer(t=>t+1,0),s=e.join("\0"),c=n.useRef(e.every(t=>z(t,r,o))),u=n.useRef(null);return n.useLayoutEffect(()=>{if(c.current=e.every(t=>z(t,r,o)),c.current){return}let n=!0;return(async()=>{c.current=!1,l();const a=v(`text fonts ${s}`);await Promise.all(e.map(e=>t.loadFont(e,r,o,i))),n?(u.current=a,c.current=!0,l()):a()})(),()=>{u.current&&(u.current(),u.current=null),n=!1}},[s,r,o]),n.useEffect(()=>{c.current&&setTimeout(()=>{u.current&&(u.current(),u.current=null)})},[c.current]),[c.current]};export const getLineHeight=({fontLoaded:t,fontFamily:e,fontSize:r,lineHeight:o})=>n.useMemo(()=>F({fontFamily:e,fontSize:r,lineHeight:o}),[t,e,r,o]);export function usePrevious(t){const e=n.useRef(t),r=n.useRef(t);return n.useMemo(()=>{r.current=e.current,e.current=t},[t]),r.current}function N(t,e,r=!1){const n=t.fontSize(),o=t.height(),i=O(e.text);let a=e.a.fontSize;t.height(void 0);const l=Math.round(2*e.a.fontSize)-1;for(let s=1;s<l;s++){const n=e.a.height&&t.height()>e.a.height;let o=i.split("\n").join(" ").split(/[\s-]+/).reduce((t,e)=>(e=e.toLowerCase(),/[\u3000-\u303F\u3040-\u309F\u30A0-\u30FF\uFF00-\uFFEF\u4E00-\u9FAF\uAC00-\uD7AF]/.test(e)?t.concat(e.split("")):t.concat(e)),[]),l=t.textArr.map(t=>t.text.toLowerCase()).join(";");const s=o.find(t=>!l.includes(t)||(l=l.replace(t,""),!1));if(!(n||s&&!r)){break}a-=.5,t.fontSize(a)}return t.fontSize(n),t.height(o),a}export{getCurvePath}from"@polotno/core/text-html";export const TextElement=o(({element:o,store:c})=>{const{textOverflowIndicatorStyle:d}=x(),z=n.useRef(null),F=n.useRef(null),P=n.useRef(null),X=n.useRef([]),W=n.useRef(!0),[,D]=n.useReducer(t=>t+1,0),{editorEnabled:$,selectAll:B}=(t=>{const[e,r]=n.useState(!1),o=n.useRef(!1);return n.useEffect(()=>{var e=!0;return setTimeout(()=>{e&&(t._editModeEnabled&&(o.current=!0),r(!0),setTimeout(()=>{o.current=!1},50))},50),()=>{e=!1}},[]),{editorEnabled:e&&t._editModeEnabled,selectAll:o.current}})(o),[J,_]=n.useState(!1),[V,q]=n.useState(!1),U=n.useRef(o.a.height),Z=n.useRef(0),G=n.useRef(""),K=n.useRef(0),Q=o.isSelected,tt=usePrevious(Q),{textVerticalResizeEnabled:et}=k,rt=k.autoDeleteEmptyText,nt=usePrevious(o.fontFamily),[ot,it]=n.useState([]);n.useEffect(()=>{var t,e;const r=null!==(e=null===(t=z.current)||void 0===t?void 0:t.textArr)&&void 0!==e?e:[];JSON.stringify(r)!==JSON.stringify(ot)&&it(r)}),n.useEffect(()=>{if(o.a.width||"tablecell"===o.type){return}const t=z.current;t.width(600),o.set({width:1.4*t.getTextWidth()})},[]),n.useEffect(()=>{tt&&!Q&&rt&&""===o.text&&o.removable&&!Y(o.placeholder)&&c.deleteElements([o.id])},[rt,o.placeholder,o.removable,o.text,Q,tt]);const at=()=>{if(o.curveEnabled){const t=z.current;null==t||t.clearCache(),null==t||t.setAttrs({filters:[]});const e=F.current;e&&j(e,o)}else{const t=z.current;t&&j(t,o)}};n.useLayoutEffect(()=>{if(!V){return u(o,()=>{at()})}}),n.useEffect(()=>{const t=X.current;t.length>0&&(X.current=[],t.forEach(t=>t()))}),n.useEffect(()=>()=>{W.current=!1;const t=X.current;t.length>0&&(X.current=[],t.forEach(t=>t()))},[]);let lt=O(o.text);"uppercase"===o.textTransform&&(lt=lt.toUpperCase());const[st]=useFontLoader(c,o.fontFamily,o.fontStyle,o.fontWeight,o.text||o.placeholder),ct=()=>{if(o.curveEnabled){const t=F.current;return t.getSelfRect().height||t.fontSize()}const t=z.current.clone({height:void 0}),e=Math.ceil(t.fontSize()*t.lineHeight()*t.textArr.length+1);return t.destroy(),e};n.useLayoutEffect(()=>{if(!st){return}if("tablecell"===o.type){const{textOverflow:t}=k;if("resize"===t){const t=ct(),e=C(o)?H(o,2):null;(null==e?void 0:e.setCellContentHeight)&&e.setCellContentHeight(o.id,t)}else if("change-font-size"===t){const t=z.current;if(t){const e=N(t,o,k.textSplitAllowed);e!==o.fontSize&&c.history.ignore(()=>{o.set({fontSize:e})})}}return}const{textOverflow:t,textSplitAllowed:e}=k,r=(t,e,r,n)=>{const i=v(`text ${o.id}`),a=()=>{c.history.ignore(t,e,r).then(()=>{W.current?(X.current.push(i),D()):i()})};n?queueMicrotask(a):a()};if(!o.height){const t=ct();return void r(()=>{o.height||o.set({height:t})},void 0,void 0,!0)}if(!c.isPlaying){if("change-font-size"!==t||J){if("resize"===t){const t=ct();et&&o.height<t&&!J&&r(()=>{var e;C(o)&&o.set({height:t}),null===(e=z.current)||void 0===e||e.height(t)},!1,!0),et||o.height===t||J||r(()=>{var e;C(o)&&o.set({height:t}),null===(e=z.current)||void 0===e||e.height(t)},!1,!0)}}else{const t=z.current,n=o.curveEnabled?o.fontSize:N(t,o,e);if(n!==o.fontSize){return void r(()=>{o.set(y(o,n))},!1,!0)}const i=ct();o.height===i||et||r(()=>{o.set({height:i})},!1,!0)}}}),n.useLayoutEffect(()=>{var t;if(st&&o.curveEnabled){const e=null===(t=F.current)||void 0===t?void 0:t.getSelfRect().width;if(e){const t=e-o.a.width,r=o.a.rotation*Math.PI/180,n=-t/2*Math.cos(r),i=-t/2*Math.sin(r);o.set({width:e,x:o.a.x+n,y:o.a.y+i})}}},[st,o.curveEnabled,o.curvePower,o.text,o.fontSize,o.fontFamily,o.fontWeight,o.fontStyle,o.letterSpacing]),n.useLayoutEffect(()=>{const t=z.current;t&&(t.width(t.width()+1e-8),t.width(t.width()-1e-8),t._setTextData(),at())},[st]);const ut=n.useRef(null),dt=n.useRef(o.width),ft=n.useRef(0),ht=t=>{t.evt.preventDefault();const e=c.selectedShapes.find(t=>t===o);e&&o.contentEditable&&(ft.current=function(t){var e;const r=t.target,n=function(t){var e=t.getAbsoluteTransform().copy();e.invert();var r=t.getStage().getPointerPosition();return e.point(r)}(r),o=r.textArr,i=Math.floor(n.y/(r.fontSize()*r.lineHeight())),a=o.slice(0,i).reduce((t,e)=>t+e.text.length,i),l=null!==(e=o[i])&&void 0!==e?e:o[0];let s=0;return"right"===r.align()?s=r.width()-l.width:"center"===r.align()&&(s=r.width()/2-l.width/2),a+Math.round((n.x-s)/l.width*l.text.length)}(t),o.toggleEditMode())},gt=Y(o.placeholder),mt=!lt&&gt?.6:o.a.opacity;L(z,mt);const pt=getLineHeight({fontLoaded:st,fontFamily:o.fontFamily,fontSize:o.a.fontSize,lineHeight:o.lineHeight}),xt=o.selectable||c.role===w.ADMIN,wt=p(o),vt=p(o,o.stroke,"stroke"),yt=n.useMemo(()=>o.backgroundEnabled?o.curveEnabled?function({width:t,height:e,padding:r=0,cornerRadius:n=0}){const o=-r,i=-r,a=t+r,l=e+r,s=f(`M ${o} ${i} L ${a} ${i} L ${a} ${l} L ${o} ${l} Z`);return h(s,n).path}({width:o.a.width,height:o.a.height,cornerRadius:o.backgroundCornerRadius*(o.a.fontSize*pt*.5),padding:o.backgroundPadding*(o.a.fontSize*pt*.5)}):function({lines:t,lineHeight:e,width:r,align:n="left",padding:o=0,cornerRadius:i=0}){const a=m({lines:t,lineHeight:e,width:r,align:n});return g({rects:a,padding:o,cornerRadius:i})}({lines:JSON.parse(JSON.stringify(ot)),cornerRadius:o.backgroundCornerRadius*(o.a.fontSize*pt*.5),lineHeight:pt*o.a.fontSize,padding:o.backgroundPadding*(o.a.fontSize*pt*.5),width:o.a.width,align:o.align}):"",[o.backgroundEnabled,o.curveEnabled,o.backgroundCornerRadius,o.a.fontSize,o.a.height,pt,o.backgroundPadding,o.a.width,o.align,ot]),St=T();let bt=0;o.curveEnabled||("middle"===o.verticalAlign?bt=(o.a.height-ot.length*pt*o.a.fontSize)/2:"bottom"===o.verticalAlign&&(bt=o.a.height-ot.length*pt*o.a.fontSize));const Et=o.curveEnabled?A(o.a.width,o.a.height,o.curvePower,o.a.fontSize):"",zt=st?'"'+o.fontFamily+'"':nt===o.fontFamily?"Arial":'"'+nt+'"',kt=R(lt);return r(e,{children:[t(a,{ref:P,x:o.a.x,y:o.a.y,rotation:o.a.rotation,hideInExport:!o.showInExport,listening:!1,visible:o.backgroundEnabled,opacity:o.backgroundOpacity*mt,data:yt,fill:o.backgroundColor,offsetY:-bt}),t(a,{data:Et,stroke:d.stroke,strokeWidth:1,x:o.a.x,y:o.a.y,rotation:o.a.rotation,visible:!1}),t(s,Object.assign({ref:F,visible:o.curveEnabled,data:Et,text:lt||gt,listening:!1,align:"center",textBaseline:"middle",direction:kt},wt,vt,{strokeWidth:o.strokeWidth,lineJoin:M(o.strokeLineJoin),fillAfterStrokeEnabled:!0,fontSize:o.a.fontSize,fontFamily:`"${o.fontFamily}", "${nt}"`,fontStyle:o.fontStyle+" "+o.fontWeight,textDecoration:o.textDecoration.trim(),letterSpacing:o.letterSpacing*o.a.fontSize,x:o.a.x,y:o.a.y,rotation:o.a.rotation,opacity:o._editModeEnabled?.3:mt,hideInExport:!o.showInExport,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity})),t(l,Object.assign({ref:z,id:o.selectable?o.id:void 0,name:o.selectable?"element":"",hideInExport:!o.showInExport,editModeEnabled:o._editModeEnabled,x:o.a.x,y:o.a.y,rotation:o.a.rotation,width:o.a.width,height:o.a.height,text:lt||gt,direction:kt},wt,vt,{lineJoin:M(o.strokeLineJoin),strokeWidth:o.strokeWidth,fillAfterStrokeEnabled:!0,fontSize:o.a.fontSize,fontFamily:zt,fontStyle:o.fontStyle+" "+o.fontWeight,textDecoration:o.textDecoration,align:o.align,verticalAlign:o.verticalAlign,draggable:St?o.draggable&&Q:o.draggable,preventDefault:!St||Q,opacity:o.curveEnabled?0:mt,visible:!o._editModeEnabled,ellipsis:"ellipsis"===k.textOverflow,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity,lineHeight:pt,letterSpacing:o.letterSpacing*o.a.fontSize,listening:!!o.selectable&&xt,onDragStart:()=>{q(!0)},onDragMove:t=>{o.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{q(!1),o.set({x:t.target.x(),y:t.target.y()})},onClick:ht,onTap:ht,onTransformStart:()=>{var t,e;_(!0);const r=z.current;U.current=r.height(),dt.current=o.a.width,ut.current=r.position(),Z.current=r.rotation(),K.current=r.height();const n=null===(t=r.getStage())||void 0===t?void 0:t.findOne("Transformer");G.current=null!==(e=null==n?void 0:n.getActiveAnchor())&&void 0!==e?e:""},onTransform:t=>{var e,r,n;const i=t.target;null===(e=P.current)||void 0===e||e.setAttrs({x:i.x(),y:i.y(),rotation:i.rotation(),scale:i.scale()});const a=(null===(r=i.getStage())||void 0===r?void 0:r.findOne("Transformer")).getActiveAnchor();if("middle-left"===a||"middle-right"===a){const t=i.scaleX(),e=i.width()*t,r=E(dt.current,o.a.fontSize);let n=e;e<r&&(n=r,ut.current&&i.position(ut.current)),i.width(n),i.scaleX(1),i.scaleY(1);let a=ct();if("ellipsis"===k.textOverflow){a=U.current}else{const t=Math.max(a,U.current);i.height(t),o.set({height:i.height()})}const l=k.textVerticalResizeEnabled?Math.max(a,U.current):ct();o.set({x:i.x(),width:i.width(),rotation:i.rotation(),height:l}),i.skewX(0),i.skewY(0),at()}if("top-center"===a||"bottom-center"===a){const e="resize"===k.textOverflow?ct():pt*o.a.fontSize,r=t.target.height()*t.target.scaleY();if(r<e){if(t.target.height(e),ut.current){if("top-center"===G.current){const r=Z.current*Math.PI/180,n=K.current-e;t.target.x(ut.current.x-n*Math.sin(r)),t.target.y(ut.current.y+n*Math.cos(r))}else{t.target.position(ut.current)}}}else{t.target.height(r)}t.target.scaleY(1),t.target.scaleX(1),t.target.rotation(Z.current),t.target.skewX(0),t.target.skewY(0),K.current=Math.max(e,r)}ut.current=t.target.position();const l=t.target.scaleX();null===(n=P.current)||void 0===n||n.setAttrs({scaleX:1,scaleY:1}),t.target.scaleX(1),t.target.scaleY(1),o.set({fontSize:o.a.fontSize*l,width:t.target.width()*l,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),height:t.target.height()*l,shadowBlur:o.shadowBlur*l,shadowOffsetX:o.shadowOffsetX*l,shadowOffsetY:o.shadowOffsetY*l,strokeWidth:o.strokeWidth*l})},onTransformEnd:t=>{var e;const r=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),o.set(Object.assign(Object.assign({},S(o,o.fontSize*r)),{width:Math.ceil(t.target.width()*r),x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),height:t.target.height()*r})),null===(e=P.current)||void 0===e||e.setAttrs({scaleX:1,scaleY:1}),_(!1)}})),$&&o.contentEditable&&t(i,{x:o.a.x,y:o.a.y,rotation:o.a.rotation,children:t(I,{textNodeRef:z,element:o,selectAll:B,cursorPosition:ft.current,onBlur:()=>{o.set(b(o)),o.toggleEditMode(!1)}})})]})});
1
+ import{jsx as t,Fragment as e,jsxs as r}from"react/jsx-runtime";import n from"react";import{observer as o}from"mobx-react-lite";import{Group as i,Path as a,Text as l,TextPath as s}from"react-konva";import{Html as c}from"react-konva-utils";import{nodeAutorun as u}from"../utils/mobx.js";import d from"konva";import{parsePath as f,roundCommands as h}from"svg-round-corners/lib/index.js";import{generateBackgroundShapeFromRects as g,textLinesToRects as p}from"@polotno/core/background-shape";import{useColor as m}from"./use-color.js";import{useWorkspaceStyle as x}from"./workspace-style.js";import{ROLES as w}from"../model/store.js";import{incrementLoader as v}from"../utils/loader.js";import{scaledFontSizeAttrs as y,roundedFontSizeAttrs as S,roundedTextDecorationAttrs as b,textMinResizeWidth as E}from"../utils/px.js";import{isFontLoaded as z}from"../utils/fonts.js";import{flags as k}from"../utils/flags.js";import{removeTags as O}from"@polotno/core/text";import{getDir as R,getCurvePath as A,resolveLineHeight as F,normalizeStrokeLineJoin as M}from"@polotno/core/text-html";import{applyFilter as j}from"./apply-filters.js";import{useFadeIn as L}from"./use-fadein.js";import{isTouchDevice as T}from"../utils/screen.js";import{isAlive as C,getParent as H}from"mobx-state-tree";import{getLimitedFontSize as P}from"./text-element/max-font-size.js";import{getOptimalCaretColor as X}from"./text-element/caret-color.js";import{visiblePlaceholder as Y}from"./text-element/placeholder.js";import{hasMeasuredHeight as W,resolveTextBoxHeight as D}from"@polotno/core/text-types";let $;function B(){return $||($=document.getElementById("polotno-text-style"),$||($=document.createElement("style"),$.id="polotno-text-style",document.head.appendChild($)),$)}d._fixTextRendering=!0;const I={border:"none",padding:"0px",overflow:"hidden",background:"none",outline:"none",resize:"none",overflowWrap:"break-word",whiteSpace:"pre-wrap",userSelect:"text",wordBreak:"normal",textTransform:"none"};export{getDir}from"@polotno/core/text-html";const N=o(({textNodeRef:e,element:r,onBlur:o,selectAll:i,cursorPosition:a})=>{const[l,s]=n.useState(I),c=e.current;n.useLayoutEffect(()=>{if(!c){return}const t={};t.width=c.width()-2*c.padding()+"px",t.height=c.height()-2*c.padding()+c.fontSize()*c.lineHeight()+"px",t.fontSize=c.fontSize()+"px",t.lineHeight=c.lineHeight()+.01,t.fontFamily=c.fontFamily(),t.textAlign=c.align(),t.color=c.fill(),t.fontWeight=r.fontWeight,t.fontStyle=r.fontStyle,t.letterSpacing=r.letterSpacing+"em",t.opacity=Math.max(r.a.opacity,.2),t.textTransform=r.textTransform,t.caretColor=X(r);const e=`\n .polotno-input::placeholder {\n color: ${l.color};\n opacity: 0.6;\n }\n `,n=B();n.innerHTML="",n.appendChild(document.createTextNode(e)),JSON.stringify(t)!==JSON.stringify(l)&&s(t)});const u=n.useRef(null);if(n.useLayoutEffect(()=>{var t;const e=u.current;if(!e){return}null===(t=u.current)||void 0===t||t.focus({preventScroll:!0});const r=a||e.value.length;e.selectionStart=e.selectionEnd=r,i&&(null==e||e.select(),document.execCommand("selectAll",!1,void 0))},[]),n.useEffect(()=>{window.addEventListener("blur",o);const t=t=>{var e;(null===(e=u.current)||void 0===e?void 0:e.contains(t.target))||o()};return window.addEventListener("touchstart",t),()=>{window.removeEventListener("blur",o),window.removeEventListener("touchstart",t)}},[]),!c){return null}let d=0;const f=c.textArr.length*c.lineHeight()*c.fontSize(),h=D(r.a,f);"middle"===r.verticalAlign&&(d=(h-f)/2),"bottom"===r.verticalAlign&&(d=h-f);const g=O(r.text);return t("textarea",{className:"polotno-input",ref:u,dir:R(g),style:Object.assign(Object.assign(Object.assign({},I),l),{paddingTop:d+"px"}),value:g,onChange:t=>{const e=P({oldText:r.text,newText:t.target.value,element:r});r.set(Object.assign({text:t.target.value},y(r,e)))},placeholder:Y(r.placeholder),onBlur:o})}),J=e=>t(c,{children:t(N,Object.assign({},e))});export const useFontLoader=(t,e,r,o,i)=>{const[a,l]=n.useReducer(t=>t+1,0),s=n.useRef(z(e,r,o)),c=n.useRef(null);return n.useLayoutEffect(()=>{if(s.current=z(e,r,o),s.current){return}let n=!0;return(async()=>{s.current=!1,l();const a=v(`text ${e}`);await t.loadFont(e,r,o,i),n?(c.current=a,s.current=!0,l()):a()})(),()=>{c.current&&(c.current(),c.current=null),n=!1}},[e,r,o]),n.useEffect(()=>{s.current&&setTimeout(()=>{c.current&&(c.current(),c.current=null)})},[s.current]),[s.current]};export const useFontFamiliesLoader=(t,e,r,o,i)=>{const[a,l]=n.useReducer(t=>t+1,0),s=e.join("\0"),c=n.useRef(e.every(t=>z(t,r,o))),u=n.useRef(null);return n.useLayoutEffect(()=>{if(c.current=e.every(t=>z(t,r,o)),c.current){return}let n=!0;return(async()=>{c.current=!1,l();const a=v(`text fonts ${s}`);await Promise.all(e.map(e=>t.loadFont(e,r,o,i))),n?(u.current=a,c.current=!0,l()):a()})(),()=>{u.current&&(u.current(),u.current=null),n=!1}},[s,r,o]),n.useEffect(()=>{c.current&&setTimeout(()=>{u.current&&(u.current(),u.current=null)})},[c.current]),[c.current]};export const getLineHeight=({fontLoaded:t,fontFamily:e,fontSize:r,lineHeight:o})=>n.useMemo(()=>F({fontFamily:e,fontSize:r,lineHeight:o}),[t,e,r,o]);export function usePrevious(t){const e=n.useRef(t),r=n.useRef(t);return n.useMemo(()=>{r.current=e.current,e.current=t},[t]),r.current}function _(t,e,r=!1){const n=t.fontSize(),o=t.height(),i=O(e.text);let a=e.a.fontSize;t.height(void 0);const l=Math.round(2*e.a.fontSize)-1;for(let s=1;s<l;s++){const n=W(e.a)&&t.height()>e.a.height;let o=i.split("\n").join(" ").split(/[\s-]+/).reduce((t,e)=>(e=e.toLowerCase(),/[\u3000-\u303F\u3040-\u309F\u30A0-\u30FF\uFF00-\uFFEF\u4E00-\u9FAF\uAC00-\uD7AF]/.test(e)?t.concat(e.split("")):t.concat(e)),[]),l=t.textArr.map(t=>t.text.toLowerCase()).join(";");const s=o.find(t=>!l.includes(t)||(l=l.replace(t,""),!1));if(!(n||s&&!r)){break}a-=.5,t.fontSize(a)}return t.fontSize(n),t.height(o),a}export{getCurvePath}from"@polotno/core/text-html";export const TextElement=o(({element:o,store:c})=>{const{textOverflowIndicatorStyle:d}=x(),z=n.useRef(null),F=n.useRef(null),P=n.useRef(null),X=n.useRef([]),$=n.useRef(!0),[,B]=n.useReducer(t=>t+1,0),{editorEnabled:I,selectAll:N}=(t=>{const[e,r]=n.useState(!1),o=n.useRef(!1);return n.useEffect(()=>{var e=!0;return setTimeout(()=>{e&&(t._editModeEnabled&&(o.current=!0),r(!0),setTimeout(()=>{o.current=!1},50))},50),()=>{e=!1}},[]),{editorEnabled:e&&t._editModeEnabled,selectAll:o.current}})(o),[V,q]=n.useState(!1),[U,Z]=n.useState(!1),G=n.useRef(o.a.height),K=n.useRef(0),Q=n.useRef(""),tt=n.useRef(0),et=o.isSelected,rt=usePrevious(et),{textVerticalResizeEnabled:nt}=k,ot=k.autoDeleteEmptyText,it=usePrevious(o.fontFamily),[at,lt]=n.useState([]);n.useEffect(()=>{var t,e;const r=null!==(e=null===(t=z.current)||void 0===t?void 0:t.textArr)&&void 0!==e?e:[];JSON.stringify(r)!==JSON.stringify(at)&&lt(r)}),n.useEffect(()=>{if(o.a.width||"tablecell"===o.type){return}const t=z.current;t.width(600),o.set({width:1.4*t.getTextWidth()})},[]),n.useEffect(()=>{rt&&!et&&ot&&""===o.text&&o.removable&&!Y(o.placeholder)&&c.deleteElements([o.id])},[ot,o.placeholder,o.removable,o.text,et,rt]);const st=()=>{if(o.curveEnabled){const t=z.current;null==t||t.clearCache(),null==t||t.setAttrs({filters:[]});const e=F.current;e&&j(e,o)}else{const t=z.current;t&&j(t,o)}};n.useLayoutEffect(()=>{if(!U){return u(o,()=>{st()})}}),n.useEffect(()=>{const t=X.current;t.length>0&&(X.current=[],t.forEach(t=>t()))}),n.useEffect(()=>()=>{$.current=!1;const t=X.current;t.length>0&&(X.current=[],t.forEach(t=>t()))},[]);let ct=O(o.text);"uppercase"===o.textTransform&&(ct=ct.toUpperCase());const[ut]=useFontLoader(c,o.fontFamily,o.fontStyle,o.fontWeight,o.text||o.placeholder),dt=()=>{if(o.curveEnabled){const t=F.current;return t.getSelfRect().height||t.fontSize()}const t=z.current.clone({height:void 0}),e=Math.ceil(t.fontSize()*t.lineHeight()*t.textArr.length+1);return t.destroy(),e};n.useLayoutEffect(()=>{if(!ut){return}if("tablecell"===o.type){const{textOverflow:t}=k;if("resize"===t){const t=dt(),e=C(o)?H(o,2):null;(null==e?void 0:e.setCellContentHeight)&&e.setCellContentHeight(o.id,t)}else if("change-font-size"===t){const t=z.current;if(t){const e=_(t,o,k.textSplitAllowed);e!==o.fontSize&&c.history.ignore(()=>{o.set({fontSize:e})})}}return}const{textOverflow:t,textSplitAllowed:e}=k,r=(t,e,r,n)=>{const i=v(`text ${o.id}`),a=()=>{c.history.ignore(t,e,r).then(()=>{$.current?(X.current.push(i),B()):i()})};n?queueMicrotask(a):a()};if(!W(o)){const t=dt();return void r(()=>{W(o)||o.set({height:t})},void 0,void 0,!0)}if(!c.isPlaying){if("change-font-size"!==t||V){if("resize"===t){const t=dt();nt&&o.height<t&&!V&&r(()=>{var e;C(o)&&o.set({height:t}),null===(e=z.current)||void 0===e||e.height(t)},!1,!0),nt||o.height===t||V||r(()=>{var e;C(o)&&o.set({height:t}),null===(e=z.current)||void 0===e||e.height(t)},!1,!0)}}else{const t=z.current,n=o.curveEnabled?o.fontSize:_(t,o,e);if(n!==o.fontSize){return void r(()=>{o.set(y(o,n))},!1,!0)}const i=dt();o.height===i||nt||r(()=>{o.set({height:i})},!1,!0)}}}),n.useLayoutEffect(()=>{var t;if(ut&&o.curveEnabled){const e=null===(t=F.current)||void 0===t?void 0:t.getSelfRect().width;if(e){const t=e-o.a.width,r=o.a.rotation*Math.PI/180,n=-t/2*Math.cos(r),i=-t/2*Math.sin(r);o.set({width:e,x:o.a.x+n,y:o.a.y+i})}}},[ut,o.curveEnabled,o.curvePower,o.text,o.fontSize,o.fontFamily,o.fontWeight,o.fontStyle,o.letterSpacing]),n.useLayoutEffect(()=>{const t=z.current;t&&(t.width(t.width()+1e-8),t.width(t.width()-1e-8),t._setTextData(),st())},[ut]);const ft=n.useRef(null),ht=n.useRef(o.width),gt=n.useRef(0),pt=t=>{t.evt.preventDefault();const e=c.selectedShapes.find(t=>t===o);e&&o.contentEditable&&(gt.current=function(t){var e;const r=t.target,n=function(t){var e=t.getAbsoluteTransform().copy();e.invert();var r=t.getStage().getPointerPosition();return e.point(r)}(r),o=r.textArr,i=Math.floor(n.y/(r.fontSize()*r.lineHeight())),a=o.slice(0,i).reduce((t,e)=>t+e.text.length,i),l=null!==(e=o[i])&&void 0!==e?e:o[0];let s=0;return"right"===r.align()?s=r.width()-l.width:"center"===r.align()&&(s=r.width()/2-l.width/2),a+Math.round((n.x-s)/l.width*l.text.length)}(t),o.toggleEditMode())},mt=Y(o.placeholder),xt=!ct&&mt?.6:o.a.opacity;L(z,xt);const wt=getLineHeight({fontLoaded:ut,fontFamily:o.fontFamily,fontSize:o.a.fontSize,lineHeight:o.lineHeight}),vt=o.selectable||c.role===w.ADMIN,yt=m(o),St=m(o,o.stroke,"stroke"),bt=n.useMemo(()=>o.backgroundEnabled?o.curveEnabled?function({width:t,height:e,padding:r=0,cornerRadius:n=0}){const o=-r,i=-r,a=t+r,l=e+r,s=f(`M ${o} ${i} L ${a} ${i} L ${a} ${l} L ${o} ${l} Z`);return h(s,n).path}({width:o.a.width,height:o.a.height,cornerRadius:o.backgroundCornerRadius*(o.a.fontSize*wt*.5),padding:o.backgroundPadding*(o.a.fontSize*wt*.5)}):function({lines:t,lineHeight:e,width:r,align:n="left",padding:o=0,cornerRadius:i=0}){const a=p({lines:t,lineHeight:e,width:r,align:n});return g({rects:a,padding:o,cornerRadius:i})}({lines:JSON.parse(JSON.stringify(at)),cornerRadius:o.backgroundCornerRadius*(o.a.fontSize*wt*.5),lineHeight:wt*o.a.fontSize,padding:o.backgroundPadding*(o.a.fontSize*wt*.5),width:o.a.width,align:o.align}):"",[o.backgroundEnabled,o.curveEnabled,o.backgroundCornerRadius,o.a.fontSize,o.a.height,wt,o.backgroundPadding,o.a.width,o.align,at]),Et=T();let zt=0;if(!o.curveEnabled){const t=at.length*wt*o.a.fontSize,e=D(o.a,t);"middle"===o.verticalAlign?zt=(e-t)/2:"bottom"===o.verticalAlign&&(zt=e-t)}const kt=o.curveEnabled?A(o.a.width,o.a.height,o.curvePower,o.a.fontSize):"",Ot=ut?'"'+o.fontFamily+'"':it===o.fontFamily?"Arial":'"'+it+'"',Rt=R(ct);return r(e,{children:[t(a,{ref:P,x:o.a.x,y:o.a.y,rotation:o.a.rotation,hideInExport:!o.showInExport,listening:!1,visible:o.backgroundEnabled,opacity:o.backgroundOpacity*xt,data:bt,fill:o.backgroundColor,offsetY:-zt}),t(a,{data:kt,stroke:d.stroke,strokeWidth:1,x:o.a.x,y:o.a.y,rotation:o.a.rotation,visible:!1}),t(s,Object.assign({ref:F,visible:o.curveEnabled,data:kt,text:ct||mt,listening:!1,align:"center",textBaseline:"middle",direction:Rt},yt,St,{strokeWidth:o.strokeWidth,lineJoin:M(o.strokeLineJoin),fillAfterStrokeEnabled:!0,fontSize:o.a.fontSize,fontFamily:`"${o.fontFamily}", "${it}"`,fontStyle:o.fontStyle+" "+o.fontWeight,textDecoration:o.textDecoration.trim(),letterSpacing:o.letterSpacing*o.a.fontSize,x:o.a.x,y:o.a.y,rotation:o.a.rotation,opacity:o._editModeEnabled?.3:xt,hideInExport:!o.showInExport,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity})),t(l,Object.assign({ref:z,id:o.selectable?o.id:void 0,name:o.selectable?"element":"",hideInExport:!o.showInExport,editModeEnabled:o._editModeEnabled,x:o.a.x,y:o.a.y,rotation:o.a.rotation,width:o.a.width,height:W(o.a)?o.a.height:void 0,text:ct||mt,direction:Rt},yt,St,{lineJoin:M(o.strokeLineJoin),strokeWidth:o.strokeWidth,fillAfterStrokeEnabled:!0,fontSize:o.a.fontSize,fontFamily:Ot,fontStyle:o.fontStyle+" "+o.fontWeight,textDecoration:o.textDecoration,align:o.align,verticalAlign:o.verticalAlign,draggable:Et?o.draggable&&et:o.draggable,preventDefault:!Et||et,opacity:o.curveEnabled?0:xt,visible:!o._editModeEnabled,ellipsis:"ellipsis"===k.textOverflow,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity,lineHeight:wt,letterSpacing:o.letterSpacing*o.a.fontSize,listening:!!o.selectable&&vt,onDragStart:()=>{Z(!0)},onDragMove:t=>{o.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{Z(!1),o.set({x:t.target.x(),y:t.target.y()})},onClick:pt,onTap:pt,onTransformStart:()=>{var t,e;q(!0);const r=z.current;G.current=r.height(),ht.current=o.a.width,ft.current=r.position(),K.current=r.rotation(),tt.current=r.height();const n=null===(t=r.getStage())||void 0===t?void 0:t.findOne("Transformer");Q.current=null!==(e=null==n?void 0:n.getActiveAnchor())&&void 0!==e?e:""},onTransform:t=>{var e,r,n;const i=t.target;null===(e=P.current)||void 0===e||e.setAttrs({x:i.x(),y:i.y(),rotation:i.rotation(),scale:i.scale()});const a=(null===(r=i.getStage())||void 0===r?void 0:r.findOne("Transformer")).getActiveAnchor();if("middle-left"===a||"middle-right"===a){const t=i.scaleX(),e=i.width()*t,r=E(ht.current,o.a.fontSize);let n=e;e<r&&(n=r,ft.current&&i.position(ft.current)),i.width(n),i.scaleX(1),i.scaleY(1);let a=dt();if("ellipsis"===k.textOverflow){a=G.current}else{const t=Math.max(a,G.current);i.height(t),o.set({height:i.height()})}const l=k.textVerticalResizeEnabled?Math.max(a,G.current):dt();o.set({x:i.x(),width:i.width(),rotation:i.rotation(),height:l}),i.skewX(0),i.skewY(0),st()}if("top-center"===a||"bottom-center"===a){const e="resize"===k.textOverflow?dt():wt*o.a.fontSize,r=t.target.height()*t.target.scaleY();if(r<e){if(t.target.height(e),ft.current){if("top-center"===Q.current){const r=K.current*Math.PI/180,n=tt.current-e;t.target.x(ft.current.x-n*Math.sin(r)),t.target.y(ft.current.y+n*Math.cos(r))}else{t.target.position(ft.current)}}}else{t.target.height(r)}t.target.scaleY(1),t.target.scaleX(1),t.target.rotation(K.current),t.target.skewX(0),t.target.skewY(0),tt.current=Math.max(e,r)}ft.current=t.target.position();const l=t.target.scaleX();null===(n=P.current)||void 0===n||n.setAttrs({scaleX:1,scaleY:1}),t.target.scaleX(1),t.target.scaleY(1),o.set({fontSize:o.a.fontSize*l,width:t.target.width()*l,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),height:t.target.height()*l,shadowBlur:o.shadowBlur*l,shadowOffsetX:o.shadowOffsetX*l,shadowOffsetY:o.shadowOffsetY*l,strokeWidth:o.strokeWidth*l})},onTransformEnd:t=>{var e;const r=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),o.set(Object.assign(Object.assign({},S(o,o.fontSize*r)),{width:Math.ceil(t.target.width()*r),x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),height:t.target.height()*r})),null===(e=P.current)||void 0===e||e.setAttrs({scaleX:1,scaleY:1}),q(!1)}})),I&&o.contentEditable&&t(i,{x:o.a.x,y:o.a.y,rotation:o.a.rotation,children:t(J,{textNodeRef:z,element:o,selectAll:N,cursorPosition:gt.current,onBlur:()=>{o.set(b(o)),o.toggleEditMode(!1)}})})]})});
@@ -1,5 +1,5 @@
1
- import React from "react";
2
- import type { StoreType, PageType } from "../ui-types.js";
1
+ import React from 'react';
2
+ import type { StoreType, PageType } from '../ui-types.js';
3
3
  export declare const Tooltip: (({ store, page, components, stageRef, tooltipSafeArea, }: {
4
4
  store: StoreType;
5
5
  page: PageType;
@@ -1 +1 @@
1
- import e from"react";import t from"konva";import{getClientRect as n}from"../utils/math.js";import{useWorkspaceStyle as o}from"./workspace-style.js";let r=({targetKonvaNodes:e,guideKonvaNode:t,distance:n,snapDirection:o})=>n<5;export const setSnapFilterFunc=e=>{r=e};function s(e,t){var n=[],o=[];e.vertical.forEach(e=>{t.vertical.forEach(t=>{var o=Math.abs(e.offset-t.guide);r({targetKonvaNodes:t.nodes,guideKonvaNode:e.node,distance:o,snapDirection:e.snap})&&n.push({lineGuide:e.offset,diff:o,snap:t.snap,offset:t.offset})})}),e.horizontal.forEach(e=>{t.horizontal.forEach(t=>{var n=Math.abs(e.offset-t.guide);r({targetKonvaNodes:t.nodes,guideKonvaNode:e.node,distance:n,snapDirection:e.snap})&&o.push({lineGuide:e.offset,diff:n,snap:t.snap,offset:t.offset})})});var s=[];const i=n.sort((e,t)=>e.diff-t.diff),a=o.sort((e,t)=>e.diff-t.diff);var d=i[0],c=a[0];return d&&i.filter(e=>Math.abs(e.diff-d.diff)<.1).forEach(e=>{s.push(Object.assign({orientation:"V"},e))}),c&&a.filter(e=>Math.abs(e.diff-c.diff)<.1).forEach(e=>{s.push(Object.assign({orientation:"H"},e))}),s}export const ensureDragOrder=()=>{if(0===t.DD._dragElements.size){return}const e=[...t.DD._dragElements.entries()],n=e.find(([e,n])=>n.node instanceof t.Transformer);n&&(e.splice(e.indexOf(n),1),e.unshift(n),t.DD._dragElements.clear(),e.forEach(([e,n])=>{t.DD._dragElements.set(e,n)}))};function i(e,n,o){return new t.Line({x:-e.x(),y:-e.y(),points:o,stroke:n.stroke,strokeWidth:n.strokeWidth,name:"guid-line",dash:n.dash})}function a(e,t,n){const o=null==e?void 0:e.children.find(e=>"line-guides"===e.name()),r=e.getStage();n.forEach(e=>{"H"===e.orientation?null==o||o.add(i(r,t,[-6e3,e.lineGuide,6e3,e.lineGuide])):"V"===e.orientation&&(null==o||o.add(i(r,t,[e.lineGuide,-6e3,e.lineGuide,6e3])))})}export function useSnap(r,f){const u=e.useRef(null),l=e.useRef(null),h=e.useRef(new Map),g=e.useRef(null),{snapGuideStyle:y}=o(),p=e.useRef(y);p.current=y;const x=e=>e.hasName("element")||e.hasName("page-background")||!u.current&&e.hasName("elements-area");function v(e){var t;const n=null===(t=r.current)||void 0===t?void 0:t.getStage(),o=[],s=[];return n.find(x).forEach(t=>{if(!(e.indexOf(t)>=0)){var n=t.getClientRect({skipShadow:!0,skipStroke:!0});o.push({offset:n.x,node:t,snap:"start"},{offset:n.x+n.width,node:t,snap:"end"},{offset:n.x+n.width/2,node:t,snap:"center"}),s.push({offset:n.y,node:t,snap:"start"},{offset:n.y+n.height,node:t,snap:"end"},{offset:n.y+n.height/2,node:t,snap:"center"})}}),{vertical:o,horizontal:s}}function m(e){var t;a(null===(t=r.current)||void 0===t?void 0:t.getLayer(),p.current,e)}const b=e=>{var o;const r=e.target.getLayer(),a=r.children.find(e=>"line-guides"===e.name());null==a||a.destroyChildren();const d=l.current;if((null===(o=e.evt)||void 0===o?void 0:o.shiftKey)&&d){const t=e.target.getAbsolutePosition();let n=t.x-d.x,o=t.y-d.y;const s=Math.abs(n),c=Math.abs(o);if(s>2.414*c){o=0}else if(c>2.414*s){n=0}else{const e=(s+c)/2;n=Math.sign(n)*e,o=Math.sign(o)*e}e.target.nodes().forEach(e=>{const t=h.current.get(e);t&&e.setAbsolutePosition({x:t.x+n,y:t.y+o})});const f=g.current;if(f&&(s>0||c>0)){const e=Math.sign(n),t=Math.sign(o);null==a||a.add(i(r.getStage(),p.current,[f.x-6e3*e,f.y-6e3*t,f.x+6e3*e,f.y+6e3*t]))}return}var c=v(e.target.nodes()),f=function(e){const o=e.__getNodeRect(),r=n(Object.assign(Object.assign({},o),{rotation:t.Util.radToDeg(o.rotation)})),s=e.getAbsolutePosition();return{vertical:[{guide:r.x,offset:s.x-r.x,snap:"start",nodes:e.nodes()},{guide:r.x+r.width/2,offset:s.x-r.x-r.width/2,snap:"center",nodes:e.nodes()},{guide:r.x+r.width,offset:s.x-r.x-r.width,snap:"end",nodes:e.nodes()}],horizontal:[{guide:r.y,offset:s.y-r.y,snap:"start",nodes:e.nodes()},{guide:r.y+r.height/2,offset:s.y-r.y-r.height/2,snap:"center",nodes:e.nodes()},{guide:r.y+r.height,offset:s.y-r.y-r.height,snap:"end",nodes:e.nodes()}]}}(e.target),u=s(c,f);if(!u.length){return}m(u);const y=e.target.getAbsolutePosition(),x=(e.target.nodes().map(e=>e.getAbsolutePosition()),Object.assign({},y));u.forEach(e=>{switch(e.snap){case"start":case"center":case"end":switch(e.orientation){case"V":x.x=e.lineGuide+e.offset;break;case"H":x.y=e.lineGuide+e.offset}}});const b=x.x-y.x,w=x.y-y.y;e.evt.ctrlKey||e.evt.metaKey||e.target.nodes().forEach(e=>{const t=e.getAbsolutePosition();e.setAbsolutePosition({x:t.x+b,y:t.y+w})})},w=(e,t,n)=>{var o;const i=r.current,a=i.getLayer().children.find(e=>"line-guides"===e.name());if(null==a||a.destroyChildren(),"rotater"===i.getActiveAnchor()){return t}const f=i.getActiveAnchor(),u=c[f],l=null===(o=i.findOne(`.${u}`))||void 0===o?void 0:o.getAbsolutePosition();if(!l){return t}const h={x:e.x-l.x,y:e.y-l.y},g=function(e,t){const n=d(e,t)/d(t,t);return{x:n*t.x,y:n*t.y}}({x:t.x-e.x,y:t.y-e.y},h);if(Math.sqrt(Math.pow(g.x,2)+Math.pow(g.y,2))>5){return t}const y={x:e.x+g.x,y:e.y+g.y};var p=s(v(i.nodes()),{vertical:[{guide:y.x,offset:0,snap:"start",nodes:i.nodes()}],horizontal:[{guide:y.y,offset:0,snap:"start",nodes:i.nodes()}]});if(!p.length){return t}if(m(p),n.ctrlKey||n.metaKey){return t}const x=[];if(p.forEach(e=>{const t=function(e,t,n){if("V"===n.orientation){const o=n.lineGuide;if(Math.abs(t.x-e.x)<1e-4){return null}const r=(t.y-e.y)/(t.x-e.x);return{x:o,y:r*o+(e.y-r*e.x)}}{const o=n.lineGuide;if(Math.abs(t.y-e.y)<1e-4){return null}const r=(t.y-e.y)/(t.x-e.x);return{x:(o-e.y)/r+e.x,y:o}}}(y,l,{orientation:e.orientation,lineGuide:e.lineGuide});t&&x.push(t)}),x.length>0){let e=x[0],t=Math.sqrt(Math.pow(y.x-e.x,2)+Math.pow(y.y-e.y,2));if(x.forEach(n=>{const o=Math.sqrt(Math.pow(y.x-n.x,2)+Math.pow(y.y-n.y,2));o<t&&(t=o,e=n)}),t<10){return e}}return y},M=e=>{if(l.current=null,h.current=new Map,g.current=null,!e.target){return}const t=e.target.getLayer(),n=t.children.find(e=>"line-guides"===e.name());null==n||n.destroyChildren(),t.batchDraw()};e.useEffect(()=>{r.current&&(r.current.anchorDragBoundFunc(w),r.current.on("dragstart",e=>{const t=r.current;if(t){l.current=t.getAbsolutePosition(),h.current=new Map(t.nodes().map(e=>[e,e.getAbsolutePosition()]));const e=t.getClientRect();g.current={x:e.x+e.width/2,y:e.y+e.height/2}}setTimeout(()=>{ensureDragOrder()})}),r.current.on("dragmove",b),r.current.on("dragend",M),r.current.on("transformend",M),r.current.on("transform",e=>{var t,n;e.evt.ctrlKey||e.evt.metaKey?null===(t=r.current)||void 0===t||t.rotationSnapTolerance(0):null===(n=r.current)||void 0===n||n.rotationSnapTolerance(5)}))},[])}export function useAnchorSnap(t,n,r){const{snapGuideStyle:i}=o(),d=e.useRef(i);d.current=i;const c=e=>e.hasName("element")||e.hasName("line-anchor")||e.hasName("page-background")||e.hasName("elements-area"),f=e=>{const o=e.target.getLayer().children.find(e=>"line-guides"===e.name());null==o||o.destroyChildren();var r,i=s(function(e){var n;const o=null===(n=t.current)||void 0===n?void 0:n.getStage();var r=[],s=[];return o.find(c).forEach(t=>{if(!(e.indexOf(t)>=0)){var n=t.getClientRect({skipShadow:!0,skipStroke:!0});t.hasName("line-anchor")&&(n={x:t.absolutePosition().x,y:t.absolutePosition().y,width:0,height:0}),r.push({offset:n.x,node:t,snap:"start"},{offset:n.x+n.width,node:t,snap:"end"},{offset:n.x+n.width/2,node:t,snap:"center"}),s.push({offset:n.y,node:t,snap:"start"},{offset:n.y+n.height,node:t,snap:"end"},{offset:n.y+n.height/2,node:t,snap:"center"})}}),{vertical:r,horizontal:s}}([e.target,...n.map(e=>e.current)]),{vertical:[{guide:(r=e.target).absolutePosition().x,offset:0,snap:"center",nodes:[r]}],horizontal:[{guide:r.absolutePosition().y,offset:0,snap:"center",nodes:[r]}]});if(!i.length){return}!function(e){var n;a(null===(n=t.current)||void 0===n?void 0:n.getLayer(),d.current,e)}(i);const f=e.target.getAbsolutePosition(),u=Object.assign({},f);i.forEach(e=>{switch(e.snap){case"start":case"center":case"end":switch(e.orientation){case"V":u.x=e.lineGuide+e.offset;break;case"H":u.y=e.lineGuide+e.offset}}});const l=u.x-f.x,h=u.y-f.y;if(!e.evt.ctrlKey&&!e.evt.metaKey){const t=e.target.getAbsolutePosition();e.target.absolutePosition({x:t.x+l,y:t.y+h})}},u=e=>{if(!e.target){return}const t=e.target.getLayer(),n=t.children.find(e=>"line-guides"===e.name());null==n||n.destroyChildren(),t.batchDraw()};e.useEffect(()=>{t.current&&(t.current.on("dragmove",f),t.current.on("dragend",u))},r)}function d(e,t){return e.x*t.x+e.y*t.y}const c={"top-left":"bottom-right","top-center":"bottom-center","top-right":"bottom-left","middle-right":"middle-left","bottom-right":"top-left","bottom-center":"top-center","bottom-left":"top-right","middle-left":"middle-right"};
1
+ import e from"react";import t from"konva";import{getClientRect as n}from"../utils/math.js";import{useWorkspaceStyle as o}from"./workspace-style.js";let r=({targetKonvaNodes:e,guideKonvaNode:t,distance:n,snapDirection:o})=>n<5;export const setSnapFilterFunc=e=>{r=e};function s(e,t){var n=[],o=[];e.vertical.forEach(e=>{t.vertical.forEach(t=>{var o=Math.abs(e.offset-t.guide);r({targetKonvaNodes:t.nodes,guideKonvaNode:e.node,distance:o,snapDirection:e.snap})&&n.push({lineGuide:e.offset,diff:o,snap:t.snap,offset:t.offset})})}),e.horizontal.forEach(e=>{t.horizontal.forEach(t=>{var n=Math.abs(e.offset-t.guide);r({targetKonvaNodes:t.nodes,guideKonvaNode:e.node,distance:n,snapDirection:e.snap})&&o.push({lineGuide:e.offset,diff:n,snap:t.snap,offset:t.offset})})});var s=[];const i=n.sort((e,t)=>e.diff-t.diff),a=o.sort((e,t)=>e.diff-t.diff);var d=i[0],c=a[0];return d&&i.filter(e=>Math.abs(e.diff-d.diff)<.1).forEach(e=>{s.push(Object.assign({orientation:"V"},e))}),c&&a.filter(e=>Math.abs(e.diff-c.diff)<.1).forEach(e=>{s.push(Object.assign({orientation:"H"},e))}),s}export const ensureDragOrder=()=>{if(0===t.DD._dragElements.size){return}const e=[...t.DD._dragElements.entries()],n=e.find(([e,n])=>n.node instanceof t.Transformer);n&&(e.splice(e.indexOf(n),1),e.unshift(n),t.DD._dragElements.clear(),e.forEach(([e,n])=>{t.DD._dragElements.set(e,n)}))};function i(e,n,o){return new t.Line({x:-e.x(),y:-e.y(),points:o,stroke:n.stroke,strokeWidth:n.strokeWidth,name:"guid-line",dash:n.dash})}function a(e,t,n){const o=null==e?void 0:e.children.find(e=>"line-guides"===e.name()),r=e.getStage();n.forEach(e=>{"H"===e.orientation?null==o||o.add(i(r,t,[-6e3,e.lineGuide,6e3,e.lineGuide])):"V"===e.orientation&&(null==o||o.add(i(r,t,[e.lineGuide,-6e3,e.lineGuide,6e3])))})}export function useSnap(r,f){const u=e.useRef(null),l=e.useRef(null),h=e.useRef(new Map),g=e.useRef(null),{snapGuideStyle:y}=o(),p=e.useRef(y);p.current=y;const x=e=>e.hasName("element")||e.hasName("page-background")||!u.current&&e.hasName("elements-area");function v(e){var t;const n=null===(t=r.current)||void 0===t?void 0:t.getStage(),o=[],s=[];return n.find(x).forEach(t=>{if(!(e.indexOf(t)>=0)){var n=t.getClientRect({skipShadow:!0,skipStroke:!0});o.push({offset:n.x,node:t,snap:"start"},{offset:n.x+n.width,node:t,snap:"end"},{offset:n.x+n.width/2,node:t,snap:"center"}),s.push({offset:n.y,node:t,snap:"start"},{offset:n.y+n.height,node:t,snap:"end"},{offset:n.y+n.height/2,node:t,snap:"center"})}}),{vertical:o,horizontal:s}}function m(e){var t;a(null===(t=r.current)||void 0===t?void 0:t.getLayer(),p.current,e)}const b=e=>{var o,r;const a=null===(o=e.target)||void 0===o?void 0:o.getLayer();if(!a){return}const d=a.children.find(e=>"line-guides"===e.name());null==d||d.destroyChildren();const c=l.current;if((null===(r=e.evt)||void 0===r?void 0:r.shiftKey)&&c){const t=e.target.getAbsolutePosition();let n=t.x-c.x,o=t.y-c.y;const r=Math.abs(n),s=Math.abs(o);if(r>2.414*s){o=0}else if(s>2.414*r){n=0}else{const e=(r+s)/2;n=Math.sign(n)*e,o=Math.sign(o)*e}e.target.nodes().forEach(e=>{const t=h.current.get(e);t&&e.setAbsolutePosition({x:t.x+n,y:t.y+o})});const f=g.current;if(f&&(r>0||s>0)){const e=Math.sign(n),t=Math.sign(o);null==d||d.add(i(a.getStage(),p.current,[f.x-6e3*e,f.y-6e3*t,f.x+6e3*e,f.y+6e3*t]))}return}var f=v(e.target.nodes()),u=function(e){const o=e.__getNodeRect(),r=n(Object.assign(Object.assign({},o),{rotation:t.Util.radToDeg(o.rotation)})),s=e.getAbsolutePosition();return{vertical:[{guide:r.x,offset:s.x-r.x,snap:"start",nodes:e.nodes()},{guide:r.x+r.width/2,offset:s.x-r.x-r.width/2,snap:"center",nodes:e.nodes()},{guide:r.x+r.width,offset:s.x-r.x-r.width,snap:"end",nodes:e.nodes()}],horizontal:[{guide:r.y,offset:s.y-r.y,snap:"start",nodes:e.nodes()},{guide:r.y+r.height/2,offset:s.y-r.y-r.height/2,snap:"center",nodes:e.nodes()},{guide:r.y+r.height,offset:s.y-r.y-r.height,snap:"end",nodes:e.nodes()}]}}(e.target),y=s(f,u);if(!y.length){return}m(y);const x=e.target.getAbsolutePosition(),b=(e.target.nodes().map(e=>e.getAbsolutePosition()),Object.assign({},x));y.forEach(e=>{switch(e.snap){case"start":case"center":case"end":switch(e.orientation){case"V":b.x=e.lineGuide+e.offset;break;case"H":b.y=e.lineGuide+e.offset}}});const w=b.x-x.x,M=b.y-x.y;e.evt.ctrlKey||e.evt.metaKey||e.target.nodes().forEach(e=>{const t=e.getAbsolutePosition();e.setAbsolutePosition({x:t.x+w,y:t.y+M})})},w=(e,t,n)=>{var o;const i=r.current;if(!i){return t}const a=i.getLayer();if(!a){return t}const f=a.children.find(e=>"line-guides"===e.name());if(null==f||f.destroyChildren(),"rotater"===i.getActiveAnchor()){return t}const u=i.getActiveAnchor(),l=c[u],h=null===(o=i.findOne(`.${l}`))||void 0===o?void 0:o.getAbsolutePosition();if(!h){return t}const g={x:e.x-h.x,y:e.y-h.y},y=function(e,t){const n=d(e,t)/d(t,t);return{x:n*t.x,y:n*t.y}}({x:t.x-e.x,y:t.y-e.y},g);if(Math.sqrt(Math.pow(y.x,2)+Math.pow(y.y,2))>5){return t}const p={x:e.x+y.x,y:e.y+y.y};var x=s(v(i.nodes()),{vertical:[{guide:p.x,offset:0,snap:"start",nodes:i.nodes()}],horizontal:[{guide:p.y,offset:0,snap:"start",nodes:i.nodes()}]});if(!x.length){return t}if(m(x),n.ctrlKey||n.metaKey){return t}const b=[];if(x.forEach(e=>{const t=function(e,t,n){if("V"===n.orientation){const o=n.lineGuide;if(Math.abs(t.x-e.x)<1e-4){return null}const r=(t.y-e.y)/(t.x-e.x);return{x:o,y:r*o+(e.y-r*e.x)}}{const o=n.lineGuide;if(Math.abs(t.y-e.y)<1e-4){return null}const r=(t.y-e.y)/(t.x-e.x);return{x:(o-e.y)/r+e.x,y:o}}}(p,h,{orientation:e.orientation,lineGuide:e.lineGuide});t&&b.push(t)}),b.length>0){let e=b[0],t=Math.sqrt(Math.pow(p.x-e.x,2)+Math.pow(p.y-e.y,2));if(b.forEach(n=>{const o=Math.sqrt(Math.pow(p.x-n.x,2)+Math.pow(p.y-n.y,2));o<t&&(t=o,e=n)}),t<10){return e}}return p},M=e=>{if(l.current=null,h.current=new Map,g.current=null,!e.target){return}const t=e.target.getLayer();if(!t){return}const n=t.children.find(e=>"line-guides"===e.name());null==n||n.destroyChildren(),t.batchDraw()};e.useEffect(()=>{r.current&&(r.current.anchorDragBoundFunc(w),r.current.on("dragstart",e=>{const t=r.current;if(t){l.current=t.getAbsolutePosition(),h.current=new Map(t.nodes().map(e=>[e,e.getAbsolutePosition()]));const e=t.getClientRect();g.current={x:e.x+e.width/2,y:e.y+e.height/2}}setTimeout(()=>{ensureDragOrder()})}),r.current.on("dragmove",b),r.current.on("dragend",M),r.current.on("transformend",M),r.current.on("transform",e=>{var t,n;e.evt.ctrlKey||e.evt.metaKey?null===(t=r.current)||void 0===t||t.rotationSnapTolerance(0):null===(n=r.current)||void 0===n||n.rotationSnapTolerance(5)}))},[])}export function useAnchorSnap(t,n,r){const{snapGuideStyle:i}=o(),d=e.useRef(i);d.current=i;const c=e=>e.hasName("element")||e.hasName("line-anchor")||e.hasName("page-background")||e.hasName("elements-area"),f=e=>{var o;const r=null===(o=e.target)||void 0===o?void 0:o.getLayer();if(!r){return}const i=r.children.find(e=>"line-guides"===e.name());null==i||i.destroyChildren();var f,u=function(e){var n;const o=null===(n=t.current)||void 0===n?void 0:n.getStage();var r=[],s=[];return o.find(c).forEach(t=>{if(!(e.indexOf(t)>=0)){var n=t.getClientRect({skipShadow:!0,skipStroke:!0});t.hasName("line-anchor")&&(n={x:t.absolutePosition().x,y:t.absolutePosition().y,width:0,height:0}),r.push({offset:n.x,node:t,snap:"start"},{offset:n.x+n.width,node:t,snap:"end"},{offset:n.x+n.width/2,node:t,snap:"center"}),s.push({offset:n.y,node:t,snap:"start"},{offset:n.y+n.height,node:t,snap:"end"},{offset:n.y+n.height/2,node:t,snap:"center"})}}),{vertical:r,horizontal:s}}([e.target,...n.map(e=>e.current)]),l=s(u,{vertical:[{guide:(f=e.target).absolutePosition().x,offset:0,snap:"center",nodes:[f]}],horizontal:[{guide:f.absolutePosition().y,offset:0,snap:"center",nodes:[f]}]});if(!l.length){return}!function(e){var n;a(null===(n=t.current)||void 0===n?void 0:n.getLayer(),d.current,e)}(l);const h=e.target.getAbsolutePosition(),g=Object.assign({},h);l.forEach(e=>{switch(e.snap){case"start":case"center":case"end":switch(e.orientation){case"V":g.x=e.lineGuide+e.offset;break;case"H":g.y=e.lineGuide+e.offset}}});const y=g.x-h.x,p=g.y-h.y;if(!e.evt.ctrlKey&&!e.evt.metaKey){const t=e.target.getAbsolutePosition();e.target.absolutePosition({x:t.x+y,y:t.y+p})}},u=e=>{if(!e.target){return}const t=e.target.getLayer();if(!t){return}const n=t.children.find(e=>"line-guides"===e.name());null==n||n.destroyChildren(),t.batchDraw()};e.useEffect(()=>{t.current&&(t.current.on("dragmove",f),t.current.on("dragend",u))},r)}function d(e,t){return e.x*t.x+e.y*t.y}const c={"top-left":"bottom-right","top-center":"bottom-center","top-right":"bottom-left","middle-right":"middle-left","bottom-right":"top-left","bottom-center":"top-center","bottom-left":"top-right","middle-left":"middle-right"};