polotno 4.14.1 → 4.15.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 (132) hide show
  1. package/blueprint/side-panel/select-video.d.ts +22 -2
  2. package/canvas/crop-overlay.d.ts +36 -7
  3. package/canvas/crop-overlay.js +1 -1
  4. package/canvas/drawing-layer.js +1 -1
  5. package/canvas/fade-overlay.js +1 -1
  6. package/canvas/figure-element.js +1 -1
  7. package/canvas/gif-element.js +1 -1
  8. package/canvas/hotkeys.d.ts +5 -5
  9. package/canvas/hotkeys.js +1 -1
  10. package/canvas/html-element.js +1 -1
  11. package/canvas/image-element.js +1 -1
  12. package/canvas/image-processing.d.ts +5 -0
  13. package/canvas/image-processing.js +1 -0
  14. package/canvas/image-tool-controls.d.ts +15 -0
  15. package/canvas/image-tool-controls.js +1 -0
  16. package/canvas/line-element.js +1 -1
  17. package/canvas/page-controls.js +1 -1
  18. package/canvas/page.js +1 -1
  19. package/canvas/parent-frame.d.ts +5 -0
  20. package/canvas/parent-frame.js +1 -0
  21. package/canvas/quill-font-formats.js +1 -1
  22. package/canvas/rect-control.d.ts +13 -0
  23. package/canvas/rect-control.js +1 -0
  24. package/canvas/render-tag-element.js +1 -1
  25. package/canvas/rich-editor.js +3 -3
  26. package/canvas/table-element.js +1 -1
  27. package/canvas/text-element/caret-color.js +1 -1
  28. package/canvas/text-element.js +1 -1
  29. package/canvas/tooltip.js +1 -1
  30. package/canvas/use-color.d.ts +4 -0
  31. package/canvas/use-color.js +1 -1
  32. package/canvas/video-element.js +1 -1
  33. package/canvas/workspace-canvas.js +1 -1
  34. package/config.d.ts +4 -0
  35. package/config.js +1 -1
  36. package/icons/registry.d.ts +2 -0
  37. package/icons/registry.js +1 -1
  38. package/image-tools/geometry.d.ts +20 -0
  39. package/image-tools/geometry.js +1 -0
  40. package/image-tools/host.d.ts +62 -0
  41. package/image-tools/host.js +1 -0
  42. package/image-tools/messages.d.ts +5 -0
  43. package/image-tools/messages.js +1 -0
  44. package/image-tools/operations.d.ts +22 -0
  45. package/image-tools/operations.js +1 -0
  46. package/image-tools/raster.d.ts +13 -0
  47. package/image-tools/raster.js +1 -0
  48. package/image-tools/sessions.d.ts +73 -0
  49. package/image-tools/sessions.js +1 -0
  50. package/image-tools/target.d.ts +37 -0
  51. package/image-tools/target.js +1 -0
  52. package/image-tools/types.d.ts +62 -0
  53. package/image-tools/types.js +1 -0
  54. package/model/crop-mode.d.ts +18 -20
  55. package/model/crop-mode.js +1 -1
  56. package/model/gif-model.d.ts +11 -1
  57. package/model/group-model.d.ts +43 -6
  58. package/model/group-model.js +1 -1
  59. package/model/history.d.ts +8 -0
  60. package/model/history.js +1 -1
  61. package/model/image-edit-state.d.ts +14 -0
  62. package/model/image-edit-state.js +1 -0
  63. package/model/image-model.d.ts +11 -1
  64. package/model/image-model.js +1 -1
  65. package/model/image-tools.d.ts +26 -0
  66. package/model/image-tools.js +1 -0
  67. package/model/page-model.d.ts +111 -12
  68. package/model/store.d.ts +26 -3
  69. package/model/store.js +1 -1
  70. package/model/svg-model.d.ts +2 -1
  71. package/model/text-model.d.ts +2 -0
  72. package/model/text-model.js +1 -1
  73. package/model/video-model.d.ts +11 -1
  74. package/package.json +20 -20
  75. package/polotno.bundle.js +165 -165
  76. package/primitives/toggle.js +1 -1
  77. package/side-panel/ai-images-panel.js +1 -1
  78. package/side-panel/background-panel.js +1 -1
  79. package/side-panel/effect-card.js +1 -1
  80. package/side-panel/effects-panel.js +1 -1
  81. package/side-panel/image-edit-panel.d.ts +11 -0
  82. package/side-panel/image-edit-panel.js +1 -0
  83. package/side-panel/photos-panel.js +1 -1
  84. package/side-panel/select-video.d.ts +22 -2
  85. package/side-panel/side-panel.d.ts +1 -0
  86. package/side-panel/side-panel.js +1 -1
  87. package/side-panel/upload-panel.js +1 -1
  88. package/toolbar/color-picker.js +1 -1
  89. package/toolbar/element-container.js +1 -1
  90. package/toolbar/html-toolbar.js +3 -3
  91. package/toolbar/image-remove-background-button.d.ts +1 -1
  92. package/toolbar/image-remove-background-button.js +1 -1
  93. package/toolbar/image-toolbar.d.ts +1 -0
  94. package/toolbar/image-toolbar.js +1 -1
  95. package/toolbar/image-tools.d.ts +43 -0
  96. package/toolbar/image-tools.js +1 -0
  97. package/toolbar/sketch.d.ts +4 -1
  98. package/toolbar/sketch.js +1 -1
  99. package/toolbar/stop-track.d.ts +28 -0
  100. package/toolbar/stop-track.js +1 -0
  101. package/toolbar/toolbar.js +1 -1
  102. package/toolbar/use-copy-style.js +1 -1
  103. package/ui.css +1 -1
  104. package/utils/api.d.ts +14 -0
  105. package/utils/api.js +1 -1
  106. package/utils/clipboard.d.ts +4 -0
  107. package/utils/errors.d.ts +1 -0
  108. package/utils/errors.js +1 -1
  109. package/utils/fade-gradient.d.ts +5 -6
  110. package/utils/fade-gradient.js +1 -1
  111. package/utils/flags.d.ts +7 -1
  112. package/utils/flags.js +1 -1
  113. package/utils/gradient-stops.d.ts +25 -0
  114. package/utils/gradient-stops.js +1 -0
  115. package/utils/image-edit.d.ts +37 -0
  116. package/utils/image-edit.js +1 -0
  117. package/utils/l10n.d.ts +35 -0
  118. package/utils/l10n.js +1 -1
  119. package/utils/luma.js +1 -1
  120. package/utils/px.d.ts +4 -0
  121. package/utils/px.js +1 -1
  122. package/utils/rich-text-html.d.ts +5 -0
  123. package/utils/rich-text-html.js +1 -1
  124. package/utils/stops.d.ts +17 -0
  125. package/utils/stops.js +1 -0
  126. package/utils/text-format-state.d.ts +3 -2
  127. package/utils/text-format-state.js +1 -1
  128. package/utils/text-format.d.ts +4 -1
  129. package/utils/text-format.js +1 -1
  130. package/utils/to-pptx.d.ts +1 -1
  131. package/utils/to-pptx.js +1 -1
  132. package/utils/validate-key.js +1 -1
package/canvas/tooltip.js CHANGED
@@ -1 +1 @@
1
- import{jsx as t,jsxs as e}from"react/jsx-runtime";import n from"react";import{observer as o}from"mobx-react-lite";import{Html as r}from"react-konva-utils";import{getTotalClientRect as l}from"../utils/math.js";import{extendToolbar as i}from"../toolbar/element-container.js";import{TextAiWrite as s}from"../toolbar/text-ai-write.js";import{flags as u}from"../utils/flags.js";import{DuplicateButton as a}from"../toolbar/duplicate-button.js";import{RemoveButton as c}from"../toolbar/remove-button.js";import{PositionPicker as d}from"../toolbar/position-picker.js";import{GroupButton as m}from"../toolbar/group-button.js";import{Navbar as v}from"../primitives/navbar.js";import{MAIN_TRANSFORMER_NAME as p}from"../utils/px.js";function f(t,e){return t.classList.contains(e)?t:t.parentElement?f(t.parentElement,e):null}const h=()=>null,g=({stage:t})=>{var e,n;return(null===(e=null==t?void 0:t.container())||void 0===e?void 0:e.closest(".polotno-workspace-container"))||(null===(n=null==t?void 0:t.container())||void 0===n?void 0:n.parentNode)};export const Tooltip=o(({store:o,page:b,components:x,stageRef:j,tooltipSafeArea:E})=>{var w,y;const N=o.selectedShapes.every(t=>t.page===b),I=n.useRef(null),O=n.useRef(null),[S,R]=n.useState(!1),[,C]=n.useReducer(t=>t+1,0),F=n.useCallback(t=>{var e,n;t?(I.current=t,null===(e=O.current)||void 0===e||e.disconnect(),O.current=new ResizeObserver(C),O.current.observe(t),C()):I.current&&!I.current.isConnected&&(I.current=null,null===(n=O.current)||void 0===n||n.disconnect(),O.current=null)},[]),k=o._hasCroppedImages;n.useEffect(()=>{var t,e,n;const o=()=>{R(!0)},r=()=>{R(!1)};null===(t=null==j?void 0:j.current)||void 0===t||t.on("dragstart",o),null===(e=null==j?void 0:j.current)||void 0===e||e.on("dragend",r);const l=null===(n=null==j?void 0:j.current)||void 0===n?void 0:n.findOne(`.${p}`);return null==l||l.on("transformstart",o),null==l||l.on("transformend",r),()=>{var t,e;null===(t=null==j?void 0:j.current)||void 0===t||t.off("dragstart",o),null===(e=null==j?void 0:j.current)||void 0===e||e.off("dragend",r),null==l||l.off("transformstart",o),null==l||l.off("transformend",r)}},[]),n.useEffect(()=>{if(!(null==j?void 0:j.current)){return}const t=f(j.current.content,"polotno-workspace-inner");if(!t){return}const e=()=>{o.selectedShapes.length&&C()};return t.addEventListener("scroll",e),()=>{t.removeEventListener("scroll",e)}},[]);const T=o.selectedElements.map(t=>t.id).join(",");if(n.useEffect(()=>{if(!T){return}const t=requestAnimationFrame(()=>C());return()=>cancelAnimationFrame(t)},[T]),0===o.selectedShapes.length){return null}if(S){return null}if(!N){return null}if(o.activePage!==b){return null}if(k){return null}const M=l(o.selectedShapes),P=(null==x?void 0:x.Position)||d,X=(null==x?void 0:x.Duplicate)||a,Y=(null==x?void 0:x.Remove)||c,A=(null==x?void 0:x.Group)||m,L=(null==x?void 0:x.Lock)||h,B=null===(w=o.selectedElements[0])||void 0===w?void 0:w.type,_=Object.assign(Object.assign({},u.aiTextEnabled?{TextAiWrite:s}:{}),x||{}),z=i({components:_,type:B,usedItems:[]}),J=!!(null===(y=I.current)||void 0===y?void 0:y.isConnected);return t(r,{parentNodeFunc:g,transformFunc:t=>{var e,n,o;const r=M.x+M.width/2,l=null===(e=null==j?void 0:j.current)||void 0===e?void 0:e.container(),i=(null==l?void 0:l.getBoundingClientRect())||{left:0,top:0,width:0,height:0,right:0,bottom:0,x:0,y:0,toJSON:()=>({})},s=null==l?void 0:l.closest(".polotno-workspace-container"),u=(null==s?void 0:s.getBoundingClientRect())||{left:0,top:0,width:Number.POSITIVE_INFINITY,height:Number.POSITIVE_INFINITY,right:0,bottom:0,x:0,y:0,toJSON:()=>({})},a=i.left-u.left,c=i.top-u.top,d=(null===(n=I.current)||void 0===n?void 0:n.isConnected)?I.current.getBoundingClientRect():null,m=(null==d?void 0:d.width)||0,v=(null==d?void 0:d.height)||34,p=((null==E?void 0:E.top)||0)+8,f=(null!==(o=null==E?void 0:E.bottom)&&void 0!==o?o:45)+8,h=c+t.y+M.y*t.scaleY,g=c+t.y+(M.y+M.height)*t.scaleY,b=Number.isFinite(u.height),x=p+v/2,w=u.height-f-v/2;let y=h-80;b&&(y=Math.max(x,y));let N=y+v/2<=h-48?y:g+80;b&&(N=Math.min(w,Math.max(x,N)));let O=a+t.x+r*t.scaleX,S=O-M.width*t.scaleX/2,R=O+M.width*t.scaleX/2;const C=Math.min(50,M.width/2*t.scaleX),F=R>=C&&S<=u.width-C,k=(null==E?void 0:E.left)||0,T=(null==E?void 0:E.right)||0;if(Number.isFinite(u.width)&&m>0&&F){const t=8+m/2+k,e=u.width-8-m/2-T;e>=t&&(O=Math.max(t,Math.min(O,e)))}return R<C&&(O-=m+8),S>u.width-C&&(O+=m+8),Object.assign(Object.assign({},t),{x:O,y:N,scaleX:1,scaleY:1})},divProps:{style:{pointerEvents:"none",position:"absolute",visibility:J?"visible":"hidden",zIndex:9}},children:t("div",{ref:F,className:"polotno-selection-tooltip",style:{pointerEvents:"none"},children:e(v,{floating:!0,height:34,className:"pn:gap-0.5 pn:bg-popover pn:px-0.5",style:{transform:"translate(-50%, -50%)",pointerEvents:"auto"},children:[z.map(e=>{const n=_[e];return t(n,{elements:o.selectedElements,element:o.selectedElements[0],store:o},e)}),t(A,{store:o}),t(L,{store:o}),t(X,{store:o}),t(Y,{store:o}),t(P,{store:o})]})})})});
1
+ import{jsx as e,jsxs as t}from"react/jsx-runtime";import n from"react";import{observer as o}from"mobx-react-lite";import{Html as r}from"react-konva-utils";import{getTotalClientRect as l}from"../utils/math.js";import{extendToolbar as i}from"../toolbar/element-container.js";import{TextAiWrite as s}from"../toolbar/text-ai-write.js";import{flags as u}from"../utils/flags.js";import{DuplicateButton as a}from"../toolbar/duplicate-button.js";import{RemoveButton as c}from"../toolbar/remove-button.js";import{PositionPicker as d}from"../toolbar/position-picker.js";import{GroupButton as m}from"../toolbar/group-button.js";import{Navbar as p}from"../primitives/navbar.js";import{MAIN_TRANSFORMER_NAME as v}from"../utils/px.js";function f(e,t){return e.classList.contains(t)?e:e.parentElement?f(e.parentElement,t):null}const h=()=>null,g=({stage:e})=>{var t,n;return(null===(t=null==e?void 0:e.container())||void 0===t?void 0:t.closest(".polotno-workspace-container"))||(null===(n=null==e?void 0:e.container())||void 0===n?void 0:n.parentNode)};export const Tooltip=o(({store:o,page:b,components:x,stageRef:E,tooltipSafeArea:j})=>{var w,y;const N=o.selectedShapes.every(e=>e.page===b),I=n.useRef(null),S=n.useRef(null),[O,R]=n.useState(!1),[,C]=n.useReducer(e=>e+1,0),F=n.useCallback(e=>{var t,n;e?(I.current=e,null===(t=S.current)||void 0===t||t.disconnect(),S.current=new ResizeObserver(C),S.current.observe(e),C()):I.current&&!I.current.isConnected&&(I.current=null,null===(n=S.current)||void 0===n||n.disconnect(),S.current=null)},[]),T=o._hasCroppedImages;n.useEffect(()=>{var e,t,n;const o=()=>{R(!0)},r=()=>{R(!1)};null===(e=null==E?void 0:E.current)||void 0===e||e.on("dragstart",o),null===(t=null==E?void 0:E.current)||void 0===t||t.on("dragend",r);const l=null===(n=null==E?void 0:E.current)||void 0===n?void 0:n.findOne(`.${v}`);return null==l||l.on("transformstart",o),null==l||l.on("transformend",r),()=>{var e,t;null===(e=null==E?void 0:E.current)||void 0===e||e.off("dragstart",o),null===(t=null==E?void 0:E.current)||void 0===t||t.off("dragend",r),null==l||l.off("transformstart",o),null==l||l.off("transformend",r)}},[]),n.useEffect(()=>{if(!(null==E?void 0:E.current)){return}const e=f(E.current.content,"polotno-workspace-inner");if(!e){return}const t=()=>{o.selectedShapes.length&&C()};return e.addEventListener("scroll",t),()=>{e.removeEventListener("scroll",t)}},[]);const k=o.selectedElements.map(e=>e.id).join(",");if(n.useEffect(()=>{if(!k){return}const e=requestAnimationFrame(()=>C());return()=>cancelAnimationFrame(e)},[k]),0===o.selectedShapes.length){return null}if(O){return null}if(!N){return null}if(o.activePage!==b){return null}if(T||o.activeTool||o.selectedShapes.some(e=>"pendingEdit"in e&&e.pendingEdit)){return null}const M=l(o.selectedShapes),P=(null==x?void 0:x.Position)||d,X=(null==x?void 0:x.Duplicate)||a,Y=(null==x?void 0:x.Remove)||c,A=(null==x?void 0:x.Group)||m,L=(null==x?void 0:x.Lock)||h,B=null===(w=o.selectedElements[0])||void 0===w?void 0:w.type,_=Object.assign(Object.assign({},u.aiTextEnabled?{TextAiWrite:s}:{}),x||{}),z=i({components:_,type:B,usedItems:[]}),J=!!(null===(y=I.current)||void 0===y?void 0:y.isConnected);return e(r,{parentNodeFunc:g,transformFunc:e=>{var t,n,o;const r=M.x+M.width/2,l=null===(t=null==E?void 0:E.current)||void 0===t?void 0:t.container(),i=(null==l?void 0:l.getBoundingClientRect())||{left:0,top:0,width:0,height:0,right:0,bottom:0,x:0,y:0,toJSON:()=>({})},s=null==l?void 0:l.closest(".polotno-workspace-container"),u=(null==s?void 0:s.getBoundingClientRect())||{left:0,top:0,width:Number.POSITIVE_INFINITY,height:Number.POSITIVE_INFINITY,right:0,bottom:0,x:0,y:0,toJSON:()=>({})},a=i.left-u.left,c=i.top-u.top,d=(null===(n=I.current)||void 0===n?void 0:n.isConnected)?I.current.getBoundingClientRect():null,m=(null==d?void 0:d.width)||0,p=(null==d?void 0:d.height)||34,v=((null==j?void 0:j.top)||0)+8,f=(null!==(o=null==j?void 0:j.bottom)&&void 0!==o?o:45)+8,h=c+e.y+M.y*e.scaleY,g=c+e.y+(M.y+M.height)*e.scaleY,b=Number.isFinite(u.height),x=v+p/2,w=u.height-f-p/2;let y=h-80;b&&(y=Math.max(x,y));let N=y+p/2<=h-48?y:g+80;b&&(N=Math.min(w,Math.max(x,N)));let S=a+e.x+r*e.scaleX,O=S-M.width*e.scaleX/2,R=S+M.width*e.scaleX/2;const C=Math.min(50,M.width/2*e.scaleX),F=R>=C&&O<=u.width-C,T=(null==j?void 0:j.left)||0,k=(null==j?void 0:j.right)||0;if(Number.isFinite(u.width)&&m>0&&F){const e=8+m/2+T,t=u.width-8-m/2-k;t>=e&&(S=Math.max(e,Math.min(S,t)))}return R<C&&(S-=m+8),O>u.width-C&&(S+=m+8),Object.assign(Object.assign({},e),{x:S,y:N,scaleX:1,scaleY:1})},divProps:{style:{pointerEvents:"none",position:"absolute",visibility:J?"visible":"hidden",zIndex:9}},children:e("div",{ref:F,className:"polotno-selection-tooltip",style:{pointerEvents:"none"},children:t(p,{floating:!0,height:34,className:"pn:gap-0.5 pn:bg-popover pn:px-0.5",style:{transform:"translate(-50%, -50%)",pointerEvents:"auto"},children:[z.map(t=>{const n=_[t];return e(n,{elements:o.selectedElements,element:o.selectedElements[0],store:o},t)}),e(A,{store:o}),e(L,{store:o}),e(X,{store:o}),e(Y,{store:o}),e(P,{store:o})]})})})});
@@ -5,6 +5,10 @@ type ColorElement = {
5
5
  height: number;
6
6
  fill?: string;
7
7
  };
8
+ export declare const withDisplayTextPaints: <T extends {
9
+ fill: string;
10
+ stroke: string;
11
+ }>(element: T) => T;
8
12
  export declare const useColor: (element: ColorElement, value?: string, propName?: string) => {
9
13
  [x: string]: string;
10
14
  fillLinearGradientStartPointX?: undefined;
@@ -1 +1 @@
1
- import t from"react";import*as i from"@polotno/core/gradient";import r from"konva";export const useColor=(o,a,n)=>{var e;return void 0===a&&(a=null!==(e=o.fill)&&void 0!==e?e:""),void 0===n&&(n="fill"),t.useMemo(()=>{if(!i.isGradient(a)){return{[n]:a}}const{stops:t,rotation:e}=i.parseColor(a),l=o.a.width/2,s=o.a.height/2,d=(e%180+180)%180,h=d>45&&d<135?o.a.width:o.a.height,f=r.Util.degToRad(e)-Math.PI/2,c=[];return t.forEach(({offset:t,color:i})=>{c.push(t,i)}),"fill"===n?{fillLinearGradientStartPointX:l-h/2*Math.cos(f),fillLinearGradientStartPointY:s-h/2*Math.sin(f),fillLinearGradientColorStops:c,fillLinearGradientEndPointX:l+h/2*Math.cos(f),fillLinearGradientEndPointY:s+h/2*Math.sin(f),fill:t[1].color,fillPriority:"linear-gradient"}:{strokeLinearGradientStartPointX:l-h/2*Math.cos(f),strokeLinearGradientStartPointY:s-h/2*Math.sin(f),strokeLinearGradientColorStops:c,strokeLinearGradientEndPointX:l+h/2*Math.cos(f),strokeLinearGradientEndPointY:s+h/2*Math.sin(f)}},[a,o.width,o.height])};
1
+ import t from"react";import*as i from"@polotno/core/gradient";import{containsCmykColor as o,toDisplayColor as r}from"@polotno/core/color";import n from"konva";export const withDisplayTextPaints=t=>o(t.fill)||o(t.stroke)?Object.assign(Object.assign({},t),{fill:r(t.fill),stroke:r(t.stroke)}):t;export const useColor=(o,a,e)=>{var l;return void 0===a&&(a=null!==(l=o.fill)&&void 0!==l?l:""),void 0===e&&(e="fill"),t.useMemo(()=>{if(!i.isGradient(a)){return{[e]:r(a)}}const{stops:t,rotation:l}=i.parseColor(a),s=o.a.width/2,d=o.a.height/2,f=(l%180+180)%180,h=f>45&&f<135?o.a.width:o.a.height,c=n.Util.degToRad(l)-Math.PI/2,p=[];return t.forEach(({offset:t,color:i})=>{p.push(t,i)}),"fill"===e?{fillLinearGradientStartPointX:s-h/2*Math.cos(c),fillLinearGradientStartPointY:d-h/2*Math.sin(c),fillLinearGradientColorStops:p,fillLinearGradientEndPointX:s+h/2*Math.cos(c),fillLinearGradientEndPointY:d+h/2*Math.sin(c),fill:t[1].color,fillPriority:"linear-gradient"}:{strokeLinearGradientStartPointX:s-h/2*Math.cos(c),strokeLinearGradientStartPointY:d-h/2*Math.sin(c),strokeLinearGradientColorStops:p,strokeLinearGradientEndPointX:s+h/2*Math.cos(c),strokeLinearGradientEndPointY:d+h/2*Math.sin(c)}},[a,o.width,o.height])};
@@ -1 +1 @@
1
- import{jsx as e,jsxs as t,Fragment as r}from"react/jsx-runtime";import{elementOpacity as i}from"./paint-opacity.js";import o from"react";import{observer as n}from"mobx-react-lite";import{isAlive as a}from"mobx-state-tree";import{nodeAutorun as s}from"../utils/mobx.js";import{Arc as d,Group as c,Image as h,Rect as l,Text as u}from"react-konva";import{ROLES as m}from"../model/store.js";import{DEFAULT_RETRIES as g,isDeterministicUrl as p,retryDelayMs as f}from"@polotno/core/retry";import v from"konva";import{useWorkspaceStyle as w}from"./workspace-style.js";import{incrementLoader as x,triggerLoadError as E}from"../utils/loader.js";import{polotnoError as y}from"@polotno/core/errors";import{getCropRect as M}from"@polotno/core/image";import*as L from"@polotno/core/svg";import{roundEnabledPx as b,activeAnchorOf as C,roundedCropFraction as T,roundedGeometryPx as k,roundedPosition as I,isCornerAnchor as R,scaledBoxStyleAttrs as j,roundedBoxStyleAttrs as S}from"../utils/px.js";import{useFilteredSource as P}from"./use-filtered-source.js";import{useEvent as A}from"../hooks/use-event.js";import{useFadeIn as O}from"./use-fadein.js";import{isTouchDevice as X}from"../utils/screen.js";import{createPlayGate as Y,playMedia as H}from"../utils/media.js";import{useMediabunnyVideo as W}from"./use-mediabunny-video.js";import{getElementTimeRange as _,getVideoRestMs as z}from"../utils/timeline.js";import{drawReduced as D,exportKernelEnabled as V,shouldResample as U,sourceSize as N}from"./downscale.js";import{trySetCanvasSize as Z}from"../utils/canvas.js";import{useClipImage as B}from"./image-element.js";import{CropOverlay as F,CROP_CORNER_ANCHORS as $}from"./crop-overlay.js";const q=new window.Image;q.src=L.svgToURL('\n <svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path opacity="0.6" d="M4 5.49683V18.5032C4 20.05 5.68077 21.0113 7.01404 20.227L18.0694 13.7239C19.384 12.9506 19.384 11.0494 18.0694 10.2761L7.01404 3.77296C5.68077 2.98869 4 3.95 4 5.49683Z" fill="white"/>\n <path d="M4 5.49683V18.5032C4 20.05 5.68077 21.0113 7.01404 20.227L18.0694 13.7239C19.384 12.9506 19.384 11.0494 18.0694 10.2761L7.01404 3.77296C5.68077 2.98869 4 3.95 4 5.49683Z" stroke="#323232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n');const G=new window.Image;G.src=L.svgToURL('\n <svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path opacity="0.6" d="M14 19L14 5C14 3.89543 14.8954 3 16 3L17 3C18.1046 3 19 3.89543 19 5L19 19C19 20.1046 18.1046 21 17 21L16 21C14.8954 21 14 20.1046 14 19Z" fill="white"/>\n <path opacity="0.6" d="M10 19L10 5C10 3.89543 9.10457 3 8 3L7 3C5.89543 3 5 3.89543 5 5L5 19C5 20.1046 5.89543 21 7 21L8 21C9.10457 21 10 20.1046 10 19Z" fill="white"/>\n <path d="M14 19L14 5C14 3.89543 14.8954 3 16 3L17 3C18.1046 3 19 3.89543 19 5L19 19C19 20.1046 18.1046 21 17 21L16 21C14.8954 21 14 20.1046 14 19Z" stroke="#323232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n <path d="M10 19L10 5C10 3.89543 9.10457 3 8 3L7 3C5.89543 3 5 3.89543 5 5L5 19C5 20.1046 5.89543 21 7 21L8 21C9.10457 21 10 20.1046 10 19Z" stroke="#323232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n');export const useCornerRadiusAndCrop=(e,t,r,i,n=0,a=!1)=>{var s;const d=Math.floor(Math.max(e.width*i,1)),c=Math.floor(Math.max(e.height*i,1)),h=Math.min(n*i,d/2,c/2),l=Math.max(e.width/r.width,e.height/r.height)*i,u=V(e.page)&&!a&&U(l,d,c),{width:m,height:g}=t?N(t):{},p=0===r.x&&0===r.y&&r.width===m&&r.height===g,f=o.useMemo(()=>{if(t&&m&&g){return p&&0===h&&!u?void 0:document.createElement("canvas")}},[t,h,u,p,m,g]),w=()=>{if(!f||!t){return}f.width=d,f.height=c;const e=f.getContext("2d");e&&(h&&(e.beginPath(),e.moveTo(h,0),e.lineTo(d-h,0),e.arc(d-h,h,h,3*Math.PI/2,0,!1),e.lineTo(d,c-h),e.arc(d-h,c-h,h,0,Math.PI/2,!1),e.lineTo(h,c),e.arc(h,c-h,h,Math.PI/2,Math.PI,!1),e.lineTo(0,h),e.arc(h,h,h,Math.PI,3*Math.PI/2,!1),e.clip()),u?D(e,t,r,f.width,f.height):e.drawImage(t,r.x,r.y,r.width,r.height,0,0,f.width,f.height))};return o.useLayoutEffect(()=>{w()},[f,e.width,e.height,r.x,r.y,r.width,r.height,n,i,a,null===(s=e.page)||void 0===s?void 0:s._exportingOrRendering,u]),o.useEffect(()=>()=>{f&&"CANVAS"===f.nodeName&&v.Util.releaseCanvas(f)},[f]),[f||t,w]};export const useClip=(e,t,r,i)=>{const[n,a]=B(e.clipSrc||""),s=e.clipSrc?a:"loaded";useLoader(s,e.clipSrc,e.id);const d=!!t&&!!n,c=o.useMemo(()=>d?{canvas:document.createElement("canvas"),mask:document.createElement("canvas"),width:0,height:0}:void 0,[d]),h=null==c?void 0:c.canvas;function l(){if(!c||!h||!t){return}const{width:i,height:o}=N(t);if(!i||!o){return}const n=Math.min(1e4,Math.max(i,Math.ceil(e.a.width*r),1)),a=Math.min(1e4,Math.max(o,Math.ceil(e.a.height*r),1));c.width===n&&c.height===a||(Z(h,n,a),c.width=n,c.height=a);const s=h.getContext("2d");s&&(s.clearRect(0,0,h.width,h.height),s.save(),s.drawImage(c.mask,0,0,h.width,h.height),s.globalCompositeOperation="source-in",s.drawImage(t,0,0,h.width,h.height),s.restore())}return o.useLayoutEffect(()=>{var t;if(!c||!(null==n?void 0:n.width)||!n.height){return}const i=Math.max(e.a.width/n.width*r,e.a.height/n.height*r);Z(c.mask,Math.min(1e4,Math.max(n.width*i,1)),Math.min(1e4,Math.max(n.height*i,1))),null===(t=c.mask.getContext("2d"))||void 0===t||t.drawImage(n,0,0,c.mask.width,c.mask.height)},[c,n,e.a.width,e.a.height,r]),o.useLayoutEffect(()=>{l()},[c,t,n,e.a.width,e.a.height,r,...i]),o.useEffect(()=>()=>{c&&v.Util.releaseCanvas(c.canvas,c.mask)},[c]),[d?h:t,l]};const J=document.createElement("canvas"),K=n(({element:r})=>{const n=Math.min(30,r.width/4,r.height/4),a=o.useRef(null);o.useEffect(()=>{const e=a.current;if(!e){return}const t=new v.Animation(t=>{e.rotate(((null==t?void 0:t.timeDiff)||0)/2)},e.getLayer());return t.start(),()=>{t.stop()}});const{mediaLoadingStyle:s}=w();return t(c,{x:r.a.x,y:r.a.y,rotation:r.a.rotation,listening:!1,opacity:i(r),hideInExport:!r.showInExport,children:[e(l,{width:r.width,height:r.height,fill:s.fill}),e(d,{ref:a,x:r.width/2,y:r.height/2,fill:s.textFill,outerRadius:Math.abs(n),innerRadius:Math.max(1,n-5),angle:270})]})}),Q=n(({element:r})=>{const{mediaErrorStyle:o}=w(),n=Math.max(10,Math.min(30,r.width/25));return t(c,{x:r.a.x,y:r.a.y,rotation:r.a.rotation,listening:!1,opacity:i(r),hideInExport:!r.showInExport,children:[e(l,{width:r.width,height:r.height,fill:o.fill}),e(u,{text:"Can not load the video...",fontSize:n,width:r.width,height:r.height,align:"center",fill:o.textFill,verticalAlign:"middle",padding:5})]})});let ee=function(e,t,r){const i=o.useRef("loading"),n=o.useRef(void 0),[a,s]=o.useState(0),d=o.useRef(void 0),c=o.useRef(void 0),h=o.useRef(void 0);return d.current===e&&c.current===t&&h.current===r||(i.current="loading",n.current=void 0,d.current=e,c.current=t,h.current=r),o.useLayoutEffect(()=>{if(!e){return}const o=p(e)?1:g;let a,d,c,h=0,l=!1,u=!1;const m=e=>{e&&(e.removeAttribute("src"),e.load())},v=()=>{h+=1;const g=document.createElement("video");function p(){l||(g.removeEventListener("canplay",p),u=!0,i.current="loaded",n.current=g,g.currentTime=0,s(Math.random()))}function w(e){var t;const r=4===g.readyState,c=g.buffered&&g.buffered.length>0&&g.buffered.end(g.buffered.length-1)/g.duration*100>=100;if(r&&c){return}if(l){return}if(!u&&h<o){return null==d||d(),m(g),void(a=setTimeout(v,f(h)))}const p=e.message||(null===(t=g.error)||void 0===t?void 0:t.message)||"Unknown error";console.error(new Error("Video failed to load: "+p)),i.current="failed",n.current=void 0,s(Math.random())}c=g,g.addEventListener("canplay",p),g.addEventListener("error",w),d=()=>{g.removeEventListener("canplay",p),g.removeEventListener("error",w)},t&&(g.crossOrigin=t),r&&(g.referrerPolicy=r),g.src=e,g.load()};return v(),()=>{l=!0,clearTimeout(a),null==d||d(),u||m(c)}},[e,t,r]),[n.current,i.current]};export const setVideoLoaderHook=e=>{ee=e};function te(e){return!e.seeking&&e.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA}export const useLoader=(e,t,r)=>{const i=o.useRef(void 0),n=()=>{var e;null===(e=i.current)||void 0===e||e.call(i),i.current=void 0};o.useEffect(()=>n,[]),o.useLayoutEffect(()=>{const o=t.slice(0,200),a=`video with id ${r} url: ${o}`;"loading"!==e||i.current||(i.current=x(a)),"loading"!==e&&n(),"failed"===e&&E(y("VIDEO_FAILED",a,{src:o,elementId:r,reason:"load"}))},[e])};export const VideoElement=n(({element:n,store:d})=>{var u,g,p;const[f,w]=o.useState(!1),E=o.useRef(null),y=n.isSelected,[D,V]=o.useState(!1),[U,Z]=ee(n.src,"anonymous"),[B,re]=o.useState(!1),ie=d.activePage===n.page,oe=(null===(u=n.page)||void 0===u?void 0:u._exportingOrRendering)&&"loaded"===Z,ne=W(n,d,oe);useLoader(Z,n.src,n.id),U&&(U.playsInline=!0);const ae=((e,t,r)=>{const i=o.useMemo(()=>{var i,o;const{flipX:n,flipY:a}=e,s="svg"===e.type||L.isSvgUrl(e.src),d=navigator.userAgent.toLowerCase().indexOf("firefox")>-1;if(!(n||a||d&&s)){return t}if(!t){return null}const{width:c,height:h}=N(t);if(!c||!h){return null}const l=document.createElement("canvas");let u=1;"svg"===e.type&&(u=Math.max(e.width/c*r,e.height/h*r)),l.width=Math.max(c*u,1),l.height=Math.max(h*u,1);let m=n?-l.width:0,g=a?-l.height:0;return null===(i=l.getContext("2d"))||void 0===i||i.scale(n?-1:1,a?-1:1),null===(o=l.getContext("2d"))||void 0===o||o.drawImage(t,m,g,l.width,l.height),l},[e.flipX,e.flipY,t,e.width,e.height,r]);return o.useEffect(()=>()=>{i&&"CANVAS"===i.nodeName&&v.Util.releaseCanvas(i)},[i]),i})(n,U,d._elementsPixelRatio),se=oe&&ne||ae||J,[de=J,ce]=P(n,se);o.useEffect(()=>{U&&d.history.ignore(()=>{n.set({duration:1e3*U.duration})})},[U]);const he=o.useMemo(Y,[U]);o.useEffect(()=>{var e;if(!U){return}const t=d.animatedElementsIds,r=(!t.length||t.includes(n.id))&&d.isPlaying;if(!ie||!r&&!D){return void U.pause()}D&&(U.muted=!1,U.currentTime=n.startTime*U.duration,H(U).then(e=>{"refused"===e&&V(!1)}));const i=new v.Animation(()=>{ke()},null===(e=E.current)||void 0===e?void 0:e.getLayer());i.start();const o=()=>{V(!1),U.currentTime=n.startTime*U.duration},a=()=>{U.currentTime>=n.endTime*U.duration&&(U.pause(),U.currentTime=n.startTime*U.duration,V(!1))};return U.addEventListener("ended",o),U.addEventListener("timeupdate",a),()=>{U.pause(),i.stop(),U.removeEventListener("ended",o),U.removeEventListener("timeupdate",a)}},[U,D,d.isPlaying,ie]),o.useEffect(()=>{U&&(U.volume=n.volume)},[U,n.volume]),o.useEffect(()=>{U&&(U.playbackRate=n.speed,U.preservesPitch=!1)},[U,n.speed]);const le=o.useRef(null);o.useEffect(()=>{const e=s(n,()=>{var e,t;if(U){if(oe&&ne){return ke(),void d.currentTime}const r=d.animatedElementsIds;if(r.length&&!r.includes(n.id)){return}const i=d.activePage===n.page,o=d.currentTime>=n.page.startTime&&d.currentTime<n.page.startTime+n.page.duration,a=n.startTime*U.duration*1e3,s=U.duration*(n.endTime-n.startTime)*1e3,{start:c,end:h}=_(n.animations,n.page.duration),l=(d.currentTime||n.page.startTime)-n.page.startTime,u=o?z(d.currentTime,n.page.startTime,c,s,a,n.speed):0,m=u/1e3,g=o&&l>=c&&l<h;D||(U.muted=!g,g&&d.isPlaying&&i?U.paused?(U.currentTime=m,he.play(U)):Math.abs(1e3*U.currentTime-u)>500&&(U.currentTime=m):(he.reset(),U.paused||U.pause(),m!==U.currentTime&&(U.currentTime=m),!te(U)&&!d.isPlaying&&!le.current&&(le.current=x(`video ${n.id}`)))),ke(),null===(t=null===(e=E.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()}});return()=>{e(),le.current&&(le.current(),le.current=null)}},[d,U,oe,ne,D]),o.useEffect(()=>{var e,t;if(!U){return}if(oe){return null===(e=le.current)||void 0===e||e.call(le),void(le.current=null)}const r=()=>{var e;te(U)&&(ke(),null===(e=le.current)||void 0===e||e.call(le),le.current=null)};let i;return(null===(t=n.page)||void 0===t?void 0:t._exportingOrRendering)&&(i=setInterval(r,20)),U.addEventListener("timeupdate",r),U.addEventListener("canplay",r),U.addEventListener("seeked",r),()=>{clearInterval(i),U.removeEventListener("timeupdate",r),U.removeEventListener("canplay",r),U.removeEventListener("seeked",r)}},[null===(g=n.page)||void 0===g?void 0:g._exportingOrRendering,U,n.id,x,oe]);let{cropX:ue,cropY:me,cropWidth:ge,cropHeight:pe}=n;"loaded"!==Z&&(ue=me=0,ge=pe=1);const{width:fe,height:ve}=N(de),we=M({stretchEnabled:n.stretchEnabled,cropX:ue,cropY:me,cropWidth:ge,cropHeight:pe,width:n.a.width,height:n.a.height},{width:fe,height:ve}),xe=we.width,Ee=we.height,ye=n.stretchEnabled,Me=null!==(p=n.cornerRadius)&&void 0!==p?p:0,[Le,be]=useCornerRadiusAndCrop(n,de,we,d._elementsPixelRatio,Me,!0);let[Ce,Te]=useClip(n,Le,d._elementsPixelRatio,[we,Me,d._elementsPixelRatio]);const ke=A(()=>{var e,t;ce(),be(),Te(),null===(t=null===(e=E.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()});o.useEffect(()=>{ke()});const Ie=()=>{n._cropEnabled&&setTimeout(()=>{a(n)&&n.toggleCropMode(!0)})},Re="loading"===Z,je="failed"===Z,Se=!Re&&!je,Pe=o.useRef({cropX:0,cropY:0,cropWidth:0,cropHeight:0}),Ae=o.useRef(!1),Oe=Se?i(n):0;O(E,Oe);const Xe=n.selectable||d.role===m.ADMIN,Ye=X();return e(r,{children:t(c,{onMouseEnter:()=>re(!0),onMouseLeave:()=>re(!1),children:[Re&&e(K,{element:n}),je&&e(Q,{element:n}),e(h,{ref:E,name:"element",id:n.id,image:Ce,x:n.a.x,y:n.a.y,width:n.a.width||1,height:n.a.height||1,rotation:n.a.rotation,opacity:Oe,shadowEnabled:n.shadowEnabled,shadowBlur:n.shadowBlur,shadowOffsetX:n.shadowOffsetX,shadowOffsetY:n.shadowOffsetY,shadowColor:n.shadowColor,shadowOpacity:n.shadowOpacity,customCrop:we,listening:Xe,draggable:Ye?n.draggable&&y:n.draggable,preventDefault:!Ye||y,hideInExport:!n.showInExport,onDragMove:e=>{n.set({x:e.target.x(),y:e.target.y()})},onDragEnd:e=>{n.set(I(e.target))},onDblClick:Ie,onDblTap:Ie,onTransformStart:e=>{w(!0),Ae.current=R(C(e.target)),Pe.current={cropX:n.cropX,cropY:n.cropY,cropWidth:n.cropWidth,cropHeight:n.cropHeight}},onTransform:e=>{const t=e.currentTarget,r=Math.abs(t.scaleX()-1)<1e-7?1:t.scaleX(),i=Math.abs(t.scaleY()-1)<1e-7?1:t.scaleY();t.scaleX(1),t.scaleY(1);const o=1-xe/fe,a=Math.min(o,Math.max(0,n.cropX)),s=1-Ee/ve,d=Math.min(s,Math.max(0,n.cropY)),c=Ae.current,h=!c&&r<1&&Pe.current.cropHeight>Ee/ve;let l=c?n.cropWidth:n.cropWidth*r;h&&(l=n.cropWidth);const u=!c&&i<1&&Pe.current.cropWidth>xe/fe;let m=c?n.cropHeight:n.cropHeight*i;u&&(m=n.cropHeight),ye&&(l=n.cropWidth,m=n.cropHeight);const g=c?Math.min(r,i):1;n.set(Object.assign({cropX:a,cropY:d,x:t.x(),y:t.y(),width:t.width()*r,height:t.height()*i,rotation:e.target.rotation(),cropWidth:Math.min(l,1-a),cropHeight:Math.min(m,1-d)},1!==g&&Object.assign(Object.assign({},j(n,g)),{borderSize:n.borderSize*g})))},onTransformEnd:e=>{const t=e.currentTarget;n.set(Object.assign(Object.assign({width:k(t.width()),height:k(t.height()),x:k(t.x()),y:k(t.y()),rotation:k(e.target.rotation()),cropX:T(n.cropX),cropY:T(n.cropY),cropWidth:T(xe/fe),cropHeight:T(Ee/ve)},S(n)),{borderSize:b(n.borderSize)})),w(!1)}}),e(l,{x:n.a.x,y:n.a.y,width:Math.max(n.a.width-n.borderSize,0),height:Math.max(n.a.height-n.borderSize,0),opacity:Oe,offsetX:-n.borderSize/2,offsetY:-n.borderSize/2,stroke:n.borderColor,strokeWidth:n.borderSize,listening:!1,visible:!!n.borderSize,rotation:n.rotation,cornerRadius:Math.max(0,Me-n.borderSize),hideInExport:!n.showInExport}),!d.isPlaying&&e(h,{image:D?B||Ye?G:void 0:q,x:n.a.x,y:n.a.y,offsetX:-n.a.width/2+15/d.scale,offsetY:-n.a.height/2+15/d.scale,rotation:n.a.rotation,width:30/d.scale,height:30/d.scale,hideInExport:!0,onClick:()=>V(!D),onTap:()=>V(!D)}),n._cropModeEnabled&&e(F,{element:n,store:d,previewImage:Ce,sourceImage:de,sourceWidth:fe,sourceHeight:ve,cropAbsoluteWidth:xe,cropAbsoluteHeight:Ee,innerAnchors:$})]})})});
1
+ import{jsx as e,jsxs as t,Fragment as r}from"react/jsx-runtime";import{elementOpacity as i}from"./paint-opacity.js";import o from"react";import{toDisplayColor as n}from"@polotno/core/color";import{observer as a}from"mobx-react-lite";import{isAlive as s}from"mobx-state-tree";import{nodeAutorun as d}from"../utils/mobx.js";import{Arc as c,Group as h,Image as l,Rect as u,Text as m}from"react-konva";import{ROLES as p}from"../model/store.js";import{DEFAULT_RETRIES as g,isDeterministicUrl as f,retryDelayMs as v}from"@polotno/core/retry";import w from"konva";import{useWorkspaceStyle as x}from"./workspace-style.js";import{incrementLoader as E,triggerLoadError as y}from"../utils/loader.js";import{polotnoError as M}from"@polotno/core/errors";import{getCropRect as L}from"@polotno/core/image";import*as b from"@polotno/core/svg";import{roundEnabledPx as T,activeAnchorOf as C,roundedCropFraction as k,roundedGeometryPx as I,roundedPosition as R,isCornerAnchor as j,scaledBoxStyleAttrs as S,roundedBoxStyleAttrs as P}from"../utils/px.js";import{useFilteredSource as H}from"./use-filtered-source.js";import{useEvent as O}from"../hooks/use-event.js";import{useFadeIn as X}from"./use-fadein.js";import{isTouchDevice as Y}from"../utils/screen.js";import{createPlayGate as A,playMedia as W}from"../utils/media.js";import{useMediabunnyVideo as z}from"./use-mediabunny-video.js";import{getElementTimeRange as _,getVideoRestMs as D}from"../utils/timeline.js";import{drawReduced as V,exportKernelEnabled as U,shouldResample as Z,sourceSize as B}from"./downscale.js";import{trySetCanvasSize as F}from"../utils/canvas.js";import{useClipImage as N}from"./image-element.js";import{CropOverlay as $,CROP_CORNER_ANCHORS as q}from"./crop-overlay.js";const G=new window.Image;G.src=b.svgToURL('\n <svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path opacity="0.6" d="M4 5.49683V18.5032C4 20.05 5.68077 21.0113 7.01404 20.227L18.0694 13.7239C19.384 12.9506 19.384 11.0494 18.0694 10.2761L7.01404 3.77296C5.68077 2.98869 4 3.95 4 5.49683Z" fill="white"/>\n <path d="M4 5.49683V18.5032C4 20.05 5.68077 21.0113 7.01404 20.227L18.0694 13.7239C19.384 12.9506 19.384 11.0494 18.0694 10.2761L7.01404 3.77296C5.68077 2.98869 4 3.95 4 5.49683Z" stroke="#323232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n');const J=new window.Image;J.src=b.svgToURL('\n <svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path opacity="0.6" d="M14 19L14 5C14 3.89543 14.8954 3 16 3L17 3C18.1046 3 19 3.89543 19 5L19 19C19 20.1046 18.1046 21 17 21L16 21C14.8954 21 14 20.1046 14 19Z" fill="white"/>\n <path opacity="0.6" d="M10 19L10 5C10 3.89543 9.10457 3 8 3L7 3C5.89543 3 5 3.89543 5 5L5 19C5 20.1046 5.89543 21 7 21L8 21C9.10457 21 10 20.1046 10 19Z" fill="white"/>\n <path d="M14 19L14 5C14 3.89543 14.8954 3 16 3L17 3C18.1046 3 19 3.89543 19 5L19 19C19 20.1046 18.1046 21 17 21L16 21C14.8954 21 14 20.1046 14 19Z" stroke="#323232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n <path d="M10 19L10 5C10 3.89543 9.10457 3 8 3L7 3C5.89543 3 5 3.89543 5 5L5 19C5 20.1046 5.89543 21 7 21L8 21C9.10457 21 10 20.1046 10 19Z" stroke="#323232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n');export const useCornerRadiusAndCrop=(e,t,r,i,n=0,a=!1)=>{var s;const d=Math.floor(Math.max(e.width*i,1)),c=Math.floor(Math.max(e.height*i,1)),h=Math.min(n*i,d/2,c/2),l=Math.max(e.width/r.width,e.height/r.height)*i,u=U(e.page)&&!a&&Z(l,d,c),{width:m,height:p}=t?B(t):{},g=0===r.x&&0===r.y&&r.width===m&&r.height===p,f=o.useMemo(()=>{if(t&&m&&p){return g&&0===h&&!u?void 0:document.createElement("canvas")}},[t,h,u,g,m,p]),v=()=>{if(!f||!t){return}f.width=d,f.height=c;const e=f.getContext("2d");e&&(h&&(e.beginPath(),e.moveTo(h,0),e.lineTo(d-h,0),e.arc(d-h,h,h,3*Math.PI/2,0,!1),e.lineTo(d,c-h),e.arc(d-h,c-h,h,0,Math.PI/2,!1),e.lineTo(h,c),e.arc(h,c-h,h,Math.PI/2,Math.PI,!1),e.lineTo(0,h),e.arc(h,h,h,Math.PI,3*Math.PI/2,!1),e.clip()),u?V(e,t,r,f.width,f.height):e.drawImage(t,r.x,r.y,r.width,r.height,0,0,f.width,f.height))};return o.useLayoutEffect(()=>{v()},[f,e.width,e.height,r.x,r.y,r.width,r.height,n,i,a,null===(s=e.page)||void 0===s?void 0:s._exportingOrRendering,u]),o.useEffect(()=>()=>{f&&"CANVAS"===f.nodeName&&w.Util.releaseCanvas(f)},[f]),[f||t,v]};export const useClip=(e,t,r,i)=>{const[n,a]=N(e.clipSrc||""),s=e.clipSrc?a:"loaded";useLoader(s,e.clipSrc,e.id);const d=!!t&&!!n,c=o.useMemo(()=>d?{canvas:document.createElement("canvas"),mask:document.createElement("canvas"),width:0,height:0}:void 0,[d]),h=null==c?void 0:c.canvas;function l(){if(!c||!h||!t){return}const{width:i,height:o}=B(t);if(!i||!o){return}const n=Math.min(1e4,Math.max(i,Math.ceil(e.a.width*r),1)),a=Math.min(1e4,Math.max(o,Math.ceil(e.a.height*r),1));c.width===n&&c.height===a||(F(h,n,a),c.width=n,c.height=a);const s=h.getContext("2d");s&&(s.clearRect(0,0,h.width,h.height),s.save(),s.drawImage(c.mask,0,0,h.width,h.height),s.globalCompositeOperation="source-in",s.drawImage(t,0,0,h.width,h.height),s.restore())}return o.useLayoutEffect(()=>{var t;if(!c||!(null==n?void 0:n.width)||!n.height){return}const i=Math.max(e.a.width/n.width*r,e.a.height/n.height*r);F(c.mask,Math.min(1e4,Math.max(n.width*i,1)),Math.min(1e4,Math.max(n.height*i,1))),null===(t=c.mask.getContext("2d"))||void 0===t||t.drawImage(n,0,0,c.mask.width,c.mask.height)},[c,n,e.a.width,e.a.height,r]),o.useLayoutEffect(()=>{l()},[c,t,n,e.a.width,e.a.height,r,...i]),o.useEffect(()=>()=>{c&&w.Util.releaseCanvas(c.canvas,c.mask)},[c]),[d?h:t,l]};const K=document.createElement("canvas"),Q=a(({element:r})=>{const n=Math.min(30,r.width/4,r.height/4),a=o.useRef(null);o.useEffect(()=>{const e=a.current;if(!e){return}const t=new w.Animation(t=>{e.rotate(((null==t?void 0:t.timeDiff)||0)/2)},e.getLayer());return t.start(),()=>{t.stop()}});const{mediaLoadingStyle:s}=x();return t(h,{x:r.a.x,y:r.a.y,rotation:r.a.rotation,listening:!1,opacity:i(r),hideInExport:!r.showInExport,children:[e(u,{width:r.width,height:r.height,fill:s.fill}),e(c,{ref:a,x:r.width/2,y:r.height/2,fill:s.textFill,outerRadius:Math.abs(n),innerRadius:Math.max(1,n-5),angle:270})]})}),ee=a(({element:r})=>{const{mediaErrorStyle:o}=x(),n=Math.max(10,Math.min(30,r.width/25));return t(h,{x:r.a.x,y:r.a.y,rotation:r.a.rotation,listening:!1,opacity:i(r),hideInExport:!r.showInExport,children:[e(u,{width:r.width,height:r.height,fill:o.fill}),e(m,{text:"Can not load the video...",fontSize:n,width:r.width,height:r.height,align:"center",fill:o.textFill,verticalAlign:"middle",padding:5})]})});let te=function(e,t,r){const i=o.useRef("loading"),n=o.useRef(void 0),[a,s]=o.useState(0),d=o.useRef(void 0),c=o.useRef(void 0),h=o.useRef(void 0);return d.current===e&&c.current===t&&h.current===r||(i.current="loading",n.current=void 0,d.current=e,c.current=t,h.current=r),o.useLayoutEffect(()=>{if(!e){return}const o=f(e)?1:g;let a,d,c,h=0,l=!1,u=!1;const m=e=>{e&&(e.removeAttribute("src"),e.load())},p=()=>{h+=1;const g=document.createElement("video");function f(){l||(g.removeEventListener("canplay",f),u=!0,i.current="loaded",n.current=g,g.currentTime=0,s(Math.random()))}function w(e){var t;const r=4===g.readyState,c=g.buffered&&g.buffered.length>0&&g.buffered.end(g.buffered.length-1)/g.duration*100>=100;if(r&&c){return}if(l){return}if(!u&&h<o){return null==d||d(),m(g),void(a=setTimeout(p,v(h)))}const f=e.message||(null===(t=g.error)||void 0===t?void 0:t.message)||"Unknown error";console.error(new Error("Video failed to load: "+f)),i.current="failed",n.current=void 0,s(Math.random())}c=g,g.addEventListener("canplay",f),g.addEventListener("error",w),d=()=>{g.removeEventListener("canplay",f),g.removeEventListener("error",w)},t&&(g.crossOrigin=t),r&&(g.referrerPolicy=r),g.src=e,g.load()};return p(),()=>{l=!0,clearTimeout(a),null==d||d(),u||m(c)}},[e,t,r]),[n.current,i.current]};export const setVideoLoaderHook=e=>{te=e};function re(e){return!e.seeking&&e.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA}export const useLoader=(e,t,r)=>{const i=o.useRef(void 0),n=()=>{var e;null===(e=i.current)||void 0===e||e.call(i),i.current=void 0};o.useEffect(()=>n,[]),o.useLayoutEffect(()=>{const o=t.slice(0,200),a=`video with id ${r} url: ${o}`;"loading"!==e||i.current||(i.current=E(a)),"loading"!==e&&n(),"failed"===e&&y(M("VIDEO_FAILED",a,{src:o,elementId:r,reason:"load"}))},[e])};export const VideoElement=a(({element:a,store:c})=>{var m,g,f,v,x;const[y,M]=o.useState(!1),b=o.useRef(null),V=a.isSelected,[U,Z]=o.useState(!1),[F,N]=te(a.src,"anonymous"),[ie,oe]=o.useState(!1),ne=c.activePage===a.page,ae=(null===(m=a.page)||void 0===m?void 0:m._exportingOrRendering)&&"loaded"===N,se=z(a,c,ae);useLoader(N,a.src,a.id),F&&(F.playsInline=!0);const de=ae&&se||F,[ce,he]=((e,t)=>{const{flipX:r,flipY:i}=e,{width:n,height:a}=t?B(t):{},s=e=>{if(!t){return}const o=e.getContext("2d");o&&(o.clearRect(0,0,e.width,e.height),o.save(),o.scale(r?-1:1,i?-1:1),o.drawImage(t,r?-e.width:0,i?-e.height:0,e.width,e.height),o.restore())},d=o.useMemo(()=>{if(!r&&!i||!n||!a){return}const e=document.createElement("canvas");return e.width=n,e.height=a,s(e),e},[r,i,t,n,a]);return o.useEffect(()=>()=>{d&&w.Util.releaseCanvas(d)},[d]),[d||t,()=>{d&&s(d)}]})(a,de),[le=K,ue]=H(a,ce||K);o.useEffect(()=>{F&&c.history.ignore(()=>{a.set({duration:1e3*F.duration})})},[F]);const me=o.useMemo(A,[F]);o.useEffect(()=>{var e;if(!F){return}const t=c.animatedElementsIds,r=(!t.length||t.includes(a.id))&&c.isPlaying;if(!ne||!r&&!U){return void F.pause()}U&&(F.muted=!1,F.currentTime=a.startTime*F.duration,W(F).then(e=>{"refused"===e&&Z(!1)}));const i=new w.Animation(()=>{Pe()},null===(e=b.current)||void 0===e?void 0:e.getLayer());i.start();const o=()=>{Z(!1),F.currentTime=a.startTime*F.duration},n=()=>{F.currentTime>=a.endTime*F.duration&&(F.pause(),F.currentTime=a.startTime*F.duration,Z(!1))};return F.addEventListener("ended",o),F.addEventListener("timeupdate",n),()=>{F.pause(),i.stop(),F.removeEventListener("ended",o),F.removeEventListener("timeupdate",n)}},[F,U,c.isPlaying,ne]),o.useEffect(()=>{F&&(F.volume=a.volume)},[F,a.volume]),o.useEffect(()=>{F&&(F.playbackRate=a.speed,F.preservesPitch=!1)},[F,a.speed]);const pe=o.useRef(null);o.useEffect(()=>{const e=d(a,()=>{var e,t;if(F){if(ae&&se){return Pe(),void c.currentTime}const r=c.animatedElementsIds;if(r.length&&!r.includes(a.id)){return}const i=c.activePage===a.page,o=c.currentTime>=a.page.startTime&&c.currentTime<a.page.startTime+a.page.duration,n=a.startTime*F.duration*1e3,s=F.duration*(a.endTime-a.startTime)*1e3,{start:d,end:h}=_(a.animations,a.page.duration),l=(c.currentTime||a.page.startTime)-a.page.startTime,u=o?D(c.currentTime,a.page.startTime,d,s,n,a.speed):0,m=u/1e3,p=o&&l>=d&&l<h;U||(F.muted=!p,p&&c.isPlaying&&i?F.paused?(F.currentTime=m,me.play(F)):Math.abs(1e3*F.currentTime-u)>500&&(F.currentTime=m):(me.reset(),F.paused||F.pause(),m!==F.currentTime&&(F.currentTime=m),!re(F)&&!c.isPlaying&&!pe.current&&(pe.current=E(`video ${a.id}`)))),Pe(),null===(t=null===(e=b.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()}});return()=>{e(),pe.current&&(pe.current(),pe.current=null)}},[c,F,ae,se,U]),o.useEffect(()=>{var e,t;if(!F){return}if(ae){return null===(e=pe.current)||void 0===e||e.call(pe),void(pe.current=null)}const r=()=>{var e;re(F)&&(Pe(),null===(e=pe.current)||void 0===e||e.call(pe),pe.current=null)};let i;return(null===(t=a.page)||void 0===t?void 0:t._exportingOrRendering)&&(i=setInterval(r,20)),F.addEventListener("timeupdate",r),F.addEventListener("canplay",r),F.addEventListener("seeked",r),()=>{clearInterval(i),F.removeEventListener("timeupdate",r),F.removeEventListener("canplay",r),F.removeEventListener("seeked",r)}},[null===(g=a.page)||void 0===g?void 0:g._exportingOrRendering,F,a.id,E,ae]);let{cropX:ge,cropY:fe,cropWidth:ve,cropHeight:we}=a;"loaded"!==N&&(ge=fe=0,ve=we=1);const{width:xe,height:Ee}=B(le),ye=null!==(f=null==F?void 0:F.videoWidth)&&void 0!==f?f:0,Me=null!==(v=null==F?void 0:F.videoHeight)&&void 0!==v?v:0;o.useLayoutEffect(()=>{"loaded"===N&&ye>0&&Me>0&&a._setSourceSize({width:ye,height:Me},a.src)},[a,a.src,N,ye,Me]);const Le=L({stretchEnabled:a.stretchEnabled,cropX:ge,cropY:fe,cropWidth:ve,cropHeight:we,width:a.a.width,height:a.a.height},{width:xe,height:Ee}),be=Le.width,Te=Le.height,Ce=a.stretchEnabled,ke=null!==(x=a.cornerRadius)&&void 0!==x?x:0,[Ie,Re]=useCornerRadiusAndCrop(a,le,Le,c._elementsPixelRatio,ke,!0);let[je,Se]=useClip(a,Ie,c._elementsPixelRatio,[Le,ke,c._elementsPixelRatio]);const Pe=O(()=>{var e,t;he(),ue(),Re(),Se(),null===(t=null===(e=b.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()});o.useEffect(()=>{Pe()});const He=()=>{a._cropEnabled&&setTimeout(()=>{s(a)&&a.toggleCropMode(!0)})},Oe="loading"===N,Xe="failed"===N,Ye=!Oe&&!Xe,Ae=o.useRef({cropX:0,cropY:0,cropWidth:0,cropHeight:0}),We=o.useRef(!1),ze=Ye?i(a):0;X(b,ze);const _e=a.selectable||c.role===p.ADMIN,De=Y();return e(r,{children:t(h,{onMouseEnter:()=>oe(!0),onMouseLeave:()=>oe(!1),children:[Oe&&e(Q,{element:a}),Xe&&e(ee,{element:a}),e(l,{ref:b,name:"element",id:a.id,image:je,x:a.a.x,y:a.a.y,width:a.a.width||1,height:a.a.height||1,rotation:a.a.rotation,opacity:ze,shadowEnabled:a.shadowEnabled,shadowBlur:a.shadowBlur,shadowOffsetX:a.shadowOffsetX,shadowOffsetY:a.shadowOffsetY,shadowColor:n(a.shadowColor),shadowOpacity:a.shadowOpacity,customCrop:Le,listening:_e,draggable:De?a.draggable&&V:a.draggable,preventDefault:!De||V,hideInExport:!a.showInExport,onDragMove:e=>{a.set({x:e.target.x(),y:e.target.y()})},onDragEnd:e=>{a.set(R(e.target))},onDblClick:He,onDblTap:He,onTransformStart:e=>{M(!0),We.current=j(C(e.target)),Ae.current={cropX:a.cropX,cropY:a.cropY,cropWidth:a.cropWidth,cropHeight:a.cropHeight}},onTransform:e=>{const t=e.currentTarget,r=Math.abs(t.scaleX()-1)<1e-7?1:t.scaleX(),i=Math.abs(t.scaleY()-1)<1e-7?1:t.scaleY();t.scaleX(1),t.scaleY(1);const o=1-be/xe,n=Math.min(o,Math.max(0,a.cropX)),s=1-Te/Ee,d=Math.min(s,Math.max(0,a.cropY)),c=We.current,h=!c&&r<1&&Ae.current.cropHeight>Te/Ee;let l=c?a.cropWidth:a.cropWidth*r;h&&(l=a.cropWidth);const u=!c&&i<1&&Ae.current.cropWidth>be/xe;let m=c?a.cropHeight:a.cropHeight*i;u&&(m=a.cropHeight),Ce&&(l=a.cropWidth,m=a.cropHeight);const p=c?Math.min(r,i):1;a.set(Object.assign({cropX:n,cropY:d,x:t.x(),y:t.y(),width:t.width()*r,height:t.height()*i,rotation:e.target.rotation(),cropWidth:Math.min(l,1-n),cropHeight:Math.min(m,1-d)},1!==p&&Object.assign(Object.assign({},S(a,p)),{borderSize:a.borderSize*p})))},onTransformEnd:e=>{const t=e.currentTarget;a.set(Object.assign(Object.assign({width:I(t.width()),height:I(t.height()),x:I(t.x()),y:I(t.y()),rotation:I(e.target.rotation()),cropX:k(a.cropX),cropY:k(a.cropY),cropWidth:k(be/xe),cropHeight:k(Te/Ee)},P(a)),{borderSize:T(a.borderSize)})),M(!1)}}),e(u,{x:a.a.x,y:a.a.y,width:Math.max(a.a.width-a.borderSize,0),height:Math.max(a.a.height-a.borderSize,0),opacity:ze,offsetX:-a.borderSize/2,offsetY:-a.borderSize/2,stroke:n(a.borderColor),strokeWidth:a.borderSize,listening:!1,visible:!!a.borderSize,rotation:a.rotation,cornerRadius:Math.max(0,ke-a.borderSize),hideInExport:!a.showInExport}),!c.isPlaying&&e(l,{image:U?ie||De?J:void 0:G,x:a.a.x,y:a.a.y,offsetX:-a.a.width/2+15/c.scale,offsetY:-a.a.height/2+15/c.scale,rotation:a.a.rotation,width:30/c.scale,height:30/c.scale,hideInExport:!0,onClick:()=>Z(!U),onTap:()=>Z(!U)}),a._cropModeEnabled&&"loaded"===N&&e($,{element:a,store:c,previewImage:je,sourceImage:le,sourceWidth:xe,sourceHeight:Ee,cropAbsoluteWidth:be,cropAbsoluteHeight:Te,innerAnchors:q})]})})});
@@ -1 +1 @@
1
- import{jsx as e,jsxs as t}from"react/jsx-runtime";import r from"react";import{observer as o}from"mobx-react-lite";import n from"./page.js";import{TopRules as l}from"./rules.js";import{AudioElement as i}from"./audio.js";import{handleHotkey as s,handleCopyEvent as a,handleCutEvent as c,handlePasteEvent as u}from"./hotkeys.js";import{t as d}from"../utils/l10n.js";import{WorkspaceStyleProvider as h,useResolvedWorkspaceStyle as g}from"./workspace-style.js";const p=(e,t,r)=>Math.max(t,Math.min(r,e)),f=(e,t)=>Math.sqrt(Math.pow(t.clientX-e.clientX,2)+Math.pow(t.clientY-e.clientY,2)),m=({store:r})=>t("div",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",textAlign:"center"},children:[e("p",{children:d("workspace.noPages")}),e("button",{onClick:()=>{r.addPage()},children:d("workspace.addPage")})]}),v=({width:t,height:r,xPadding:o,yPadding:n,backgroundColor:l})=>e("div",{style:{width:t+"px",height:r+"px",backgroundColor:l,paddingLeft:o+"px",paddingRight:o+"px",paddingTop:n+"px",paddingBottom:n+"px",flexShrink:0},children:e("div",{style:{width:" 100%",height:"100%",backgroundColor:"white"}})});export const WorkspaceCanvas=o(({store:o,layout:d="vertical",pageControlsEnabled:w,backgroundColor:x,transparencyBackgroundColor:y,pageBorderColor:L,activePageBorderColor:T,bleedColor:b,snapGuideStroke:k,snapGuideStrokeWidth:S,snapGuideDash:E,selectionRectFill:M,selectionRectStroke:C,selectionRectStrokeWidth:P,transformLabelFill:R,transformLabelTextFill:F,cropOverlayFill:W,cropGridStyle:B,transformerStyle:O,innerImageCropTransformerStyle:z,outerImageCropTransformerStyle:j,highlighterStyle:N,mediaLoadingStyle:H,mediaErrorStyle:G,textOverflowIndicatorStyle:I,distanceGuideStroke:_,distanceLabelFill:Y,distanceLabelTextFill:D,rulerBackgroundColor:X,rulerTextColor:A,rulerBorderColor:K,rulerBorderSize:q,rulerTickColor:V,rulerTickSize:J,components:Q,onKeyDown:U,onPaste:Z,paddingX:$,paddingY:ee,pageGap:te,altCloneEnabled:re=!0,groupSelectionMode:oe="drill",visiblePagesOffset:ne,renderOnlyActivePage:le,scrollToPageThreshold:ie=.5,tooltipSafeArea:se})=>{var ae;const ce="horizontal"===d,ue=null!=$?$:20,de=null!=ee?ee:55,[he,ge]=r.useState({width:100,height:100}),pe=r.useRef(he),fe=r.useRef(null),me=r.useRef(null),ve=r.useRef(0);let we=0,xe=0,ye=0,Le=0;if(o.bleedVisible){for(const e of o.pages){const t=e.computedBleed;we=Math.max(we,t.left),xe=Math.max(xe,t.right),ye=Math.max(ye,t.top),Le=Math.max(Le,t.bottom)}}const Te=Math.max(...o.pages.map(e=>e.computedWidth)),be=Math.max(...o.pages.map(e=>e.computedHeight)),ke=(null===(ae=o.activePage)||void 0===ae?void 0:ae.computedHeight)||0,Se=Te+we+xe,Ee=(le?ke:be)+ye+Le,Me=async({skipTimeout:e}={skipTimeout:!1})=>{if(e||await new Promise(e=>setTimeout(e,50)),null===fe.current){return}if(!Number.isFinite(Se)||!Number.isFinite(Ee)){return}const t=fe.current.getBoundingClientRect();0!==t.width&&0!==t.height||(console.warn("Polotno warning: <Workspace /> component can not automatically detect its size.\nWidth or height of parent elements is equal 0.\nPlease make sure it has non-zero size. You may need to adjust it with your styles. <Workspace /> will automatically fit into parent container.\nFor simpler debugging here is the log of the parent element:"),console.log(fe.current));const r=me.current.clientWidth||t.width,n={width:r,height:t.height};(pe.current.width!==n.width||pe.current.height!==n.height)&&(ge(n),pe.current=n);const l=(r-2*ue)/Se,i=o.pages.length>1?3.1:2,s=(t.height-de*i)/Ee,a=o.pages.length>1?3.1:2,c=(r-ue*a)/Se,u=(t.height-2*de)/Ee,d=o.pages.length?Math.max(Math.min(ce?c:l,ce?u:s),.01):1;o.scaleToFit!==d&&(o.setScale(d),o._setScaleToFit(d))};r.useLayoutEffect(()=>{Me({skipTimeout:!0})},[]),r.useEffect(()=>{Me()},[Se,Ee,ee,$]),r.useLayoutEffect(()=>{Me({skipTimeout:!0})},[o.openedSidePanel]),r.useEffect(()=>{o.__()},[]),r.useEffect(()=>{const e=fe.current;if(window.ResizeObserver){const t=new ResizeObserver(()=>{Me({skipTimeout:!0})});return t.observe(e),()=>t.unobserve(e)}{const e=setInterval(()=>{Me({skipTimeout:!0})},100);return()=>clearInterval(e)}},[Se,Ee]);const Ce=le?1:o.pages.length;let Pe,Re;if(ce){const e=Se*o.scale*Ce;Pe=Math.max(ue,(he.width-e)/Ce/2),Re=Math.max(de,(he.height-Ee*o.scale)/2)}else{Pe=Math.max(ue,(he.width-Se*o.scale)/2);const e=Ee*o.scale*Ce;Re=Math.max(de,(he.height-e)/Ce/2)}Number.isNaN(Pe)&&(Pe=ue),Number.isNaN(Re)&&(Re=de),r.useEffect(()=>{const e=e=>{(U||s)(e,o)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[]),r.useEffect(()=>{const e=e=>a(e,o),t=e=>c(e,o),r=e=>(Z||u)(e,o);return window.addEventListener("copy",e),window.addEventListener("cut",t),window.addEventListener("paste",r),()=>{window.removeEventListener("copy",e),window.removeEventListener("cut",t),window.removeEventListener("paste",r)}},[Z]),r.useEffect(()=>{const e=e=>{if(e.ctrlKey||e.metaKey){e.preventDefault();const t=Math.max(5,o.scaleToFit);let r=Math.min(.1,o.scaleToFit);ce&&Se>0&&Number.isFinite(Se)&&(r=Math.max(r,300/Se)),r=Math.max(r,.01);const n=.03,l=p(e.deltaY<0?o.scale*(1+n):o.scale/(1+n),r,t);return void o.setScale(l)}},t=me.current;return null==t||t.addEventListener("wheel",e),()=>null==t?void 0:t.removeEventListener("wheel",e)},[ce,Se,o]),r.useEffect(()=>{const e=me.current;if(!e){return}const t=e=>{2===e.touches.length&&(ve.current=f(e.touches[0],e.touches[1]))},r=t=>{if(2===t.touches.length&&ve.current>0){t.preventDefault();const r=f(t.touches[0],t.touches[1]),n=r/ve.current,l=Math.max(5,o.scaleToFit);let i=Math.min(.1,o.scaleToFit);ce&&Se>0&&Number.isFinite(Se)&&(i=Math.max(i,300/Se)),i=Math.max(i,.01);const s=o.scale,a=p(s*n,i,l),c=a/s,u=e.getBoundingClientRect(),d=(t.touches[0].clientX+t.touches[1].clientX)/2-u.left,h=(t.touches[0].clientY+t.touches[1].clientY)/2-u.top,g=e.scrollLeft+d,m=e.scrollTop+h;Ne.current=!0,o.setScale(a),e.scrollLeft=g*c-d,e.scrollTop=m*c-h,ve.current=r}},n=()=>{ve.current=0};return e.addEventListener("touchstart",t,{passive:!0}),e.addEventListener("touchmove",r,{passive:!1}),e.addEventListener("touchend",n,{passive:!0}),()=>{e.removeEventListener("touchstart",t),e.removeEventListener("touchmove",r),e.removeEventListener("touchend",n)}},[ce,Se,o]);const Fe=void 0!==te,We=o.pages.map(e=>{if(ce){const t=(e.computedWidth+we+xe)*o.scale;return Fe?t+te:t+2*Pe}{const t=(e.computedHeight+ye+Le)*o.scale;return Fe?t+te:t+2*Re}}),Be=[];let Oe=Fe?ce?Pe:Re:0;for(let e=0;e<We.length;e++){Be.push(Oe),Oe+=We[e]}const ze=We.reduce((e,t)=>e+t,0),je=Fe?ze+(ce?2*Pe:2*Re):ze,Ne=r.useRef(!1),[,He]=r.useReducer(e=>e+1,0);((e,t,o,n,l)=>{const i=r.useRef(0),s=r.useRef(0),a=r.useRef(null),c=r.useRef(null),u=r.useRef(!1),d=r.useRef(n.pages.length);u.current=d.current!==n.pages.length,d.current=n.pages.length,r.useEffect(()=>{const t=e.current,r=()=>{i.current=t.scrollLeft,s.current=t.scrollTop,a.current=t.scrollWidth,c.current=t.scrollHeight};return t.addEventListener("scroll",r),r(),()=>{t.removeEventListener("scroll",r)}},[]),r.useLayoutEffect(()=>{if(!e.current){return}if(u.current){const t=e.current;return a.current=t.scrollWidth,c.current=t.scrollHeight,i.current=t.scrollLeft,void(s.current=t.scrollTop)}const t=e.current,r=a.current,o=c.current;if(null===r||null===o){return a.current=t.scrollWidth,c.current=t.scrollHeight,i.current=t.scrollLeft,void(s.current=t.scrollTop)}l.current=!0;const n=t.offsetWidth,d=t.offsetHeight,h=(i.current+n/2)/r,g=(s.current+d/2)/o,f=Math.max(0,t.scrollWidth-n),m=Math.max(0,t.scrollHeight-d);t.scrollLeft=p(h*t.scrollWidth-n/2,0,f),t.scrollTop=p(g*t.scrollHeight-d/2,0,m),a.current=t.scrollWidth,c.current=t.scrollHeight,i.current=t.scrollLeft,s.current=t.scrollTop},[o,t])})(me,je,o.scale,o,Ne);const{handleScroll:Ge}=((e,t,o,n,l,i,s,a,c,u)=>{const d=r.useRef(!1),h=r.useRef(null),g=r.useRef(!1),p="horizontal"===c;r.useEffect(()=>{const t=e.current,r=()=>{s.current};return t.addEventListener("scroll",r),()=>{t.removeEventListener("scroll",r)}},[]);const f=n.pages.indexOf(n.activePage);return r.useLayoutEffect(()=>{if(a){return}if(!n.activePage){return}if(!e.current){return}if(d.current){return}const r=e.current,i=n.pages.indexOf(n.activePage),s=t[i]||0,c=p?r.scrollLeft:r.scrollTop,h=p?r.scrollWidth-r.clientWidth:r.scrollHeight-r.clientHeight,f=Math.min(s,Math.max(0,h)),m=o[i]||o[0]||0;let v=()=>{};return(Math.abs(f-c)>m*l||g.current)&&(g.current=!0,v=(({element:e,scrollTop:t,scrollLeft:r,duration:o=300,onFinish:n=()=>{}})=>{const l=void 0!==t,i=l?e.scrollTop:e.scrollLeft,s=l?t:r,a=s-i;let c=0,u=!1;if(0===o){return l?e.scrollTop=s:e.scrollLeft=s,()=>{}}const d=()=>{if(u){return}c+=20;const t=h(c,i,a,o);l?e.scrollTop=t:e.scrollLeft=t,c<o?setTimeout(d,20):n()},h=(e,t,r,o)=>(e/=o/2)<1?r/2*e*e+t:-r/2*(--e*(e-2)-1)+t;return d(),()=>{u=!0}})(Object.assign(Object.assign({element:r},p?{scrollLeft:f}:{scrollTop:f}),{onFinish:()=>{g.current=!1,null==u||u()},duration:n.isPlaying?0:300}))),v},[n.activePage,f,n.isPlaying,a,c]),{handleScroll:e=>{if(a){return}if(g.current){return}d.current=!0,clearTimeout(h.current),h.current=setTimeout(()=>{d.current=!1},300);const r=(p?e.currentTarget.scrollLeft:e.currentTarget.scrollTop)+(p?i.width:i.height)/3;let o=0;for(let n=t.length-1;n>=0;n--){if(r>=t[n]){o=n;break}}const l=n.pages[o];l&&n.activePage!==l&&l.select()}}})(me,Be,We,o,ie,he,Ne,le,d,He),Ie=he.width>=Se*o.scale+2*Pe,_e=he.height>=Ee*o.scale+2*Re,Ye=x||"rgba(232, 232, 232, 0.9)",De=(null==Q?void 0:Q.NoPages)||m,Xe=ce?he.width:he.height,Ae=me.current?ce?me.current.scrollLeft:me.current.scrollTop:0,Ke=e=>{for(let t=Be.length-1;t>=0;t--){if(e>=Be[t]){return t}}return 0},qe=Math.max(0,Ke(Ae)),Ve=Math.min(o.pages.length-1,Ke(Ae+Xe)),Je=null!=ne?ne:1,Qe=Math.max(0,qe-Je),Ue=Math.min(o.pages.length-1,Ve+Je),Ze=g({cropOverlayFill:W,cropGridStyle:B,workspaceBackgroundColor:x,pageBorderColor:L,activePageBorderColor:T,bleedColor:b,transparencyBackgroundColor:y,transformerStyle:O,innerImageCropTransformerStyle:z,outerImageCropTransformerStyle:j,highlighterStyle:N,snapGuideStroke:k,snapGuideStrokeWidth:S,snapGuideDash:E,selectionRectFill:M,selectionRectStroke:C,selectionRectStrokeWidth:P,transformLabelFill:R,transformLabelTextFill:F,distanceGuideStroke:_,distanceLabelFill:Y,distanceLabelTextFill:D,mediaLoadingStyle:H,mediaErrorStyle:G,textOverflowIndicatorStyle:I,rulerBackgroundColor:X,rulerTextColor:A,rulerBorderColor:K,rulerBorderSize:q,rulerTickColor:V,rulerTickSize:J});return e(h,{value:Ze,children:e("div",{ref:fe,style:{width:"100%",height:"100%",position:"relative",outline:"none",flex:1,backgroundColor:Ye,overflow:"hidden"},tabIndex:0,className:"polotno-workspace-container",children:t("div",{ref:me,onScroll:Ge,style:Object.assign({position:"absolute",top:0,left:0,width:"100%",height:"100%",display:"flex",flexDirection:ce?"row":"column",overflow:"auto",overflowX:ce?"auto":Ie?"hidden":"auto",overflowY:ce&&_e?"hidden":"auto"},Fe&&{paddingTop:ce?0:Re,paddingBottom:ce?0:Re,paddingLeft:ce?Pe:0,paddingRight:ce?Pe:0,boxSizing:"border-box"}),className:"polotno-workspace-inner",children:[o.pages.map((t,r)=>{const l=t===o.activePage;if(le&&!l&&!t._exportingOrRendering&&!t._forceMount){return null}const i=l||r>=Qe&&r<=Ue||t._exportingOrRendering||t._forceMount,s=ce?We[r]:Se*o.scale+2*Pe,a=ce?Ee*o.scale+2*Re:We[r];if(!i){return e("div",{style:{flexShrink:0},children:e(v,{width:s,height:a,backgroundColor:Ye,xPadding:Pe,yPadding:Re})},t.id)}const c=e(n,{page:t,xPadding:Pe,yPadding:Re,width:s,height:a,store:o,pageControlsEnabled:w,altCloneEnabled:re,groupSelectionMode:oe,components:Q,viewportSize:he,layout:d,tooltipSafeArea:se},t.id);return(t._exportingOrRendering||t._forceMount)&&!l&&le?e("div",{style:{display:"none",flexShrink:0},children:c},t.id):c}),o.rulesVisible&&e(l,{store:o,xPadding:Pe,yPadding:Re,width:Se*o.scale+2*Pe,height:Ee*o.scale+2*Re,pageSizes:We,layout:d,renderOnlyActivePage:le}),0===o.pages.length&&e(De,{store:o}),o.audios.map(t=>e(i,{audio:t,store:o},t.id))]})})})});export default WorkspaceCanvas;
1
+ import{jsx as e,jsxs as t}from"react/jsx-runtime";import r from"react";import{observer as o}from"mobx-react-lite";import n from"./page.js";import{TopRules as l}from"./rules.js";import{AudioElement as i}from"./audio.js";import{handleHotkey as s,handleCopyEvent as a,handleCutEvent as c,handlePasteEvent as u}from"./hotkeys.js";import{t as d}from"../utils/l10n.js";import{WorkspaceStyleProvider as h,useResolvedWorkspaceStyle as g}from"./workspace-style.js";const p=(e,t,r)=>Math.max(t,Math.min(r,e)),f=(e,t)=>Math.sqrt(Math.pow(t.clientX-e.clientX,2)+Math.pow(t.clientY-e.clientY,2)),m=({store:r})=>t("div",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",textAlign:"center"},children:[e("p",{children:d("workspace.noPages")}),e("button",{onClick:()=>{r.addPage()},children:d("workspace.addPage")})]}),v=({width:t,height:r,xPadding:o,yPadding:n,backgroundColor:l})=>e("div",{style:{width:t+"px",height:r+"px",backgroundColor:l,paddingLeft:o+"px",paddingRight:o+"px",paddingTop:n+"px",paddingBottom:n+"px",flexShrink:0},children:e("div",{style:{width:" 100%",height:"100%",backgroundColor:"white"}})});export const WorkspaceCanvas=o(({store:o,layout:d="vertical",pageControlsEnabled:w,backgroundColor:x,transparencyBackgroundColor:y,pageBorderColor:L,activePageBorderColor:T,bleedColor:b,snapGuideStroke:k,snapGuideStrokeWidth:S,snapGuideDash:E,selectionRectFill:M,selectionRectStroke:C,selectionRectStrokeWidth:P,transformLabelFill:R,transformLabelTextFill:F,cropOverlayFill:W,cropGridStyle:B,transformerStyle:O,innerImageCropTransformerStyle:z,outerImageCropTransformerStyle:j,highlighterStyle:N,mediaLoadingStyle:H,mediaErrorStyle:G,textOverflowIndicatorStyle:I,distanceGuideStroke:_,distanceLabelFill:Y,distanceLabelTextFill:D,rulerBackgroundColor:X,rulerTextColor:A,rulerBorderColor:K,rulerBorderSize:q,rulerTickColor:V,rulerTickSize:J,components:Q,onKeyDown:U,onPaste:Z,paddingX:$,paddingY:ee,pageGap:te,altCloneEnabled:re=!0,groupSelectionMode:oe="drill",visiblePagesOffset:ne,renderOnlyActivePage:le,scrollToPageThreshold:ie=.5,tooltipSafeArea:se})=>{var ae;const ce="horizontal"===d,ue=null!=$?$:20,de=null!=ee?ee:55,[he,ge]=r.useState({width:100,height:100}),pe=r.useRef(he),fe=r.useRef(null),me=r.useRef(null),ve=r.useRef(0);let we=0,xe=0,ye=0,Le=0;if(o.bleedVisible){for(const e of o.pages){const t=e.computedBleed;we=Math.max(we,t.left),xe=Math.max(xe,t.right),ye=Math.max(ye,t.top),Le=Math.max(Le,t.bottom)}}const Te=Math.max(...o.pages.map(e=>e.computedWidth)),be=Math.max(...o.pages.map(e=>e.computedHeight)),ke=(null===(ae=o.activePage)||void 0===ae?void 0:ae.computedHeight)||0,Se=Te+we+xe,Ee=(le?ke:be)+ye+Le,Me=async({skipTimeout:e}={skipTimeout:!1})=>{if(e||await new Promise(e=>setTimeout(e,50)),null===fe.current){return}if(!Number.isFinite(Se)||!Number.isFinite(Ee)){return}const t=fe.current.getBoundingClientRect();0!==t.width&&0!==t.height||(console.warn("Polotno warning: <Workspace /> component can not automatically detect its size.\nWidth or height of parent elements is equal 0.\nPlease make sure it has non-zero size. You may need to adjust it with your styles. <Workspace /> will automatically fit into parent container.\nFor simpler debugging here is the log of the parent element:"),console.log(fe.current));const r=me.current.clientWidth||t.width,n={width:r,height:t.height};(pe.current.width!==n.width||pe.current.height!==n.height)&&(ge(n),pe.current=n);const l=(r-2*ue)/Se,i=o.pages.length>1?3.1:2,s=(t.height-de*i)/Ee,a=o.pages.length>1?3.1:2,c=(r-ue*a)/Se,u=(t.height-2*de)/Ee,d=o.pages.length?Math.max(Math.min(ce?c:l,ce?u:s),.01):1;o.scaleToFit!==d&&(o.setScale(d),o._setScaleToFit(d))};r.useLayoutEffect(()=>{Me({skipTimeout:!0})},[]),r.useEffect(()=>{Me()},[Se,Ee,ee,$]),r.useLayoutEffect(()=>{Me({skipTimeout:!0})},[o.openedSidePanel]),r.useEffect(()=>{o.__()},[]),r.useEffect(()=>{const e=fe.current;if(window.ResizeObserver){const t=new ResizeObserver(()=>{Me({skipTimeout:!0})});return t.observe(e),()=>t.unobserve(e)}{const e=setInterval(()=>{Me({skipTimeout:!0})},100);return()=>clearInterval(e)}},[Se,Ee]);const Ce=le?1:o.pages.length;let Pe,Re;if(ce){const e=Se*o.scale*Ce;Pe=Math.max(ue,(he.width-e)/Ce/2),Re=Math.max(de,(he.height-Ee*o.scale)/2)}else{Pe=Math.max(ue,(he.width-Se*o.scale)/2);const e=Ee*o.scale*Ce;Re=Math.max(de,(he.height-e)/Ce/2)}Number.isNaN(Pe)&&(Pe=ue),Number.isNaN(Re)&&(Re=de),r.useEffect(()=>{const e=e=>{U?U(e,o):s(e,o,fe.current)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[]),r.useEffect(()=>{const e=e=>a(e,o,fe.current),t=e=>c(e,o,fe.current),r=e=>{Z?Z(e,o):u(e,o,fe.current)};return window.addEventListener("copy",e),window.addEventListener("cut",t),window.addEventListener("paste",r),()=>{window.removeEventListener("copy",e),window.removeEventListener("cut",t),window.removeEventListener("paste",r)}},[Z]),r.useEffect(()=>{const e=e=>{if(e.ctrlKey||e.metaKey){e.preventDefault();const t=Math.max(5,o.scaleToFit);let r=Math.min(.1,o.scaleToFit);ce&&Se>0&&Number.isFinite(Se)&&(r=Math.max(r,300/Se)),r=Math.max(r,.01);const n=.03,l=p(e.deltaY<0?o.scale*(1+n):o.scale/(1+n),r,t);return void o.setScale(l)}},t=me.current;return null==t||t.addEventListener("wheel",e),()=>null==t?void 0:t.removeEventListener("wheel",e)},[ce,Se,o]),r.useEffect(()=>{const e=me.current;if(!e){return}const t=e=>{2===e.touches.length&&(ve.current=f(e.touches[0],e.touches[1]))},r=t=>{if(2===t.touches.length&&ve.current>0){t.preventDefault();const r=f(t.touches[0],t.touches[1]),n=r/ve.current,l=Math.max(5,o.scaleToFit);let i=Math.min(.1,o.scaleToFit);ce&&Se>0&&Number.isFinite(Se)&&(i=Math.max(i,300/Se)),i=Math.max(i,.01);const s=o.scale,a=p(s*n,i,l),c=a/s,u=e.getBoundingClientRect(),d=(t.touches[0].clientX+t.touches[1].clientX)/2-u.left,h=(t.touches[0].clientY+t.touches[1].clientY)/2-u.top,g=e.scrollLeft+d,m=e.scrollTop+h;Ne.current=!0,o.setScale(a),e.scrollLeft=g*c-d,e.scrollTop=m*c-h,ve.current=r}},n=()=>{ve.current=0};return e.addEventListener("touchstart",t,{passive:!0}),e.addEventListener("touchmove",r,{passive:!1}),e.addEventListener("touchend",n,{passive:!0}),()=>{e.removeEventListener("touchstart",t),e.removeEventListener("touchmove",r),e.removeEventListener("touchend",n)}},[ce,Se,o]);const Fe=void 0!==te,We=o.pages.map(e=>{if(ce){const t=(e.computedWidth+we+xe)*o.scale;return Fe?t+te:t+2*Pe}{const t=(e.computedHeight+ye+Le)*o.scale;return Fe?t+te:t+2*Re}}),Be=[];let Oe=Fe?ce?Pe:Re:0;for(let e=0;e<We.length;e++){Be.push(Oe),Oe+=We[e]}const ze=We.reduce((e,t)=>e+t,0),je=Fe?ze+(ce?2*Pe:2*Re):ze,Ne=r.useRef(!1),[,He]=r.useReducer(e=>e+1,0);((e,t,o,n,l)=>{const i=r.useRef(0),s=r.useRef(0),a=r.useRef(null),c=r.useRef(null),u=r.useRef(!1),d=r.useRef(n.pages.length);u.current=d.current!==n.pages.length,d.current=n.pages.length,r.useEffect(()=>{const t=e.current,r=()=>{i.current=t.scrollLeft,s.current=t.scrollTop,a.current=t.scrollWidth,c.current=t.scrollHeight};return t.addEventListener("scroll",r),r(),()=>{t.removeEventListener("scroll",r)}},[]),r.useLayoutEffect(()=>{if(!e.current){return}if(u.current){const t=e.current;return a.current=t.scrollWidth,c.current=t.scrollHeight,i.current=t.scrollLeft,void(s.current=t.scrollTop)}const t=e.current,r=a.current,o=c.current;if(null===r||null===o){return a.current=t.scrollWidth,c.current=t.scrollHeight,i.current=t.scrollLeft,void(s.current=t.scrollTop)}l.current=!0;const n=t.offsetWidth,d=t.offsetHeight,h=(i.current+n/2)/r,g=(s.current+d/2)/o,f=Math.max(0,t.scrollWidth-n),m=Math.max(0,t.scrollHeight-d);t.scrollLeft=p(h*t.scrollWidth-n/2,0,f),t.scrollTop=p(g*t.scrollHeight-d/2,0,m),a.current=t.scrollWidth,c.current=t.scrollHeight,i.current=t.scrollLeft,s.current=t.scrollTop},[o,t])})(me,je,o.scale,o,Ne);const{handleScroll:Ge}=((e,t,o,n,l,i,s,a,c,u)=>{const d=r.useRef(!1),h=r.useRef(null),g=r.useRef(!1),p="horizontal"===c;r.useEffect(()=>{const t=e.current,r=()=>{s.current};return t.addEventListener("scroll",r),()=>{t.removeEventListener("scroll",r)}},[]);const f=n.pages.indexOf(n.activePage);return r.useLayoutEffect(()=>{if(a){return}if(!n.activePage){return}if(!e.current){return}if(d.current){return}const r=e.current,i=n.pages.indexOf(n.activePage),s=t[i]||0,c=p?r.scrollLeft:r.scrollTop,h=p?r.scrollWidth-r.clientWidth:r.scrollHeight-r.clientHeight,f=Math.min(s,Math.max(0,h)),m=o[i]||o[0]||0;let v=()=>{};return(Math.abs(f-c)>m*l||g.current)&&(g.current=!0,v=(({element:e,scrollTop:t,scrollLeft:r,duration:o=300,onFinish:n=()=>{}})=>{const l=void 0!==t,i=l?e.scrollTop:e.scrollLeft,s=l?t:r,a=s-i;let c=0,u=!1;if(0===o){return l?e.scrollTop=s:e.scrollLeft=s,()=>{}}const d=()=>{if(u){return}c+=20;const t=h(c,i,a,o);l?e.scrollTop=t:e.scrollLeft=t,c<o?setTimeout(d,20):n()},h=(e,t,r,o)=>(e/=o/2)<1?r/2*e*e+t:-r/2*(--e*(e-2)-1)+t;return d(),()=>{u=!0}})(Object.assign(Object.assign({element:r},p?{scrollLeft:f}:{scrollTop:f}),{onFinish:()=>{g.current=!1,null==u||u()},duration:n.isPlaying?0:300}))),v},[n.activePage,f,n.isPlaying,a,c]),{handleScroll:e=>{if(a){return}if(g.current){return}d.current=!0,clearTimeout(h.current),h.current=setTimeout(()=>{d.current=!1},300);const r=(p?e.currentTarget.scrollLeft:e.currentTarget.scrollTop)+(p?i.width:i.height)/3;let o=0;for(let n=t.length-1;n>=0;n--){if(r>=t[n]){o=n;break}}const l=n.pages[o];l&&n.activePage!==l&&l.select()}}})(me,Be,We,o,ie,he,Ne,le,d,He),Ie=he.width>=Se*o.scale+2*Pe,_e=he.height>=Ee*o.scale+2*Re,Ye=x||"rgba(232, 232, 232, 0.9)",De=(null==Q?void 0:Q.NoPages)||m,Xe=ce?he.width:he.height,Ae=me.current?ce?me.current.scrollLeft:me.current.scrollTop:0,Ke=e=>{for(let t=Be.length-1;t>=0;t--){if(e>=Be[t]){return t}}return 0},qe=Math.max(0,Ke(Ae)),Ve=Math.min(o.pages.length-1,Ke(Ae+Xe)),Je=null!=ne?ne:1,Qe=Math.max(0,qe-Je),Ue=Math.min(o.pages.length-1,Ve+Je),Ze=g({cropOverlayFill:W,cropGridStyle:B,workspaceBackgroundColor:x,pageBorderColor:L,activePageBorderColor:T,bleedColor:b,transparencyBackgroundColor:y,transformerStyle:O,innerImageCropTransformerStyle:z,outerImageCropTransformerStyle:j,highlighterStyle:N,snapGuideStroke:k,snapGuideStrokeWidth:S,snapGuideDash:E,selectionRectFill:M,selectionRectStroke:C,selectionRectStrokeWidth:P,transformLabelFill:R,transformLabelTextFill:F,distanceGuideStroke:_,distanceLabelFill:Y,distanceLabelTextFill:D,mediaLoadingStyle:H,mediaErrorStyle:G,textOverflowIndicatorStyle:I,rulerBackgroundColor:X,rulerTextColor:A,rulerBorderColor:K,rulerBorderSize:q,rulerTickColor:V,rulerTickSize:J});return e(h,{value:Ze,children:e("div",{ref:fe,style:{width:"100%",height:"100%",position:"relative",outline:"none",flex:1,backgroundColor:Ye,overflow:"hidden"},tabIndex:0,className:"polotno-workspace-container",children:t("div",{ref:me,onScroll:Ge,style:Object.assign({position:"absolute",top:0,left:0,width:"100%",height:"100%",display:"flex",flexDirection:ce?"row":"column",overflow:"auto",overflowX:ce?"auto":Ie?"hidden":"auto",overflowY:ce&&_e?"hidden":"auto"},Fe&&{paddingTop:ce?0:Re,paddingBottom:ce?0:Re,paddingLeft:ce?Pe:0,paddingRight:ce?Pe:0,boxSizing:"border-box"}),className:"polotno-workspace-inner",children:[o.pages.map((t,r)=>{const l=t===o.activePage;if(le&&!l&&!t._exportingOrRendering&&!t._forceMount){return null}const i=l||r>=Qe&&r<=Ue||t._exportingOrRendering||t._forceMount,s=ce?We[r]:Se*o.scale+2*Pe,a=ce?Ee*o.scale+2*Re:We[r];if(!i){return e("div",{style:{flexShrink:0},children:e(v,{width:s,height:a,backgroundColor:Ye,xPadding:Pe,yPadding:Re})},t.id)}const c=e(n,{page:t,xPadding:Pe,yPadding:Re,width:s,height:a,store:o,pageControlsEnabled:w,altCloneEnabled:re,groupSelectionMode:oe,components:Q,viewportSize:he,layout:d,tooltipSafeArea:se},t.id);return(t._exportingOrRendering||t._forceMount)&&!l&&le?e("div",{style:{display:"none",flexShrink:0},children:c},t.id):c}),o.rulesVisible&&e(l,{store:o,xPadding:Pe,yPadding:Re,width:Se*o.scale+2*Pe,height:Ee*o.scale+2*Re,pageSizes:We,layout:d,renderOnlyActivePage:le}),0===o.pages.length&&e(De,{store:o}),o.audios.map(t=>e(i,{audio:t,store:o},t.id))]})})})});export default WorkspaceCanvas;
package/config.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  export { setGoogleFonts, addGlobalFont, removeGlobalFont, replaceGlobalFonts, setGoogleFontsVariants, } from './utils/fonts.js';
2
2
  export { setUploadFunc } from './side-panel/upload-panel.js';
3
+ export { setExpandFunc, setReplaceObjectFunc, setRemoveObjectFunc, setUpscaleFunc, setRemoveBackgroundFunc, } from './utils/api.js';
4
+ export type { ExpandRequest, ReplaceObjectRequest, RemoveObjectRequest, ImageEditResult, ImageEditApplyContext, ImageToolOptions, ExpandFunc, ReplaceObjectFunc, RemoveObjectFunc, UpscaleFunc, RemoveBackgroundFunc, RemoveBackgroundRequest, ImageEditRequest, } from './image-tools/types.js';
3
5
  export { setFontUploadFunc } from './side-panel/text-panel.js';
4
6
  export { toggleFadeInAnimation } from './canvas/use-fadein.js';
5
7
  export { setTransformerStyle, setHighlighterStyle, setInnerImageCropTransformerStyle, setOuterImageCropTransformerStyle, } from './canvas/workspace-style.js';
@@ -26,4 +28,6 @@ export { setTextOverflow as unstable_setTextOverflow, setTextOverflow, } from '.
26
28
  export { setTextVerticalResizeEnabled as unstable_setTextVerticalResizeEnabled, setTextVerticalResizeEnabled, } from './utils/flags.js';
27
29
  export { setAnimationsEnabled as unstable_setAnimationsEnabled, setAnimationsEnabled, } from './utils/flags.js';
28
30
  export { setAiTextEnabled } from './utils/flags.js';
31
+ export { setCmykInputEnabled } from './utils/flags.js';
32
+ export { setCmykPreview } from '@polotno/core/color';
29
33
  export { setAutoDeleteEmptyText } from './utils/flags.js';
package/config.js CHANGED
@@ -1 +1 @@
1
- export{setGoogleFonts,addGlobalFont,removeGlobalFont,replaceGlobalFonts,setGoogleFontsVariants}from"./utils/fonts.js";export{setUploadFunc}from"./side-panel/upload-panel.js";export{setFontUploadFunc}from"./side-panel/text-panel.js";export{toggleFadeInAnimation}from"./canvas/use-fadein.js";export{setTransformerStyle,setHighlighterStyle,setInnerImageCropTransformerStyle,setOuterImageCropTransformerStyle}from"./canvas/workspace-style.js";export{setImageLoaderHook as unstable_setImageLoaderHook}from"./canvas/image-element.js";export{registerShapeModel as unstable_registerShapeModel}from"./model/group-model.js";export{registerShapeComponent as unstable_registerShapeComponent}from"./canvas/element.js";export{registerTransformerAttrs as unstable_registerTransformerAttrs}from"./canvas/page.js";export{registerToolbarComponent as unstable_registerToolbarComponent}from"./toolbar/toolbar.js";export{onLoadError,setAssetLoadTimeout,setFontLoadTimeout}from"./utils/loader.js";export{setSnapFilterFunc as unstable_setSnapFilterFunc}from"./canvas/use-transformer-snap.js";export{setTranslations,getTranslations}from"./utils/l10n.js";export{setIcons}from"./icons/registry.js";export{registerNextDomDrop as unstable_registerNextDomDrop}from"./canvas/page.js";export{getGoogleFontsListAPI,getGoogleFontImage,setAPI}from"./utils/api.js";export{setColorsPresetFunc}from"./toolbar/color-picker.js";export{setQuillFormats as unstable_setQuillFormats}from"./canvas/rich-editor.js";export{useDownScaling,setDownScalingEnabled}from"./utils/flags.js";export{useRemoveBackground as unstable_setRemoveBackgroundEnabled,setRemoveBackgroundEnabled}from"./utils/flags.js";export{useHtmlTextRender as unstable_useHtmlTextRender,setRichTextEnabled}from"./utils/flags.js";export{setLegacyRichTextEnabled}from"./utils/flags.js";export{setForceTextFit as unstable_setForceTextFit}from"./utils/flags.js";export{setTextSplitAllowed as unstable_setTextSplitAllowed}from"./utils/flags.js";export{setTextOverflow as unstable_setTextOverflow,setTextOverflow}from"./utils/flags.js";export{setTextVerticalResizeEnabled as unstable_setTextVerticalResizeEnabled,setTextVerticalResizeEnabled}from"./utils/flags.js";export{setAnimationsEnabled as unstable_setAnimationsEnabled,setAnimationsEnabled}from"./utils/flags.js";export{setAiTextEnabled}from"./utils/flags.js";export{setAutoDeleteEmptyText}from"./utils/flags.js";
1
+ export{setGoogleFonts,addGlobalFont,removeGlobalFont,replaceGlobalFonts,setGoogleFontsVariants}from"./utils/fonts.js";export{setUploadFunc}from"./side-panel/upload-panel.js";export{setExpandFunc,setReplaceObjectFunc,setRemoveObjectFunc,setUpscaleFunc,setRemoveBackgroundFunc}from"./utils/api.js";export{setFontUploadFunc}from"./side-panel/text-panel.js";export{toggleFadeInAnimation}from"./canvas/use-fadein.js";export{setTransformerStyle,setHighlighterStyle,setInnerImageCropTransformerStyle,setOuterImageCropTransformerStyle}from"./canvas/workspace-style.js";export{setImageLoaderHook as unstable_setImageLoaderHook}from"./canvas/image-element.js";export{registerShapeModel as unstable_registerShapeModel}from"./model/group-model.js";export{registerShapeComponent as unstable_registerShapeComponent}from"./canvas/element.js";export{registerTransformerAttrs as unstable_registerTransformerAttrs}from"./canvas/page.js";export{registerToolbarComponent as unstable_registerToolbarComponent}from"./toolbar/toolbar.js";export{onLoadError,setAssetLoadTimeout,setFontLoadTimeout}from"./utils/loader.js";export{setSnapFilterFunc as unstable_setSnapFilterFunc}from"./canvas/use-transformer-snap.js";export{setTranslations,getTranslations}from"./utils/l10n.js";export{setIcons}from"./icons/registry.js";export{registerNextDomDrop as unstable_registerNextDomDrop}from"./canvas/page.js";export{getGoogleFontsListAPI,getGoogleFontImage,setAPI}from"./utils/api.js";export{setColorsPresetFunc}from"./toolbar/color-picker.js";export{setQuillFormats as unstable_setQuillFormats}from"./canvas/rich-editor.js";export{useDownScaling,setDownScalingEnabled}from"./utils/flags.js";export{useRemoveBackground as unstable_setRemoveBackgroundEnabled,setRemoveBackgroundEnabled}from"./utils/flags.js";export{useHtmlTextRender as unstable_useHtmlTextRender,setRichTextEnabled}from"./utils/flags.js";export{setLegacyRichTextEnabled}from"./utils/flags.js";export{setForceTextFit as unstable_setForceTextFit}from"./utils/flags.js";export{setTextSplitAllowed as unstable_setTextSplitAllowed}from"./utils/flags.js";export{setTextOverflow as unstable_setTextOverflow,setTextOverflow}from"./utils/flags.js";export{setTextVerticalResizeEnabled as unstable_setTextVerticalResizeEnabled,setTextVerticalResizeEnabled}from"./utils/flags.js";export{setAnimationsEnabled as unstable_setAnimationsEnabled,setAnimationsEnabled}from"./utils/flags.js";export{setAiTextEnabled}from"./utils/flags.js";export{setCmykInputEnabled}from"./utils/flags.js";export{setCmykPreview}from"@polotno/core/color";export{setAutoDeleteEmptyText}from"./utils/flags.js";
@@ -81,6 +81,8 @@ declare const defaults: {
81
81
  'toolbar.zoomIn': import("lucide-react").LucideIcon;
82
82
  'toolbar.zoomOut': import("lucide-react").LucideIcon;
83
83
  'toolbar.crop': import("lucide-react").LucideIcon;
84
+ 'imageEdit.ai': import("lucide-react").LucideIcon;
85
+ 'colorPicker.reverseGradient': import("lucide-react").LucideIcon;
84
86
  'download.export': import("lucide-react").LucideIcon;
85
87
  'download.image': import("lucide-react").LucideIcon;
86
88
  'download.pdf': import("lucide-react").LucideIcon;
package/icons/registry.js CHANGED
@@ -1 +1 @@
1
- var t=this&&this.__rest||function(t,o){var e={};for(var i in t){Object.prototype.hasOwnProperty.call(t,i)&&o.indexOf(i)<0&&(e[i]=t[i])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(t);n<i.length;n++){o.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(t,i[n])&&(e[i[n]]=t[i[n]])}}return e};import{jsx as o}from"react/jsx-runtime";import{observable as e,action as i}from"mobx";import{observer as n}from"mobx-react-lite";import{AlignCenter as a,AlignCenterHorizontal as r,AlignCenterVertical as l,AlignEndHorizontal as s,AlignEndVertical as c,AlignHorizontalSpaceAround as p,AlignJustify as d,AlignLeft as m,AlignRight as g,AlignStartHorizontal as u,AlignStartVertical as b,AlignVerticalJustifyCenter as f,AlignVerticalJustifyEnd as x,AlignVerticalJustifyStart as y,AlignVerticalSpaceAround as h,ArrowDown as v,ArrowDownLeft as w,ArrowDownRight as P,ArrowLeft as z,ArrowLeftRight as O,ArrowRight as j,ArrowUp as k,ArrowUpDown as L,ArrowUpLeft as R,ArrowUpRight as T,Ban as I,Bold as B,CaseSensitive as C,Check as D,ChevronDown as H,ChevronLeft as M,ChevronRight as F,ChevronsDown as S,ChevronsUp as U,ChevronUp as V,CloudUpload as $,Contrast as _,Copy as E,CreditCard as J,Crop as W,Edit as Z,Eye as q,EyeOff as A,Files as G,FileText as K,GripVertical as N,HelpCircle as Q,Highlighter as X,Image as Y,Italic as tt,Layers as ot,LayoutTemplate as et,List as it,ListOrdered as nt,Lock as at,MousePointer as rt,MoreHorizontal as lt,PaintBucket as st,Palette as ct,Pause as pt,Pencil as dt,Pilcrow as mt,Pipette as gt,Play as ut,Plus as bt,Redo2 as ft,Scaling as xt,Scissors as yt,Search as ht,SkipBack as vt,Settings as wt,Shapes as Pt,Sparkles as zt,Strikethrough as Ot,TextCursorInput as jt,Timer as kt,Trash2 as Lt,Type as Rt,Underline as Tt,Undo2 as It,Unlock as Bt,Upload as Ct,Video as Dt,Volume2 as Ht,VolumeX as Mt,WandSparkles as Ft,WrapText as St,X as Ut,ZoomIn as Vt,ZoomOut as $t}from"lucide-react";import{Instagram as _t,Facebook as Et,Youtube as Jt,Linkedin as Wt,Twitter as Zt}from"./brand-icons.js";import{MoveIcon as qt,FadeIcon as At,ZoomIcon as Gt,RotateIcon as Kt,BlinkIcon as Nt,BounceIcon as Qt}from"./animation-icons.js";const Xt={"action.duplicate":E,"action.split":yt,"action.rename":dt,"action.remove":Lt,"action.lock":at,"action.unlock":Bt,"action.undo":It,"action.redo":ft,"action.add":bt,"action.more":lt,"action.settings":wt,"action.search":ht,"action.close":Ut,"action.confirm":D,"action.none":I,"action.visible":q,"action.hidden":A,"action.dragHandle":N,"action.eyeDropper":gt,"action.unmuted":Ht,"action.muted":Mt,"action.help":Q,"ui.chevronUp":V,"ui.chevronDown":H,"ui.chevronLeft":M,"ui.chevronRight":F,"layering.menu":ot,"layering.up":V,"layering.down":H,"layering.top":U,"layering.bottom":S,"text.bold":B,"text.italic":tt,"text.underline":Tt,"text.strikethrough":Ot,"text.alignLeft":m,"text.alignCenter":a,"text.alignRight":g,"text.alignJustify":d,"text.valignTop":y,"text.valignMiddle":f,"text.valignBottom":x,"text.uppercase":C,"text.spacing":St,"text.bulletList":it,"text.numberedList":nt,"text.paragraph":mt,"text.richText":jt,"text.uploadFont":Ct,"position.alignLeft":b,"position.alignCenter":l,"position.alignRight":c,"position.alignTop":u,"position.alignMiddle":r,"position.alignBottom":s,"position.distributeVertical":h,"position.distributeHorizontal":p,"sidePanel.templates":et,"sidePanel.text":Rt,"sidePanel.photos":Y,"sidePanel.elements":Pt,"sidePanel.upload":$,"sidePanel.background":st,"sidePanel.pages":G,"sidePanel.layers":ot,"sidePanel.resize":xt,"sidePanel.draw":dt,"sidePanel.videos":Dt,"toolbar.opacity":_,"toolbar.filters":Ft,"toolbar.aiWrite":zt,"toolbar.duration":kt,"toolbar.trim":yt,"toolbar.flipHorizontal":O,"toolbar.flipVertical":L,"toolbar.zoomIn":Vt,"toolbar.zoomOut":$t,"toolbar.crop":W,"download.export":Ct,"download.image":Y,"download.pdf":K,"download.video":Dt,"draw.select":rt,"draw.brush":Z,"draw.highlighter":X,"background.colorPicker":ct,"pagesTimeline.play":ut,"pagesTimeline.pause":pt,"pagesTimeline.rewind":vt,"size.instagram":_t,"size.facebook":Et,"size.youtube":Jt,"size.linkedin":Wt,"size.twitter":Zt,"size.video":Dt,"size.print":K,"size.businessCard":J,"animation.directionRight":j,"animation.directionLeft":z,"animation.directionUp":k,"animation.directionDown":v,"animation.directionBottomRight":P,"animation.directionBottomLeft":w,"animation.directionTopRight":T,"animation.directionTopLeft":R,"animation.typeMove":qt,"animation.typeFade":At,"animation.typeZoom":Gt,"animation.typeRotate":Kt,"animation.typeBlink":Nt,"animation.typeBounce":Qt},Yt=e.map();export const setIcons=i(t=>{for(const o of Object.keys(t)){const e=t[o];null!=e&&("function"==typeof e||"object"==typeof e?Yt.set(o,e):console.warn(`polotno: setIcons('${o}') expects a React component, received ${typeof e}. Ignored.`))}});export const resetIcons=i(()=>Yt.clear());export const PolotnoIcon=n(e=>{var i,{name:n}=e,a=t(e,["name"]);const r=null!==(i=Yt.get(n))&&void 0!==i?i:Xt[n];return o(r,Object.assign({"data-pn-icon":""},a))});
1
+ var t=this&&this.__rest||function(t,o){var e={};for(var i in t){Object.prototype.hasOwnProperty.call(t,i)&&o.indexOf(i)<0&&(e[i]=t[i])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(t);n<i.length;n++){o.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(t,i[n])&&(e[i[n]]=t[i[n]])}}return e};import{jsx as o}from"react/jsx-runtime";import{observable as e,action as i}from"mobx";import{observer as n}from"mobx-react-lite";import{AlignCenter as a,AlignCenterHorizontal as r,AlignCenterVertical as l,AlignEndHorizontal as c,AlignEndVertical as s,AlignHorizontalSpaceAround as p,AlignJustify as d,AlignLeft as m,AlignRight as g,AlignStartHorizontal as u,AlignStartVertical as b,AlignVerticalJustifyCenter as f,AlignVerticalJustifyEnd as x,AlignVerticalJustifyStart as y,AlignVerticalSpaceAround as h,ArrowDown as v,ArrowDownLeft as w,ArrowDownRight as P,ArrowLeft as z,ArrowLeftRight as O,ArrowRight as j,ArrowUp as k,ArrowUpDown as L,ArrowUpLeft as R,ArrowUpRight as T,Ban as I,Bold as B,CaseSensitive as C,Check as D,ChevronDown as H,ChevronLeft as M,ChevronRight as E,ChevronsDown as F,ChevronsUp as S,ChevronUp as U,CloudUpload as V,Contrast as $,Copy as _,CreditCard as G,Crop as J,Edit as W,Eye as Z,EyeOff as q,Files as A,FileText as K,GripVertical as N,HelpCircle as Q,Highlighter as X,Image as Y,Italic as tt,Layers as ot,LayoutTemplate as et,List as it,ListOrdered as nt,Lock as at,MousePointer as rt,MoreHorizontal as lt,PaintBucket as ct,Palette as st,Pause as pt,Pencil as dt,Pilcrow as mt,Pipette as gt,Play as ut,Plus as bt,Redo2 as ft,Scaling as xt,Scissors as yt,Search as ht,SkipBack as vt,Settings as wt,Shapes as Pt,Sparkles as zt,Strikethrough as Ot,TextCursorInput as jt,Timer as kt,Trash2 as Lt,Type as Rt,Underline as Tt,Undo2 as It,Unlock as Bt,Upload as Ct,Video as Dt,Volume2 as Ht,VolumeX as Mt,WandSparkles as Et,WrapText as Ft,X as St,ZoomIn as Ut,ZoomOut as Vt}from"lucide-react";import{Instagram as $t,Facebook as _t,Youtube as Gt,Linkedin as Jt,Twitter as Wt}from"./brand-icons.js";import{MoveIcon as Zt,FadeIcon as qt,ZoomIcon as At,RotateIcon as Kt,BlinkIcon as Nt,BounceIcon as Qt}from"./animation-icons.js";const Xt={"action.duplicate":_,"action.split":yt,"action.rename":dt,"action.remove":Lt,"action.lock":at,"action.unlock":Bt,"action.undo":It,"action.redo":ft,"action.add":bt,"action.more":lt,"action.settings":wt,"action.search":ht,"action.close":St,"action.confirm":D,"action.none":I,"action.visible":Z,"action.hidden":q,"action.dragHandle":N,"action.eyeDropper":gt,"action.unmuted":Ht,"action.muted":Mt,"action.help":Q,"ui.chevronUp":U,"ui.chevronDown":H,"ui.chevronLeft":M,"ui.chevronRight":E,"layering.menu":ot,"layering.up":U,"layering.down":H,"layering.top":S,"layering.bottom":F,"text.bold":B,"text.italic":tt,"text.underline":Tt,"text.strikethrough":Ot,"text.alignLeft":m,"text.alignCenter":a,"text.alignRight":g,"text.alignJustify":d,"text.valignTop":y,"text.valignMiddle":f,"text.valignBottom":x,"text.uppercase":C,"text.spacing":Ft,"text.bulletList":it,"text.numberedList":nt,"text.paragraph":mt,"text.richText":jt,"text.uploadFont":Ct,"position.alignLeft":b,"position.alignCenter":l,"position.alignRight":s,"position.alignTop":u,"position.alignMiddle":r,"position.alignBottom":c,"position.distributeVertical":h,"position.distributeHorizontal":p,"sidePanel.templates":et,"sidePanel.text":Rt,"sidePanel.photos":Y,"sidePanel.elements":Pt,"sidePanel.upload":V,"sidePanel.background":ct,"sidePanel.pages":A,"sidePanel.layers":ot,"sidePanel.resize":xt,"sidePanel.draw":dt,"sidePanel.videos":Dt,"toolbar.opacity":$,"toolbar.filters":Et,"toolbar.aiWrite":zt,"toolbar.duration":kt,"toolbar.trim":yt,"toolbar.flipHorizontal":O,"toolbar.flipVertical":L,"toolbar.zoomIn":Ut,"toolbar.zoomOut":Vt,"toolbar.crop":J,"imageEdit.ai":zt,"colorPicker.reverseGradient":O,"download.export":Ct,"download.image":Y,"download.pdf":K,"download.video":Dt,"draw.select":rt,"draw.brush":W,"draw.highlighter":X,"background.colorPicker":st,"pagesTimeline.play":ut,"pagesTimeline.pause":pt,"pagesTimeline.rewind":vt,"size.instagram":$t,"size.facebook":_t,"size.youtube":Gt,"size.linkedin":Jt,"size.twitter":Wt,"size.video":Dt,"size.print":K,"size.businessCard":G,"animation.directionRight":j,"animation.directionLeft":z,"animation.directionUp":k,"animation.directionDown":v,"animation.directionBottomRight":P,"animation.directionBottomLeft":w,"animation.directionTopRight":T,"animation.directionTopLeft":R,"animation.typeMove":Zt,"animation.typeFade":qt,"animation.typeZoom":At,"animation.typeRotate":Kt,"animation.typeBlink":Nt,"animation.typeBounce":Qt},Yt=e.map();export const setIcons=i(t=>{for(const o of Object.keys(t)){const e=t[o];null!=e&&("function"==typeof e||"object"==typeof e?Yt.set(o,e):console.warn(`polotno: setIcons('${o}') expects a React component, received ${typeof e}. Ignored.`))}});export const resetIcons=i(()=>Yt.clear());export const PolotnoIcon=n(e=>{var i,{name:n}=e,a=t(e,["name"]);const r=null!==(i=Yt.get(n))&&void 0!==i?i:Xt[n];return o(r,Object.assign({"data-pn-icon":""},a))});
@@ -0,0 +1,20 @@
1
+ import type { ImageSnapshot, Rect, Size } from './types.js';
2
+ export declare const UNIT: Readonly<Rect>;
3
+ export declare const validRect: (rect: Rect) => boolean;
4
+ export declare const contains: (outer: Rect, inner: Rect) => boolean;
5
+ export declare const sameRect: (a: Rect, b: Rect) => boolean;
6
+ export declare function intersection(a: Rect, b: Rect): Rect;
7
+ export declare function relativeRect(rect: Rect, base: Rect): Rect;
8
+ export declare function frameBox(element: Pick<ImageSnapshot, 'x' | 'y' | 'width' | 'height' | 'rotation'>, frame: Rect): Rect;
9
+ export declare function sourceBounds(snapshot: ImageSnapshot, size: Size): Rect;
10
+ export declare function cropFrame(snapshot: ImageSnapshot, size: Size, frame: Rect): {
11
+ cropX: number;
12
+ cropY: number;
13
+ cropWidth: number;
14
+ cropHeight: number;
15
+ x: number;
16
+ y: number;
17
+ width: number;
18
+ height: number;
19
+ };
20
+ export declare const matchesAspect: (a: Size, b: Size) => boolean;
@@ -0,0 +1 @@
1
+ import{getCropRect as t}from"@polotno/core/image";import{degToRad as h}from"../utils/math.js";export const UNIT=Object.freeze({x:0,y:0,width:1,height:1});export const validRect=t=>!!t&&[t.x,t.y,t.width,t.height].every(Number.isFinite)&&t.width>0&&t.height>0;export const contains=(t,h)=>h.x>=t.x-1e-9&&h.y>=t.y-1e-9&&h.x+h.width<=t.x+t.width+1e-9&&h.y+h.height<=t.y+t.height+1e-9;export const sameRect=(t,h)=>t.x===h.x&&t.y===h.y&&t.width===h.width&&t.height===h.height;export function intersection(t,h){const i=Math.max(t.x,h.x),e=Math.max(t.y,h.y);return{x:i,y:e,width:Math.max(0,Math.min(t.x+t.width,h.x+h.width)-i),height:Math.max(0,Math.min(t.y+t.height,h.y+h.height)-e)}}export function relativeRect(t,h){return{x:(t.x-h.x)/h.width,y:(t.y-h.y)/h.height,width:t.width/h.width,height:t.height/h.height}}export function frameBox(t,i){const e=h(t.rotation),o=i.x*t.width,r=i.y*t.height;return{x:t.x+o*Math.cos(e)-r*Math.sin(e),y:t.y+o*Math.sin(e)+r*Math.cos(e),width:t.width*i.width,height:t.height*i.height}}export function sourceBounds(h,i){return relativeRect(Object.assign({x:0,y:0},i),t(h,i))}export function cropFrame(h,i,e){const o=t(h,i);return Object.assign(Object.assign({},frameBox(h,e)),{cropX:(o.x+e.x*o.width)/i.width,cropY:(o.y+e.y*o.height)/i.height,cropWidth:e.width*o.width/i.width,cropHeight:e.height*o.height/i.height})}export const matchesAspect=(t,h)=>Math.abs(t.width/t.height/(h.width/h.height)-1)<=.02+Number.EPSILON;
@@ -0,0 +1,62 @@
1
+ import type { IAnyStateTreeNode } from 'mobx-state-tree';
2
+ import type { ImageSnapshot, Rect, Size } from './types.js';
3
+ import type { ImageToolSession, ImageToolName } from './sessions.js';
4
+ export type CloseOutcome = 'commit' | 'discard' | 'stale' | 'drop';
5
+ export interface PendingEdit {
6
+ readonly tool: 'expand' | 'inpaint' | 'upscale' | 'remove-background';
7
+ cancel(): void;
8
+ }
9
+ export interface PendingOperation extends PendingEdit {
10
+ readonly applying: boolean;
11
+ readonly rect: Rect;
12
+ invalidate(): void;
13
+ }
14
+ interface ParentNode {
15
+ readonly id: string;
16
+ readonly type?: string;
17
+ readonly parent?: ParentNode | null;
18
+ readonly selectable?: boolean;
19
+ readonly visible?: boolean;
20
+ readonly contentEditable?: boolean;
21
+ readonly resizable?: boolean;
22
+ }
23
+ export interface ToolTarget extends IAnyStateTreeNode, ImageSnapshot {
24
+ readonly id: string;
25
+ readonly type: string;
26
+ readonly contentEditable: boolean;
27
+ readonly resizable: boolean;
28
+ readonly selectable: boolean;
29
+ readonly visible: boolean;
30
+ readonly maskSrc?: string;
31
+ readonly page: ParentNode | null;
32
+ readonly parent: ParentNode | null;
33
+ readonly store: ToolStore | null;
34
+ readonly _sourceSize: Size | null;
35
+ _setSourceSize(size: Size, src: string): void;
36
+ readonly _pendingEdit?: PendingOperation | null;
37
+ readonly pendingEdit?: PendingEdit | null;
38
+ set(props: Partial<ImageSnapshot>): void;
39
+ _setPendingEdit?(operation: PendingOperation | null): void;
40
+ _setImageEditError?(message: string | null): void;
41
+ }
42
+ export type BasicToolName = 'selection' | 'draw' | 'pan' | 'text' | 'eraser';
43
+ export type ToolName = BasicToolName | ImageToolName;
44
+ export interface ToolStore extends IAnyStateTreeNode {
45
+ tool: ToolName;
46
+ readonly activeTool: ImageToolSession | null;
47
+ readonly role: string;
48
+ readonly history: {
49
+ _whenIdle(signal: AbortSignal): Promise<void>;
50
+ _commitToolChange(change: () => void): boolean;
51
+ _startDraft(id: string, entry: Record<string, unknown>): void;
52
+ _draftChange(change: () => void): void;
53
+ _commitDraft(): void;
54
+ _discardDraft(): void;
55
+ };
56
+ getElementById(id: string): ToolTarget | undefined;
57
+ selectElements(ids: string[]): void;
58
+ selectPage(id: string): void;
59
+ _closeImageTool(outcome?: CloseOutcome): void;
60
+ _didApplyImageEdit(elementId: string): void;
61
+ }
62
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,5 @@
1
+ import type { ImageToolName } from './sessions.js';
2
+ export declare function reportImageEditError(element: {
3
+ _setImageEditError(message: string | null): void;
4
+ }, error: unknown): void;
5
+ export declare function toolLabel(name: ImageToolName): string;
@@ -0,0 +1 @@
1
+ import{isAlive as o}from"mobx-state-tree";import{t as e}from"../utils/l10n.js";export function reportImageEditError(r,i){var t,l;const d=i;"TOOL_FAILED"===(null==d?void 0:d.code)&&["canceled","stale-result","busy"].includes(null!==(l=null===(t=d.details)||void 0===t?void 0:t.reason)&&void 0!==l?l:"")||o(r)&&r._setImageEditError(function(o){var r,i,t;const l=o;if("TOOL_FAILED"===(null==l?void 0:l.code)&&"handler-failed"===(null===(r=l.details)||void 0===r?void 0:r.reason)){const o=null===(i=l.cause)||void 0===i?void 0:i.userMessage;if("string"==typeof o){return o}}return"IMAGE_FAILED"===(null==l?void 0:l.code)&&"raster-failed"===(null===(t=l.details)||void 0===t?void 0:t.reason)?e("imageEdit.rasterFailed"):e("imageEdit.failed")}(i))}export function toolLabel(o){return e("crop"===o?"toolbar.crop":"remove-background"===o?"toolbar.removeBackground":`imageEdit.${o}`)}
@@ -0,0 +1,22 @@
1
+ import type { ToolTarget } from './host.js';
2
+ import type { ImageToolOptions, Rect } from './types.js';
3
+ type ImageEditRun = {
4
+ options?: ImageToolOptions;
5
+ } & ({
6
+ tool: 'expand';
7
+ frame: Rect;
8
+ prompt?: string;
9
+ } | {
10
+ tool: 'inpaint';
11
+ region: Rect;
12
+ operation: 'replace';
13
+ prompt: string;
14
+ } | {
15
+ tool: 'inpaint';
16
+ region: Rect;
17
+ operation: 'remove';
18
+ } | {
19
+ tool: 'upscale' | 'remove-background';
20
+ });
21
+ export declare function editImage(element: ToolTarget, run: ImageEditRun): Promise<void>;
22
+ export {};
@@ -0,0 +1 @@
1
+ import{getCrop as t,getImageSize as e}from"@polotno/core/image";import{isAlive as o,onPatch as r}from"mobx-state-tree";import{getRemoveBackgroundFunc as i,imageEditHandlers as n}from"../utils/api.js";import{contains as a,cropFrame as s,frameBox as l,intersection as c,matchesAspect as p,relativeRect as d,sameRect as g,UNIT as f,validRect as m}from"./geometry.js";import{eligible as u,imageSnapshot as h,targetSnapshot as b,toolError as w}from"./target.js";import{rasterizeImageInput as v,rectangleMask as j}from"./raster.js";import{deepEqual as y}from"../utils/deep-equal.js";export async function editImage(O,E){var x;const{tool:z}=E,_=O.id,I=(t,e)=>w(z,_,t,e),k=()=>O._pendingEdit;if(k()){throw I("busy")}const A=O.store;if(!A||!u(O,A,z)){throw I("unsupported-target")}const L=Object.freeze(Object.assign({},"expand"===E.tool?E.frame:"inpaint"===E.tool?E.region:f));if(!m(L)||("inpaint"===z?!a(f,L):!m(c(L,f)))){throw I("invalid-geometry")}const P=Object.freeze(h(O)),T=l(P,"expand"===z?L:f);if(!m(T)){throw I("invalid-geometry")}if(null===(x=O._setImageEditError)||void 0===x||x.call(O,null),"expand"===z&&g(L,f)){return}const C="expand"===z&&a(f,L),D=Object.assign({},n),q=i(),F="expand"===E.tool?D.expand:"inpaint"===E.tool?"replace"===E.operation?D.replace:D.remove:"upscale"===E.tool?D.upscale:q;if(!C&&!F){throw I("unavailable")}const R=b(O,A),W=new AbortController,{signal:X}=W;let Y=!1,B=!1;const G=Object.freeze({tool:z,rect:Object.freeze(Object.assign({},L)),get applying(){return B},cancel(){W.abort()},invalidate(){var t;B||(Y=!0,W.abort(),(null===(t=A.activeTool)||void 0===t?void 0:t.elementId)===_&&A._closeImageTool("discard"))}});O._setPendingEdit(G);const H=()=>o(O)&&O._pendingEdit===G&&y(b(O,A),R),J=()=>{if(Y||!H()){throw I("stale-result")}if(X.aborted){throw I("canceled")}},K=r(A,()=>{B||H()||G.invalidate()}),M=t=>new Promise((e,o)=>{const r=()=>o(I(Y?"stale-result":"canceled"));if(X.aborted){return t.catch(()=>{}),void r()}X.addEventListener("abort",r,{once:!0}),t.then(e,o).finally(()=>X.removeEventListener("abort",r))});try{let o;if(J(),C){const t=await M(e(P.src)),r=s(P,t,L);o=()=>O.set(r)}else{const r="expand"===z?c(f,L):f,i="remove-background"===z?null:await M(v(P,r).catch(t=>{throw t instanceof RangeError?I("unsupported-target",t):t}));J();const n="expand"===z?d(L,r):f,a=i&&{width:i.size.width*n.width,height:i.size.height*n.height},s=i&&{image:i.image,size:i.size,signal:X,options:E.options},g="inpaint"===E.tool?await M(j(i.size,L)):null;J();const m=()=>{switch(E.tool){case"expand":return D.expand(Object.assign(Object.assign({},s),{frame:n,prompt:E.prompt}));case"inpaint":{const t=Object.assign(Object.assign({},s),{mask:g,region:Object.assign({},L)});return"replace"===E.operation?D.replace(Object.assign(Object.assign({},t),{prompt:E.prompt})):D.remove(t)}case"upscale":return D.upscale(s);default:return q(P.src,X,{src:P.src,signal:X,options:E.options})}};let u;try{const t=await M(m());u="string"==typeof t?{src:t}:t}catch(Q){if(J(),"AbortError"===(null==(N=Q)?void 0:N.name)){throw I("canceled",Q)}throw I("handler-failed",Q)}J();const h=null==u?void 0:u.apply;if(!u||"string"!=typeof u.src||!u.src.trim()||u.src.startsWith("blob:")||void 0!==h&&"function"!=typeof h){throw I("invalid-result")}const b=u.src,w=await M(e(b));J();const y=null!=a?a:await M(e(P.src));J();const x=()=>{if(!p(w,y)){throw I("invalid-result")}O.set("remove-background"===z?{src:b}:Object.assign(Object.assign(Object.assign({},T),{src:b,flipX:!1,flipY:!1}),t(T,w)))};if(h){const t=Object.freeze({element:O,src:b,selection:"inpaint"===z?Object.freeze(Object.assign(Object.assign({},l(P,L)),{rotation:P.rotation})):null,applyDefault:x});o=()=>{try{const e=h(t);if(void 0!==e){throw Promise.resolve(e).catch(()=>{}),new Error("apply must be synchronous and return nothing.")}}catch(Q){throw(t=>"TOOL_FAILED"===(null==t?void 0:t.code))(Q)?Q:I("handler-failed",Q)}}}else{if(!p(w,y)){throw I("invalid-result")}o=x}}for(;;){await M(A.history._whenIdle(X)),J(),B=!0;try{if(A.history._commitToolChange(o)){break}}finally{B=!1}}A._didApplyImageEdit(_)}finally{K(),o(O)&&k()===G&&O._setPendingEdit(null)}var N}
@@ -0,0 +1,13 @@
1
+ import type { ImageSnapshot, Rect, Size } from './types.js';
2
+ export declare const WORKING_MAX_SIDE = 4096;
3
+ export declare function rasterCanvas(size: Size, stage: string): {
4
+ canvas: HTMLCanvasElement;
5
+ ctx: CanvasRenderingContext2D;
6
+ };
7
+ export declare function encodeRaster(canvas: HTMLCanvasElement, stage: string): Promise<Blob>;
8
+ export declare function withBlobImage<T>(blob: Blob, use: (image: HTMLImageElement) => Promise<T> | T): Promise<T>;
9
+ export declare function rasterizeImageInput(snapshot: Omit<ImageSnapshot, 'x' | 'y' | 'rotation'>, seed?: Rect): Promise<{
10
+ image: Blob;
11
+ size: Size;
12
+ }>;
13
+ export declare function rectangleMask(size: Size, region: Rect): Promise<Blob>;
@@ -0,0 +1 @@
1
+ import{getFlippedCropRect as t,loadImage as e}from"@polotno/core/image";import{polotnoError as i}from"@polotno/core/errors";import{isSvgUrl as h,prepareSvgSource as a,urlToString as r}from"@polotno/core/svg";import{UNIT as o,matchesAspect as n}from"./geometry.js";export const WORKING_MAX_SIDE=4096;const c=(t,e,h)=>i("IMAGE_FAILED","This device could not prepare the image. Try a smaller image.",{reason:"raster-failed",stage:t,width:e.width,height:e.height},h);export function rasterCanvas(t,e){try{if(![t.width,t.height].every(t=>Number.isInteger(t)&&t>0&&t<=4096)){throw new Error("Invalid working dimensions")}const e=document.createElement("canvas");e.width=t.width,e.height=t.height;const i=e.getContext("2d");if(!i){throw new Error("Canvas 2D unavailable")}return{canvas:e,ctx:i}}catch(i){throw c(e,t,i)}}export async function encodeRaster(t,e){try{return await new Promise((e,i)=>t.toBlob(t=>t?e(t):i(new Error("PNG encoding failed")),"image/png"))}catch(i){throw c(e,t,i)}}export async function withBlobImage(t,i){const h=URL.createObjectURL(t);try{return await i(await e(h))}finally{URL.revokeObjectURL(h)}}export async function rasterizeImageInput(i,s=o){const w=h(i.src)?a(await r(i.src)):i.src,g=await e(w),l={width:g.naturalWidth,height:g.naturalHeight},d=t(i,l),m=Math.max(d.width,d.height)/Math.max(i.width,i.height),f=function(t){const e=Math.max(t.width,t.height);if(!Number.isFinite(e)||Math.min(t.width,t.height)<=0){throw c("compose",t)}for(let i=Math.min(4096,Math.ceil(e));i>0;i--){const h=i/e,a={width:Math.max(1,Math.round(t.width*h)),height:Math.max(1,Math.round(t.height*h))};if(n(a,t)){return a}}throw new RangeError("The image aspect cannot fit the working raster.")}({width:i.width*s.width*m,height:i.height*s.height*m}),{canvas:p,ctx:u}=rasterCanvas(f,"compose"),x=i.flipX?1-s.x-s.width:s.x,M=i.flipY?1-s.y-s.height:s.y;u.translate(i.flipX?f.width:0,i.flipY?f.height:0),u.scale(i.flipX?-1:1,i.flipY?-1:1);try{u.drawImage(g,d.x+x*d.width,d.y+M*d.height,s.width*d.width,s.height*d.height,0,0,f.width,f.height)}catch(y){throw c("compose",f,y)}return{image:await encodeRaster(p,"compose"),size:f}}export async function rectangleMask(t,e){const{canvas:i,ctx:h}=rasterCanvas(t,"mask");h.fillStyle="black",h.fillRect(0,0,t.width,t.height);const a=Math.max(0,Math.floor(e.x*t.width)),r=Math.max(0,Math.floor(e.y*t.height)),o=Math.min(t.width,Math.ceil((e.x+e.width)*t.width)),n=Math.min(t.height,Math.ceil((e.y+e.height)*t.height));return h.fillStyle="white",h.fillRect(a,r,o-a,n-r),encodeRaster(i,"mask")}
@@ -0,0 +1,73 @@
1
+ import type { CloseOutcome, ToolStore, ToolTarget } from './host.js';
2
+ import type { ImageSnapshot, ImageToolOptions, Rect } from './types.js';
3
+ interface SessionBase {
4
+ readonly elementId: string;
5
+ readonly pending: boolean;
6
+ cancel(): void;
7
+ }
8
+ type RunOptions = {
9
+ options?: ImageToolOptions;
10
+ };
11
+ export interface CropSession extends SessionBase {
12
+ readonly name: 'crop';
13
+ readonly frame: Rect;
14
+ setFrame(frame: Rect): void;
15
+ run(): Promise<void>;
16
+ }
17
+ export interface ExpandSession extends SessionBase {
18
+ readonly name: 'expand';
19
+ readonly frame: Rect;
20
+ setFrame(frame: Rect): void;
21
+ run(options?: {
22
+ prompt?: string;
23
+ } & RunOptions): Promise<void>;
24
+ }
25
+ export interface InpaintSession extends SessionBase {
26
+ readonly name: 'inpaint';
27
+ readonly region: Rect | null;
28
+ setRegion(region: Rect | null): void;
29
+ run(options: ({
30
+ operation: 'replace';
31
+ prompt: string;
32
+ } | {
33
+ operation: 'remove';
34
+ }) & RunOptions): Promise<void>;
35
+ }
36
+ export interface UpscaleSession extends SessionBase {
37
+ readonly name: 'upscale';
38
+ run(options?: RunOptions): Promise<void>;
39
+ }
40
+ export interface RemoveBackgroundSession extends SessionBase {
41
+ readonly name: 'remove-background';
42
+ run(options?: RunOptions): Promise<void>;
43
+ }
44
+ export interface ImageToolSessions {
45
+ crop: CropSession;
46
+ expand: ExpandSession;
47
+ inpaint: InpaintSession;
48
+ upscale: UpscaleSession;
49
+ 'remove-background': RemoveBackgroundSession;
50
+ }
51
+ export type ImageToolSession = ImageToolSessions[keyof ImageToolSessions];
52
+ type CropDraft = Partial<Pick<ImageSnapshot, 'x' | 'y' | 'width' | 'height' | 'cropX' | 'cropY' | 'cropWidth' | 'cropHeight'>>;
53
+ interface SessionControls {
54
+ close(outcome: CloseOutcome): void;
55
+ undo(): boolean;
56
+ didApply(): void;
57
+ readonly drafting: boolean;
58
+ setDraft?(change: CropDraft): void;
59
+ }
60
+ export declare const sessionControls: (session: ImageToolSession) => SessionControls;
61
+ declare function createCropSession(element: ToolTarget, store: ToolStore): CropSession;
62
+ declare function createExpandSession(element: ToolTarget, store: ToolStore): ExpandSession;
63
+ declare function createInpaintSession(element: ToolTarget, store: ToolStore): InpaintSession;
64
+ export declare const IMAGE_TOOLS: {
65
+ readonly crop: typeof createCropSession;
66
+ readonly expand: typeof createExpandSession;
67
+ readonly inpaint: typeof createInpaintSession;
68
+ readonly upscale: (element: ToolTarget, store: ToolStore) => UpscaleSession;
69
+ readonly 'remove-background': (element: ToolTarget, store: ToolStore) => RemoveBackgroundSession;
70
+ };
71
+ export type ImageToolName = keyof typeof IMAGE_TOOLS;
72
+ export declare function toolAvailable(name: ImageToolName): boolean;
73
+ export {};
@@ -0,0 +1 @@
1
+ var e=this&&this.__rest||function(e,t){var n={};for(var r in e){Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++){t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}}return n};import{observable as t,runInAction as n}from"mobx";import{isAlive as r}from"mobx-state-tree";import{getCropRect as o,getImageSize as i}from"@polotno/core/image";import{getVideoSize as s}from"@polotno/core/video";import{imageEditHandlers as a}from"../utils/api.js";import{flags as c}from"../utils/flags.js";import{contains as l,cropFrame as d,frameBox as p,intersection as u,relativeRect as g,sameRect as f,sourceBounds as m,UNIT as b,validRect as h}from"./geometry.js";import{editImage as v}from"./operations.js";import{imageSnapshot as y,toolError as w}from"./target.js";const _=new WeakMap;export const sessionControls=e=>_.get(e);function O(e,o,i,s){var a;const c=o.id,l=t.box((null===(a=o._pendingEdit)||void 0===a?void 0:a.tool)===e?o._pendingEdit:null,{deep:!1}),d=t=>w(e,c,t),p={elementId:c,get pending(){const e=l.get();return r(o)&&!!e&&o._pendingEdit===e},fail:d,assertActive(e){if(!r(o)){throw d("stale-result")}if(o._pendingEdit){throw d("busy")}if(i.activeTool!==e){throw d("stale-result")}},start:e=>(n(()=>{var e;return l.set(null!==(e=o._pendingEdit)&&void 0!==e?e:null)}),e),cancel(e){p.pending&&l.get().cancel(),i.activeTool===e&&i._closeImageTool("discard")},controls:{drafting:!1,close(){},undo:()=>!1,didApply:s}};return p}function j(e){return(t,n)=>{const r=O(e,t,n,()=>{}),o={name:e,elementId:r.elementId,get pending(){return r.pending},cancel:()=>r.cancel(o),async run({options:n}={}){r.assertActive(o),await r.start(v(t,{tool:e,options:n}))}};return _.set(o,r.controls),o}}export const IMAGE_TOOLS={crop:function(a,c){const u=a.id,v=y(a),{src:O,rotation:j,flipX:x,flipY:E,stretchEnabled:I}=v,z=e(v,["src","rotation","flipX","flipY","stretchEnabled"]),A=t.box(b,{deep:!1}),S=t.box(null,{deep:!1});let T=!1,D=!1,P=!1;const k=e=>w("crop",u,e),M=()=>D||!f(A.get(),b),C=e=>{const t=S.get();n(()=>S.set(null)),null==t||t(e)},F=()=>{if(!r(a)){throw k("stale-result")}if(a._pendingEdit||S.get()){throw k("busy")}if(c.activeTool!==G){throw k("stale-result")}},X=e=>{if(!(Math.abs(e.width/v.width-1)<1e-9&&Math.abs(e.height/v.height-1)<1e-9||a.resizable)){throw k("unsupported-target")}},Y=e=>{P=!0;try{c.history._draftChange(()=>a.set(e))}finally{P=!1}T=!0};c.history._startDraft(u,z);const B=()=>{T&&r(a)&&Y(z),T=D=!1,n(()=>A.set(b))},G={elementId:u,name:"crop",get pending(){return!!S.get()},get frame(){return A.get()},setFrame(e){F();const t=a._sourceSize;if(!h(e)||!h(p(v,e))||t&&!l(m(v,t),e)){throw k("invalid-geometry")}X(p(v,e)),n(()=>A.set(Object.freeze(Object.assign({},e)))),D=!1,t&&Y(d(v,t,e))},cancel(){C("canceled"),c.activeTool===G&&c._closeImageTool("discard")},async run(){if(F(),M()&&!a._sourceSize){let e,t=null;const r=new Promise((n,r)=>{e=e=>{t=e,r(k(e))}});n(()=>S.set(e));try{const e=await Promise.race(["video"===a.type?s(v.src):i(v.src),r]);if(t){throw k(t)}a._setSourceSize(e,v.src)}finally{S.get()===e&&n(()=>S.set(null))}}c.activeTool===G&&c._closeImageTool("commit")}};return _.set(G,{get drafting(){return P},close(e){if(C("commit"===e||"discard"===e?"canceled":"stale-result"),"commit"===e||"stale"===e&&T){return(()=>{const e=a._sourceSize;if(!M()||!r(a)||!T&&!e){return c.history._discardDraft()}T||Y(d(v,e,A.get())),c.history._commitDraft()})()}"discard"===e&&B(),c.history._discardDraft()},undo:()=>!!M()&&(C("canceled"),B(),!0),didApply(){},setDraft(e){F();const t=a._sourceSize;if(!t){throw k("busy")}const r=Object.assign(Object.assign({},y(a)),e);X(r),Y(e),D=!0,n(()=>A.set(Object.freeze(g(o(r,t),o(v,t)))))}}),G},expand:function(e,r){let o=y(e);const i=e._pendingEdit,s=t.box("expand"===(null==i?void 0:i.tool)?i.rect:b,{deep:!1}),a=O("expand",e,r,()=>{o=y(e),n(()=>s.set(b))}),c={name:"expand",elementId:a.elementId,get pending(){return a.pending},get frame(){return s.get()},setFrame(e){if(a.assertActive(c),!h(e)||!h(p(o,e))||!h(u(e,b))){throw a.fail("invalid-geometry")}n(()=>s.set(Object.freeze(Object.assign({},e))))},cancel:()=>a.cancel(c),async run({prompt:t,options:n}={}){a.assertActive(c),await a.start(v(e,{tool:"expand",frame:s.get(),prompt:t,options:n}))}};return _.set(c,a.controls),c},inpaint:function(e,r){const o=e._pendingEdit,i=t.box("inpaint"===(null==o?void 0:o.tool)?o.rect:null,{deep:!1}),s=O("inpaint",e,r,()=>n(()=>i.set(null))),a={name:"inpaint",elementId:s.elementId,get pending(){return s.pending},get region(){return i.get()},setRegion(e){if(s.assertActive(a),e&&(!h(e)||!l(b,e))){throw s.fail("invalid-geometry")}n(()=>i.set(e?Object.freeze(Object.assign({},e)):null))},cancel:()=>s.cancel(a),async run(t){s.assertActive(a);const n=i.get();if(!n){throw s.fail("invalid-geometry")}await s.start(v(e,Object.assign(Object.assign({tool:"inpaint"},t),{region:n})))}};return _.set(a,s.controls),a},upscale:j("upscale"),"remove-background":j("remove-background")};export function toolAvailable(e){switch(e){case"crop":return!0;case"expand":return!!a.expand;case"inpaint":return!(!a.replace&&!a.remove);case"upscale":return!!a.upscale;default:return c.removeBackgroundEnabled}}
@@ -0,0 +1,37 @@
1
+ import { type PolotnoErrorDetailsMap } from '@polotno/core/errors';
2
+ import type { ToolStore, ToolTarget } from './host.js';
3
+ import type { ImageSnapshot } from './types.js';
4
+ export declare function toolError(tool: PolotnoErrorDetailsMap['TOOL_FAILED']['tool'], elementId: string, reason: PolotnoErrorDetailsMap['TOOL_FAILED']['reason'], cause?: unknown): Error & {
5
+ code: "TOOL_FAILED";
6
+ details?: {
7
+ reason: "handler-failed" | "busy" | "canceled" | "stale-result" | "unsupported-target" | "unavailable" | "invalid-geometry" | "invalid-result";
8
+ tool: "crop" | "expand" | "inpaint" | "upscale" | "remove-background";
9
+ elementId: string;
10
+ } | undefined;
11
+ cause?: unknown;
12
+ };
13
+ export declare function imageSnapshot(element: ToolTarget): ImageSnapshot;
14
+ export declare function eligible(element: ToolTarget, store: Pick<ToolStore, 'role'>, tool: PolotnoErrorDetailsMap['TOOL_FAILED']['tool']): boolean;
15
+ export declare function targetSnapshot(element: ToolTarget, store: ToolStore): {
16
+ selectable: boolean;
17
+ visible: boolean;
18
+ contentEditable: boolean;
19
+ resizable: boolean;
20
+ maskSrc: string | undefined;
21
+ pageId: string | undefined;
22
+ ancestors: unknown[];
23
+ role: string;
24
+ src: string;
25
+ rotation: number;
26
+ cropX: number;
27
+ cropY: number;
28
+ cropWidth: number;
29
+ cropHeight: number;
30
+ flipX: boolean;
31
+ flipY: boolean;
32
+ stretchEnabled: boolean;
33
+ x: number;
34
+ y: number;
35
+ width: number;
36
+ height: number;
37
+ } | null;
@@ -0,0 +1 @@
1
+ import{getRoot as e,isAlive as t}from"mobx-state-tree";import{polotnoError as r}from"@polotno/core/errors";export function toolError(e,t,o,i){return r("TOOL_FAILED",`Image tool ${e}: ${o}`,{reason:o,tool:e,elementId:t},i)}export function imageSnapshot(e){return{src:e.src,x:e.x,y:e.y,width:e.width,height:e.height,rotation:e.rotation,cropX:e.cropX,cropY:e.cropY,cropWidth:e.cropWidth,cropHeight:e.cropHeight,flipX:e.flipX,flipY:e.flipY,stretchEnabled:e.stretchEnabled}}export function eligible(r,o,i){var l;if(!t(r)||e(r)!==o||"viewer"===o.role||!r.page){return!1}if(!r.contentEditable||"expand"===i&&!r.resizable){return!1}if("crop"===i?!["image","svg","video"].includes(r.type)||r.maskSrc:"image"!==r.type){return!1}for(let e=r;e&&e!==r.page;e=null!==(l=e.parent)&&void 0!==l?l:null){if(!e.visible||"admin"!==o.role&&!e.selectable){return!1}}return!0}export function targetSnapshot(r,o){var i,l;if(!t(r)||e(r)!==o){return null}const n=[];for(let e=r.parent;e;e=null!==(i=e.parent)&&void 0!==i?i:null){n.push([e.id,e.selectable,e.visible])}return Object.assign(Object.assign({},imageSnapshot(r)),{selectable:r.selectable,visible:r.visible,contentEditable:r.contentEditable,resizable:r.resizable,maskSrc:r.maskSrc,pageId:null===(l=r.page)||void 0===l?void 0:l.id,ancestors:n,role:o.role})}