polotno 4.21.0 → 4.22.1

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 (99) hide show
  1. package/THIRD_PARTY_NOTICES.md +4 -4
  2. package/blueprint/side-panel/select-video.d.ts +74 -0
  3. package/blueprint.polotno.css +90 -180
  4. package/canvas/crop-overlay.d.ts +20 -8
  5. package/canvas/crop-overlay.js +1 -1
  6. package/canvas/element.js +1 -1
  7. package/canvas/fade-overlay.js +1 -1
  8. package/canvas/figure-element.js +1 -1
  9. package/canvas/gif-element.js +1 -1
  10. package/canvas/image-element.js +1 -1
  11. package/canvas/lottie-element.js +1 -1
  12. package/canvas/media-resize.js +1 -1
  13. package/canvas/page.js +1 -1
  14. package/canvas/quill-font-formats.d.ts +1 -1
  15. package/canvas/quill-font-formats.js +1 -1
  16. package/canvas/render-tag-element.js +1 -1
  17. package/canvas/rich-editor.js +5 -7
  18. package/canvas/text-element/render-tag-source.d.ts +5 -0
  19. package/canvas/text-element/render-tag-source.js +1 -1
  20. package/canvas/tooltip.js +1 -1
  21. package/canvas/use-mediabunny-video.js +1 -1
  22. package/canvas/video-element.js +1 -1
  23. package/canvas/workspace-canvas.js +1 -1
  24. package/icons/registry.d.ts +7 -0
  25. package/icons/registry.js +1 -1
  26. package/image-tools/host.d.ts +3 -0
  27. package/image-tools/sessions.js +1 -1
  28. package/image-tools/target.d.ts +5 -0
  29. package/image-tools/target.js +1 -1
  30. package/image-tools/types.d.ts +5 -0
  31. package/model/crop-mode.d.ts +3 -0
  32. package/model/crop-mode.js +1 -1
  33. package/model/figure-model.d.ts +29 -0
  34. package/model/gif-model.d.ts +40 -0
  35. package/model/group-model.d.ts +302 -1
  36. package/model/group-model.js +1 -1
  37. package/model/history.js +1 -1
  38. package/model/image-model.d.ts +40 -0
  39. package/model/image-model.js +1 -1
  40. package/model/line-model.d.ts +29 -0
  41. package/model/lottie-model.d.ts +40 -0
  42. package/model/node-model.d.ts +32 -0
  43. package/model/node-model.js +1 -1
  44. package/model/page-model.d.ts +906 -3
  45. package/model/shape-model.d.ts +29 -0
  46. package/model/shape-model.js +1 -1
  47. package/model/store.d.ts +61 -2
  48. package/model/store.js +1 -1
  49. package/model/svg-model.d.ts +27 -0
  50. package/model/table-model.d.ts +37 -1
  51. package/model/table-model.js +1 -1
  52. package/model/text-model.d.ts +27 -0
  53. package/model/video-model.d.ts +40 -0
  54. package/package.json +14 -14
  55. package/polotno.bundle.js +207 -208
  56. package/primitives/autocomplete.d.ts +11 -0
  57. package/primitives/autocomplete.js +1 -0
  58. package/primitives/select.js +1 -1
  59. package/side-panel/index.d.ts +1 -0
  60. package/side-panel/index.js +1 -1
  61. package/side-panel/layers-panel.js +1 -1
  62. package/side-panel/select-image.js +1 -1
  63. package/side-panel/select-video.d.ts +74 -0
  64. package/side-panel/select-video.js +1 -1
  65. package/side-panel/side-panel.d.ts +1 -0
  66. package/side-panel/side-panel.js +1 -1
  67. package/side-panel/variables-panel.d.ts +10 -0
  68. package/side-panel/variables-panel.js +1 -0
  69. package/toolbar/element-container.d.ts +6 -0
  70. package/toolbar/element-container.js +1 -1
  71. package/toolbar/figure-toolbar.d.ts +8 -9
  72. package/toolbar/figure-toolbar.js +1 -1
  73. package/toolbar/gif-toolbar.d.ts +4 -5
  74. package/toolbar/gif-toolbar.js +1 -1
  75. package/toolbar/group-toolbar.d.ts +2 -3
  76. package/toolbar/group-toolbar.js +1 -1
  77. package/toolbar/image-toolbar.d.ts +11 -12
  78. package/toolbar/image-toolbar.js +1 -1
  79. package/toolbar/index.d.ts +1 -0
  80. package/toolbar/index.js +1 -1
  81. package/toolbar/line-toolbar.js +1 -1
  82. package/toolbar/many-toolbar.d.ts +2 -3
  83. package/toolbar/many-toolbar.js +1 -1
  84. package/toolbar/page-toolbar.d.ts +2 -3
  85. package/toolbar/page-toolbar.js +1 -1
  86. package/toolbar/svg-toolbar.d.ts +2 -3
  87. package/toolbar/svg-toolbar.js +1 -1
  88. package/toolbar/text-toolbar.js +1 -1
  89. package/toolbar/text-variables.d.ts +15 -0
  90. package/toolbar/text-variables.js +1 -0
  91. package/toolbar/toolbar.js +1 -1
  92. package/toolbar/video-toolbar.js +1 -1
  93. package/ui.css +1 -1
  94. package/utils/animations.js +1 -1
  95. package/utils/clipboard.d.ts +50 -0
  96. package/utils/l10n.d.ts +32 -0
  97. package/utils/l10n.js +1 -1
  98. package/utils/selection-transform.js +1 -1
  99. package/utils/validate-key.js +1 -1
@@ -1,4 +1,4 @@
1
- var t=this&&this.__rest||function(t,e){var o={};for(var n in t){Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(o[n]=t[n])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(t);r<n.length;r++){e.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(t,n[r])&&(o[n[r]]=t[n[r]])}}return o};import{jsx as e}from"react/jsx-runtime";import o from"react";import n from"quill";import*as r from"mobx";import{nodeReaction as i}from"../utils/mobx.js";import{isAlive as l}from"mobx-state-tree";import{geckoRtlOverhangCss as s,getDir as a,getMeasureCtx as c,getQuillEditorHtml as d,letterSpacingOverhang as u,OVERHANG_PROPERTY as f,textLayoutWidth as p}from"@polotno/core/text-html";import{quillHtmlToModelText as m,isQuillFormatMixed as h,isBoldWeight as g,detachNativeColorsInHtml as b}from"../utils/rich-text-html.js";import{toDisplayColor as y}from"@polotno/core/color";import{LIST_INDENT_EM as v}from"@polotno/core/css-values";import{resetStyleContent as x,wrapHtmlForRenderTag as w}from"@polotno/core/reset-style";import{layout as S,lineBaselineOffset as k}from"render-tag";import{removeTags as T}from"@polotno/core/text";import{cssFontFamily as E}from"@polotno/core/fonts";import{isGradient as q,firstStopColor as C}from"@polotno/core/gradient";import{getOptimalCaretColor as O}from"./text-element/caret-color.js";import{visiblePlaceholder as R}from"./text-element/placeholder.js";import{registerQuillUnrestrictedFontFormats as L,PRESERVED_INLINE_STYLES as F,PRESERVED_BLOCK_STYLES as $}from"./quill-font-formats.js";import{ALL_QUILL_MIXED_KEYS as N,setActiveTextEditor as z,updateActiveTextFormat as j,clearActiveTextEditor as M,getActiveTextEditor as P}from"../utils/text-format-state.js";import D from"../utils/styled.js";import{applyOpacityToColor as H}from"@polotno/core/svg";import{elementDropShadow as A,shadowCastByBackground as I}from"@polotno/core/filters";export{H as applyOpacityToColor};export const quillRef=r.observable({enabled:!1,currentFormat:{},pendingToolbarInteraction:!1,editor:r.observable.object({instance:null},{},{deep:!1})});const Q=N;export function syncQuillFormatState(t,e){const o=e?t.getFormat(e):{},n=function(t,e){const o={};if(!e||e.length<=0){return o}const n=t.getContents(e.index,e.length);for(const r of Q){h(n,r)&&(o[r]=!0)}return o}(t,e);r.runInAction(()=>{quillRef.currentFormat=o}),j(o,n,e)}const _="polotno-saved-selection";function W(){const t=window.getSelection();if(!t||0===t.rangeCount||t.isCollapsed){return}if("undefined"==typeof Highlight||!CSS.highlights){return}const e=t.getRangeAt(0).cloneRange();CSS.highlights.set(_,new Highlight(e)),V()}function B(){"undefined"!=typeof CSS&&CSS.highlights&&CSS.highlights.delete(_)}function V(){setTimeout(()=>{"undefined"!=typeof CSS&&CSS.highlights&&CSS.highlights.has(_)&&(document.querySelector(".polotno-portal")||it(document.activeElement)?V():B())},300)}if("undefined"!=typeof document&&"undefined"!=typeof CSS&&CSS.highlights&&!document.querySelector("[data-polotno-highlight]")){const lt=document.createElement("style");lt.setAttribute("data-polotno-highlight",""),lt.textContent=`::highlight(${_}) { background-color: Highlight; }`,document.head.appendChild(lt)}export function collectRTText(t,e){"text"===t.type?e.push(t):t.children.forEach(t=>collectRTText(t,e))}export function computeMarkerVars(t){var e,o,n;const r=t.fontSize;if(!r||r<=0){return null}const i=E(t.fontFamily),l=g(t.fontWeight)?700:400,s="italic"===t.fontStyle?"italic":"normal",a=c();a.fontKerning="normal",a.font=`${r}px ${i}`;const d=a.measureText("M"),u=(null!==(e=d.fontBoundingBoxAscent)&&void 0!==e?e:0)/r,f=(null!==(o=d.fontBoundingBoxDescent)&&void 0!==o?o:0)/r,p=`font-family:${i};font-size:${r}px;font-weight:${l};font-style:${s};line-height:${t.lineHeight};letter-spacing:${t.letterSpacing}em`,m=w(`<div style="${p}"><ul><li>x</li></ul><ol><li>x</li></ol></div>`);let h;try{h=S({html:m,width:Math.max(12*r,600)})}catch(R){return null}const b=[];collectRTText(h.layoutRoot,b);const y=b.find(t=>"•"===t.text),x=b.find(t=>/^\d/.test(t.text));if(!y){return null}const T=y.style.fontSize,q=y.x,C=y.y-k(T,T*u,T*f),O=v*r;return{bulletLeft:q,bulletTop:C,bulletFontSize:T,numberGap:x?Math.max(0,O-x.x-(null!==(n=x.width)&&void 0!==n?n:0)):0}}export const RichTextContainer=D("div",o.forwardRef)`
1
+ var t=this&&this.__rest||function(t,e){var o={};for(var n in t){Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(o[n]=t[n])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(t);r<n.length;r++){e.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(t,n[r])&&(o[n[r]]=t[n[r]])}}return o};import{jsx as e}from"react/jsx-runtime";import o from"react";import n from"quill";import*as r from"mobx";import{nodeReaction as i}from"../utils/mobx.js";import{isAlive as l}from"mobx-state-tree";import{geckoRtlOverhangCss as s,getDir as a,getMeasureCtx as c,getQuillEditorHtml as d,letterSpacingOverhang as u,OVERHANG_PROPERTY as f,textLayoutWidth as p}from"@polotno/core/text-html";import{quillHtmlToModelText as m,isQuillFormatMixed as h,isBoldWeight as g,detachNativeColorsInHtml as b}from"../utils/rich-text-html.js";import{toDisplayColor as v}from"@polotno/core/color";import{LIST_INDENT_EM as y}from"@polotno/core/css-values";import{resetStyleContent as x,linkStyle as w,wrapHtmlForRenderTag as S}from"@polotno/core/reset-style";import{layout as k,lineBaselineOffset as T}from"render-tag";import{removeTags as E}from"@polotno/core/text";import{cssFontFamily as q}from"@polotno/core/fonts";import{isGradient as C,firstStopColor as L}from"@polotno/core/gradient";import{getOptimalCaretColor as O}from"./text-element/caret-color.js";import{visiblePlaceholder as R}from"./text-element/placeholder.js";import{registerQuillUnrestrictedFontFormats as F,PRESERVED_INLINE_STYLES as $,PRESERVED_BLOCK_STYLES as N}from"./quill-font-formats.js";import{ALL_QUILL_MIXED_KEYS as z,setActiveTextEditor as j,updateActiveTextFormat as M,clearActiveTextEditor as D,getActiveTextEditor as P}from"../utils/text-format-state.js";import A from"../utils/styled.js";import{applyOpacityToColor as H}from"@polotno/core/svg";import{elementDropShadow as I,shadowCastByBackground as Q}from"@polotno/core/filters";export{H as applyOpacityToColor};export const quillRef=r.observable({enabled:!1,currentFormat:{},pendingToolbarInteraction:!1,editor:r.observable.object({instance:null},{},{deep:!1})});const _=z;export function syncQuillFormatState(t,e){const o=e?t.getFormat(e):{},n=function(t,e){const o={};if(!e||e.length<=0){return o}const n=t.getContents(e.index,e.length);for(const r of _){h(n,r)&&(o[r]=!0)}return o}(t,e);r.runInAction(()=>{quillRef.currentFormat=o}),M(o,n,e)}const W="polotno-saved-selection";function B(){const t=window.getSelection();if(!t||0===t.rangeCount||t.isCollapsed){return}if("undefined"==typeof Highlight||!CSS.highlights){return}const e=t.getRangeAt(0).cloneRange();CSS.highlights.set(W,new Highlight(e)),X()}function V(){"undefined"!=typeof CSS&&CSS.highlights&&CSS.highlights.delete(W)}function X(){setTimeout(()=>{"undefined"!=typeof CSS&&CSS.highlights&&CSS.highlights.has(W)&&(document.querySelector(".polotno-portal")||lt(document.activeElement)?X():V())},300)}if("undefined"!=typeof document&&"undefined"!=typeof CSS&&CSS.highlights&&!document.querySelector("[data-polotno-highlight]")){const st=document.createElement("style");st.setAttribute("data-polotno-highlight",""),st.textContent=`::highlight(${W}) { background-color: Highlight; }`,document.head.appendChild(st)}export function collectRTText(t,e){"text"===t.type?e.push(t):t.children.forEach(t=>collectRTText(t,e))}export function computeMarkerVars(t){var e,o,n;const r=t.fontSize;if(!r||r<=0){return null}const i=q(t.fontFamily),l=g(t.fontWeight)?700:400,s="italic"===t.fontStyle?"italic":"normal",a=c();a.fontKerning="normal",a.font=`${r}px ${i}`;const d=a.measureText("M"),u=(null!==(e=d.fontBoundingBoxAscent)&&void 0!==e?e:0)/r,f=(null!==(o=d.fontBoundingBoxDescent)&&void 0!==o?o:0)/r,p=`font-family:${i};font-size:${r}px;font-weight:${l};font-style:${s};line-height:${t.lineHeight};letter-spacing:${t.letterSpacing}em`,m=S(`<div style="${p}"><ul><li>x</li></ul><ol><li>x</li></ol></div>`);let h;try{h=k({html:m,width:Math.max(12*r,600)})}catch(O){return null}const b=[];collectRTText(h.layoutRoot,b);const v=b.find(t=>"•"===t.text),x=b.find(t=>/^\d/.test(t.text));if(!v){return null}const w=v.style.fontSize,E=v.x,C=v.y-T(w,w*u,w*f),L=y*r;return{bulletLeft:E,bulletTop:C,bulletFontSize:w,numberGap:x?Math.max(0,L-x.x-(null!==(n=x.width)&&void 0!==n?n:0)):0}}export const RichTextContainer=A("div",o.forwardRef)`
2
2
  .ql-editor {
3
3
  outline: none;
4
4
  /* anchor for the absolutely-positioned ::before placeholder below */
@@ -6,9 +6,6 @@ var t=this&&this.__rest||function(t,e){var o={};for(var n in t){Object.prototype
6
6
  /* Element-level underline/strike — text-decoration doesn't inherit, so it is
7
7
  applied here on the editable root (mirrors the static getHtml render). */
8
8
  text-decoration: var(--polotno-text-decoration, none);
9
- /* Chrome would otherwise break the underline at every descender; the
10
- canvas draws one solid band. Mirrors getHtml (@polotno/core). */
11
- text-decoration-skip-ink: none;
12
9
  }
13
10
  /* Placeholder for an empty editor. Quill toggles ql-blank + data-placeholder
14
11
  but its core stylesheet (which paints it) is not loaded — do it here. Same
@@ -26,6 +23,7 @@ var t=this&&this.__rest||function(t,e){var o={};for(var n in t){Object.prototype
26
23
  opacity: 0;
27
24
  }
28
25
  ${x}
26
+ ${w}
29
27
 
30
28
  /* ===== Editor-only list markers (Quill flat-DOM hack) ======================
31
29
  Quill emits a FLAT <ol> with per-item data-list + ql-indent classes (not
@@ -62,7 +60,7 @@ var t=this&&this.__rest||function(t,e){var o={};for(var n in t){Object.prototype
62
60
  }
63
61
  .ql-editor li {
64
62
  position: relative; /* anchor for the absolutely-positioned ::before */
65
- padding-inline-start: ${v}em; /* marker space + per-level indent (start side) */
63
+ padding-inline-start: ${y}em; /* marker space + per-level indent (start side) */
66
64
  }
67
65
  .ql-editor li[data-list='ordered'] {
68
66
  counter-increment: list-0;
@@ -89,7 +87,7 @@ var t=this&&this.__rest||function(t,e){var o={};for(var n in t){Object.prototype
89
87
  inset-inline-start: 0;
90
88
  top: 0;
91
89
  box-sizing: border-box;
92
- width: ${v}em;
90
+ width: ${y}em;
93
91
  text-align: end;
94
92
  }
95
93
  .ql-editor li[data-list='ordered']::before {
@@ -166,4 +164,4 @@ var t=this&&this.__rest||function(t,e){var o={};for(var n in t){Object.prototype
166
164
  .ql-editor [style*='background-clip'] {
167
165
  -webkit-text-stroke-width: 0;
168
166
  }
169
- `;const X=[...F,...$,"header"];let G=["background","font-weight","color","gradient","font","italic","size","script","strike","underline","text-transform","indent","list","direction",...X];export const setQuillFormats=t=>{G=t};let Y=!1;function U(){Y||(Y=!0,console.warn("[polotno] The Quill 'bold' format is deprecated. Use the numeric 'font-weight' format instead, e.g. quill.format('font-weight', '700') or applyTextFormat({ fontWeight: 700 })."))}function K(t){return t?"700":"400"}const J=n.import("delta"),Z="data-polotno-rich-text",tt=["text-decoration-color","text-decoration-style","text-decoration-thickness"],et=(t,e)=>{const{style:o}=t,n=o.textDecorationLine,r={};if(n.includes("underline")&&(r.underline=!0),n.includes("line-through")&&(r.strike=!0),!r.underline&&!r.strike){return e}for(const i of tt){const t=o.getPropertyValue(i);t&&!/^(initial|currentcolor|solid|auto)$/i.test(t)&&(r[i]=t)}return e.ops.reduce((t,e)=>void 0===e.insert?t:t.insert(e.insert,Object.assign(Object.assign({},r),e.attributes)),new J)};export const createQuill=(e,o)=>{L();const r=new n(e,{toolbar:!1,keyboard:!1,placeholder:(null==o?void 0:o.placeholder)||void 0,clipboard:{matchVisual:!1},formats:G});!function(e){const o=e.format.bind(e),n=e.formatText.bind(e),r=e.getFormat.bind(e);e.format=(t,e,n)=>"bold"===t?(U(),o("font-weight",K(e),n)):o(t,e,n),e.formatText=(e,o,r,i,l)=>{if(r&&"object"==typeof r){if("bold"in r){U();const{bold:l}=r,s=t(r,["bold"]);return n(e,o,Object.assign(Object.assign({},s),{"font-weight":K(l)}),i)}return n(e,o,r,i)}return"bold"===r?(U(),n(e,o,"font-weight",K(i),l)):n(e,o,r,i,l)},e.getFormat=(...t)=>{const e=r(...t);return e&&null!=e["font-weight"]&&!("bold"in e)&&(e.bold=g(e["font-weight"])),e}}(r);const i=(t,e)=>e.compose((new J).retain(e.length(),{"font-weight":"700"}));r.clipboard.addMatcher("STRONG",i),r.clipboard.addMatcher("B",i),r.clipboard.addMatcher(Node.ELEMENT_NODE,et);const l=r.clipboard,s=l.onPaste.bind(l);return l.onPaste=(t,e)=>{var o;if(null===(o=e.html)||void 0===o?void 0:o.includes(Z)){return rt(r,()=>s(t,e))}const n=l.convert;l.convert=(...t)=>((t,e)=>{for(const o of t.ops){if(o.attributes){for(const t of e){delete o.attributes[t]}}}return t})(n.apply(l,t),X);try{return s(t,e)}finally{l.convert=n}},r};const ot=(t,e)=>e.insert(t.data),nt=(t,e)=>{const o=e.ops[0];return parseFloat(t.style.textIndent)>0&&"string"==typeof(null==o?void 0:o.insert)&&o.insert.startsWith("\t")?e.compose((new J).delete(1)):e};function rt(t,e){const{matchers:o}=t.clipboard,n=o.findIndex(([t])=>t===Node.TEXT_NODE),r=o[n];-1!==n&&(o[n]=[Node.TEXT_NODE,ot]),o.push([Node.ELEMENT_NODE,nt]);try{return e()}finally{o.pop(),-1!==n&&(o[n]=r)}}export const setQuillContent=(t,e)=>{const o=rt(t,()=>t.clipboard.convert({html:"<div class='ql-editor' style='outline: none;'>"+e+"<p><br></p></div>",text:""}));t.setContents(o),t.history.clear()};export const editorHtml=t=>d({text:b(t.text),width:t.width,fontSize:t.fontSize,fontFamily:t.fontFamily},t.fontFamily);export const RichEditor=({onBlur:t,onChange:n,element:s,clickCoords:c,initialCaret:d="start",fitScale:h=1,fitScaleFor:g})=>{const b=o.useRef(null),v=o.useRef(!1),x=o.useRef(h);x.current=h;const[w,S]=o.useState(null),k=null!=w?w:h,L=o.useRef(g);L.current=g;const F=t=>({width:p(s.a.width/t,s.letterSpacing,s.fontSize),zoom:1!==t?t:void 0}),$=o.useRef(null),N=o.useRef(void 0),j=()=>`${s.text}\0${s.fontSize}\0${s.fontFamily}`,D=t=>m(t,{fontSize:s.fontSize,fontFamily:s.fontFamily}),H=t=>{setQuillContent(t,editorHtml(s)),$.current=D(t.root.innerHTML),N.current=j()},Q=o.useRef(()=>{}),_=()=>{Q.current(),t()};o.useLayoutEffect(()=>{let t,e,o=!1,i=null,a=null,u=null,f=null,p=null;const m=()=>{if(!o&&b.current){try{t=createQuill(b.current,{placeholder:R(s.placeholder)}),r.runInAction(()=>{quillRef.editor.instance=t}),quillRef.pendingToolbarInteraction=!1,window.__polotnoQuill=t,z({instance:t,store:s.store,element:s});const o=e=>{e&&syncQuillFormatState(t,e)},m=()=>{let e=t.root;if(e.querySelector(".ql-cursor")){e=e.cloneNode(!0);const t=e.querySelector(".ql-cursor");t.replaceWith(t.textContent.replace(/\uFEFF/g,""))}return D(e.innerHTML)},h=()=>{const t=L.current;t&&l(s)&&(t=>{const e=b.current;if(!e){return}const o=F(t);e.style.width=`${o.width}px`,e.style.zoom=void 0===o.zoom?"":String(o.zoom)})(t(m()))},g=()=>{var o,r;if(clearTimeout(e),e=void 0,!l(s)){return}const i=m();if(i===$.current){return}$.current=i,v.current=!0,n(i);const a=t.getContents(),c=s.fill;let d=null,u=!0;for(const t of a.ops){if("string"!=typeof t.insert||"\n"===t.insert){continue}if(null===(o=t.attributes)||void 0===o?void 0:o.gradient){u=!1;break}const e=(null===(r=t.attributes)||void 0===r?void 0:r.color)||c;if(null===d){d=e}else if(e!==d){u=!1;break}}u&&d&&d!==s.fill&&s.set({fill:d})};Q.current=()=>{(void 0!==e||t.composition.isComposing)&&g()},t.on("text-change",()=>{const n=P(),r=n&&n.instance===t?n.lastSelection:null;o(t.getSelection()||r),t.composition.isComposing||h(),void 0===e&&(e=setTimeout(g,10))}),t.on("selection-change",o),t.on("composition-start",()=>S(x.current)),t.on("composition-end",()=>{h(),S(null)}),H(t);const y=b.current.closest(".polotno-workspace-inner"),w=null==y?void 0:y.scrollLeft,k=null==y?void 0:y.scrollTop,T="end"===d?t.getLength()-1:0;c?setCursorFromCoords(t,c,T):t.setSelection(T,0,"api"),y&&void 0!==w&&void 0!==k&&(y.scrollLeft=w,y.scrollTop=k);const E=t.root;f=t=>{const e=t.relatedTarget;(null==e?void 0:e.classList.contains("ql-clipboard"))||(it(e)||quillRef.pendingToolbarInteraction?W():setTimeout(()=>{quillRef.pendingToolbarInteraction||it(document.activeElement)?W():(B(),_())},0))},p=()=>{B()},E.addEventListener("blur",f),E.addEventListener("focus",p),i=E,a=e=>{var o,n;const r=t.getSelection();if(!r||0===r.length){return}const i=t.getText(r.index,r.length).replace(/\n$/,""),l=window.getSelection();let s="";if(l&&l.rangeCount>0){const t=l.getRangeAt(0);let e=t.cloneContents(),o=t.startContainer;o&&o.nodeType===Node.TEXT_NODE&&(o=o.parentNode);let n=t.endContainer;if(n&&n.nodeType===Node.TEXT_NODE&&(n=n.parentNode),o&&o===n){let t=o;for(;t&&t!==E&&t.nodeType===Node.ELEMENT_NODE;){const o=t.tagName;if("SPAN"!==o&&"EM"!==o&&"STRONG"!==o&&"U"!==o&&"S"!==o&&"A"!==o){break}const n=t.cloneNode(!1);n.appendChild(e),e=n,t=t.parentNode}}const r=document.createElement("div");r.appendChild(e),s=r.innerHTML}if(null===(o=e.clipboardData)||void 0===o||o.setData("text/plain",i),s){const t=`<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>\x3c!--StartFragment--\x3e<div ${Z} style="white-space: pre-wrap; overflow-wrap: break-word;">`+s+"</div>\x3c!--EndFragment--\x3e</body></html>";null===(n=e.clipboardData)||void 0===n||n.setData("text/html",t)}e.preventDefault()},u=e=>{a&&a(e);const o=t.getSelection();o&&o.length>0&&t.deleteText(o.index,o.length)},i.addEventListener("copy",a),i.addEventListener("cut",u)}catch(m){console.error("RichEditor init failed:",m)}}};return b.current?m():queueMicrotask(m),()=>{o=!0,Q.current(),clearTimeout(e),i&&f&&i.removeEventListener("blur",f),i&&p&&i.removeEventListener("focus",p),B(),i&&a&&u&&(i.removeEventListener("copy",a),i.removeEventListener("cut",u)),r.runInAction(()=>{quillRef.editor.instance=null,quillRef.currentFormat={}}),M(t),delete window.__polotnoQuill}},[]),o.useEffect(()=>i(s,j,t=>{const e=quillRef.editor.instance;if(!e){return}if(v.current){return v.current=!1,void(N.current=t)}if(t===N.current){return}const o=e.getSelection();H(e),o&&(e.setSelection(o.index,o.length),syncQuillFormatState(e,e.getSelection()))},{fireImmediately:!0}),[]),o.useEffect(()=>i(s,()=>`${s.fontFamily}\0${s.fontSize}\0${s.fontWeight}\0${s.fontStyle}\0${s.lineHeight}\0${s.letterSpacing}\0${a(T(s.text))}`,()=>{const t=b.current;if(!t){return}const e="ltr"===a(T(s.text)),o=computeMarkerVars(s);o&&t.style.setProperty("--rt-number-gap",`${o.numberGap}px`),o&&e?(t.style.setProperty("--rt-bullet-left",`${o.bulletLeft}px`),t.style.setProperty("--rt-bullet-top",`${o.bulletTop}px`),t.style.setProperty("--rt-bullet-fs",`${o.bulletFontSize}px`),t.classList.add("rt-marker-geom")):t.classList.remove("rt-marker-geom")},{fireImmediately:!0}),[]),o.useEffect(()=>{window.addEventListener("blur",_);const t=t=>{var e;const o=t.target;"number"==typeof(null==o?void 0:o.nodeType)&&(null===(e=b.current)||void 0===e?void 0:e.contains(o))||it(o)||quillRef.pendingToolbarInteraction||(B(),_())};return window.addEventListener("mousedown",t),window.addEventListener("touchstart",t),()=>{window.removeEventListener("blur",_),window.removeEventListener("mousedown",t),window.removeEventListener("touchstart",t)}},[]);const V=y(s.fill),X={color:V};V.indexOf("gradient")>=0&&(X["--polotno-gradient"]=V,X.color="transparent"),s.strokeWidth>0&&(X.WebkitTextStroke=`${s.strokeWidth}px ${C(s.stroke)}`,X.paintOrder="stroke fill");const G=q(s.fill)?C(s.fill):O(s),Y=s.shadowEnabled&&!I(s);return e(RichTextContainer,{ref:b,style:Object.assign(Object.assign(Object.assign(Object.assign({},X),{fontSize:s.fontSize,fontFamily:E(s.fontFamily),fontWeight:s.fontWeight,fontStyle:s.fontStyle,"--polotno-text-decoration":s.textDecoration||"none",textTransform:s.textTransform}),F(k)),{[f]:u(s.letterSpacing,s.fontSize)+"px",lineHeight:s.lineHeight,letterSpacing:s.letterSpacing*s.fontSize+"px",textAlign:s.align,opacity:Math.max(s.a.opacity,.2),filter:Y?A({shadowOffsetX:s.shadowOffsetX,shadowOffsetY:s.shadowOffsetY,shadowBlur:s.shadowBlur,shadowColor:s.shadowColor,shadowOpacity:s.shadowOpacity,rotation:s.a.rotation}):void 0,caretColor:G}),dir:a(T(s.text))})};function it(t){const e=t;return!("function"!=typeof(null==e?void 0:e.closest)||!e.closest(".sketch-picker")&&!e.closest("[data-polotno-keep-focus]")&&!e.closest(".polotno-portal")&&!e.closest(".polotno-toolbar"))}export function setCursorFromCoords(t,e,o=0){if(!t||!e){return}const{x:r,y:i}=e;try{let e=null;if(document.caretRangeFromPoint){e=document.caretRangeFromPoint(r,i)}else if(document.caretPositionFromPoint){const t=document.caretPositionFromPoint(r,i);t&&(e=document.createRange(),e.setStart(t.offsetNode,t.offset))}if(e){const o=n.find(e.startContainer,!0);if(o){const n=o.offset(t.scroll)+e.startOffset;return void t.setSelection(n,0,"api")}}}catch(l){}t.setSelection(o,0,"api")}
167
+ `;const G=[...$,...N,"header"];let Y=["link","background","font-weight","color","gradient","font","italic","size","script","strike","underline","text-transform","indent","list","direction",...G];export const setQuillFormats=t=>{Y=t};let U=!1;function K(){U||(U=!0,console.warn("[polotno] The Quill 'bold' format is deprecated. Use the numeric 'font-weight' format instead, e.g. quill.format('font-weight', '700') or applyTextFormat({ fontWeight: 700 })."))}function J(t){return t?"700":"400"}const Z=n.import("delta"),tt="data-polotno-rich-text",et=["text-decoration-color","text-decoration-style","text-decoration-thickness"],ot=(t,e)=>{const{style:o}=t,n=o.textDecorationLine,r={};if(n.includes("underline")&&(r.underline=!0),n.includes("line-through")&&(r.strike=!0),!r.underline&&!r.strike){return e}for(const i of et){const t=o.getPropertyValue(i);t&&!/^(initial|currentcolor|solid|auto)$/i.test(t)&&(r[i]=t)}return e.ops.reduce((t,e)=>void 0===e.insert?t:t.insert(e.insert,Object.assign(Object.assign({},r),e.attributes)),new Z)};export const createQuill=(e,o)=>{F();const r=new n(e,{toolbar:!1,keyboard:!1,placeholder:(null==o?void 0:o.placeholder)||void 0,clipboard:{matchVisual:!1},formats:Y});r.root.addEventListener("click",t=>{t.target instanceof Element&&t.target.closest("a")&&t.preventDefault()}),function(e){const o=e.format.bind(e),n=e.formatText.bind(e),r=e.getFormat.bind(e);e.format=(t,e,n)=>"bold"===t?(K(),o("font-weight",J(e),n)):o(t,e,n),e.formatText=(e,o,r,i,l)=>{if(r&&"object"==typeof r){if("bold"in r){K();const{bold:l}=r,s=t(r,["bold"]);return n(e,o,Object.assign(Object.assign({},s),{"font-weight":J(l)}),i)}return n(e,o,r,i)}return"bold"===r?(K(),n(e,o,"font-weight",J(i),l)):n(e,o,r,i,l)},e.getFormat=(...t)=>{const e=r(...t);return e&&null!=e["font-weight"]&&!("bold"in e)&&(e.bold=g(e["font-weight"])),e}}(r);const i=(t,e)=>e.compose((new Z).retain(e.length(),{"font-weight":"700"}));r.clipboard.addMatcher("STRONG",i),r.clipboard.addMatcher("B",i),r.clipboard.addMatcher(Node.ELEMENT_NODE,ot);const l=r.clipboard,s=l.onPaste.bind(l);return l.onPaste=(t,e)=>{var o;if(null===(o=e.html)||void 0===o?void 0:o.includes(tt)){return it(r,()=>s(t,e))}const n=l.convert;l.convert=(...t)=>((t,e)=>{for(const o of t.ops){if(o.attributes){for(const t of e){delete o.attributes[t]}}}return t})(n.apply(l,t),G);try{return s(t,e)}finally{l.convert=n}},r};const nt=(t,e)=>e.insert(t.data),rt=(t,e)=>{const o=e.ops[0];return parseFloat(t.style.textIndent)>0&&"string"==typeof(null==o?void 0:o.insert)&&o.insert.startsWith("\t")?e.compose((new Z).delete(1)):e};function it(t,e){const{matchers:o}=t.clipboard,n=o.findIndex(([t])=>t===Node.TEXT_NODE),r=o[n];-1!==n&&(o[n]=[Node.TEXT_NODE,nt]),o.push([Node.ELEMENT_NODE,rt]);try{return e()}finally{o.pop(),-1!==n&&(o[n]=r)}}export const setQuillContent=(t,e)=>{const o=it(t,()=>t.clipboard.convert({html:"<div class='ql-editor' style='outline: none;'>"+e+"<p><br></p></div>",text:""}));t.setContents(o),t.history.clear()};export const editorHtml=t=>d({text:b(t.text),width:t.width,fontSize:t.fontSize,fontFamily:t.fontFamily},t.fontFamily);export const RichEditor=({onBlur:t,onChange:n,element:s,clickCoords:c,initialCaret:d="start",fitScale:h=1,fitScaleFor:g})=>{const b=o.useRef(null),y=o.useRef(!1),x=o.useRef(h);x.current=h;const[w,S]=o.useState(null),k=null!=w?w:h,T=o.useRef(g);T.current=g;const F=t=>({width:p(s.a.width/t,s.letterSpacing,s.fontSize),zoom:1!==t?t:void 0}),$=o.useRef(null),N=o.useRef(void 0),z=()=>`${s.text}\0${s.fontSize}\0${s.fontFamily}`,M=t=>m(t,{fontSize:s.fontSize,fontFamily:s.fontFamily}),A=t=>{setQuillContent(t,editorHtml(s)),$.current=M(t.root.innerHTML),N.current=z()},H=o.useRef(()=>{}),_=()=>{H.current(),t()};o.useLayoutEffect(()=>{let t,e,o=!1,i=null,a=null,u=null,f=null,p=null;const m=()=>{if(!o&&b.current){try{t=createQuill(b.current,{placeholder:R(s.placeholder)}),r.runInAction(()=>{quillRef.editor.instance=t}),quillRef.pendingToolbarInteraction=!1,window.__polotnoQuill=t,j({instance:t,store:s.store,element:s});const o=e=>{e&&syncQuillFormatState(t,e)},m=()=>{let e=t.root;if(e.querySelector(".ql-cursor")){e=e.cloneNode(!0);const t=e.querySelector(".ql-cursor");t.replaceWith(t.textContent.replace(/\uFEFF/g,""))}return M(e.innerHTML)},h=()=>{const t=T.current;t&&l(s)&&(t=>{const e=b.current;if(!e){return}const o=F(t);e.style.width=`${o.width}px`,e.style.zoom=void 0===o.zoom?"":String(o.zoom)})(t(m()))},g=()=>{var o,r;if(clearTimeout(e),e=void 0,!l(s)){return}const i=m();if(i===$.current){return}$.current=i,y.current=!0,n(i);const a=t.getContents(),c=s.fill;let d=null,u=!0;for(const t of a.ops){if("string"!=typeof t.insert||"\n"===t.insert){continue}if(null===(o=t.attributes)||void 0===o?void 0:o.gradient){u=!1;break}const e=(null===(r=t.attributes)||void 0===r?void 0:r.color)||c;if(null===d){d=e}else if(e!==d){u=!1;break}}u&&d&&d!==s.fill&&s.set({fill:d})};H.current=()=>{(void 0!==e||t.composition.isComposing)&&g()},t.on("text-change",()=>{const n=P(),r=n&&n.instance===t?n.lastSelection:null;o(t.getSelection()||r),t.composition.isComposing||h(),void 0===e&&(e=setTimeout(g,10))}),t.on("selection-change",o),t.on("composition-start",()=>S(x.current)),t.on("composition-end",()=>{h(),S(null)}),A(t);const v=b.current.closest(".polotno-workspace-inner"),w=null==v?void 0:v.scrollLeft,k=null==v?void 0:v.scrollTop,E="end"===d?t.getLength()-1:0;c?setCursorFromCoords(t,c,E):t.setSelection(E,0,"api"),v&&void 0!==w&&void 0!==k&&(v.scrollLeft=w,v.scrollTop=k);const q=t.root;f=t=>{const e=t.relatedTarget;(null==e?void 0:e.classList.contains("ql-clipboard"))||(lt(e)||quillRef.pendingToolbarInteraction?B():setTimeout(()=>{quillRef.pendingToolbarInteraction||lt(document.activeElement)?B():(V(),_())},0))},p=()=>{V()},q.addEventListener("blur",f),q.addEventListener("focus",p),i=q,a=e=>{var o,n;const r=t.getSelection();if(!r||0===r.length){return}const i=t.getText(r.index,r.length).replace(/\n$/,""),l=window.getSelection();let s="";if(l&&l.rangeCount>0){const t=l.getRangeAt(0);let e=t.cloneContents(),o=t.startContainer;o&&o.nodeType===Node.TEXT_NODE&&(o=o.parentNode);let n=t.endContainer;if(n&&n.nodeType===Node.TEXT_NODE&&(n=n.parentNode),o&&o===n){let t=o;for(;t&&t!==q&&t.nodeType===Node.ELEMENT_NODE;){const o=t.tagName;if("SPAN"!==o&&"EM"!==o&&"STRONG"!==o&&"U"!==o&&"S"!==o&&"A"!==o){break}const n=t.cloneNode(!1);n.appendChild(e),e=n,t=t.parentNode}}const r=document.createElement("div");r.appendChild(e),s=r.innerHTML}if(null===(o=e.clipboardData)||void 0===o||o.setData("text/plain",i),s){const t=`<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>\x3c!--StartFragment--\x3e<div ${tt} style="white-space: pre-wrap; overflow-wrap: break-word;">`+s+"</div>\x3c!--EndFragment--\x3e</body></html>";null===(n=e.clipboardData)||void 0===n||n.setData("text/html",t)}e.preventDefault()},u=e=>{a&&a(e);const o=t.getSelection();o&&o.length>0&&t.deleteText(o.index,o.length)},i.addEventListener("copy",a),i.addEventListener("cut",u)}catch(m){console.error("RichEditor init failed:",m)}}};return b.current?m():queueMicrotask(m),()=>{o=!0,H.current(),clearTimeout(e),i&&f&&i.removeEventListener("blur",f),i&&p&&i.removeEventListener("focus",p),V(),i&&a&&u&&(i.removeEventListener("copy",a),i.removeEventListener("cut",u)),r.runInAction(()=>{quillRef.editor.instance=null,quillRef.currentFormat={}}),D(t),delete window.__polotnoQuill}},[]),o.useEffect(()=>i(s,z,t=>{const e=quillRef.editor.instance;if(!e){return}if(y.current){return y.current=!1,void(N.current=t)}if(t===N.current){return}const o=e.getSelection();A(e),o&&(e.setSelection(o.index,o.length),syncQuillFormatState(e,e.getSelection()))},{fireImmediately:!0}),[]),o.useEffect(()=>i(s,()=>`${s.fontFamily}\0${s.fontSize}\0${s.fontWeight}\0${s.fontStyle}\0${s.lineHeight}\0${s.letterSpacing}\0${a(E(s.text))}`,()=>{const t=b.current;if(!t){return}const e="ltr"===a(E(s.text)),o=computeMarkerVars(s);o&&t.style.setProperty("--rt-number-gap",`${o.numberGap}px`),o&&e?(t.style.setProperty("--rt-bullet-left",`${o.bulletLeft}px`),t.style.setProperty("--rt-bullet-top",`${o.bulletTop}px`),t.style.setProperty("--rt-bullet-fs",`${o.bulletFontSize}px`),t.classList.add("rt-marker-geom")):t.classList.remove("rt-marker-geom")},{fireImmediately:!0}),[]),o.useEffect(()=>{window.addEventListener("blur",_);const t=t=>{var e;const o=t.target;"number"==typeof(null==o?void 0:o.nodeType)&&(null===(e=b.current)||void 0===e?void 0:e.contains(o))||lt(o)||quillRef.pendingToolbarInteraction||(V(),_())};return window.addEventListener("mousedown",t),window.addEventListener("touchstart",t),()=>{window.removeEventListener("blur",_),window.removeEventListener("mousedown",t),window.removeEventListener("touchstart",t)}},[]);const W=v(s.fill),X={color:W};W.indexOf("gradient")>=0&&(X["--polotno-gradient"]=W,X.color="transparent"),s.strokeWidth>0&&(X.WebkitTextStroke=`${s.strokeWidth}px ${L(s.stroke)}`,X.paintOrder="stroke fill");const G=C(s.fill)?L(s.fill):O(s),Y=s.shadowEnabled&&!Q(s);return e(RichTextContainer,{ref:b,style:Object.assign(Object.assign(Object.assign(Object.assign({},X),{fontSize:s.fontSize,fontFamily:q(s.fontFamily),fontWeight:s.fontWeight,fontStyle:s.fontStyle,"--polotno-text-decoration":s.textDecoration||"none",textTransform:s.textTransform}),F(k)),{[f]:u(s.letterSpacing,s.fontSize)+"px",lineHeight:s.lineHeight,letterSpacing:s.letterSpacing*s.fontSize+"px",textAlign:s.align,opacity:Math.max(s.a.opacity,.2),filter:Y?I({shadowOffsetX:s.shadowOffsetX,shadowOffsetY:s.shadowOffsetY,shadowBlur:s.shadowBlur,shadowColor:s.shadowColor,shadowOpacity:s.shadowOpacity,rotation:s.a.rotation}):void 0,caretColor:G}),dir:a(E(s.text))})};function lt(t){const e=t;return!("function"!=typeof(null==e?void 0:e.closest)||!e.closest(".sketch-picker")&&!e.closest("[data-polotno-keep-focus]")&&!e.closest(".polotno-portal")&&!e.closest(".polotno-toolbar"))}export function setCursorFromCoords(t,e,o=0){if(!t||!e){return}const{x:r,y:i}=e;try{let e=null;if(document.caretRangeFromPoint){e=document.caretRangeFromPoint(r,i)}else if(document.caretPositionFromPoint){const t=document.caretPositionFromPoint(r,i);t&&(e=document.createRange(),e.setStart(t.offsetNode,t.offset))}if(e){const o=n.find(e.startContainer,!0);if(o){const n=o.offset(t.scroll)+e.startOffset;return void t.setSelection(n,0,"api")}}}catch(l){}t.setSelection(o,0,"api")}
@@ -15,6 +15,11 @@ export interface RenderTagSourceElement {
15
15
  width: number;
16
16
  height: number;
17
17
  };
18
+ filled: {
19
+ text?: string;
20
+ placeholder?: string;
21
+ fill?: string;
22
+ };
18
23
  }
19
24
  export declare function useRenderTagSource(element: RenderTagSourceElement, store: StoreType): {
20
25
  fontLoaded: boolean;
@@ -1 +1 @@
1
- import t from"react";import{removeTags as o}from"@polotno/core/text";import{layoutTextSizing as e,renderTagLayoutAt as i}from"@polotno/core/text-sizing";import{xmlEscape as r}from"@polotno/core/xml";import{extractFontSpecsFromHtml as l,normalizeRichTextHtml as n}from"../../utils/rich-text-html.js";import{usePrevious as m}from"../text-element.js";import{useColor as f,withDisplayTextPaints as a}from"../use-color.js";import{useFontSpecsLoader as s}from"./font-specs-loader.js";import{visiblePlaceholder as c}from"./placeholder.js";export function useRenderTagSource(e,i){const a=m(e.fontFamily),p=t.useMemo(()=>n(e.text,{fontSize:e.fontSize,fontFamily:e.fontFamily}),[e.text,e.fontSize,e.fontFamily]),x=t.useMemo(()=>l(p,{fontFamily:e.fontFamily,fontWeight:e.fontWeight,fontStyle:e.fontStyle}),[p,e.fontFamily,e.fontWeight,e.fontStyle]),[y]=s(i,x,e.text||e.placeholder),u=y?e.fontFamily:a&&a!==e.fontFamily?a:"Arial",d=f(e).fill,g=c(e.placeholder),F=!!g&&!o(e.text),h=F?r(g):p;return{fontLoaded:y,fontFamily:u,color:d,isPlaceholder:F,normalizedSourceText:h,getHtmlOptions:{fontFamily:u,color:d,forEditor:!0,text:h,textIsNormalized:!0}}}export function liveFitScale(t,o,r,l,n){try{return e({element:Object.assign(Object.assign({},t),{text:l}),sizing:o,layoutAt:i(a(t),{getHtmlOptions:Object.assign(Object.assign({},r),{text:l,textIsNormalized:!1})})}).scale}catch(m){return n}}
1
+ import t from"react";import{removeTags as o}from"@polotno/core/text";import{layoutTextSizing as e,renderTagLayoutAt as l}from"@polotno/core/text-sizing";import{xmlEscape as i}from"@polotno/core/xml";import{extractFontSpecsFromHtml as r,normalizeRichTextHtml as n}from"../../utils/rich-text-html.js";import{usePrevious as f}from"../text-element.js";import{useColor as m,withDisplayTextPaints as a}from"../use-color.js";import{useFontSpecsLoader as s}from"./font-specs-loader.js";import{visiblePlaceholder as c}from"./placeholder.js";export function useRenderTagSource(e,l){var a,p,d;const u=f(e.fontFamily),y=null!==(a=e.filled.text)&&void 0!==a?a:e.text,x=null!==(p=e.filled.placeholder)&&void 0!==p?p:e.placeholder,g=t.useMemo(()=>n(y,{fontSize:e.fontSize,fontFamily:e.fontFamily}),[y,e.fontSize,e.fontFamily]),F=t.useMemo(()=>r(g,{fontFamily:e.fontFamily,fontWeight:e.fontWeight,fontStyle:e.fontStyle}),[g,e.fontFamily,e.fontWeight,e.fontStyle]),[h]=s(l,F,y||x),j=h?e.fontFamily:u&&u!==e.fontFamily?u:"Arial",S=m(e,null!==(d=e.filled.fill)&&void 0!==d?d:e.fill).fill,z=c(x),O=!!z&&!o(y),v=O?i(z):g;return{fontLoaded:h,fontFamily:j,color:S,isPlaceholder:O,normalizedSourceText:v,getHtmlOptions:{fontFamily:j,color:S,forEditor:!0,text:v,textIsNormalized:!0}}}export function liveFitScale(t,o,i,r,n){try{return e({element:Object.assign(Object.assign({},t),{text:r}),sizing:o,layoutAt:l(a(t),{getHtmlOptions:Object.assign(Object.assign({},i),{text:r,textIsNormalized:!1})})}).scale}catch(f){return n}}
package/canvas/tooltip.js CHANGED
@@ -1 +1 @@
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})]})})})});
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{TextVariables as u,offersVariables as a}from"../toolbar/text-variables.js";import{flags as c}from"../utils/flags.js";import{DuplicateButton as d}from"../toolbar/duplicate-button.js";import{RemoveButton as m}from"../toolbar/remove-button.js";import{PositionPicker as p}from"../toolbar/position-picker.js";import{GroupButton as v}from"../toolbar/group-button.js";import{Navbar as f}from"../primitives/navbar.js";import{MAIN_TRANSFORMER_NAME as h}from"../utils/px.js";function g(e,t){return e.classList.contains(t)?e:e.parentElement?g(e.parentElement,t):null}const b=()=>null,x=({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:j,components:E,stageRef:w,tooltipSafeArea:y})=>{var N,I;const O=o.selectedShapes.every(e=>e.page===j),S=n.useRef(null),R=n.useRef(null),[T,C]=n.useState(!1),[,F]=n.useReducer(e=>e+1,0),k=n.useCallback(e=>{var t,n;e?(S.current=e,null===(t=R.current)||void 0===t||t.disconnect(),R.current=new ResizeObserver(F),R.current.observe(e),F()):S.current&&!S.current.isConnected&&(S.current=null,null===(n=R.current)||void 0===n||n.disconnect(),R.current=null)},[]),M=o._hasCroppedImages;n.useEffect(()=>{var e,t,n;const o=()=>{C(!0)},r=()=>{C(!1)};null===(e=null==w?void 0:w.current)||void 0===e||e.on("dragstart",o),null===(t=null==w?void 0:w.current)||void 0===t||t.on("dragend",r);const l=null===(n=null==w?void 0:w.current)||void 0===n?void 0:n.findOne(`.${h}`);return null==l||l.on("transformstart",o),null==l||l.on("transformend",r),()=>{var e,t;null===(e=null==w?void 0:w.current)||void 0===e||e.off("dragstart",o),null===(t=null==w?void 0:w.current)||void 0===t||t.off("dragend",r),null==l||l.off("transformstart",o),null==l||l.off("transformend",r)}},[]),n.useEffect(()=>{if(!(null==w?void 0:w.current)){return}const e=g(w.current.content,"polotno-workspace-inner");if(!e){return}const t=()=>{o.selectedShapes.length&&F()};return e.addEventListener("scroll",t),()=>{e.removeEventListener("scroll",t)}},[]);const P=o.selectedElements.map(e=>e.id).join(",");if(n.useEffect(()=>{if(!P){return}const e=requestAnimationFrame(()=>F());return()=>cancelAnimationFrame(e)},[P]),0===o.selectedShapes.length){return null}if(T){return null}if(!O){return null}if(o.activePage!==j){return null}if(M||o.activeTool||o.selectedShapes.some(e=>"pendingEdit"in e&&e.pendingEdit)){return null}const X=l(o.selectedShapes),Y=(null==E?void 0:E.Position)||p,A=(null==E?void 0:E.Duplicate)||d,L=(null==E?void 0:E.Remove)||m,B=(null==E?void 0:E.Group)||v,V=(null==E?void 0:E.Lock)||b,_=null===(N=o.selectedElements[0])||void 0===N?void 0:N.type,z=Object.assign(Object.assign(Object.assign({},c.aiTextEnabled?{TextAiWrite:s}:{}),a(o)?{TextVariables:u}:{}),E||{}),J=i({components:z,type:_,usedItems:[]}),q=!!(null===(I=S.current)||void 0===I?void 0:I.isConnected);return e(r,{parentNodeFunc:x,transformFunc:e=>{var t,n,o;const r=X.x+X.width/2,l=null===(t=null==w?void 0:w.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=S.current)||void 0===n?void 0:n.isConnected)?S.current.getBoundingClientRect():null,m=(null==d?void 0:d.width)||0,p=(null==d?void 0:d.height)||34,v=((null==y?void 0:y.top)||0)+8,f=(null!==(o=null==y?void 0:y.bottom)&&void 0!==o?o:45)+8,h=c+e.y+X.y*e.scaleY,g=c+e.y+(X.y+X.height)*e.scaleY,b=Number.isFinite(u.height),x=v+p/2,j=u.height-f-p/2;let E=h-80;b&&(E=Math.max(x,E));let N=E+p/2<=h-48?E:g+80;b&&(N=Math.min(j,Math.max(x,N)));let I=a+e.x+r*e.scaleX,O=I-X.width*e.scaleX/2,R=I+X.width*e.scaleX/2;const T=Math.min(50,X.width/2*e.scaleX),C=R>=T&&O<=u.width-T,F=(null==y?void 0:y.left)||0,k=(null==y?void 0:y.right)||0;if(Number.isFinite(u.width)&&m>0&&C){const e=8+m/2+F,t=u.width-8-m/2-k;t>=e&&(I=Math.max(e,Math.min(I,t)))}return R<T&&(I-=m+8),O>u.width-T&&(I+=m+8),Object.assign(Object.assign({},e),{x:I,y:N,scaleX:1,scaleY:1})},divProps:{style:{pointerEvents:"none",position:"absolute",visibility:q?"visible":"hidden",zIndex:9}},children:e("div",{ref:k,className:"polotno-selection-tooltip",style:{pointerEvents:"none"},children:t(f,{floating:!0,height:34,className:"pn:gap-0.5 pn:bg-popover pn:px-0.5",style:{transform:"translate(-50%, -50%)",pointerEvents:"auto"},children:[J.map(t=>{const n=z[t];return e(n,{elements:o.selectedElements,element:o.selectedElements[0],store:o},t)}),e(B,{store:o}),e(V,{store:o}),e(A,{store:o}),e(L,{store:o}),e(Y,{store:o})]})})})});
@@ -1 +1 @@
1
- import e from"react";import{nodeAutorun as r}from"../utils/mobx.js";import{Input as t,UrlSource as n,BufferSource as u,VideoSampleSink as i,ALL_FORMATS as a}from"mediabunny";import{incrementLoader as c,triggerLoadError as o}from"../utils/loader.js";import{polotnoError as s}from"@polotno/core/errors";import{getElementTimeRange as l,getVideoRestMs as d}from"../utils/timeline.js";import{decodeBase64 as m}from"../utils/base64.js";function f(e,r){const t=p(e);return t>0&&r>=e.timestamp&&r<e.timestamp+t}function p(e){var r;const t=null!==(r=e.duration)&&void 0!==r?r:0;return Number.isFinite(t)&&t>0?t:0}function h(e){var r;null===(r=null==e?void 0:e.close)||void 0===r||r.call(e)}function v(e){for(const r of e.current){h(r.frame)}e.current=[]}export const useMediabunnyVideo=(g,w,y)=>{const[b,T]=e.useState({input:null,videoSink:null,duration:0,isReady:!1,error:null,hasAlpha:!1});e.useRef(b).current=b;const R=e.useRef(0),E=e.useRef(null),k=e.useRef(null),$=e.useRef(null),S=e.useRef(null),O=e.useRef(null),F=e.useRef(null),j=e.useRef(null),x=e.useRef(!1),D=e.useRef(null),I=e.useRef([]),A=e.useRef(null),_=e.useRef(!1),[,M]=e.useReducer(e=>e+1,0);return e.useEffect(()=>{if(!y){return}let e=!0;const r=++R.current;let l=null;return(async()=>{try{if(!e||r!==R.current){return}l=c(`mediabunny init ${g.id}`);const o=await async function(e){if(function(e){return e.startsWith("data:")}(e)){const r=function(e){const r=e.indexOf(",");if(-1===r){throw new Error("Invalid data URL format")}return m(e.slice(r+1)).buffer}(e);return new u(r)}if(function(e){return e.startsWith("file://")}(e)){try{const r=await fetch(e),t=await r.arrayBuffer();return new u(t)}catch(r){throw new Error(`Failed to load file URL: ${e}. File URLs may not be supported in this environment. Error: ${r}`)}}return new n(e)}(g.src);if(!e||r!==R.current){return void(l&&(l(),l=null))}const d=new t({source:o,formats:a}),f=await d.computeDuration(),p=await d.getPrimaryVideoTrack();if(!p){throw s("VIDEO_FAILED","No video track found",{reason:"no-video-track"})}if(null===p.codec){throw s("VIDEO_FAILED","Unsupported video codec",{reason:"unsupported-codec"})}if(!await p.canDecode()){throw s("VIDEO_FAILED","Unable to decode the video track",{reason:"cannot-decode"})}const h=await p.canBeTransparent(),v=new i(p);if(!e||r!==R.current){return d.dispose(),void(l&&(l(),l=null))}l&&(l(),l=null),T(e=>Object.assign(Object.assign({},e),{input:d,videoSink:v,duration:f,isReady:!0,error:null,hasAlpha:h}))}catch(d){if(console.error("Failed to initialize mediabunny:",d),l&&(l(),l=null),e&&r===R.current){const e=`Failed to initialize mediabunny for video ${g.id}: ${d}`;o(s("VIDEO_FAILED",e,Object.assign({reason:"load"},null==d?void 0:d.details),d)),T(e=>Object.assign(Object.assign({},e),{error:String(d),isReady:!1}))}}})(),()=>{e=!1,l&&(l(),l=null)}},[g.src,y]),e.useEffect(()=>()=>{k.current&&(k.current.return(),k.current=null),E.current&&(E.current(),E.current=null),$.current=null,S.current=null,O.current=null,F.current=null,x.current=!1,D.current=null,v(I),A.current=null,_.current=!1,T({input:null,videoSink:null,duration:0,isReady:!1,error:null,hasAlpha:!1})},[y]),e.useEffect(()=>{if(!y||!b.isReady||!b.videoSink){return}const e=++R.current,t="string"==typeof g.src?g.src.slice(0,120):String(g.src),n=(e,r={},n="debug")=>{var u;let i="";try{i=JSON.stringify(Object.assign(Object.assign({},r),{timeCalc:j.current}))}catch(c){i=`[unserializable extras: ${String(c)}]`}const a=`mediabunny event=${e} elementId=${g.id} targetTime=${F.current} duration=${b.duration} lastFrameTimestamp=${null===(u=O.current)||void 0===u?void 0:u.timestamp} hasIterator=${Boolean(k.current)} prefetchSize=${I.current.length} srcHint=${t} extras=${i}`;"error"===n?console.error(a):"warn"===n?console.warn(a):console.debug(a)},u=e=>{const r=b.duration||0;return r&&Number.isFinite(r)?Math.max(0,Math.min(e,r)):e},i=e=>{const r=e.displayWidth,t=e.displayHeight;let n=$.current;n&&n.width===r&&n.height===t||(n||(n=document.createElement("canvas"),$.current=n,S.current=n.getContext("2d",{alpha:b.hasAlpha})),n.width=r,n.height=t);const u=S.current,i=e.timestamp,a=p(e);try{u&&(b.hasAlpha&&u.clearRect(0,0,n.width,n.height),e.drawWithFit(u,{fit:"contain"}))}finally{h(e)}O.current={timestamp:i,duration:a}},a=e=>{const r=k.current;r&&(_.current||(_.current=!0,A.current=(async()=>{try{for(;I.current.length<4&&e===R.current;){const t=await r.next();if(e!==R.current){return void h(t.value)}if(t.done||!t.value){break}I.current.push({timestamp:t.value.timestamp,frame:t.value})}}catch(t){}finally{_.current=!1,A.current=null}})()))},o=e=>{const r=I.current;let t=-1;for(let u=0;u<r.length&&!(r[u].timestamp>e);u++){t=u}if(-1===t){return null}const n=r[t];if(!(t<r.length-1||f(n.frame,e))){return null}for(let u=0;u<t;u++){h(r[u].frame)}return I.current=r.slice(t+1),n},s=()=>v(I),m=async(e,r,t=0)=>{const c=u(e),l=(e=>{const r=O.current;return!r||e<r.timestamp||e>r.timestamp+.5})(c)?"seek":"iterate";try{const t=b.videoSink,u=O.current;if(u&&f(u,c)){return void(F.current=e)}const d=o(c);if(d){return i(d.frame),F.current=e,a(r),void M()}if(A.current){await A.current;const t=o(c);if(t){return i(t.frame),F.current=e,a(r),void M()}}s();const m=()=>n("iterator_exhausted",{mode:l,requestedTargetTime:e,clampedTargetTime:c},"warn"),p=async e=>{k.current&&(await k.current.return(),k.current=null),s();const n=t.samples(e);k.current=n;const u=await n.next();return r!==R.current?(u.value&&h(u.value),await n.return(),k.current===n&&(k.current=null),"cancelled"):u.done||!u.value?"empty":(i(u.value),a(r),"drawn")};if("seek"===l){const e=await p(c);if("cancelled"===e){return}if("empty"===e){return void m()}}else{const e=k.current;if(!e){return}for(;r===R.current;){const t=await e.next();if(r!==R.current){t.value&&h(t.value);break}if(t.done||!t.value){"empty"===await p(c)&&m();break}const n=t.value;if(f(n,c)||n.timestamp>=c){i(n),a(r);break}h(n)}}F.current=e,M()}catch(d){const u=d instanceof Error?{name:d.name,message:d.message,stack:d.stack}:{message:String(d)},i=d instanceof Error?`${d.name}: ${d.message}`:String(d),a=i.includes("Unsupported configuration")||i.includes("isConfigSupported")||i.includes("OperationError");if(n("frame_process_failed",{mode:l,requestedTargetTime:e,clampedTargetTime:c,unsupportedConfigAttempt:t,isUnsupportedConfig:a,error:u},"error"),a&&t<1){try{k.current&&(await k.current.return(),k.current=null),s(),A.current=null,_.current=!1,O.current=null,await m(e,r,t+1)}catch(p){}}}},T=r(g,()=>{var r;const t=b.videoSink,n=b.duration;if(!t||!n){return}const i=g.startTime*n*1e3,a=n*(g.endTime-g.startTime)*1e3,{start:o,end:s}=l(g.animations,g.page.duration),f=d(null!==(r=g.page._mediaLocalTime)&&void 0!==r?r:0,0,o,a,i,g.speed,{windowEnd:s,frameMs:w._renderFrameMs,renderEnd:w._renderEndMs-g.page.startTime}),p=f/1e3+1e-6,h=u(p);j.current={pageStartTime:g.page.startTime,storeCurrentTime:w.currentTime,offsetMs:i,durationMs:a,restMs:f,targetTime:p,clampedTargetTime:h,startTime:g.startTime,endTime:g.endTime,videoDuration:n},((e,r)=>{x.current?D.current=e:(x.current=!0,E.current||(E.current=c(`mediabunny video frame ${g.id}`)),(async()=>{let t=e;for(;null!==t&&r===R.current;){await m(t,r),t=D.current,D.current=null}E.current&&(E.current(),E.current=null),x.current=!1})())})(p,e)});return()=>{T(),R.current++,E.current&&(E.current(),E.current=null)}},[y,b.isReady,b.videoSink,b.duration,w,g]),y&&b.isReady?$.current:null};
1
+ import e from"react";import{nodeAutorun as r}from"../utils/mobx.js";import{Input as t,UrlSource as n,BufferSource as u,VideoSampleSink as i,ALL_FORMATS as a}from"mediabunny";import{incrementLoader as c,triggerLoadError as o}from"../utils/loader.js";import{polotnoError as s}from"@polotno/core/errors";import{getElementTimeRange as l,getVideoRestMs as d}from"../utils/timeline.js";import{decodeBase64 as m}from"../utils/base64.js";function f(e,r){const t=p(e);return t>0&&r>=e.timestamp&&r<e.timestamp+t}function p(e){var r;const t=null!==(r=e.duration)&&void 0!==r?r:0;return Number.isFinite(t)&&t>0?t:0}function h(e){var r;null===(r=null==e?void 0:e.close)||void 0===r||r.call(e)}function v(e){for(const r of e.current){h(r.frame)}e.current=[]}export const useMediabunnyVideo=(g,w,y)=>{const[b,T]=e.useState({input:null,videoSink:null,duration:0,isReady:!1,error:null,hasAlpha:!1});e.useRef(b).current=b;const R=e.useRef(0),E=e.useRef(null),k=e.useRef(null),$=e.useRef(null),S=e.useRef(null),O=e.useRef(null),F=e.useRef(null),j=e.useRef(null),x=e.useRef(!1),D=e.useRef(null),I=e.useRef([]),A=e.useRef(null),_=e.useRef(!1),[,M]=e.useReducer(e=>e+1,0);return e.useEffect(()=>{if(!y){return}let e=!0;const r=++R.current;let l=null;return(async()=>{try{if(!e||r!==R.current){return}l=c(`mediabunny init ${g.id}`);const o=await async function(e){if(function(e){return e.startsWith("data:")}(e)){const r=function(e){const r=e.indexOf(",");if(-1===r){throw new Error("Invalid data URL format")}return m(e.slice(r+1)).buffer}(e);return new u(r)}if(function(e){return e.startsWith("file://")}(e)){try{const r=await fetch(e),t=await r.arrayBuffer();return new u(t)}catch(r){throw new Error(`Failed to load file URL: ${e}. File URLs may not be supported in this environment. Error: ${r}`)}}return new n(e)}(g.a.src);if(!e||r!==R.current){return void(l&&(l(),l=null))}const d=new t({source:o,formats:a}),f=await d.computeDuration(),p=await d.getPrimaryVideoTrack();if(!p){throw s("VIDEO_FAILED","No video track found",{reason:"no-video-track"})}if(null===p.codec){throw s("VIDEO_FAILED","Unsupported video codec",{reason:"unsupported-codec"})}if(!await p.canDecode()){throw s("VIDEO_FAILED","Unable to decode the video track",{reason:"cannot-decode"})}const h=await p.canBeTransparent(),v=new i(p);if(!e||r!==R.current){return d.dispose(),void(l&&(l(),l=null))}l&&(l(),l=null),T(e=>Object.assign(Object.assign({},e),{input:d,videoSink:v,duration:f,isReady:!0,error:null,hasAlpha:h}))}catch(d){if(console.error("Failed to initialize mediabunny:",d),l&&(l(),l=null),e&&r===R.current){const e=`Failed to initialize mediabunny for video ${g.id}: ${d}`;o(s("VIDEO_FAILED",e,Object.assign({reason:"load"},null==d?void 0:d.details),d)),T(e=>Object.assign(Object.assign({},e),{error:String(d),isReady:!1}))}}})(),()=>{e=!1,l&&(l(),l=null)}},[g.a.src,y]),e.useEffect(()=>()=>{k.current&&(k.current.return(),k.current=null),E.current&&(E.current(),E.current=null),$.current=null,S.current=null,O.current=null,F.current=null,x.current=!1,D.current=null,v(I),A.current=null,_.current=!1,T({input:null,videoSink:null,duration:0,isReady:!1,error:null,hasAlpha:!1})},[y]),e.useEffect(()=>{if(!y||!b.isReady||!b.videoSink){return}const e=++R.current,t="string"==typeof g.a.src?g.a.src.slice(0,120):String(g.a.src),n=(e,r={},n="debug")=>{var u;let i="";try{i=JSON.stringify(Object.assign(Object.assign({},r),{timeCalc:j.current}))}catch(c){i=`[unserializable extras: ${String(c)}]`}const a=`mediabunny event=${e} elementId=${g.id} targetTime=${F.current} duration=${b.duration} lastFrameTimestamp=${null===(u=O.current)||void 0===u?void 0:u.timestamp} hasIterator=${Boolean(k.current)} prefetchSize=${I.current.length} srcHint=${t} extras=${i}`;"error"===n?console.error(a):"warn"===n?console.warn(a):console.debug(a)},u=e=>{const r=b.duration||0;return r&&Number.isFinite(r)?Math.max(0,Math.min(e,r)):e},i=e=>{const r=e.displayWidth,t=e.displayHeight;let n=$.current;n&&n.width===r&&n.height===t||(n||(n=document.createElement("canvas"),$.current=n,S.current=n.getContext("2d",{alpha:b.hasAlpha})),n.width=r,n.height=t);const u=S.current,i=e.timestamp,a=p(e);try{u&&(b.hasAlpha&&u.clearRect(0,0,n.width,n.height),e.drawWithFit(u,{fit:"contain"}))}finally{h(e)}O.current={timestamp:i,duration:a}},a=e=>{const r=k.current;r&&(_.current||(_.current=!0,A.current=(async()=>{try{for(;I.current.length<4&&e===R.current;){const t=await r.next();if(e!==R.current){return void h(t.value)}if(t.done||!t.value){break}I.current.push({timestamp:t.value.timestamp,frame:t.value})}}catch(t){}finally{_.current=!1,A.current=null}})()))},o=e=>{const r=I.current;let t=-1;for(let u=0;u<r.length&&!(r[u].timestamp>e);u++){t=u}if(-1===t){return null}const n=r[t];if(!(t<r.length-1||f(n.frame,e))){return null}for(let u=0;u<t;u++){h(r[u].frame)}return I.current=r.slice(t+1),n},s=()=>v(I),m=async(e,r,t=0)=>{const c=u(e),l=(e=>{const r=O.current;return!r||e<r.timestamp||e>r.timestamp+.5})(c)?"seek":"iterate";try{const t=b.videoSink,u=O.current;if(u&&f(u,c)){return void(F.current=e)}const d=o(c);if(d){return i(d.frame),F.current=e,a(r),void M()}if(A.current){await A.current;const t=o(c);if(t){return i(t.frame),F.current=e,a(r),void M()}}s();const m=()=>n("iterator_exhausted",{mode:l,requestedTargetTime:e,clampedTargetTime:c},"warn"),p=async e=>{k.current&&(await k.current.return(),k.current=null),s();const n=t.samples(e);k.current=n;const u=await n.next();return r!==R.current?(u.value&&h(u.value),await n.return(),k.current===n&&(k.current=null),"cancelled"):u.done||!u.value?"empty":(i(u.value),a(r),"drawn")};if("seek"===l){const e=await p(c);if("cancelled"===e){return}if("empty"===e){return void m()}}else{const e=k.current;if(!e){return}for(;r===R.current;){const t=await e.next();if(r!==R.current){t.value&&h(t.value);break}if(t.done||!t.value){"empty"===await p(c)&&m();break}const n=t.value;if(f(n,c)||n.timestamp>=c){i(n),a(r);break}h(n)}}F.current=e,M()}catch(d){const u=d instanceof Error?{name:d.name,message:d.message,stack:d.stack}:{message:String(d)},i=d instanceof Error?`${d.name}: ${d.message}`:String(d),a=i.includes("Unsupported configuration")||i.includes("isConfigSupported")||i.includes("OperationError");if(n("frame_process_failed",{mode:l,requestedTargetTime:e,clampedTargetTime:c,unsupportedConfigAttempt:t,isUnsupportedConfig:a,error:u},"error"),a&&t<1){try{k.current&&(await k.current.return(),k.current=null),s(),A.current=null,_.current=!1,O.current=null,await m(e,r,t+1)}catch(p){}}}},T=r(g,()=>{var r;const t=b.videoSink,n=b.duration;if(!t||!n){return}const i=g.startTime*n*1e3,a=n*(g.endTime-g.startTime)*1e3,{start:o,end:s}=l(g.animations,g.page.duration),f=d(null!==(r=g.page._mediaLocalTime)&&void 0!==r?r:0,0,o,a,i,g.speed,{windowEnd:s,frameMs:w._renderFrameMs,renderEnd:w._renderEndMs-g.page.startTime}),p=f/1e3+1e-6,h=u(p);j.current={pageStartTime:g.page.startTime,storeCurrentTime:w.currentTime,offsetMs:i,durationMs:a,restMs:f,targetTime:p,clampedTargetTime:h,startTime:g.startTime,endTime:g.endTime,videoDuration:n},((e,r)=>{x.current?D.current=e:(x.current=!0,E.current||(E.current=c(`mediabunny video frame ${g.id}`)),(async()=>{let t=e;for(;null!==t&&r===R.current;){await m(t,r),t=D.current,D.current=null}E.current&&(E.current(),E.current=null),x.current=!1})())})(p,e)});return()=>{T(),R.current++,E.current&&(E.current(),E.current=null)}},[y,b.isReady,b.videoSink,b.duration,w,g]),y&&b.isReady?$.current:null};
@@ -1 +1 @@
1
- import{Fragment as e,jsx as t,jsxs as r}from"react/jsx-runtime";import{elementOpacity as o}from"./paint-opacity.js";import i from"react";import{toDisplayColor as n}from"@polotno/core/color";import{animatedShadow as a}from"./animated-shadow.js";import{observer as s}from"mobx-react-lite";import{isAlive as d}from"mobx-state-tree";import{nodeAutorun as l}from"../utils/mobx.js";import{Group as c,Image as u,Rect as h}from"react-konva";import{ROLES as m}from"../model/store.js";import{DEFAULT_RETRIES as p,isDeterministicUrl as g,retryDelayMs as f}from"@polotno/core/retry";import v from"konva";import{ErrorPlaceholder as w,LoadingPlaceholder as x}from"./media-placeholders.js";import{incrementLoader as E,triggerLoadError as L}from"../utils/loader.js";import{polotnoError as M}from"@polotno/core/errors";import{getCropRect as y}from"@polotno/core/image";import*as C from"@polotno/core/svg";import{roundedPosition as b}from"../utils/px.js";import{useMediaResize as k}from"./media-resize.js";import{useFilteredSource as T}from"./use-filtered-source.js";import{useOffscreenCanvas as j}from"./use-offscreen-canvas.js";import{useEvent as I}from"../hooks/use-event.js";import{useFadeIn as R}from"./use-fadein.js";import{useAnimatedBlur as S}from"./use-animated-blur.js";import{isTouchDevice as P}from"../utils/screen.js";import{createPlayGate as _,playMedia as A}from"../utils/media.js";import{useMediabunnyVideo as V}from"./use-mediabunny-video.js";import{getElementTimeRange as D,getVideoRestMs as z,isHeldByPreview as F}from"../utils/timeline.js";import{drawReduced as H,exportKernelEnabled as O,shouldResample as U,sourceSize as W}from"./downscale.js";import{trySetCanvasSize as Z}from"../utils/canvas.js";import{useClipImage as X}from"./image-element.js";import{CropOverlay as Y,CROP_CORNER_ANCHORS as N}from"./crop-overlay.js";const q=new window.Image;q.src=C.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 $=new window.Image;$.src=C.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 useFlip=(e,t)=>{const{flipX:r,flipY:o}=e,{width:i,height:n}=t?W(t):{},a=e=>{if(!t){return}const i=e.getContext("2d");i&&(i.clearRect(0,0,e.width,e.height),i.save(),i.scale(r?-1:1,o?-1:1),i.drawImage(t,r?-e.width:0,o?-e.height:0,e.width,e.height),i.restore())},s=j((r||o)&&!!i&&!!n,e=>{i&&n&&(e.width=i,e.height=n,a(e))},[r,o,t,i,n]);return[s||t,()=>{s&&a(s)}]};export const useCornerRadiusAndCrop=(e,t,r,o,n=0,a=!1)=>{var s;const d=Math.floor(Math.max(e.a.width*o,1)),l=Math.floor(Math.max(e.a.height*o,1)),c=Math.min(n*o,d/2,l/2),u=Math.max(e.a.width/r.width,e.a.height/r.height)*o,h=O(e.page)&&!a&&U(u,d,l),{width:m,height:p}=t?W(t):{},g=0===r.x&&0===r.y&&r.width===m&&r.height===p,f=i.useMemo(()=>{if(t&&m&&p){return g&&0===c&&!h?void 0:document.createElement("canvas")}},[t,c,h,g,m,p]),w=()=>{if(!f||!t){return}f.width=d,f.height=l;const e=f.getContext("2d");e&&(c&&(e.beginPath(),e.moveTo(c,0),e.lineTo(d-c,0),e.arc(d-c,c,c,3*Math.PI/2,0,!1),e.lineTo(d,l-c),e.arc(d-c,l-c,c,0,Math.PI/2,!1),e.lineTo(c,l),e.arc(c,l-c,c,Math.PI/2,Math.PI,!1),e.lineTo(0,c),e.arc(c,c,c,Math.PI,3*Math.PI/2,!1),e.clip()),h?H(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 i.useLayoutEffect(()=>{w()},[f,e.a.width,e.a.height,r.x,r.y,r.width,r.height,n,o,a,null===(s=e.page)||void 0===s?void 0:s._exportingOrRendering,h]),i.useEffect(()=>()=>{f&&"CANVAS"===f.nodeName&&v.Util.releaseCanvas(f)},[f]),[f||t,w]};export const useClip=(e,t,r,o)=>{const[n,a]=X(e.clipSrc||""),s=e.clipSrc?a:"loaded";useLoader(s,e.clipSrc,e.id);const d=!!t&&!!n,l=i.useMemo(()=>d?{canvas:document.createElement("canvas"),mask:document.createElement("canvas"),width:0,height:0}:void 0,[d]),c=null==l?void 0:l.canvas;function u(){if(!l||!c||!t){return}const{width:o,height:i}=W(t);if(!o||!i){return}const n=Math.min(1e4,Math.max(o,Math.ceil(e.a.width*r),1)),a=Math.min(1e4,Math.max(i,Math.ceil(e.a.height*r),1));c.width&&l.width===n&&l.height===a||(Z(c,n,a),l.width=n,l.height=a);const s=c.getContext("2d");s&&(s.clearRect(0,0,c.width,c.height),s.save(),s.drawImage(t,0,0,c.width,c.height),s.globalCompositeOperation="destination-in",s.drawImage(l.mask,0,0,c.width,c.height),s.restore())}return i.useLayoutEffect(()=>{var t;if(!l||!(null==n?void 0:n.width)||!n.height){return}const o=Math.max(e.a.width/n.width*r,e.a.height/n.height*r);Z(l.mask,Math.min(1e4,Math.max(n.width*o,1)),Math.min(1e4,Math.max(n.height*o,1))),null===(t=l.mask.getContext("2d"))||void 0===t||t.drawImage(n,0,0,l.mask.width,l.mask.height)},[l,n,e.a.width,e.a.height,r]),i.useLayoutEffect(()=>{u()},[l,t,n,e.a.width,e.a.height,r,...o]),i.useEffect(()=>()=>{l&&v.Util.releaseCanvas(l.canvas,l.mask)},[l]),[d?c:t,u]};const B=document.createElement("canvas");let G=function(e,t,r){const o=i.useRef("loading"),n=i.useRef(void 0),[a,s]=i.useState(0),d=i.useRef(void 0),l=i.useRef(void 0),c=i.useRef(void 0);return d.current===e&&l.current===t&&c.current===r||(o.current="loading",n.current=void 0,d.current=e,l.current=t,c.current=r),i.useLayoutEffect(()=>{if(!e){return}const i=g(e)?1:p;let a,d,l,c=0,u=!1,h=!1;const m=e=>{e&&(e.removeAttribute("src"),e.load())},v=()=>{c+=1;const p=document.createElement("video");function g(){u||(p.removeEventListener("canplay",g),h=!0,o.current="loaded",n.current=p,p.currentTime=0,s(Math.random()))}function w(e){var t;const r=4===p.readyState,l=p.buffered&&p.buffered.length>0&&p.buffered.end(p.buffered.length-1)/p.duration*100>=100;if(r&&l){return}if(u){return}if(!h&&c<i){return null==d||d(),m(p),void(a=setTimeout(v,f(c)))}const g=e.message||(null===(t=p.error)||void 0===t?void 0:t.message)||"Unknown error";console.error(new Error("Video failed to load: "+g)),o.current="failed",n.current=void 0,s(Math.random())}l=p,p.addEventListener("canplay",g),p.addEventListener("error",w),d=()=>{p.removeEventListener("canplay",g),p.removeEventListener("error",w)},t&&(p.crossOrigin=t),r&&(p.referrerPolicy=r),p.src=e,p.load()};return v(),()=>{u=!0,clearTimeout(a),null==d||d(),h||m(l)}},[e,t,r]),[n.current,o.current]};export const setVideoLoaderHook=e=>{G=e};function J(e){return!e.seeking&&e.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA}export const useLoader=(e,t,r)=>{const o=i.useRef(void 0),n=()=>{var e;null===(e=o.current)||void 0===e||e.call(o),o.current=void 0};i.useEffect(()=>n,[]),i.useLayoutEffect(()=>{const i=t.slice(0,200),a=`video with id ${r} url: ${i}`;"loading"!==e||o.current||(o.current=E(a)),"loading"!==e&&n(),"failed"===e&&L(M("VIDEO_FAILED",a,{src:i,elementId:r,reason:"load"}))},[e])};export const VideoElement=s(({element:s,store:p})=>{var g,f,L,M,C;const[j,H]=i.useState(!1),O=i.useRef(null),U=P(),[Z,X]=i.useState(!1),[K,Q]=G(s.src,"anonymous"),[ee,te]=i.useState(!1),re=p.activePage===s.page,oe=(null===(g=s.page)||void 0===g?void 0:g._exportingOrRendering)&&"loaded"===Q,ie=V(s,p,oe);useLoader(Q,s.src,s.id),K&&(K.playsInline=!0);const ne=oe&&ie||K,[ae,se]=useFlip(s,ne),[de=B,le]=T(s,ae||B);i.useEffect(()=>{K&&p.history.ignore(()=>{s.set({duration:1e3*K.duration})})},[K]);const ce=i.useMemo(_,[K]);i.useEffect(()=>{var e;if(!K){return}const t=!F(s)&&p.isPlaying;if(!re||!t&&!Z){return void K.pause()}Z&&(K.muted=!1,K.currentTime=s.startTime*K.duration,A(K).then(e=>{"refused"===e&&X(!1)}));const r=new v.Animation(()=>{Ie()},null===(e=O.current)||void 0===e?void 0:e.getLayer());r.start();const o=()=>{X(!1),K.currentTime=s.startTime*K.duration},i=()=>{K.currentTime>=s.endTime*K.duration&&(K.pause(),K.currentTime=s.startTime*K.duration,X(!1))};return K.addEventListener("ended",o),K.addEventListener("timeupdate",i),()=>{K.pause(),r.stop(),K.removeEventListener("ended",o),K.removeEventListener("timeupdate",i)}},[K,Z,p.isPlaying,re]),i.useEffect(()=>{K&&(K.volume=s.volume)},[K,s.volume]),i.useEffect(()=>{K&&(K.playbackRate=s.speed,K.preservesPitch=!1)},[K,s.speed]);const ue=i.useRef(null);i.useEffect(()=>{const e=l(s,()=>{var e,t;if(K){if(oe&&ie){return Ie(),void p.currentTime}if(F(s)){return}const r=p.activePage===s.page,o=s.page._mediaLocalTime,i=s.startTime*K.duration*1e3,n=K.duration*(s.endTime-s.startTime)*1e3,{start:a,end:d}=D(s.animations,s.page.duration),l=z(null!=o?o:0,0,a,n,i,s.speed,{windowEnd:d,frameMs:p._renderFrameMs,renderEnd:p._renderEndMs-s.page.startTime}),c=l/1e3,u=null!==o&&o>=a&&o<d;Z||(K.muted=!u,u&&p.isPlaying&&r?K.paused?(K.currentTime=c,ce.play(K)):Math.abs(1e3*K.currentTime-l)>500&&(K.currentTime=c):(ce.reset(),K.paused||K.pause(),c!==K.currentTime&&(K.currentTime=c),!J(K)&&!p.isPlaying&&!ue.current&&(ue.current=E(`video ${s.id}`)))),Ie(),null===(t=null===(e=O.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()}});return()=>{e(),ue.current&&(ue.current(),ue.current=null)}},[p,K,oe,ie,Z]),i.useEffect(()=>{var e,t;if(!K){return}if(oe){return null===(e=ue.current)||void 0===e||e.call(ue),void(ue.current=null)}const r=()=>{var e;null===(e=ue.current)||void 0===e||e.call(ue),ue.current=null},o=()=>{J(K)&&(Ie(),r())};let i,n;(null===(t=s.page)||void 0===t?void 0:t._exportingOrRendering)&&(i=setInterval(o,20)),K.addEventListener("timeupdate",o),K.addEventListener("canplay",o),K.addEventListener("seeked",o);const a=()=>{K.paused&&(Ie(),J(K)&&r()),n=K.requestVideoFrameCallback(a)};return"requestVideoFrameCallback"in K&&(n=K.requestVideoFrameCallback(a)),()=>{clearInterval(i),void 0!==n&&K.cancelVideoFrameCallback(n),K.removeEventListener("timeupdate",o),K.removeEventListener("canplay",o),K.removeEventListener("seeked",o)}},[null===(f=s.page)||void 0===f?void 0:f._exportingOrRendering,K,s.id,E,oe]);let{cropX:he,cropY:me,cropWidth:pe,cropHeight:ge}=s.a;"loaded"!==Q&&(he=me=0,pe=ge=1);const{width:fe,height:ve}=W(de),we=null!==(L=null==K?void 0:K.videoWidth)&&void 0!==L?L:0,xe=null!==(M=null==K?void 0:K.videoHeight)&&void 0!==M?M:0;i.useLayoutEffect(()=>{"loaded"===Q&&we>0&&xe>0&&s._setSourceSize({width:we,height:xe},s.src)},[s,s.src,Q,we,xe]);const Ee=y({stretchEnabled:s.stretchEnabled,cropX:he,cropY:me,cropWidth:pe,cropHeight:ge,width:s.a.width,height:s.a.height},{width:fe,height:ve}),Le=Ee.width,Me=Ee.height,ye=null!==(C=s.cornerRadius)&&void 0!==C?C:0,[Ce,be]=useCornerRadiusAndCrop(s,de,Ee,p._elementsPixelRatio,ye,!0);let[ke,Te]=useClip(s,Ce,p._elementsPixelRatio,[Ee,ye,p._elementsPixelRatio]);const je=S(O,s,ke),Ie=I(()=>{var e,t;se(),le(),be(),Te(),je(),null===(t=null===(e=O.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()});i.useEffect(()=>{Ie()});const Re=()=>{s._cropEnabled&&setTimeout(()=>{d(s)&&s.toggleCropMode(!0)})},Se="loading"===Q,Pe="failed"===Q,_e=!Se&&!Pe,Ae=k(s,Ee,"loaded"===Q?{width:fe,height:ve}:void 0,H),Ve=_e?o(s):0;R(O,Ve);const De=s.selectable||p.role===m.ADMIN;return t(e,{children:r(c,{onMouseEnter:()=>te(!0),onMouseLeave:()=>te(!1),children:[Se&&t(x,{element:s}),Pe&&t(w,{element:s,text:"Can not load the video..."}),t(u,Object.assign({ref:O,name:"element",id:s.id,image:ke,x:s.a.x,y:s.a.y,width:s.a.width||1,height:s.a.height||1,rotation:s.a.rotation,opacity:Ve},a(s),{customCrop:Ee,listening:De,draggable:U?s.draggable&&s.isSelected:s.draggable,preventDefault:!U||s.isSelected,hideInExport:!s.showInExport,onDragMove:e=>{s.set({x:e.target.x(),y:e.target.y()})},onDragEnd:e=>{s.set(b(e.target))},onDblClick:Re,onDblTap:Re},Ae)),!!s.borderSize&&t(h,{x:s.a.x,y:s.a.y,width:Math.max(s.a.width-s.borderSize,0),height:Math.max(s.a.height-s.borderSize,0),opacity:Ve,offsetX:-s.borderSize/2,offsetY:-s.borderSize/2,stroke:n(s.borderColor),strokeWidth:s.borderSize,listening:!1,rotation:s.a.rotation,cornerRadius:Math.max(0,ye-s.borderSize),hideInExport:!s.showInExport}),!p.isPlaying&&t(u,{image:Z?ee||U?$:void 0:q,x:s.a.x,y:s.a.y,offsetX:-s.a.width/2+15/p.scale,offsetY:-s.a.height/2+15/p.scale,rotation:s.a.rotation,width:30/p.scale,height:30/p.scale,hideInExport:!0,onClick:()=>X(!Z),onTap:()=>X(!Z)}),s._cropModeEnabled&&"loaded"===Q&&t(Y,{element:s,store:p,previewImage:ke,sourceImage:de,sourceWidth:fe,sourceHeight:ve,cropAbsoluteWidth:Le,cropAbsoluteHeight:Me,innerAnchors:N})]})})});
1
+ import{Fragment as e,jsx as t,jsxs as r}from"react/jsx-runtime";import{elementOpacity as o}from"./paint-opacity.js";import i from"react";import{toDisplayColor as n}from"@polotno/core/color";import{animatedShadow as a}from"./animated-shadow.js";import{observer as s}from"mobx-react-lite";import{isAlive as d}from"mobx-state-tree";import{nodeAutorun as l}from"../utils/mobx.js";import{Group as c,Image as u,Rect as h}from"react-konva";import{ROLES as m}from"../model/store.js";import{DEFAULT_RETRIES as p,isDeterministicUrl as g,retryDelayMs as f}from"@polotno/core/retry";import v from"konva";import{ErrorPlaceholder as w,LoadingPlaceholder as x}from"./media-placeholders.js";import{incrementLoader as E,triggerLoadError as L}from"../utils/loader.js";import{polotnoError as M}from"@polotno/core/errors";import{getCropRect as y}from"@polotno/core/image";import*as C from"@polotno/core/svg";import{roundedPosition as b}from"../utils/px.js";import{useMediaResize as k}from"./media-resize.js";import{useFilteredSource as T}from"./use-filtered-source.js";import{useOffscreenCanvas as j}from"./use-offscreen-canvas.js";import{useEvent as I}from"../hooks/use-event.js";import{useFadeIn as R}from"./use-fadein.js";import{useAnimatedBlur as S}from"./use-animated-blur.js";import{isTouchDevice as P}from"../utils/screen.js";import{createPlayGate as _,playMedia as A}from"../utils/media.js";import{useMediabunnyVideo as V}from"./use-mediabunny-video.js";import{getElementTimeRange as D,getVideoRestMs as z,isHeldByPreview as F}from"../utils/timeline.js";import{drawReduced as O,exportKernelEnabled as H,shouldResample as U,sourceSize as Z}from"./downscale.js";import{trySetCanvasSize as W}from"../utils/canvas.js";import{useClipImage as X}from"./image-element.js";import{CropOverlay as Y,CROP_CORNER_ANCHORS as N}from"./crop-overlay.js";const q=new window.Image;q.src=C.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 $=new window.Image;$.src=C.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 useFlip=(e,t)=>{const{flipX:r,flipY:o}=e,{width:i,height:n}=t?Z(t):{},a=e=>{if(!t){return}const i=e.getContext("2d");i&&(i.clearRect(0,0,e.width,e.height),i.save(),i.scale(r?-1:1,o?-1:1),i.drawImage(t,r?-e.width:0,o?-e.height:0,e.width,e.height),i.restore())},s=j((r||o)&&!!i&&!!n,e=>{i&&n&&(e.width=i,e.height=n,a(e))},[r,o,t,i,n]);return[s||t,()=>{s&&a(s)}]};export const useCornerRadiusAndCrop=(e,t,r,o,n=0,a=!1)=>{var s;const d=Math.floor(Math.max(e.a.width*o,1)),l=Math.floor(Math.max(e.a.height*o,1)),c=Math.min(n*o,d/2,l/2),u=Math.max(e.a.width/r.width,e.a.height/r.height)*o,h=H(e.page)&&!a&&U(u,d,l),{width:m,height:p}=t?Z(t):{},g=0===r.x&&0===r.y&&r.width===m&&r.height===p,f=i.useMemo(()=>{if(t&&m&&p){return g&&0===c&&!h?void 0:document.createElement("canvas")}},[t,c,h,g,m,p]),w=()=>{if(!f||!t){return}f.width=d,f.height=l;const e=f.getContext("2d");e&&(c&&(e.beginPath(),e.moveTo(c,0),e.lineTo(d-c,0),e.arc(d-c,c,c,3*Math.PI/2,0,!1),e.lineTo(d,l-c),e.arc(d-c,l-c,c,0,Math.PI/2,!1),e.lineTo(c,l),e.arc(c,l-c,c,Math.PI/2,Math.PI,!1),e.lineTo(0,c),e.arc(c,c,c,Math.PI,3*Math.PI/2,!1),e.clip()),h?O(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 i.useLayoutEffect(()=>{w()},[f,e.a.width,e.a.height,r.x,r.y,r.width,r.height,n,o,a,null===(s=e.page)||void 0===s?void 0:s._exportingOrRendering,h]),i.useEffect(()=>()=>{f&&"CANVAS"===f.nodeName&&v.Util.releaseCanvas(f)},[f]),[f||t,w]};export const useClip=(e,t,r,o)=>{const[n,a]=X(e.clipSrc||""),s=e.clipSrc?a:"loaded";useLoader(s,e.clipSrc,e.id);const d=!!t&&!!n,l=i.useMemo(()=>d?{canvas:document.createElement("canvas"),mask:document.createElement("canvas"),width:0,height:0}:void 0,[d]),c=null==l?void 0:l.canvas;function u(){if(!l||!c||!t){return}const{width:o,height:i}=Z(t);if(!o||!i){return}const n=Math.min(1e4,Math.max(o,Math.ceil(e.a.width*r),1)),a=Math.min(1e4,Math.max(i,Math.ceil(e.a.height*r),1));c.width&&l.width===n&&l.height===a||(W(c,n,a),l.width=n,l.height=a);const s=c.getContext("2d");s&&(s.clearRect(0,0,c.width,c.height),s.save(),s.drawImage(t,0,0,c.width,c.height),s.globalCompositeOperation="destination-in",s.drawImage(l.mask,0,0,c.width,c.height),s.restore())}return i.useLayoutEffect(()=>{var t;if(!l||!(null==n?void 0:n.width)||!n.height){return}const o=Math.max(e.a.width/n.width*r,e.a.height/n.height*r);W(l.mask,Math.min(1e4,Math.max(n.width*o,1)),Math.min(1e4,Math.max(n.height*o,1))),null===(t=l.mask.getContext("2d"))||void 0===t||t.drawImage(n,0,0,l.mask.width,l.mask.height)},[l,n,e.a.width,e.a.height,r]),i.useLayoutEffect(()=>{u()},[l,t,n,e.a.width,e.a.height,r,...o]),i.useEffect(()=>()=>{l&&v.Util.releaseCanvas(l.canvas,l.mask)},[l]),[d?c:t,u]};const B=document.createElement("canvas");let G=function(e,t,r){const o=i.useRef("loading"),n=i.useRef(void 0),[a,s]=i.useState(0),d=i.useRef(void 0),l=i.useRef(void 0),c=i.useRef(void 0);return d.current===e&&l.current===t&&c.current===r||(o.current="loading",n.current=void 0,d.current=e,l.current=t,c.current=r),i.useLayoutEffect(()=>{if(!e){return}const i=g(e)?1:p;let a,d,l,c=0,u=!1,h=!1;const m=e=>{e&&(e.removeAttribute("src"),e.load())},v=()=>{c+=1;const p=document.createElement("video");function g(){u||(p.removeEventListener("canplay",g),h=!0,o.current="loaded",n.current=p,p.currentTime=0,s(Math.random()))}function w(e){var t;const r=4===p.readyState,l=p.buffered&&p.buffered.length>0&&p.buffered.end(p.buffered.length-1)/p.duration*100>=100;if(r&&l){return}if(u){return}if(!h&&c<i){return null==d||d(),m(p),void(a=setTimeout(v,f(c)))}const g=e.message||(null===(t=p.error)||void 0===t?void 0:t.message)||"Unknown error";console.error(new Error("Video failed to load: "+g)),o.current="failed",n.current=void 0,s(Math.random())}l=p,p.addEventListener("canplay",g),p.addEventListener("error",w),d=()=>{p.removeEventListener("canplay",g),p.removeEventListener("error",w)},t&&(p.crossOrigin=t),r&&(p.referrerPolicy=r),p.src=e,p.load()};return v(),()=>{u=!0,clearTimeout(a),null==d||d(),h||m(l)}},[e,t,r]),[n.current,o.current]};export const setVideoLoaderHook=e=>{G=e};function J(e){return!e.seeking&&e.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA}export const useLoader=(e,t,r)=>{const o=i.useRef(void 0),n=()=>{var e;null===(e=o.current)||void 0===e||e.call(o),o.current=void 0};i.useEffect(()=>n,[]),i.useLayoutEffect(()=>{const i=t.slice(0,200),a=`video with id ${r} url: ${i}`;"loading"!==e||o.current||(o.current=E(a)),"loading"!==e&&n(),"failed"===e&&L(M("VIDEO_FAILED",a,{src:i,elementId:r,reason:"load"}))},[e])};export const VideoElement=s(({element:s,store:p})=>{var g,f,L,M,C;const[j,O]=i.useState(!1),H=i.useRef(null),U=P(),[W,X]=i.useState(!1),[K,Q]=G(s.a.src,"anonymous"),[ee,te]=i.useState(!1),re=p.activePage===s.page,oe=(null===(g=s.page)||void 0===g?void 0:g._exportingOrRendering)&&"loaded"===Q,ie=V(s,p,oe);useLoader(Q,s.a.src,s.id),K&&(K.playsInline=!0);const ne=oe&&ie||K,[ae,se]=useFlip(s,ne),[de=B,le]=T(s,ae||B);i.useEffect(()=>{K&&p.history.ignore(()=>{s.set({duration:1e3*K.duration})})},[K]);const ce=i.useMemo(_,[K]);i.useEffect(()=>{var e;if(!K){return}const t=!F(s)&&p.isPlaying;if(!re||!t&&!W){return void K.pause()}W&&(K.muted=!1,K.currentTime=s.startTime*K.duration,A(K).then(e=>{"refused"===e&&X(!1)}));const r=new v.Animation(()=>{Te()},null===(e=H.current)||void 0===e?void 0:e.getLayer());r.start();const o=()=>{X(!1),K.currentTime=s.startTime*K.duration},i=()=>{K.currentTime>=s.endTime*K.duration&&(K.pause(),K.currentTime=s.startTime*K.duration,X(!1))};return K.addEventListener("ended",o),K.addEventListener("timeupdate",i),()=>{K.pause(),r.stop(),K.removeEventListener("ended",o),K.removeEventListener("timeupdate",i)}},[K,W,p.isPlaying,re]),i.useEffect(()=>{K&&(K.volume=s.volume)},[K,s.volume]),i.useEffect(()=>{K&&(K.playbackRate=s.speed,K.preservesPitch=!1)},[K,s.speed]);const ue=i.useRef(null);i.useEffect(()=>{const e=l(s,()=>{var e,t;if(K){if(oe&&ie){return Te(),void p.currentTime}if(F(s)){return}const r=p.activePage===s.page,o=s.page._mediaLocalTime,i=s.startTime*K.duration*1e3,n=K.duration*(s.endTime-s.startTime)*1e3,{start:a,end:d}=D(s.animations,s.page.duration),l=z(null!=o?o:0,0,a,n,i,s.speed,{windowEnd:d,frameMs:p._renderFrameMs,renderEnd:p._renderEndMs-s.page.startTime}),c=l/1e3,u=null!==o&&o>=a&&o<d;W||(K.muted=!u,u&&p.isPlaying&&r?K.paused?(K.currentTime=c,ce.play(K)):Math.abs(1e3*K.currentTime-l)>500&&(K.currentTime=c):(ce.reset(),K.paused||K.pause(),c!==K.currentTime&&(K.currentTime=c),!J(K)&&!p.isPlaying&&!ue.current&&(ue.current=E(`video ${s.id}`)))),Te(),null===(t=null===(e=H.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()}});return()=>{e(),ue.current&&(ue.current(),ue.current=null)}},[p,K,oe,ie,W]),i.useEffect(()=>{var e,t;if(!K){return}if(oe){return null===(e=ue.current)||void 0===e||e.call(ue),void(ue.current=null)}const r=()=>{var e;null===(e=ue.current)||void 0===e||e.call(ue),ue.current=null},o=()=>{J(K)&&(Te(),r())};let i,n;(null===(t=s.page)||void 0===t?void 0:t._exportingOrRendering)&&(i=setInterval(o,20)),K.addEventListener("timeupdate",o),K.addEventListener("canplay",o),K.addEventListener("seeked",o);const a=()=>{K.paused&&(Te(),J(K)&&r()),n=K.requestVideoFrameCallback(a)};return"requestVideoFrameCallback"in K&&(n=K.requestVideoFrameCallback(a)),()=>{clearInterval(i),void 0!==n&&K.cancelVideoFrameCallback(n),K.removeEventListener("timeupdate",o),K.removeEventListener("canplay",o),K.removeEventListener("seeked",o)}},[null===(f=s.page)||void 0===f?void 0:f._exportingOrRendering,K,s.id,E,oe]);let{cropX:he,cropY:me,cropWidth:pe,cropHeight:ge}=s.a;"loaded"!==Q&&(he=me=0,pe=ge=1);const{width:fe,height:ve}=Z(de),we=null!==(L=null==K?void 0:K.videoWidth)&&void 0!==L?L:0,xe=null!==(M=null==K?void 0:K.videoHeight)&&void 0!==M?M:0;i.useLayoutEffect(()=>{"loaded"===Q&&we>0&&xe>0&&s._setSourceSize({width:we,height:xe},s.a.src)},[s,s.a.src,Q,we,xe]);const Ee=y({fit:s.a.fit,focus:s.focus,stretchEnabled:s.stretchEnabled,cropX:he,cropY:me,cropWidth:pe,cropHeight:ge,width:s.a.width,height:s.a.height},{width:fe,height:ve}),Le=(Ee.width,Ee.height,null!==(C=s.cornerRadius)&&void 0!==C?C:0),[Me,ye]=useCornerRadiusAndCrop(s,de,Ee,p._elementsPixelRatio,Le,!0);let[Ce,be]=useClip(s,Me,p._elementsPixelRatio,[Ee,Le,p._elementsPixelRatio]);const ke=S(H,s,Ce),Te=I(()=>{var e,t;se(),le(),ye(),be(),ke(),null===(t=null===(e=H.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()});i.useEffect(()=>{Te()});const je=()=>{s._cropEnabled&&setTimeout(()=>{d(s)&&s.toggleCropMode(!0)})},Ie="loading"===Q,Re="failed"===Q,Se=!Ie&&!Re,Pe=k(s,Ee,"loaded"===Q?{width:fe,height:ve}:void 0,O),_e=Se?o(s):0;R(H,_e);const Ae=s.selectable||p.role===m.ADMIN;return t(e,{children:r(c,{onMouseEnter:()=>te(!0),onMouseLeave:()=>te(!1),children:[Ie&&t(x,{element:s}),Re&&t(w,{element:s,text:"Can not load the video..."}),t(u,Object.assign({ref:H,name:"element",id:s.id,image:Ce,x:s.a.x,y:s.a.y,width:s.a.width||1,height:s.a.height||1,rotation:s.a.rotation,opacity:_e},a(s),{customCrop:Ee,listening:Ae,draggable:U?s.draggable&&s.isSelected:s.draggable,preventDefault:!U||s.isSelected,hideInExport:!s.showInExport,onDragMove:e=>{s.set({x:e.target.x(),y:e.target.y()})},onDragEnd:e=>{s.set(b(e.target))},onDblClick:je,onDblTap:je},Pe)),!!s.borderSize&&t(h,{x:s.a.x,y:s.a.y,width:Math.max(s.a.width-s.borderSize,0),height:Math.max(s.a.height-s.borderSize,0),opacity:_e,offsetX:-s.borderSize/2,offsetY:-s.borderSize/2,stroke:n(s.borderColor),strokeWidth:s.borderSize,listening:!1,rotation:s.a.rotation,cornerRadius:Math.max(0,Le-s.borderSize),hideInExport:!s.showInExport}),!p.isPlaying&&t(u,{image:W?ee||U?$:void 0:q,x:s.a.x,y:s.a.y,offsetX:-s.a.width/2+15/p.scale,offsetY:-s.a.height/2+15/p.scale,rotation:s.a.rotation,width:30/p.scale,height:30/p.scale,hideInExport:!0,onClick:()=>X(!W),onTap:()=>X(!W)}),s._cropModeEnabled&&"loaded"===Q&&t(Y,{element:s,store:p,previewImage:Ce,sourceImage:de,sourceWidth:fe,sourceHeight:ve,crop:Ee,innerAnchors:N})]})})});
@@ -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:k,activePageBorderColor:L,bleedColor:T,snapGuideStroke:b,snapGuideStrokeWidth:S,snapGuideDash:M,selectionRectFill:E,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:_,distanceGuideStroke:I,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,ke=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),ke=Math.max(ke,t.bottom)}}const Le=Math.max(...o.pages.map(e=>e.computedWidth)),Te=Math.max(...o.pages.map(e=>e.computedHeight)),be=(null===(ae=o.activePage)||void 0===ae?void 0:ae.computedHeight)||0,Se=Le+we+xe,Me=(le?be:Te)+ye+ke,Ee=async({skipTimeout:e}={skipTimeout:!1})=>{if(e||await new Promise(e=>setTimeout(e,50)),null===fe.current){return}if(!Number.isFinite(Se)||!Number.isFinite(Me)){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)/Me,a=o.pages.length>1?3.1:2,c=(r-ue*a)/Se,u=(t.height-2*de)/Me,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(()=>{Ee({skipTimeout:!0})},[]),r.useEffect(()=>(o._setWorkspaceMounted(!0),()=>o._setWorkspaceMounted(!1)),[o]),r.useEffect(()=>{Ee()},[Se,Me,ee,$]),r.useLayoutEffect(()=>{Ee({skipTimeout:!0})},[o.openedSidePanel]),r.useEffect(()=>{o.__()},[]),r.useEffect(()=>{const e=fe.current;if(window.ResizeObserver){const t=new ResizeObserver(()=>{Ee({skipTimeout:!0})});return t.observe(e),()=>t.unobserve(e)}{const e=setInterval(()=>{Ee({skipTimeout:!0})},100);return()=>clearInterval(e)}},[Se,Me]);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-Me*o.scale)/2)}else{Pe=Math.max(ue,(he.width-Se*o.scale)/2);const e=Me*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+ke)*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),_e=he.width>=Se*o.scale+2*Pe,Ie=he.height>=Me*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:k,activePageBorderColor:L,bleedColor:T,transparencyBackgroundColor:y,transformerStyle:O,innerImageCropTransformerStyle:z,outerImageCropTransformerStyle:j,highlighterStyle:N,snapGuideStroke:b,snapGuideStrokeWidth:S,snapGuideDash:M,selectionRectFill:E,selectionRectStroke:C,selectionRectStrokeWidth:P,transformLabelFill:R,transformLabelTextFill:F,distanceGuideStroke:I,distanceLabelFill:Y,distanceLabelTextFill:D,mediaLoadingStyle:H,mediaErrorStyle:G,textOverflowIndicatorStyle:_,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":_e?"hidden":"auto",overflowY:ce&&Ie?"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?Me*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:Me*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:k,activePageBorderColor:L,bleedColor:T,snapGuideStroke:b,snapGuideStrokeWidth:S,snapGuideDash:M,selectionRectFill:E,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:_,distanceGuideStroke:I,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,ke=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),ke=Math.max(ke,t.bottom)}}const Le=Math.max(...o.pages.map(e=>e.computedWidth)),Te=Math.max(...o.pages.map(e=>e.computedHeight)),be=(null===(ae=o.activePage)||void 0===ae?void 0:ae.computedHeight)||0,Se=Le+we+xe,Me=(le?be:Te)+ye+ke,Ee=async({skipTimeout:e}={skipTimeout:!1})=>{if(e||await new Promise(e=>setTimeout(e,50)),null===fe.current){return}if(!Number.isFinite(Se)||!Number.isFinite(Me)){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)/Me,a=o.pages.length>1?3.1:2,c=(r-ue*a)/Se,u=(t.height-2*de)/Me,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(()=>{Ee({skipTimeout:!0})},[]),r.useEffect(()=>(o._setWorkspaceMounted(!0),()=>o._setWorkspaceMounted(!1)),[o]),r.useEffect(()=>{Ee()},[Se,Me,ee,$]),r.useLayoutEffect(()=>{Ee({skipTimeout:!0})},[o.openedSidePanel]),r.useEffect(()=>{o.__()},[]),r.useEffect(()=>{const e=fe.current;if(window.ResizeObserver){const t=new ResizeObserver(()=>{Ee({skipTimeout:!0})});return t.observe(e),()=>t.unobserve(e)}{const e=setInterval(()=>{Ee({skipTimeout:!0})},100);return()=>clearInterval(e)}},[Se,Me]);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-Me*o.scale)/2)}else{Pe=Math.max(ue,(he.width-Se*o.scale)/2);const e=Me*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)},[U]),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+ke)*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),_e=he.width>=Se*o.scale+2*Pe,Ie=he.height>=Me*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:k,activePageBorderColor:L,bleedColor:T,transparencyBackgroundColor:y,transformerStyle:O,innerImageCropTransformerStyle:z,outerImageCropTransformerStyle:j,highlighterStyle:N,snapGuideStroke:b,snapGuideStrokeWidth:S,snapGuideDash:M,selectionRectFill:E,selectionRectStroke:C,selectionRectStrokeWidth:P,transformLabelFill:R,transformLabelTextFill:F,distanceGuideStroke:I,distanceLabelFill:Y,distanceLabelTextFill:D,mediaLoadingStyle:H,mediaErrorStyle:G,textOverflowIndicatorStyle:_,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":_e?"hidden":"auto",overflowY:ce&&Ie?"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?Me*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:Me*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;
@@ -73,9 +73,16 @@ declare const defaults: {
73
73
  'sidePanel.resize': import("lucide-react").LucideIcon;
74
74
  'sidePanel.draw': import("lucide-react").LucideIcon;
75
75
  'sidePanel.videos': import("lucide-react").LucideIcon;
76
+ 'sidePanel.variables': import("lucide-react").LucideIcon;
77
+ 'variables.text': import("lucide-react").LucideIcon;
78
+ 'variables.image': import("lucide-react").LucideIcon;
79
+ 'variables.video': import("lucide-react").LucideIcon;
80
+ 'variables.color': import("lucide-react").LucideIcon;
81
+ 'variables.boolean': import("lucide-react").LucideIcon;
76
82
  'toolbar.opacity': import("lucide-react").LucideIcon;
77
83
  'toolbar.filters': import("lucide-react").LucideIcon;
78
84
  'toolbar.aiWrite': import("lucide-react").LucideIcon;
85
+ 'toolbar.insertVariable': import("lucide-react").LucideIcon;
79
86
  'toolbar.duration': import("lucide-react").LucideIcon;
80
87
  'toolbar.trim': import("lucide-react").LucideIcon;
81
88
  'toolbar.flipHorizontal': import("lucide-react").LucideIcon;
package/icons/registry.js CHANGED
@@ -1 +1 @@
1
- var t=this&&this.__rest||function(t,i){var e={};for(var o in t){Object.prototype.hasOwnProperty.call(t,o)&&i.indexOf(o)<0&&(e[o]=t[o])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(t);n<o.length;n++){i.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(t,o[n])&&(e[o[n]]=t[o[n]])}}return e};import{jsx as i}from"react/jsx-runtime";import{observable as e,action as o}from"mobx";import{observer as n}from"mobx-react-lite";import{AlignCenter as a,AlignCenterHorizontal as r,AlignCenterVertical as l,AlignEndHorizontal as p,AlignEndVertical as s,AlignHorizontalSpaceAround as c,AlignJustify as m,AlignLeft as d,AlignRight as y,AlignStartHorizontal as u,AlignStartVertical as g,AlignVerticalJustifyCenter as b,AlignVerticalJustifyEnd as f,AlignVerticalJustifyStart as x,AlignVerticalSpaceAround as h,ArrowDown as v,ArrowDownLeft as P,ArrowDownRight as w,ArrowLeft as k,ArrowLeftRight as z,ArrowRight as L,ArrowUp as O,ArrowUpDown as j,ArrowUpLeft as R,ArrowUpRight as T,Ban as B,Bold as I,CaseSensitive as W,Check as F,ChevronDown as C,ChevronLeft as D,ChevronRight as G,ChevronsDown as H,ChevronsUp as M,ChevronUp as S,CloudUpload as E,Contrast as U,Copy as V,CreditCard as $,Crop as _,Edit as J,Eye as K,EyeOff as N,Files as Z,FileText as q,GripVertical as A,HelpCircle as Q,Highlighter as X,Image as Y,Italic as tt,Layers as it,LayoutTemplate as et,List as ot,ListOrdered as nt,Lock as at,MousePointer as rt,MoreHorizontal as lt,PaintBucket as pt,Palette as st,Pause as ct,Pencil as mt,Pilcrow as dt,Pipette as yt,Play as ut,Plus as gt,Redo2 as bt,Scaling as ft,Scissors as xt,Search as ht,SkipBack as vt,Settings as Pt,Shapes as wt,SlidersHorizontal as kt,Sparkles as zt,Strikethrough as Lt,TextCursorInput as Ot,Timer as jt,Trash2 as Rt,Type as Tt,Underline as Bt,Undo2 as It,Unlock as Wt,Upload as Ft,Video as Ct,Volume2 as Dt,VolumeX as Gt,WandSparkles as Ht,WrapText as Mt,X as St,ZoomIn as Et,ZoomOut as Ut}from"lucide-react";import{Instagram as Vt,Facebook as $t,Youtube as _t,Linkedin as Jt,Twitter as Kt}from"./brand-icons.js";import{NoneIcon as Nt,MoveIcon as Zt,FadeIcon as qt,ZoomIcon as At,RotateIcon as Qt,BlinkIcon as Xt,BounceIcon as Yt,BlurIcon as ti,CountIcon as ii,PopIcon as ei,RiseIcon as oi,FlipIcon as ni,GrowTurnIcon as ai,PulseIcon as ri,FloatIcon as li,ShakeIcon as pi,TypewriterIcon as si,LineRiseIcon as ci,WordRiseIcon as mi,WordFadeIcon as di,LetterPopIcon as yi,WordBlurIcon as ui,WipeIcon as gi,GlowIcon as bi,KenBurnsIcon as fi,LineWipeIcon as xi,LinePeekIcon as hi,LetterWaveIcon as vi}from"./animation-icons.js";const Pi={"action.duplicate":V,"action.split":xt,"action.rename":mt,"action.remove":Rt,"action.lock":at,"action.unlock":Wt,"action.undo":It,"action.redo":bt,"action.add":gt,"action.more":lt,"action.settings":Pt,"action.search":ht,"action.close":St,"action.confirm":F,"action.none":B,"action.visible":K,"action.hidden":N,"action.dragHandle":A,"action.eyeDropper":yt,"action.unmuted":Dt,"action.muted":Gt,"action.help":Q,"ui.chevronUp":S,"ui.chevronDown":C,"ui.chevronLeft":D,"ui.chevronRight":G,"layering.menu":it,"layering.up":S,"layering.down":C,"layering.top":M,"layering.bottom":H,"text.bold":I,"text.italic":tt,"text.underline":Bt,"text.strikethrough":Lt,"text.alignLeft":d,"text.alignCenter":a,"text.alignRight":y,"text.alignJustify":m,"text.valignTop":x,"text.valignMiddle":b,"text.valignBottom":f,"text.uppercase":W,"text.spacing":Mt,"text.bulletList":ot,"text.numberedList":nt,"text.paragraph":dt,"text.richText":Ot,"text.uploadFont":Ft,"position.alignLeft":g,"position.alignCenter":l,"position.alignRight":s,"position.alignTop":u,"position.alignMiddle":r,"position.alignBottom":p,"position.distributeVertical":h,"position.distributeHorizontal":c,"sidePanel.templates":et,"sidePanel.text":Tt,"sidePanel.photos":Y,"sidePanel.elements":wt,"sidePanel.upload":E,"sidePanel.background":pt,"sidePanel.pages":Z,"sidePanel.layers":it,"sidePanel.resize":ft,"sidePanel.draw":mt,"sidePanel.videos":Ct,"toolbar.opacity":U,"toolbar.filters":Ht,"toolbar.aiWrite":zt,"toolbar.duration":jt,"toolbar.trim":xt,"toolbar.flipHorizontal":z,"toolbar.flipVertical":j,"toolbar.zoomIn":Et,"toolbar.zoomOut":Ut,"toolbar.crop":_,"imageEdit.ai":zt,"colorPicker.reverseGradient":z,"download.export":Ft,"download.image":Y,"download.pdf":q,"download.video":Ct,"draw.select":rt,"draw.brush":J,"draw.highlighter":X,"background.colorPicker":st,"pagesTimeline.play":ut,"pagesTimeline.pause":ct,"pagesTimeline.rewind":vt,"size.instagram":Vt,"size.facebook":$t,"size.youtube":_t,"size.linkedin":Jt,"size.twitter":Kt,"size.video":Ct,"size.print":q,"size.businessCard":$,"animation.directionRight":L,"animation.directionLeft":k,"animation.directionUp":O,"animation.directionDown":v,"animation.directionBottomRight":w,"animation.directionBottomLeft":P,"animation.directionTopRight":T,"animation.directionTopLeft":R,"animation.typeMove":Zt,"animation.typeFade":qt,"animation.typeZoom":At,"animation.typeBlur":ti,"animation.typeCount":ii,"animation.typeRotate":Qt,"animation.typeBlink":Xt,"animation.typeBounce":Yt,"animation.typePop":ei,"animation.typeRise":oi,"animation.typeFlip":ni,"animation.typeGrowTurn":ai,"animation.typePulse":ri,"animation.typeFloat":li,"animation.typeShake":pi,"animation.typeTypewriter":si,"animation.typeLineRise":ci,"animation.typeWordRise":mi,"animation.typeWordFade":di,"animation.typeLetterPop":yi,"animation.typeWordBlur":ui,"animation.typeWipe":gi,"animation.typeGlow":bi,"animation.typeKenBurns":fi,"animation.typeLineWipe":xi,"animation.typeLinePeek":hi,"animation.typeLetterWave":vi,"animation.typeNone":Nt,"animation.settings":kt},wi=e.map();export const setIcons=o(t=>{for(const i of Object.keys(t)){const e=t[i];null!=e&&("function"==typeof e||"object"==typeof e?wi.set(i,e):console.warn(`polotno: setIcons('${i}') expects a React component, received ${typeof e}. Ignored.`))}});export const resetIcons=o(()=>wi.clear());export const PolotnoIcon=n(e=>{var o,{name:n}=e,a=t(e,["name"]);const r=null!==(o=wi.get(n))&&void 0!==o?o:Pi[n];return i(r,Object.assign({"data-pn-icon":""},a))});
1
+ var t=this&&this.__rest||function(t,i){var e={};for(var o in t){Object.prototype.hasOwnProperty.call(t,o)&&i.indexOf(o)<0&&(e[o]=t[o])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(t);n<o.length;n++){i.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(t,o[n])&&(e[o[n]]=t[o[n]])}}return e};import{jsx as i}from"react/jsx-runtime";import{observable as e,action as o}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 p,AlignHorizontalSpaceAround as c,AlignJustify as m,AlignLeft as d,AlignRight as y,AlignStartHorizontal as u,AlignStartVertical as g,AlignVerticalJustifyCenter as b,AlignVerticalJustifyEnd as f,AlignVerticalJustifyStart as x,AlignVerticalSpaceAround as v,ArrowDown as h,ArrowDownLeft as P,ArrowDownRight as w,ArrowLeft as k,ArrowLeftRight as z,ArrowRight as L,ArrowUp as O,ArrowUpDown as j,ArrowUpLeft as R,ArrowUpRight as T,Ban as B,Bold as I,Braces as W,CaseSensitive as F,Check as C,ChevronDown as D,ChevronLeft as G,ChevronRight as H,ChevronsDown as M,ChevronsUp as S,ChevronUp as V,CloudUpload as E,Contrast as U,Copy as $,CreditCard as _,Crop as J,Edit as K,Eye as N,EyeOff as Z,Files as q,FileText as A,GripVertical as Q,HelpCircle as X,Highlighter as Y,Image as tt,Italic as it,Layers as et,LayoutTemplate as ot,List as nt,ListOrdered as at,Lock as rt,MousePointer as lt,MoreHorizontal as st,PaintBucket as pt,Palette as ct,Pause as mt,Pencil as dt,Pilcrow as yt,Pipette as ut,Play as gt,Plus as bt,Redo2 as ft,Scaling as xt,Scissors as vt,Search as ht,SkipBack as Pt,Settings as wt,Shapes as kt,SlidersHorizontal as zt,Sparkles as Lt,Strikethrough as Ot,TextCursorInput as jt,Timer as Rt,ToggleRight as Tt,Trash2 as Bt,Type as It,Underline as Wt,Undo2 as Ft,Unlock as Ct,Upload as Dt,Video as Gt,Volume2 as Ht,VolumeX as Mt,WandSparkles as St,WrapText as Vt,X as Et,ZoomIn as Ut,ZoomOut as $t}from"lucide-react";import{Instagram as _t,Facebook as Jt,Youtube as Kt,Linkedin as Nt,Twitter as Zt}from"./brand-icons.js";import{NoneIcon as qt,MoveIcon as At,FadeIcon as Qt,ZoomIcon as Xt,RotateIcon as Yt,BlinkIcon as ti,BounceIcon as ii,BlurIcon as ei,CountIcon as oi,PopIcon as ni,RiseIcon as ai,FlipIcon as ri,GrowTurnIcon as li,PulseIcon as si,FloatIcon as pi,ShakeIcon as ci,TypewriterIcon as mi,LineRiseIcon as di,WordRiseIcon as yi,WordFadeIcon as ui,LetterPopIcon as gi,WordBlurIcon as bi,WipeIcon as fi,GlowIcon as xi,KenBurnsIcon as vi,LineWipeIcon as hi,LinePeekIcon as Pi,LetterWaveIcon as wi}from"./animation-icons.js";const ki={"action.duplicate":$,"action.split":vt,"action.rename":dt,"action.remove":Bt,"action.lock":rt,"action.unlock":Ct,"action.undo":Ft,"action.redo":ft,"action.add":bt,"action.more":st,"action.settings":wt,"action.search":ht,"action.close":Et,"action.confirm":C,"action.none":B,"action.visible":N,"action.hidden":Z,"action.dragHandle":Q,"action.eyeDropper":ut,"action.unmuted":Ht,"action.muted":Mt,"action.help":X,"ui.chevronUp":V,"ui.chevronDown":D,"ui.chevronLeft":G,"ui.chevronRight":H,"layering.menu":et,"layering.up":V,"layering.down":D,"layering.top":S,"layering.bottom":M,"text.bold":I,"text.italic":it,"text.underline":Wt,"text.strikethrough":Ot,"text.alignLeft":d,"text.alignCenter":a,"text.alignRight":y,"text.alignJustify":m,"text.valignTop":x,"text.valignMiddle":b,"text.valignBottom":f,"text.uppercase":F,"text.spacing":Vt,"text.bulletList":nt,"text.numberedList":at,"text.paragraph":yt,"text.richText":jt,"text.uploadFont":Dt,"position.alignLeft":g,"position.alignCenter":l,"position.alignRight":p,"position.alignTop":u,"position.alignMiddle":r,"position.alignBottom":s,"position.distributeVertical":v,"position.distributeHorizontal":c,"sidePanel.templates":ot,"sidePanel.text":It,"sidePanel.photos":tt,"sidePanel.elements":kt,"sidePanel.upload":E,"sidePanel.background":pt,"sidePanel.pages":q,"sidePanel.layers":et,"sidePanel.resize":xt,"sidePanel.draw":dt,"sidePanel.videos":Gt,"sidePanel.variables":W,"variables.text":It,"variables.image":tt,"variables.video":Gt,"variables.color":ct,"variables.boolean":Tt,"toolbar.opacity":U,"toolbar.filters":St,"toolbar.aiWrite":Lt,"toolbar.insertVariable":W,"toolbar.duration":Rt,"toolbar.trim":vt,"toolbar.flipHorizontal":z,"toolbar.flipVertical":j,"toolbar.zoomIn":Ut,"toolbar.zoomOut":$t,"toolbar.crop":J,"imageEdit.ai":Lt,"colorPicker.reverseGradient":z,"download.export":Dt,"download.image":tt,"download.pdf":A,"download.video":Gt,"draw.select":lt,"draw.brush":K,"draw.highlighter":Y,"background.colorPicker":ct,"pagesTimeline.play":gt,"pagesTimeline.pause":mt,"pagesTimeline.rewind":Pt,"size.instagram":_t,"size.facebook":Jt,"size.youtube":Kt,"size.linkedin":Nt,"size.twitter":Zt,"size.video":Gt,"size.print":A,"size.businessCard":_,"animation.directionRight":L,"animation.directionLeft":k,"animation.directionUp":O,"animation.directionDown":h,"animation.directionBottomRight":w,"animation.directionBottomLeft":P,"animation.directionTopRight":T,"animation.directionTopLeft":R,"animation.typeMove":At,"animation.typeFade":Qt,"animation.typeZoom":Xt,"animation.typeBlur":ei,"animation.typeCount":oi,"animation.typeRotate":Yt,"animation.typeBlink":ti,"animation.typeBounce":ii,"animation.typePop":ni,"animation.typeRise":ai,"animation.typeFlip":ri,"animation.typeGrowTurn":li,"animation.typePulse":si,"animation.typeFloat":pi,"animation.typeShake":ci,"animation.typeTypewriter":mi,"animation.typeLineRise":di,"animation.typeWordRise":yi,"animation.typeWordFade":ui,"animation.typeLetterPop":gi,"animation.typeWordBlur":bi,"animation.typeWipe":fi,"animation.typeGlow":xi,"animation.typeKenBurns":vi,"animation.typeLineWipe":hi,"animation.typeLinePeek":Pi,"animation.typeLetterWave":wi,"animation.typeNone":qt,"animation.settings":zt},zi=e.map();export const setIcons=o(t=>{for(const i of Object.keys(t)){const e=t[i];null!=e&&("function"==typeof e||"object"==typeof e?zi.set(i,e):console.warn(`polotno: setIcons('${i}') expects a React component, received ${typeof e}. Ignored.`))}});export const resetIcons=o(()=>zi.clear());export const PolotnoIcon=n(e=>{var o,{name:n}=e,a=t(e,["name"]);const r=null!==(o=zi.get(n))&&void 0!==o?o:ki[n];return i(r,Object.assign({"data-pn-icon":""},a))});
@@ -27,6 +27,9 @@ export interface ToolTarget extends IAnyStateTreeNode, ImageSnapshot {
27
27
  readonly resizable: boolean;
28
28
  readonly selectable: boolean;
29
29
  readonly visible: boolean;
30
+ readonly a: {
31
+ readonly src?: string;
32
+ };
30
33
  readonly maskSrc?: string;
31
34
  readonly page: ParentNode | null;
32
35
  readonly parent: ParentNode | null;
@@ -1 +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}}
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(Object.assign({},y(a)),{fit:void 0}),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}}
@@ -25,6 +25,11 @@ export declare function targetSnapshot(element: ToolTarget, store: ToolStore): {
25
25
  height: number;
26
26
  x: number;
27
27
  y: number;
28
+ fit?: 'cover' | 'contain';
29
+ focus?: {
30
+ x: number;
31
+ y: number;
32
+ };
28
33
  src: string;
29
34
  rotation: number;
30
35
  cropX: number;
@@ -1 +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!==(l=e.parent)&&void 0!==l?l: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===(i=r.page)||void 0===i?void 0:i.id,ancestors:n,role:o.role})}
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,i,o){return r("TOOL_FAILED",`Image tool ${e}: ${i}`,{reason:i,tool:e,elementId:t},o)}export function imageSnapshot(e){var t;return Object.assign(Object.assign({},e.fit&&{fit:e.fit,focus:e.focus}),{src:null!==(t=e.a.src)&&void 0!==t?t: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,i,o){var n;if(!t(r)||e(r)!==i||"viewer"===i.role||!r.page){return!1}if(!r.contentEditable||"expand"===o&&!r.resizable){return!1}if(("crop"===o||"expand"===o)&&"contain"===r.fit){return!1}if("crop"===o?!["image","svg","video"].includes(r.type)||r.maskSrc:"image"!==r.type){return!1}for(let e=r;e&&e!==r.page;e=null!==(n=e.parent)&&void 0!==n?n:null){if(!e.visible||"admin"!==i.role&&!e.selectable){return!1}}return!0}export function targetSnapshot(r,i){var o,n;if(!t(r)||e(r)!==i){return null}const l=[];for(let e=r.parent;e;e=null!==(n=e.parent)&&void 0!==n?n:null){l.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===(o=r.page)||void 0===o?void 0:o.id,ancestors:l,role:i.role})}
@@ -50,6 +50,11 @@ export interface RemoveBackgroundRequest {
50
50
  }
51
51
  export type RemoveBackgroundFunc = (src: string, signal?: AbortSignal, request?: RemoveBackgroundRequest) => Promise<string | ImageEditResult>;
52
52
  export interface ImageSnapshot extends Rect {
53
+ fit?: 'cover' | 'contain';
54
+ focus?: {
55
+ x: number;
56
+ y: number;
57
+ };
53
58
  src: string;
54
59
  rotation: number;
55
60
  cropX: number;
@@ -3,6 +3,9 @@ import type { CropSession } from '../image-tools/sessions.js';
3
3
  interface CropModeHost {
4
4
  readonly id: string;
5
5
  readonly src: string;
6
+ readonly filled: {
7
+ readonly src?: string;
8
+ };
6
9
  readonly store: {
7
10
  readonly activeTool: {
8
11
  name: string;
@@ -1 +1 @@
1
- import{observable as e}from"mobx";export const cropMode=o=>{const t=e.box(null,{deep:!1});return{views:{get _cropModeEnabled(){var e;const t=null===(e=o.store)||void 0===e?void 0:e.activeTool;return"crop"===(null==t?void 0:t.name)&&t.elementId===o.id},get _cropEnabled(){var e;return!!(null===(e=o.store)||void 0===e?void 0:e.canUseTool("crop",o.id))},get _sourceSize(){const e=t.get();return(null==e?void 0:e.src)===o.src?e.size:null}},actions:{_setSourceSize(e,o){if(e.width<=0||e.height<=0||!Number.isFinite(e.width+e.height)){return}const i=t.get();(null==i?void 0:i.src)===o&&i.size.width===e.width&&i.size.height===e.height||t.set({src:o,size:Object.assign({},e)})},toggleCropMode(e){var t,i;const n=o.store;if(!n){return}const r="crop"===(null===(t=n.activeTool)||void 0===t?void 0:t.name)&&n.activeTool.elementId===o.id;(null!=e?e:!r)?n.canUseTool("crop",o.id)&&n.setTool("crop",{elementId:o.id}):r&&(null===(i=n.activeTool)||void 0===i||i.run().catch(()=>{}))},cancelCropMode(){var e;const t=null===(e=o.store)||void 0===e?void 0:e.activeTool;(null==t?void 0:t.elementId)===o.id&&"crop"===t.name&&t.cancel()}}}};
1
+ import{observable as e}from"mobx";export const cropMode=o=>{const t=e.box(null,{deep:!1});return{views:{get _cropModeEnabled(){var e;const t=null===(e=o.store)||void 0===e?void 0:e.activeTool;return"crop"===(null==t?void 0:t.name)&&t.elementId===o.id},get _cropEnabled(){var e;return!!(null===(e=o.store)||void 0===e?void 0:e.canUseTool("crop",o.id))},get _sourceSize(){var e;const i=t.get();return(null==i?void 0:i.src)===(null!==(e=o.filled.src)&&void 0!==e?e:o.src)?i.size:null}},actions:{_setSourceSize(e,o){if(e.width<=0||e.height<=0||!Number.isFinite(e.width+e.height)){return}const i=t.get();(null==i?void 0:i.src)===o&&i.size.width===e.width&&i.size.height===e.height||t.set({src:o,size:Object.assign({},e)})},toggleCropMode(e){var t,i;const l=o.store;if(!l){return}const n="crop"===(null===(t=l.activeTool)||void 0===t?void 0:t.name)&&l.activeTool.elementId===o.id;(null!=e?e:!n)?l.canUseTool("crop",o.id)&&l.setTool("crop",{elementId:o.id}):n&&(null===(i=l.activeTool)||void 0===i||i.run().catch(()=>{}))},cancelCropMode(){var e;const t=null===(e=o.store)||void 0===e?void 0:e.activeTool;(null==t?void 0:t.elementId)===o.id&&"crop"===t.name&&t.cancel()}}}};