polotno 4.3.0 → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/blueprint/toolbar/text-toolbar.js +2 -2
  2. package/blueprint.polotno.css +297 -297
  3. package/canvas/apply-filters.d.ts +1 -2
  4. package/canvas/apply-filters.js +1 -1
  5. package/canvas/figure-element.js +1 -1
  6. package/canvas/gif-element.js +1 -1
  7. package/canvas/hotkeys.js +1 -1
  8. package/canvas/html-element.js +1 -1
  9. package/canvas/image-element.js +1 -1
  10. package/canvas/line-element.js +1 -1
  11. package/canvas/page.js +1 -1
  12. package/canvas/quill-font-formats.js +1 -1
  13. package/canvas/render-tag-element.d.ts +2 -2
  14. package/canvas/render-tag-element.js +1 -1
  15. package/canvas/rich-editor.d.ts +2 -2
  16. package/canvas/rich-editor.js +10 -3
  17. package/canvas/text-element/fit-font-size.d.ts +3 -6
  18. package/canvas/text-element/fit-font-size.js +1 -1
  19. package/canvas/text-element.d.ts +2 -2
  20. package/canvas/text-element.js +1 -1
  21. package/canvas/use-color.js +1 -1
  22. package/canvas/use-mediabunny-video.js +1 -1
  23. package/canvas/video-element.d.ts +1 -1
  24. package/canvas/video-element.js +1 -1
  25. package/model/group-model.d.ts +1 -2
  26. package/model/group-model.js +1 -1
  27. package/model/store.js +1 -1
  28. package/model/table-model.js +1 -1
  29. package/package.json +34 -48
  30. package/polotno.bundle.js +222 -221
  31. package/primitives/slider-field.d.ts +2 -1
  32. package/primitives/slider-field.js +1 -1
  33. package/primitives/slider.js +1 -1
  34. package/primitives/tabs.d.ts +1 -1
  35. package/side-panel/ai-images-panel.js +1 -1
  36. package/side-panel/draw-panel.js +1 -1
  37. package/side-panel/effect-card.d.ts +1 -1
  38. package/side-panel/effect-card.js +1 -1
  39. package/side-panel/effects-panel.js +1 -1
  40. package/side-panel/image-clip-panel.js +1 -1
  41. package/side-panel/layers-panel.js +1 -1
  42. package/side-panel/select-gif.js +1 -1
  43. package/side-panel/select-image.js +1 -1
  44. package/side-panel/select-svg.js +1 -1
  45. package/side-panel/select-video.js +1 -1
  46. package/toolbar/color-picker.js +1 -1
  47. package/toolbar/figure-toolbar.js +1 -1
  48. package/toolbar/html-toolbar.js +1 -1
  49. package/toolbar/image-toolbar.js +1 -1
  50. package/toolbar/svg-toolbar.js +1 -1
  51. package/toolbar/text-toolbar.js +1 -1
  52. package/toolbar/video-toolbar.js +1 -1
  53. package/ui.css +1 -1
  54. package/utils/background-shape.d.ts +1 -21
  55. package/utils/background-shape.js +1 -1
  56. package/utils/clipboard.js +1 -1
  57. package/utils/css-optimizer.js +1 -1
  58. package/utils/deprecation.d.ts +1 -0
  59. package/utils/deprecation.js +7 -0
  60. package/utils/errors.d.ts +3 -6
  61. package/utils/errors.js +1 -1
  62. package/utils/figure-to-svg.d.ts +1 -650
  63. package/utils/figure-to-svg.js +1 -1
  64. package/utils/filters.d.ts +1 -19
  65. package/utils/filters.js +1 -1
  66. package/utils/flags.d.ts +2 -1
  67. package/utils/fonts.d.ts +1 -3
  68. package/utils/fonts.js +1 -1
  69. package/utils/from-svg.js +1 -1
  70. package/utils/gradient.d.ts +1 -8
  71. package/utils/gradient.js +1 -1
  72. package/utils/html-to-svg/font-inliner.js +1 -1
  73. package/utils/html-to-svg/index.js +1 -1
  74. package/utils/html-to-svg/render-cache.js +1 -1
  75. package/utils/html-to-svg/xhtml.js +1 -1
  76. package/utils/html.js +1 -1
  77. package/utils/html2canvas.d.ts +1 -10
  78. package/utils/html2canvas.js +1 -1
  79. package/utils/image.d.ts +1 -14
  80. package/utils/image.js +1 -1
  81. package/utils/list-marker-geometry.d.ts +1 -14
  82. package/utils/list-marker-geometry.js +1 -1
  83. package/utils/loader.d.ts +1 -1
  84. package/utils/loader.js +1 -1
  85. package/utils/luma.js +1 -1
  86. package/utils/measure-text.js +1 -1
  87. package/utils/path-to-svg.js +1 -1
  88. package/utils/px.d.ts +48 -0
  89. package/utils/px.js +1 -0
  90. package/utils/reset-style.d.ts +1 -2
  91. package/utils/reset-style.js +1 -1
  92. package/utils/rich-text-html.d.ts +3 -16
  93. package/utils/rich-text-html.js +1 -1
  94. package/utils/svg.d.ts +2 -12
  95. package/utils/svg.js +2 -1
  96. package/utils/text-format-state.js +1 -1
  97. package/utils/text-format.js +1 -1
  98. package/utils/text-html.d.ts +3 -35
  99. package/utils/text-html.js +1 -1
  100. package/utils/text-types.d.ts +1 -48
  101. package/utils/text-types.js +1 -1
  102. package/utils/text.d.ts +1 -16
  103. package/utils/text.js +1 -1
  104. package/utils/to-html.d.ts +6 -17
  105. package/utils/to-html.js +1 -1
  106. package/utils/to-pptx.js +1 -1
  107. package/utils/to-svg.d.ts +6 -17
  108. package/utils/to-svg.js +1 -1
  109. package/utils/use-svg-colors.d.ts +1 -0
  110. package/utils/use-svg-colors.js +1 -0
  111. package/utils/validate-key.js +1 -1
  112. package/utils/video.d.ts +1 -7
  113. package/utils/video.js +1 -1
  114. package/utils/xml.d.ts +1 -1
  115. package/utils/xml.js +1 -7
@@ -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 i=0;for(n=Object.getOwnPropertySymbols(t);i<n.length;i++){e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(o[n[i]]=t[n[i]])}}return o};import{jsx as e}from"react/jsx-runtime";import o from"react";import n from"quill";import*as i from"mobx";import{nodeReaction as r}from"../utils/mobx.js";import{isAlive as l}from"mobx-state-tree";import s from"konva";import{getQuillEditorHtml as a,getDir as d}from"../utils/text-html.js";import{normalizeRichTextHtml as c,isQuillFormatMixed as u,isBoldWeight as f}from"../utils/rich-text-html.js";import{resetStyleContent as p}from"../utils/reset-style.js";import{removeTags as h}from"../utils/text.js";import{isGradient as m,parseColor as g}from"../utils/gradient.js";import{getOptimalCaretColor as b}from"./text-element/caret-color.js";import{registerQuillUnrestrictedFontFormats as v}from"./quill-font-formats.js";import{ALL_QUILL_MIXED_KEYS as y,setActiveTextEditor as x,updateActiveTextFormat as w,clearActiveTextEditor as S}from"../utils/text-format-state.js";import q from"../utils/styled.js";export function applyOpacityToColor(t,e){if(1===e){return t}const o=s.Util.colorToRGBA(t);return o?`rgba(${o.r}, ${o.g}, ${o.b}, ${o.a*e})`:t}export const quillRef=i.observable({enabled:!1,currentFormat:{},lastSelection:null,pendingToolbarInteraction:!1,editor:i.observable.object({instance:null},{},{deep:!1})});const k=y;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 i of k){u(n,i)&&(o[i]=!0)}return o}(t,e);i.runInAction(()=>{quillRef.currentFormat=o}),w(o,n,e)}const E="polotno-saved-selection";function T(){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(E,new Highlight(e)),O()}function C(){"undefined"!=typeof CSS&&CSS.highlights&&CSS.highlights.delete(E)}function O(){setTimeout(()=>{"undefined"!=typeof CSS&&CSS.highlights&&CSS.highlights.has(E)&&(document.querySelector(".polotno-portal")||N(document.activeElement)?O():C())},300)}if("undefined"!=typeof document&&"undefined"!=typeof CSS&&CSS.highlights&&!document.querySelector("[data-polotno-highlight]")){const M=document.createElement("style");M.setAttribute("data-polotno-highlight",""),M.textContent=`::highlight(${E}) { background-color: Highlight; }`,document.head.appendChild(M)}export const RichTextContainer=q("div",o.forwardRef)`
1
+ var e=this&&this.__rest||function(e,t){var o={};for(var n in e){Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(o[n]=e[n])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i<n.length;i++){t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(o[n[i]]=e[n[i]])}}return o};import{jsx as t}from"react/jsx-runtime";import o from"react";import n from"quill";import*as i from"mobx";import{nodeReaction as r}from"../utils/mobx.js";import{isAlive as l}from"mobx-state-tree";import{getQuillEditorHtml as s,getDir as a}from"@polotno/core/text-html";import{quillHtmlToModelText as d,isQuillFormatMixed as c,isBoldWeight as u}from"../utils/rich-text-html.js";import{resetStyleContent as f}from"@polotno/core/reset-style";import{removeTags as h}from"@polotno/core/text";import{isGradient as p,firstStopColor as m}from"@polotno/core/gradient";import{getOptimalCaretColor as g}from"./text-element/caret-color.js";import{registerQuillUnrestrictedFontFormats as b}from"./quill-font-formats.js";import{ALL_QUILL_MIXED_KEYS as v,setActiveTextEditor as x,updateActiveTextFormat as w,clearActiveTextEditor as y}from"../utils/text-format-state.js";import S from"../utils/styled.js";import{applyOpacityToColor as q}from"@polotno/core/svg";export{q as applyOpacityToColor};export const quillRef=i.observable({enabled:!1,currentFormat:{},lastSelection:null,pendingToolbarInteraction:!1,editor:i.observable.object({instance:null},{},{deep:!1})});const k=v;export function syncQuillFormatState(e,t){const o=t?e.getFormat(t):{},n=function(e,t){const o={};if(!t||t.length<=0){return o}const n=e.getContents(t.index,t.length);for(const i of k){c(n,i)&&(o[i]=!0)}return o}(e,t);i.runInAction(()=>{quillRef.currentFormat=o}),w(o,n,t)}const E="polotno-saved-selection";function C(){const e=window.getSelection();if(!e||0===e.rangeCount||e.isCollapsed){return}if("undefined"==typeof Highlight||!CSS.highlights){return}const t=e.getRangeAt(0).cloneRange();CSS.highlights.set(E,new Highlight(t)),O()}function T(){"undefined"!=typeof CSS&&CSS.highlights&&CSS.highlights.delete(E)}function O(){setTimeout(()=>{"undefined"!=typeof CSS&&CSS.highlights&&CSS.highlights.has(E)&&(document.querySelector(".polotno-portal")||N(document.activeElement)?O():T())},300)}if("undefined"!=typeof document&&"undefined"!=typeof CSS&&CSS.highlights&&!document.querySelector("[data-polotno-highlight]")){const M=document.createElement("style");M.setAttribute("data-polotno-highlight",""),M.textContent=`::highlight(${E}) { background-color: Highlight; }`,document.head.appendChild(M)}export const RichTextContainer=S("div",o.forwardRef)`
2
2
  .ql-editor {
3
3
  outline: none;
4
4
  /* anchor for the absolutely-positioned ::before placeholder below */
@@ -22,7 +22,7 @@ var t=this&&this.__rest||function(t,e){var o={};for(var n in t){Object.prototype
22
22
  pointer-events: none;
23
23
  opacity: 0;
24
24
  }
25
- ${p}
25
+ ${f}
26
26
 
27
27
  /* ===== Editor-only list markers (Quill flat-DOM hack) ======================
28
28
  Quill emits a FLAT <ol> with per-item data-list + ql-indent classes (not
@@ -129,4 +129,11 @@ var t=this&&this.__rest||function(t,e){var o={};for(var n in t){Object.prototype
129
129
  -webkit-text-fill-color: transparent;
130
130
  color: transparent;
131
131
  }
132
- `;let R=["background","font-weight","color","font","italic","size","script","strike","underline","indent","list","direction"];export const setQuillFormats=t=>{R=t};let F=!1;function L(){F||(F=!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"}export const createQuill=(e,o)=>{v();const i=new n(e,{toolbar:!1,keyboard:!1,placeholder:(null==o?void 0:o.placeholder)||void 0,clipboard:{matchVisual:!1},formats:R});!function(e){const o=e.format.bind(e),n=e.formatText.bind(e),i=e.getFormat.bind(e);e.format=(t,e,n)=>"bold"===t?(L(),o("font-weight",j(e),n)):o(t,e,n),e.formatText=(e,o,i,r,l)=>{if(i&&"object"==typeof i){if("bold"in i){L();const{bold:l}=i,s=t(i,["bold"]);return n(e,o,Object.assign(Object.assign({},s),{"font-weight":j(l)}),r)}return n(e,o,i,r)}return"bold"===i?(L(),n(e,o,"font-weight",j(r),l)):n(e,o,i,r,l)},e.getFormat=(...t)=>{const e=i(...t);return e&&null!=e["font-weight"]&&!("bold"in e)&&(e.bold=f(e["font-weight"])),e}}(i);const r=n.import("delta"),l=(t,e)=>e.compose((new r).retain(e.length(),{"font-weight":"700"}));return i.clipboard.addMatcher("STRONG",l),i.clipboard.addMatcher("B",l),i};export const setQuillContent=(t,e)=>{var o=t.clipboard.convert({html:"<div class='ql-editor' style='outline: none;'>"+e.replace(/\t/g,"")+"<p><br></p></div>",text:""});o.ops.forEach(t=>{"string"==typeof t.insert&&t.insert.includes("")&&(t.insert=t.insert.split("").join("\t"))}),t.setContents(o),t.history.clear()};export const RichEditor=({onBlur:t,onChange:n,element:s,clickCoords:u})=>{var f,p,v;const y=o.useRef(null),w=o.useRef(!1);o.useLayoutEffect(()=>{let e,o=!1,r=null,d=null,f=null,p=null,h=null;const m=()=>{if(!o&&y.current){try{e=createQuill(y.current,{placeholder:s.placeholder}),i.runInAction(()=>{quillRef.editor.instance=e}),quillRef.pendingToolbarInteraction=!1,window.__polotnoQuill=e,x({instance:e,store:s.store,element:s}),e.on("text-change",()=>{const t=e.getSelection();t&&(syncQuillFormatState(e,t),i.runInAction(()=>{quillRef.lastSelection={index:t.index,length:t.length}})),setTimeout(()=>{var t;const o=e.root;if(!o||!o.isConnected){return}if(!l(s)){return}const i=o.innerHTML;w.current=!0,n(c(function(t){const e=(t||"").trim();if("<p><br></p>"===e||"<p></p>"===e){return""}if(e.startsWith("<p>")&&e.endsWith("</p>")){const t=e.slice(3,-4);if(!/(<\/?(p|div|h[1-6]|ul|ol|li|table|thead|tbody|tr|td|blockquote)\b)/i.test(t)){return t}}return t}(i),{fontSize:s.fontSize,fontFamily:s.fontFamily}));const r=e.getContents(),a=s.fill;let d=null,u=!0;for(const e of r.ops){if("string"!=typeof e.insert||"\n"===e.insert){continue}const o=(null===(t=e.attributes)||void 0===t?void 0:t.color)||a;if(null===d){d=o}else if(o!==d){u=!1;break}}u&&d&&s.set({fill:d})},10)});const o=a(s,s.fontFamily);setQuillContent(e,o),w.current=!0;const m=y.current.closest(".polotno-workspace-inner"),g=null==m?void 0:m.scrollLeft,b=null==m?void 0:m.scrollTop;u?setCursorFromCoords(e,u):e.setSelection(0,0,"api"),m&&void 0!==g&&void 0!==b&&(m.scrollLeft=g,m.scrollTop=b),e.on("selection-change",(t,o,n)=>{t&&(syncQuillFormatState(e,t),i.runInAction(()=>{quillRef.lastSelection={index:t.index,length:t.length}}))});const v=e.root;p=e=>{const o=e.relatedTarget;(null==o?void 0:o.classList.contains("ql-clipboard"))||(N(o)||quillRef.pendingToolbarInteraction?T():setTimeout(()=>{quillRef.pendingToolbarInteraction||N(document.activeElement)?T():(C(),t())},0))},h=()=>{C()},v.addEventListener("blur",p),v.addEventListener("focus",h),r=v,d=t=>{var o,n;const i=e.getSelection();if(!i||0===i.length){return}const r=e.getText(i.index,i.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!==v&&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 i=document.createElement("div");i.appendChild(e),s=i.innerHTML}if(null===(o=t.clipboardData)||void 0===o||o.setData("text/plain",r),s){const e='<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>\x3c!--StartFragment--\x3e<div style="white-space: pre-wrap; overflow-wrap: break-word;">'+s+"</div>\x3c!--EndFragment--\x3e</body></html>";null===(n=t.clipboardData)||void 0===n||n.setData("text/html",e)}t.preventDefault()},f=t=>{d&&d(t);const o=e.getSelection();o&&o.length>0&&e.deleteText(o.index,o.length)},r.addEventListener("copy",d),r.addEventListener("cut",f)}catch(m){console.error("RichEditor init failed:",m)}}};return y.current?m():queueMicrotask(m),()=>{o=!0,r&&p&&r.removeEventListener("blur",p),r&&h&&r.removeEventListener("focus",h),C(),r&&d&&f&&(r.removeEventListener("copy",d),r.removeEventListener("cut",f)),i.runInAction(()=>{quillRef.editor.instance=null,quillRef.currentFormat={},quillRef.lastSelection=null}),S(e),delete window.__polotnoQuill}},[]),o.useEffect(()=>r(s,()=>`${s.text}\0${s.fontSize}\0${s.fontFamily}`,()=>{const t=quillRef.editor.instance;if(!t){return}if(w.current){return void(w.current=!1)}const e=t.getSelection();setQuillContent(t,a(s,s.fontFamily)),w.current=!0,e&&(t.setSelection(e.index,e.length),syncQuillFormatState(t,t.getSelection()))},{fireImmediately:!0}),[]),o.useEffect(()=>{window.addEventListener("blur",t);const e=e=>{var o;(null===(o=y.current)||void 0===o?void 0:o.contains(e.target))||N(e.target)||quillRef.pendingToolbarInteraction||(C(),t())};return window.addEventListener("mousedown",e),window.addEventListener("touchstart",e),()=>{window.removeEventListener("blur",t),window.removeEventListener("mousedown",e),window.removeEventListener("touchstart",e)}},[]);const q={color:s.fill};s.fill.indexOf("gradient")>=0&&(q["--polotno-gradient"]=s.fill,q.color="transparent");const k=m(s.fill)?null!==(p=null===(f=g(s.fill).stops[0])||void 0===f?void 0:f.color)&&void 0!==p?p:"#000000":b(s),E=s.a.rotation*Math.PI/180,O=s.shadowOffsetX*Math.cos(E)+s.shadowOffsetY*Math.sin(E),R=-s.shadowOffsetX*Math.sin(E)+s.shadowOffsetY*Math.cos(E);return e(RichTextContainer,{ref:y,style:Object.assign(Object.assign({},q),{fontSize:s.fontSize,fontFamily:s.fontFamily,fontWeight:s.fontWeight,fontStyle:s.fontStyle,"--polotno-text-decoration":s.textDecoration||"none",textTransform:s.textTransform,width:s.a.width,lineHeight:s.lineHeight,letterSpacing:s.letterSpacing*s.fontSize+"px",textAlign:s.align,opacity:Math.max(s.a.opacity,.2),textShadow:s.shadowEnabled?`${O}px ${R}px ${s.shadowBlur}px ${applyOpacityToColor(s.shadowColor,null!==(v=s.shadowOpacity)&&void 0!==v?v:1)}`:void 0,caretColor:k}),dir:d(h(s.text))})};function N(t){return!(!t||!t.closest(".sketch-picker")&&!t.closest("[data-polotno-keep-focus]")&&!t.closest(".polotno-portal")&&!t.closest(".polotno-toolbar"))}export function setCursorFromCoords(t,e){if(!t||!e){return}const{x:o,y:i}=e;try{let e=null;if(document.caretRangeFromPoint){e=document.caretRangeFromPoint(o,i)}else if(document.caretPositionFromPoint){const t=document.caretPositionFromPoint(o,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(r){}t.setSelection(0,0,"api")}
132
+ /* A span carrying its own solid color must win over the gradient: the
133
+ transparent -webkit-text-fill-color above is INHERITED, so without this
134
+ the span paints the clipped gradient instead of its chosen color
135
+ (mirrors getHtml's markInlineColorsForClip on the canvas side). */
136
+ &[style*='--polotno-gradient'] .ql-editor [style*='color:'] {
137
+ -webkit-text-fill-color: currentColor;
138
+ }
139
+ `;let R=["background","font-weight","color","gradient","font","italic","size","script","strike","underline","indent","list","direction"];export const setQuillFormats=e=>{R=e};let F=!1;function L(){F||(F=!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(e){return e?"700":"400"}export const createQuill=(t,o)=>{b();const i=new n(t,{toolbar:!1,keyboard:!1,placeholder:(null==o?void 0:o.placeholder)||void 0,clipboard:{matchVisual:!1},formats:R});!function(t){const o=t.format.bind(t),n=t.formatText.bind(t),i=t.getFormat.bind(t);t.format=(e,t,n)=>"bold"===e?(L(),o("font-weight",j(t),n)):o(e,t,n),t.formatText=(t,o,i,r,l)=>{if(i&&"object"==typeof i){if("bold"in i){L();const{bold:l}=i,s=e(i,["bold"]);return n(t,o,Object.assign(Object.assign({},s),{"font-weight":j(l)}),r)}return n(t,o,i,r)}return"bold"===i?(L(),n(t,o,"font-weight",j(r),l)):n(t,o,i,r,l)},t.getFormat=(...e)=>{const t=i(...e);return t&&null!=t["font-weight"]&&!("bold"in t)&&(t.bold=u(t["font-weight"])),t}}(i);const r=n.import("delta"),l=(e,t)=>t.compose((new r).retain(t.length(),{"font-weight":"700"}));return i.clipboard.addMatcher("STRONG",l),i.clipboard.addMatcher("B",l),i};export const setQuillContent=(e,t)=>{var o=e.clipboard.convert({html:"<div class='ql-editor' style='outline: none;'>"+t.replace(/\t/g,"")+"<p><br></p></div>",text:""});o.ops.forEach(e=>{"string"==typeof e.insert&&e.insert.includes("")&&(e.insert=e.insert.split("").join("\t"))}),e.setContents(o),e.history.clear()};export const RichEditor=({onBlur:e,onChange:n,element:c,clickCoords:u})=>{var f;const b=o.useRef(null),v=o.useRef(!1);o.useLayoutEffect(()=>{let t,o=!1,r=null,a=null,f=null,h=null,p=null;const m=()=>{if(!o&&b.current){try{t=createQuill(b.current,{placeholder:c.placeholder}),i.runInAction(()=>{quillRef.editor.instance=t}),quillRef.pendingToolbarInteraction=!1,window.__polotnoQuill=t,x({instance:t,store:c.store,element:c}),t.on("text-change",()=>{const e=t.getSelection();e&&(syncQuillFormatState(t,e),i.runInAction(()=>{quillRef.lastSelection={index:e.index,length:e.length}})),setTimeout(()=>{var e,o;const i=t.root;if(!i||!i.isConnected){return}if(!l(c)){return}const r=i.innerHTML;v.current=!0,n(d(r,{fontSize:c.fontSize,fontFamily:c.fontFamily}));const s=t.getContents(),a=c.fill;let u=null,f=!0;for(const t of s.ops){if("string"!=typeof t.insert||"\n"===t.insert){continue}if(null===(e=t.attributes)||void 0===e?void 0:e.gradient){f=!1;break}const n=(null===(o=t.attributes)||void 0===o?void 0:o.color)||a;if(null===u){u=n}else if(n!==u){f=!1;break}}f&&u&&c.set({fill:u})},10)});const o=s(c,c.fontFamily);setQuillContent(t,o),v.current=!0;const m=b.current.closest(".polotno-workspace-inner"),g=null==m?void 0:m.scrollLeft,w=null==m?void 0:m.scrollTop;u?setCursorFromCoords(t,u):t.setSelection(0,0,"api"),m&&void 0!==g&&void 0!==w&&(m.scrollLeft=g,m.scrollTop=w),t.on("selection-change",(e,o,n)=>{e&&(syncQuillFormatState(t,e),i.runInAction(()=>{quillRef.lastSelection={index:e.index,length:e.length}}))});const y=t.root;h=t=>{const o=t.relatedTarget;(null==o?void 0:o.classList.contains("ql-clipboard"))||(N(o)||quillRef.pendingToolbarInteraction?C():setTimeout(()=>{quillRef.pendingToolbarInteraction||N(document.activeElement)?C():(T(),e())},0))},p=()=>{T()},y.addEventListener("blur",h),y.addEventListener("focus",p),r=y,a=e=>{var o,n;const i=t.getSelection();if(!i||0===i.length){return}const r=t.getText(i.index,i.length).replace(/\n$/,""),l=window.getSelection();let s="";if(l&&l.rangeCount>0){const e=l.getRangeAt(0);let t=e.cloneContents(),o=e.startContainer;o&&o.nodeType===Node.TEXT_NODE&&(o=o.parentNode);let n=e.endContainer;if(n&&n.nodeType===Node.TEXT_NODE&&(n=n.parentNode),o&&o===n){let e=o;for(;e&&e!==y&&e.nodeType===Node.ELEMENT_NODE;){const o=e.tagName;if("SPAN"!==o&&"EM"!==o&&"STRONG"!==o&&"U"!==o&&"S"!==o&&"A"!==o){break}const n=e.cloneNode(!1);n.appendChild(t),t=n,e=e.parentNode}}const i=document.createElement("div");i.appendChild(t),s=i.innerHTML}if(null===(o=e.clipboardData)||void 0===o||o.setData("text/plain",r),s){const t='<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>\x3c!--StartFragment--\x3e<div 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()},f=e=>{a&&a(e);const o=t.getSelection();o&&o.length>0&&t.deleteText(o.index,o.length)},r.addEventListener("copy",a),r.addEventListener("cut",f)}catch(m){console.error("RichEditor init failed:",m)}}};return b.current?m():queueMicrotask(m),()=>{o=!0,r&&h&&r.removeEventListener("blur",h),r&&p&&r.removeEventListener("focus",p),T(),r&&a&&f&&(r.removeEventListener("copy",a),r.removeEventListener("cut",f)),i.runInAction(()=>{quillRef.editor.instance=null,quillRef.currentFormat={},quillRef.lastSelection=null}),y(t),delete window.__polotnoQuill}},[]),o.useEffect(()=>r(c,()=>`${c.text}\0${c.fontSize}\0${c.fontFamily}`,()=>{const e=quillRef.editor.instance;if(!e){return}if(v.current){return void(v.current=!1)}const t=e.getSelection();setQuillContent(e,s(c,c.fontFamily)),v.current=!0,t&&(e.setSelection(t.index,t.length),syncQuillFormatState(e,e.getSelection()))},{fireImmediately:!0}),[]),o.useEffect(()=>{window.addEventListener("blur",e);const t=t=>{var o;(null===(o=b.current)||void 0===o?void 0:o.contains(t.target))||N(t.target)||quillRef.pendingToolbarInteraction||(T(),e())};return window.addEventListener("mousedown",t),window.addEventListener("touchstart",t),()=>{window.removeEventListener("blur",e),window.removeEventListener("mousedown",t),window.removeEventListener("touchstart",t)}},[]);const w={color:c.fill};c.fill.indexOf("gradient")>=0&&(w["--polotno-gradient"]=c.fill,w.color="transparent"),c.strokeWidth>0&&(w.WebkitTextStroke=`${c.strokeWidth}px ${m(c.stroke)}`,w.paintOrder="stroke fill");const S=p(c.fill)?m(c.fill):g(c),k=c.a.rotation*Math.PI/180,E=c.shadowOffsetX*Math.cos(k)+c.shadowOffsetY*Math.sin(k),O=-c.shadowOffsetX*Math.sin(k)+c.shadowOffsetY*Math.cos(k);return t(RichTextContainer,{ref:b,style:Object.assign(Object.assign({},w),{fontSize:c.fontSize,fontFamily:c.fontFamily,fontWeight:c.fontWeight,fontStyle:c.fontStyle,"--polotno-text-decoration":c.textDecoration||"none",textTransform:c.textTransform,width:c.a.width,lineHeight:c.lineHeight,letterSpacing:c.letterSpacing*c.fontSize+"px",textAlign:c.align,opacity:Math.max(c.a.opacity,.2),textShadow:c.shadowEnabled?`${E}px ${O}px ${c.shadowBlur}px ${q(c.shadowColor,null!==(f=c.shadowOpacity)&&void 0!==f?f:1)}`:void 0,caretColor:S}),dir:a(h(c.text))})};function N(e){return!(!e||!e.closest(".sketch-picker")&&!e.closest("[data-polotno-keep-focus]")&&!e.closest(".polotno-portal")&&!e.closest(".polotno-toolbar"))}export function setCursorFromCoords(e,t){if(!e||!t){return}const{x:o,y:i}=t;try{let t=null;if(document.caretRangeFromPoint){t=document.caretRangeFromPoint(o,i)}else if(document.caretPositionFromPoint){const e=document.caretPositionFromPoint(o,i);e&&(t=document.createRange(),t.setStart(e.offsetNode,e.offset))}if(t){const o=n.find(t.startContainer,!0);if(o){const n=o.offset(e.scroll)+t.startOffset;return void e.setSelection(n,0,"api")}}}catch(r){}e.setSelection(0,0,"api")}
@@ -1,8 +1,5 @@
1
1
  import { TextElementType } from '../../model/text-model.js';
2
- import { GetHtmlOptions } from '../../utils/text-html.js';
3
- export type FitResult = {
4
- fontSize: number;
5
- text?: string;
6
- };
7
- export type MeasureHeight = (html: string) => number;
2
+ import { GetHtmlOptions } from '@polotno/core/text-html';
3
+ import { type FitResult, type MeasureHeight } from '@polotno/core/fit-text';
4
+ export type { FitResult, MeasureHeight };
8
5
  export declare function findFitFontSize(element: TextElementType, getHtmlOptions: GetHtmlOptions, measureHeight?: MeasureHeight): FitResult;
@@ -1 +1 @@
1
- import{getHtml as t}from"../../utils/text-html.js";import{detectSize as e,isContentWrapping as i}from"../../utils/html2canvas.js";import{normalizeRichTextHtml as o,hasAnyInlineFontSize as n,scaleRichTextFontSizesInHtml as f}from"../../utils/rich-text-html.js";import{flags as l}from"../../utils/flags.js";const r=t=>e(t).height;export function findFitFontSize(e,s,a=r){const m=o(e.text,{fontSize:e.fontSize,fontFamily:e.fontFamily});if(n(m)){return function(e,n,s=r){let a=1;for(let r=1;r<50;r++){const r=f(e.text,a),m=e.fontSize*a,S=t(Object.assign(Object.assign({},e.toJSON()),{fontSize:m,text:o(r,{fontSize:m,fontFamily:e.fontFamily})}),n),h=s(S);if(!(e.height&&h>e.height||!l.textSplitAllowed&&!e.curveEnabled&&i({html:S}))){break}a-=.02;const c=Math.max(.05,1/e.fontSize);if(a<c){a=c;break}}return a>=1?{fontSize:e.fontSize}:{fontSize:e.fontSize*a,text:f(e.text,a)}}(e,s,a)}let S=e.fontSize;for(let n=1;n<50;n++){const n=t(Object.assign(Object.assign({},e.toJSON()),{fontSize:S,text:o(e.text,{fontSize:S,fontFamily:e.fontFamily})}),s),f=a(n);if(!(e.height&&f>e.height||!l.textSplitAllowed&&!e.curveEnabled&&i({html:n}))){break}if(S-=.5,S<1){S=1;break}}return{fontSize:S}}
1
+ import{findFitFontSize as t}from"@polotno/core/fit-text";import{flags as e}from"../../utils/flags.js";export function findFitFontSize(o,i,l){return t(o.toJSON(),{getHtmlOptions:Object.assign({textOverflow:e.textOverflow},i),measureHeight:l,textSplitAllowed:e.textSplitAllowed})}
@@ -5,7 +5,7 @@ type ShapeProps = {
5
5
  store: StoreType;
6
6
  element: TextElementType;
7
7
  };
8
- export { getDir } from '../utils/text-html.js';
8
+ export { getDir } from '@polotno/core/text-html';
9
9
  export declare const useFontLoader: (store: StoreType, fontFamily: string, fontStyle?: string, fontWeight?: string, sampleText?: string) => boolean[];
10
10
  export declare const useFontFamiliesLoader: (store: StoreType, families: string[], fontStyle?: string, fontWeight?: string, sampleText?: string) => boolean[];
11
11
  export declare const getLineHeight: ({ fontLoaded, fontFamily, fontSize, lineHeight, }: {
@@ -15,7 +15,7 @@ export declare const getLineHeight: ({ fontLoaded, fontFamily, fontSize, lineHei
15
15
  lineHeight: any;
16
16
  }) => number;
17
17
  export declare function usePrevious(value: any): any;
18
- export { getCurvePath } from '../utils/text-html.js';
18
+ export { getCurvePath } from '@polotno/core/text-html';
19
19
  export declare const TextElement: (({ element, store }: ShapeProps) => React.JSX.Element) & {
20
20
  displayName: string;
21
21
  };
@@ -1 +1 @@
1
- import{jsx as t,Fragment as e,jsxs as r}from"react/jsx-runtime";import n from"react";import{observer as o}from"mobx-react-lite";import{Group as i,Path as a,Text as s,TextPath as l}from"react-konva";import{Html as c}from"react-konva-utils";import{nodeAutorun as u}from"../utils/mobx.js";import d from"konva";import{parsePath as f,roundCommands as h}from"svg-round-corners/lib/index.js";import{generateBackgroundShapeFromRects as g,textLinesToRects as m}from"../utils/background-shape.js";import{useColor as p}from"./use-color.js";import{useWorkspaceStyle as x}from"./workspace-style.js";import{ROLES as w}from"../model/store.js";import{incrementLoader as v}from"../utils/loader.js";import{isFontLoaded as y}from"../utils/fonts.js";import{flags as S}from"../utils/flags.js";import{removeTags as b}from"../utils/text.js";import{getDir as E,getCurvePath as z,resolveLineHeight as k,normalizeStrokeLineJoin as O}from"../utils/text-html.js";import{applyFilter as R}from"./apply-filters.js";import{useFadeIn as A}from"./use-fadein.js";import{isTouchDevice as F}from"../utils/screen.js";import{isAlive as M,getParent as j}from"mobx-state-tree";import{getLimitedFontSize as L}from"./text-element/max-font-size.js";import{getOptimalCaretColor as T}from"./text-element/caret-color.js";let C;function H(){return C||(C=document.getElementById("polotno-text-style"),C||(C=document.createElement("style"),C.id="polotno-text-style",document.head.appendChild(C)),C)}d._fixTextRendering=!0;const X={border:"none",padding:"0px",overflow:"hidden",background:"none",outline:"none",resize:"none",overflowWrap:"break-word",whiteSpace:"pre-wrap",userSelect:"text",wordBreak:"normal",textTransform:"none"};export{getDir}from"../utils/text-html.js";const Y=o(({textNodeRef:e,element:r,onBlur:o,selectAll:i,cursorPosition:a})=>{const[s,l]=n.useState(X),c=e.current;n.useLayoutEffect(()=>{if(!c){return}const t={};t.width=c.width()-2*c.padding()+"px",t.height=c.height()-2*c.padding()+c.fontSize()*c.lineHeight()+"px",t.fontSize=c.fontSize()+"px",t.lineHeight=c.lineHeight()+.01,t.fontFamily=c.fontFamily(),t.textAlign=c.align(),t.color=c.fill(),t.fontWeight=r.fontWeight,t.fontStyle=r.fontStyle,t.letterSpacing=r.letterSpacing+"em",t.opacity=Math.max(r.a.opacity,.2),t.textTransform=r.textTransform,t.caretColor=T(r);const e=`\n .polotno-input::placeholder {\n color: ${s.color};\n opacity: 0.6;\n }\n `,n=H();n.innerHTML="",n.appendChild(document.createTextNode(e)),JSON.stringify(t)!==JSON.stringify(s)&&l(t)});const u=n.useRef(null);if(n.useLayoutEffect(()=>{var t;const e=u.current;if(!e){return}null===(t=u.current)||void 0===t||t.focus({preventScroll:!0});const r=a||e.value.length;e.selectionStart=e.selectionEnd=r,i&&(null==e||e.select(),document.execCommand("selectAll",!1,void 0))},[]),n.useEffect(()=>{window.addEventListener("blur",o);const t=t=>{var e;(null===(e=u.current)||void 0===e?void 0:e.contains(t.target))||o()};return window.addEventListener("touchstart",t),()=>{window.removeEventListener("blur",o),window.removeEventListener("touchstart",t)}},[]),!c){return null}let d=0;const f=c.textArr.length*c.lineHeight()*c.fontSize();"middle"===r.verticalAlign&&(d=(r.a.height-f)/2),"bottom"===r.verticalAlign&&(d=r.a.height-f);const h=b(r.text);return t("textarea",{className:"polotno-input",ref:u,dir:E(h),style:Object.assign(Object.assign(Object.assign({},X),s),{paddingTop:d+"px"}),value:h,onChange:t=>{const e=L({oldText:r.text,newText:t.target.value,element:r});r.set({text:t.target.value,fontSize:e})},placeholder:r.placeholder,onBlur:o})}),P=e=>t(c,{children:t(Y,Object.assign({},e))});export const useFontLoader=(t,e,r,o,i)=>{const[a,s]=n.useReducer(t=>t+1,0),l=n.useRef(y(e,r,o)),c=n.useRef(null);return n.useLayoutEffect(()=>{if(l.current=y(e,r,o),l.current){return}let n=!0;return(async()=>{l.current=!1,s();const a=v(`text ${e}`);await t.loadFont(e,r,o,i),n?(c.current=a,l.current=!0,s()):a()})(),()=>{c.current&&(c.current(),c.current=null),n=!1}},[e,r,o]),n.useEffect(()=>{l.current&&setTimeout(()=>{c.current&&(c.current(),c.current=null)})},[l.current]),[l.current]};export const useFontFamiliesLoader=(t,e,r,o,i)=>{const[a,s]=n.useReducer(t=>t+1,0),l=e.join("\0"),c=n.useRef(e.every(t=>y(t,r,o))),u=n.useRef(null);return n.useLayoutEffect(()=>{if(c.current=e.every(t=>y(t,r,o)),c.current){return}let n=!0;return(async()=>{c.current=!1,s();const a=v(`text fonts ${l}`);await Promise.all(e.map(e=>t.loadFont(e,r,o,i))),n?(u.current=a,c.current=!0,s()):a()})(),()=>{u.current&&(u.current(),u.current=null),n=!1}},[l,r,o]),n.useEffect(()=>{c.current&&setTimeout(()=>{u.current&&(u.current(),u.current=null)})},[c.current]),[c.current]};export const getLineHeight=({fontLoaded:t,fontFamily:e,fontSize:r,lineHeight:o})=>n.useMemo(()=>k({fontFamily:e,fontSize:r,lineHeight:o}),[t,e,r,o]);export function usePrevious(t){const e=n.useRef(t),r=n.useRef(t);return n.useMemo(()=>{r.current=e.current,e.current=t},[t]),r.current}function W(t,e,r=!1){const n=t.fontSize(),o=t.height(),i=b(e.text);let a=e.a.fontSize;t.height(void 0);const s=Math.round(2*e.a.fontSize)-1;for(let l=1;l<s;l++){const n=e.a.height&&t.height()>e.a.height;let o=i.split("\n").join(" ").split(/[\s-]+/).reduce((t,e)=>(e=e.toLowerCase(),/[\u3000-\u303F\u3040-\u309F\u30A0-\u30FF\uFF00-\uFFEF\u4E00-\u9FAF\uAC00-\uD7AF]/.test(e)?t.concat(e.split("")):t.concat(e)),[]),s=t.textArr.map(t=>t.text.toLowerCase()).join(";");const l=o.find(t=>!s.includes(t)||(s=s.replace(t,""),!1));if(!(n||l&&!r)){break}a-=.5,t.fontSize(a)}return t.fontSize(n),t.height(o),a}export{getCurvePath}from"../utils/text-html.js";export const TextElement=o(({element:o,store:c})=>{const{textOverflowIndicatorStyle:d}=x(),y=n.useRef(null),k=n.useRef(null),L=n.useRef(null),T=n.useRef([]),C=n.useRef(!0),[,H]=n.useReducer(t=>t+1,0),{editorEnabled:X,selectAll:Y}=(t=>{const[e,r]=n.useState(!1),o=n.useRef(!1);return n.useEffect(()=>{var e=!0;return setTimeout(()=>{e&&(t._editModeEnabled&&(o.current=!0),r(!0),setTimeout(()=>{o.current=!1},50))},50),()=>{e=!1}},[]),{editorEnabled:e&&t._editModeEnabled,selectAll:o.current}})(o),[B,D]=n.useState(!1),[$,I]=n.useState(!1),N=n.useRef(o.a.height),J=n.useRef(0),_=n.useRef(""),V=n.useRef(0),q=o.isSelected,U=usePrevious(q),{textVerticalResizeEnabled:Z}=S,G=S.autoDeleteEmptyText,K=usePrevious(o.fontFamily),[Q,tt]=n.useState([]);n.useEffect(()=>{var t,e;const r=null!==(e=null===(t=y.current)||void 0===t?void 0:t.textArr)&&void 0!==e?e:[];JSON.stringify(r)!==JSON.stringify(Q)&&tt(r)}),n.useEffect(()=>{if(o.a.width||"tablecell"===o.type){return}const t=y.current;t.width(600),o.set({width:1.4*t.getTextWidth()})},[]),n.useEffect(()=>{U&&!q&&G&&""===o.text&&o.removable&&!o.placeholder&&c.deleteElements([o.id])},[G,o.placeholder,o.removable,o.text,q,U]);const et=()=>{if(o.curveEnabled){const t=y.current;null==t||t.clearCache(),null==t||t.setAttrs({filters:[]});const e=k.current;e&&R(e,o)}else{const t=y.current;t&&R(t,o)}};n.useLayoutEffect(()=>{if(!$){return u(o,()=>{et()})}}),n.useEffect(()=>{const t=T.current;t.length>0&&(T.current=[],t.forEach(t=>t()))}),n.useEffect(()=>()=>{C.current=!1;const t=T.current;t.length>0&&(T.current=[],t.forEach(t=>t()))},[]);let rt=b(o.text);"uppercase"===o.textTransform&&(rt=rt.toUpperCase());const[nt]=useFontLoader(c,o.fontFamily,o.fontStyle,o.fontWeight,o.text||o.placeholder),ot=()=>{if(o.curveEnabled){const t=k.current;return t.getSelfRect().height||t.fontSize()}const t=y.current.clone({height:void 0}),e=Math.ceil(t.fontSize()*t.lineHeight()*t.textArr.length+1);return t.destroy(),e};n.useLayoutEffect(()=>{if(!nt){return}if("tablecell"===o.type){const{textOverflow:t}=S;if("resize"===t){const t=ot(),e=M(o)?j(o,2):null;(null==e?void 0:e.setCellContentHeight)&&e.setCellContentHeight(o.id,t)}else if("change-font-size"===t){const t=y.current;if(t){const e=W(t,o,S.textSplitAllowed);e!==o.fontSize&&c.history.ignore(()=>{o.set({fontSize:e})})}}return}const{textOverflow:t,textSplitAllowed:e}=S,r=(t,e,r,n)=>{const i=v(`text ${o.id}`),a=()=>{c.history.ignore(t,e,r).then(()=>{C.current?(T.current.push(i),H()):i()})};n?queueMicrotask(a):a()};if(!o.height){const t=ot();return void r(()=>{o.height||o.set({height:t})},void 0,void 0,!0)}if(!c.isPlaying){if("change-font-size"!==t||B){if("resize"===t){const t=ot();Z&&o.height<t&&!B&&r(()=>{var e;M(o)&&o.set({height:t}),null===(e=y.current)||void 0===e||e.height(t)},!1,!0),Z||o.height===t||B||r(()=>{var e;M(o)&&o.set({height:t}),null===(e=y.current)||void 0===e||e.height(t)},!1,!0)}}else{const t=y.current,n=o.curveEnabled?o.fontSize:W(t,o,e);if(n!==o.fontSize){return void r(()=>{o.set({fontSize:n})},!1,!0)}const i=ot();o.height===i||Z||r(()=>{o.set({height:i})},!1,!0)}}}),n.useLayoutEffect(()=>{var t;if(nt&&o.curveEnabled){const e=null===(t=k.current)||void 0===t?void 0:t.getSelfRect().width;if(e){const t=e-o.a.width,r=o.a.rotation*Math.PI/180,n=-t/2*Math.cos(r),i=-t/2*Math.sin(r);o.set({width:e,x:o.a.x+n,y:o.a.y+i})}}},[nt,o.curveEnabled,o.curvePower,o.text,o.fontSize,o.fontFamily,o.fontWeight,o.fontStyle,o.letterSpacing]),n.useLayoutEffect(()=>{const t=y.current;t&&(t.width(t.width()+1e-8),t.width(t.width()-1e-8),t._setTextData(),et())},[nt]);const it=n.useRef(null),at=n.useRef(0),st=t=>{t.evt.preventDefault();const e=c.selectedShapes.find(t=>t===o);e&&o.contentEditable&&(at.current=function(t){var e;const r=t.target,n=function(t){var e=t.getAbsoluteTransform().copy();e.invert();var r=t.getStage().getPointerPosition();return e.point(r)}(r),o=r.textArr,i=Math.floor(n.y/(r.fontSize()*r.lineHeight())),a=o.slice(0,i).reduce((t,e)=>t+e.text.length,i),s=null!==(e=o[i])&&void 0!==e?e:o[0];let l=0;return"right"===r.align()?l=r.width()-s.width:"center"===r.align()&&(l=r.width()/2-s.width/2),a+Math.round((n.x-l)/s.width*s.text.length)}(t),o.toggleEditMode())},lt=!rt&&o.placeholder?.6:o.a.opacity;A(y,lt);const ct=getLineHeight({fontLoaded:nt,fontFamily:o.fontFamily,fontSize:o.a.fontSize,lineHeight:o.lineHeight}),ut=o.selectable||c.role===w.ADMIN,dt=p(o),ft=p(o,o.stroke,"stroke"),ht=n.useMemo(()=>o.backgroundEnabled?o.curveEnabled?function({width:t,height:e,padding:r=0,cornerRadius:n=0}){const o=-r,i=-r,a=t+r,s=e+r,l=f(`M ${o} ${i} L ${a} ${i} L ${a} ${s} L ${o} ${s} Z`);return h(l,n).path}({width:o.a.width,height:o.a.height,cornerRadius:o.backgroundCornerRadius*(o.a.fontSize*ct*.5),padding:o.backgroundPadding*(o.a.fontSize*ct*.5)}):function({lines:t,lineHeight:e,width:r,align:n="left",padding:o=0,cornerRadius:i=0}){const a=m({lines:t,lineHeight:e,width:r,align:n});return g({rects:a,padding:o,cornerRadius:i})}({lines:JSON.parse(JSON.stringify(Q)),cornerRadius:o.backgroundCornerRadius*(o.a.fontSize*ct*.5),lineHeight:ct*o.a.fontSize,padding:o.backgroundPadding*(o.a.fontSize*ct*.5),width:o.a.width,align:o.align}):"",[o.backgroundEnabled,o.curveEnabled,o.backgroundCornerRadius,o.a.fontSize,o.a.height,ct,o.backgroundPadding,o.a.width,o.align,Q]),gt=F();let mt=0;o.curveEnabled||("middle"===o.verticalAlign?mt=(o.a.height-Q.length*ct*o.a.fontSize)/2:"bottom"===o.verticalAlign&&(mt=o.a.height-Q.length*ct*o.a.fontSize));const pt=o.curveEnabled?z(o.a.width,o.a.height,o.curvePower,o.a.fontSize):"",xt=nt?'"'+o.fontFamily+'"':K===o.fontFamily?"Arial":'"'+K+'"',wt=E(rt);return r(e,{children:[t(a,{ref:L,x:o.a.x,y:o.a.y,rotation:o.a.rotation,hideInExport:!o.showInExport,listening:!1,visible:o.backgroundEnabled,opacity:o.backgroundOpacity*lt,data:ht,fill:o.backgroundColor,offsetY:-mt}),t(a,{data:pt,stroke:d.stroke,strokeWidth:1,x:o.a.x,y:o.a.y,rotation:o.a.rotation,visible:!1}),t(l,Object.assign({ref:k,visible:o.curveEnabled,data:pt,text:rt||o.placeholder,listening:!1,align:"center",textBaseline:"middle",direction:wt},dt,ft,{strokeWidth:o.strokeWidth,lineJoin:O(o.strokeLineJoin),fillAfterStrokeEnabled:!0,fontSize:o.a.fontSize,fontFamily:`"${o.fontFamily}", "${K}"`,fontStyle:o.fontStyle+" "+o.fontWeight,textDecoration:o.textDecoration.trim(),letterSpacing:o.letterSpacing*o.a.fontSize,x:o.a.x,y:o.a.y,rotation:o.a.rotation,opacity:o._editModeEnabled?.3:lt,hideInExport:!o.showInExport,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity})),t(s,Object.assign({ref:y,id:o.selectable?o.id:void 0,name:o.selectable?"element":"",hideInExport:!o.showInExport,editModeEnabled:o._editModeEnabled,x:o.a.x,y:o.a.y,rotation:o.a.rotation,width:o.a.width,height:o.a.height,text:rt||o.placeholder,direction:wt},dt,ft,{lineJoin:O(o.strokeLineJoin),strokeWidth:o.strokeWidth,fillAfterStrokeEnabled:!0,fontSize:o.a.fontSize,fontFamily:xt,fontStyle:o.fontStyle+" "+o.fontWeight,textDecoration:o.textDecoration,align:o.align,verticalAlign:o.verticalAlign,draggable:gt?o.draggable&&q:o.draggable,preventDefault:!gt||q,opacity:o.curveEnabled?0:lt,visible:!o._editModeEnabled,ellipsis:"ellipsis"===S.textOverflow,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity,lineHeight:ct,letterSpacing:o.letterSpacing*o.a.fontSize,listening:!!o.selectable&&ut,onDragStart:()=>{I(!0)},onDragMove:t=>{o.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{I(!1),o.set({x:t.target.x(),y:t.target.y()})},onClick:st,onTap:st,onTransformStart:()=>{var t,e;D(!0);const r=y.current;N.current=r.height(),J.current=r.rotation(),V.current=r.height();const n=null===(t=r.getStage())||void 0===t?void 0:t.findOne("Transformer");_.current=null!==(e=null==n?void 0:n.getActiveAnchor())&&void 0!==e?e:""},onTransform:t=>{var e,r,n;const i=t.target;null===(e=L.current)||void 0===e||e.setAttrs({x:i.x(),y:i.y(),rotation:i.rotation(),scale:i.scale()});const a=(null===(r=i.getStage())||void 0===r?void 0:r.findOne("Transformer")).getActiveAnchor();if("middle-left"===a||"middle-right"===a){const t=i.scaleX(),e=i.width()*t,r=o.a.fontSize;let n=e;e<r&&(n=r,it.current&&i.position(it.current)),i.width(n),i.scaleX(1),i.scaleY(1);let a=ot();if("ellipsis"===S.textOverflow){a=N.current}else{const t=Math.max(a,N.current);i.height(t),o.set({height:i.height()})}const s=S.textVerticalResizeEnabled?Math.max(a,N.current):ot();o.set({x:i.x(),width:i.width(),rotation:i.rotation(),height:s}),i.skewX(0),i.skewY(0),et()}if("top-center"===a||"bottom-center"===a){const e="resize"===S.textOverflow?ot():ct*o.a.fontSize,r=t.target.height()*t.target.scaleY();if(r<e){if(t.target.height(e),it.current){if("top-center"===_.current){const r=J.current*Math.PI/180,n=V.current-e;t.target.x(it.current.x-n*Math.sin(r)),t.target.y(it.current.y+n*Math.cos(r))}else{t.target.position(it.current)}}}else{t.target.height(r)}t.target.scaleY(1),t.target.scaleX(1),t.target.rotation(J.current),t.target.skewX(0),t.target.skewY(0),V.current=Math.max(e,r)}it.current=t.target.position();const s=t.target.scaleX();null===(n=L.current)||void 0===n||n.setAttrs({scaleX:1,scaleY:1}),t.target.scaleX(1),t.target.scaleY(1),o.set({fontSize:o.a.fontSize*s,width:t.target.width()*s,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),height:t.target.height()*s,shadowBlur:o.shadowBlur*s,shadowOffsetX:o.shadowOffsetX*s,shadowOffsetY:o.shadowOffsetY*s,strokeWidth:o.strokeWidth*s})},onTransformEnd:t=>{var e;const r=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),o.set({fontSize:Math.round(o.a.fontSize*r),width:Math.ceil(t.target.width()*r),x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),height:t.target.height()*r,shadowBlur:o.shadowBlur*r,shadowOffsetX:o.shadowOffsetX*r,shadowOffsetY:o.shadowOffsetY*r,strokeWidth:o.strokeWidth*r}),null===(e=L.current)||void 0===e||e.setAttrs({scaleX:1,scaleY:1}),D(!1)}})),X&&o.contentEditable&&t(i,{x:o.a.x,y:o.a.y,rotation:o.a.rotation,children:t(P,{textNodeRef:y,element:o,selectAll:Y,cursorPosition:at.current,onBlur:()=>{o.toggleEditMode(!1)}})})]})});
1
+ import{jsx as t,Fragment as e,jsxs as r}from"react/jsx-runtime";import n from"react";import{observer as o}from"mobx-react-lite";import{Group as i,Path as a,Text as l,TextPath as s}from"react-konva";import{Html as c}from"react-konva-utils";import{nodeAutorun as u}from"../utils/mobx.js";import d from"konva";import{parsePath as f,roundCommands as h}from"svg-round-corners/lib/index.js";import{generateBackgroundShapeFromRects as g,textLinesToRects as p}from"@polotno/core/background-shape";import{useColor as m}from"./use-color.js";import{useWorkspaceStyle as x}from"./workspace-style.js";import{ROLES as v}from"../model/store.js";import{incrementLoader as w}from"../utils/loader.js";import{scaledFontSizeAttrs as y,roundedFontSizeAttrs as S,roundedTextDecorationAttrs as b}from"../utils/px.js";import{isFontLoaded as E}from"../utils/fonts.js";import{flags as z}from"../utils/flags.js";import{removeTags as k}from"@polotno/core/text";import{getDir as O,getCurvePath as R,resolveLineHeight as A,normalizeStrokeLineJoin as F}from"@polotno/core/text-html";import{applyFilter as M}from"./apply-filters.js";import{useFadeIn as j}from"./use-fadein.js";import{isTouchDevice as L}from"../utils/screen.js";import{isAlive as T,getParent as C}from"mobx-state-tree";import{getLimitedFontSize as H}from"./text-element/max-font-size.js";import{getOptimalCaretColor as P}from"./text-element/caret-color.js";let X;function Y(){return X||(X=document.getElementById("polotno-text-style"),X||(X=document.createElement("style"),X.id="polotno-text-style",document.head.appendChild(X)),X)}d._fixTextRendering=!0;const W={border:"none",padding:"0px",overflow:"hidden",background:"none",outline:"none",resize:"none",overflowWrap:"break-word",whiteSpace:"pre-wrap",userSelect:"text",wordBreak:"normal",textTransform:"none"};export{getDir}from"@polotno/core/text-html";const D=o(({textNodeRef:e,element:r,onBlur:o,selectAll:i,cursorPosition:a})=>{const[l,s]=n.useState(W),c=e.current;n.useLayoutEffect(()=>{if(!c){return}const t={};t.width=c.width()-2*c.padding()+"px",t.height=c.height()-2*c.padding()+c.fontSize()*c.lineHeight()+"px",t.fontSize=c.fontSize()+"px",t.lineHeight=c.lineHeight()+.01,t.fontFamily=c.fontFamily(),t.textAlign=c.align(),t.color=c.fill(),t.fontWeight=r.fontWeight,t.fontStyle=r.fontStyle,t.letterSpacing=r.letterSpacing+"em",t.opacity=Math.max(r.a.opacity,.2),t.textTransform=r.textTransform,t.caretColor=P(r);const e=`\n .polotno-input::placeholder {\n color: ${l.color};\n opacity: 0.6;\n }\n `,n=Y();n.innerHTML="",n.appendChild(document.createTextNode(e)),JSON.stringify(t)!==JSON.stringify(l)&&s(t)});const u=n.useRef(null);if(n.useLayoutEffect(()=>{var t;const e=u.current;if(!e){return}null===(t=u.current)||void 0===t||t.focus({preventScroll:!0});const r=a||e.value.length;e.selectionStart=e.selectionEnd=r,i&&(null==e||e.select(),document.execCommand("selectAll",!1,void 0))},[]),n.useEffect(()=>{window.addEventListener("blur",o);const t=t=>{var e;(null===(e=u.current)||void 0===e?void 0:e.contains(t.target))||o()};return window.addEventListener("touchstart",t),()=>{window.removeEventListener("blur",o),window.removeEventListener("touchstart",t)}},[]),!c){return null}let d=0;const f=c.textArr.length*c.lineHeight()*c.fontSize();"middle"===r.verticalAlign&&(d=(r.a.height-f)/2),"bottom"===r.verticalAlign&&(d=r.a.height-f);const h=k(r.text);return t("textarea",{className:"polotno-input",ref:u,dir:O(h),style:Object.assign(Object.assign(Object.assign({},W),l),{paddingTop:d+"px"}),value:h,onChange:t=>{const e=H({oldText:r.text,newText:t.target.value,element:r});r.set(Object.assign({text:t.target.value},y(r,e)))},placeholder:r.placeholder,onBlur:o})}),$=e=>t(c,{children:t(D,Object.assign({},e))});export const useFontLoader=(t,e,r,o,i)=>{const[a,l]=n.useReducer(t=>t+1,0),s=n.useRef(E(e,r,o)),c=n.useRef(null);return n.useLayoutEffect(()=>{if(s.current=E(e,r,o),s.current){return}let n=!0;return(async()=>{s.current=!1,l();const a=w(`text ${e}`);await t.loadFont(e,r,o,i),n?(c.current=a,s.current=!0,l()):a()})(),()=>{c.current&&(c.current(),c.current=null),n=!1}},[e,r,o]),n.useEffect(()=>{s.current&&setTimeout(()=>{c.current&&(c.current(),c.current=null)})},[s.current]),[s.current]};export const useFontFamiliesLoader=(t,e,r,o,i)=>{const[a,l]=n.useReducer(t=>t+1,0),s=e.join("\0"),c=n.useRef(e.every(t=>E(t,r,o))),u=n.useRef(null);return n.useLayoutEffect(()=>{if(c.current=e.every(t=>E(t,r,o)),c.current){return}let n=!0;return(async()=>{c.current=!1,l();const a=w(`text fonts ${s}`);await Promise.all(e.map(e=>t.loadFont(e,r,o,i))),n?(u.current=a,c.current=!0,l()):a()})(),()=>{u.current&&(u.current(),u.current=null),n=!1}},[s,r,o]),n.useEffect(()=>{c.current&&setTimeout(()=>{u.current&&(u.current(),u.current=null)})},[c.current]),[c.current]};export const getLineHeight=({fontLoaded:t,fontFamily:e,fontSize:r,lineHeight:o})=>n.useMemo(()=>A({fontFamily:e,fontSize:r,lineHeight:o}),[t,e,r,o]);export function usePrevious(t){const e=n.useRef(t),r=n.useRef(t);return n.useMemo(()=>{r.current=e.current,e.current=t},[t]),r.current}function B(t,e,r=!1){const n=t.fontSize(),o=t.height(),i=k(e.text);let a=e.a.fontSize;t.height(void 0);const l=Math.round(2*e.a.fontSize)-1;for(let s=1;s<l;s++){const n=e.a.height&&t.height()>e.a.height;let o=i.split("\n").join(" ").split(/[\s-]+/).reduce((t,e)=>(e=e.toLowerCase(),/[\u3000-\u303F\u3040-\u309F\u30A0-\u30FF\uFF00-\uFFEF\u4E00-\u9FAF\uAC00-\uD7AF]/.test(e)?t.concat(e.split("")):t.concat(e)),[]),l=t.textArr.map(t=>t.text.toLowerCase()).join(";");const s=o.find(t=>!l.includes(t)||(l=l.replace(t,""),!1));if(!(n||s&&!r)){break}a-=.5,t.fontSize(a)}return t.fontSize(n),t.height(o),a}export{getCurvePath}from"@polotno/core/text-html";export const TextElement=o(({element:o,store:c})=>{const{textOverflowIndicatorStyle:d}=x(),E=n.useRef(null),A=n.useRef(null),H=n.useRef(null),P=n.useRef([]),X=n.useRef(!0),[,Y]=n.useReducer(t=>t+1,0),{editorEnabled:W,selectAll:D}=(t=>{const[e,r]=n.useState(!1),o=n.useRef(!1);return n.useEffect(()=>{var e=!0;return setTimeout(()=>{e&&(t._editModeEnabled&&(o.current=!0),r(!0),setTimeout(()=>{o.current=!1},50))},50),()=>{e=!1}},[]),{editorEnabled:e&&t._editModeEnabled,selectAll:o.current}})(o),[I,N]=n.useState(!1),[J,_]=n.useState(!1),V=n.useRef(o.a.height),q=n.useRef(0),U=n.useRef(""),Z=n.useRef(0),G=o.isSelected,K=usePrevious(G),{textVerticalResizeEnabled:Q}=z,tt=z.autoDeleteEmptyText,et=usePrevious(o.fontFamily),[rt,nt]=n.useState([]);n.useEffect(()=>{var t,e;const r=null!==(e=null===(t=E.current)||void 0===t?void 0:t.textArr)&&void 0!==e?e:[];JSON.stringify(r)!==JSON.stringify(rt)&&nt(r)}),n.useEffect(()=>{if(o.a.width||"tablecell"===o.type){return}const t=E.current;t.width(600),o.set({width:1.4*t.getTextWidth()})},[]),n.useEffect(()=>{K&&!G&&tt&&""===o.text&&o.removable&&!o.placeholder&&c.deleteElements([o.id])},[tt,o.placeholder,o.removable,o.text,G,K]);const ot=()=>{if(o.curveEnabled){const t=E.current;null==t||t.clearCache(),null==t||t.setAttrs({filters:[]});const e=A.current;e&&M(e,o)}else{const t=E.current;t&&M(t,o)}};n.useLayoutEffect(()=>{if(!J){return u(o,()=>{ot()})}}),n.useEffect(()=>{const t=P.current;t.length>0&&(P.current=[],t.forEach(t=>t()))}),n.useEffect(()=>()=>{X.current=!1;const t=P.current;t.length>0&&(P.current=[],t.forEach(t=>t()))},[]);let it=k(o.text);"uppercase"===o.textTransform&&(it=it.toUpperCase());const[at]=useFontLoader(c,o.fontFamily,o.fontStyle,o.fontWeight,o.text||o.placeholder),lt=()=>{if(o.curveEnabled){const t=A.current;return t.getSelfRect().height||t.fontSize()}const t=E.current.clone({height:void 0}),e=Math.ceil(t.fontSize()*t.lineHeight()*t.textArr.length+1);return t.destroy(),e};n.useLayoutEffect(()=>{if(!at){return}if("tablecell"===o.type){const{textOverflow:t}=z;if("resize"===t){const t=lt(),e=T(o)?C(o,2):null;(null==e?void 0:e.setCellContentHeight)&&e.setCellContentHeight(o.id,t)}else if("change-font-size"===t){const t=E.current;if(t){const e=B(t,o,z.textSplitAllowed);e!==o.fontSize&&c.history.ignore(()=>{o.set({fontSize:e})})}}return}const{textOverflow:t,textSplitAllowed:e}=z,r=(t,e,r,n)=>{const i=w(`text ${o.id}`),a=()=>{c.history.ignore(t,e,r).then(()=>{X.current?(P.current.push(i),Y()):i()})};n?queueMicrotask(a):a()};if(!o.height){const t=lt();return void r(()=>{o.height||o.set({height:t})},void 0,void 0,!0)}if(!c.isPlaying){if("change-font-size"!==t||I){if("resize"===t){const t=lt();Q&&o.height<t&&!I&&r(()=>{var e;T(o)&&o.set({height:t}),null===(e=E.current)||void 0===e||e.height(t)},!1,!0),Q||o.height===t||I||r(()=>{var e;T(o)&&o.set({height:t}),null===(e=E.current)||void 0===e||e.height(t)},!1,!0)}}else{const t=E.current,n=o.curveEnabled?o.fontSize:B(t,o,e);if(n!==o.fontSize){return void r(()=>{o.set(y(o,n))},!1,!0)}const i=lt();o.height===i||Q||r(()=>{o.set({height:i})},!1,!0)}}}),n.useLayoutEffect(()=>{var t;if(at&&o.curveEnabled){const e=null===(t=A.current)||void 0===t?void 0:t.getSelfRect().width;if(e){const t=e-o.a.width,r=o.a.rotation*Math.PI/180,n=-t/2*Math.cos(r),i=-t/2*Math.sin(r);o.set({width:e,x:o.a.x+n,y:o.a.y+i})}}},[at,o.curveEnabled,o.curvePower,o.text,o.fontSize,o.fontFamily,o.fontWeight,o.fontStyle,o.letterSpacing]),n.useLayoutEffect(()=>{const t=E.current;t&&(t.width(t.width()+1e-8),t.width(t.width()-1e-8),t._setTextData(),ot())},[at]);const st=n.useRef(null),ct=n.useRef(0),ut=t=>{t.evt.preventDefault();const e=c.selectedShapes.find(t=>t===o);e&&o.contentEditable&&(ct.current=function(t){var e;const r=t.target,n=function(t){var e=t.getAbsoluteTransform().copy();e.invert();var r=t.getStage().getPointerPosition();return e.point(r)}(r),o=r.textArr,i=Math.floor(n.y/(r.fontSize()*r.lineHeight())),a=o.slice(0,i).reduce((t,e)=>t+e.text.length,i),l=null!==(e=o[i])&&void 0!==e?e:o[0];let s=0;return"right"===r.align()?s=r.width()-l.width:"center"===r.align()&&(s=r.width()/2-l.width/2),a+Math.round((n.x-s)/l.width*l.text.length)}(t),o.toggleEditMode())},dt=!it&&o.placeholder?.6:o.a.opacity;j(E,dt);const ft=getLineHeight({fontLoaded:at,fontFamily:o.fontFamily,fontSize:o.a.fontSize,lineHeight:o.lineHeight}),ht=o.selectable||c.role===v.ADMIN,gt=m(o),pt=m(o,o.stroke,"stroke"),mt=n.useMemo(()=>o.backgroundEnabled?o.curveEnabled?function({width:t,height:e,padding:r=0,cornerRadius:n=0}){const o=-r,i=-r,a=t+r,l=e+r,s=f(`M ${o} ${i} L ${a} ${i} L ${a} ${l} L ${o} ${l} Z`);return h(s,n).path}({width:o.a.width,height:o.a.height,cornerRadius:o.backgroundCornerRadius*(o.a.fontSize*ft*.5),padding:o.backgroundPadding*(o.a.fontSize*ft*.5)}):function({lines:t,lineHeight:e,width:r,align:n="left",padding:o=0,cornerRadius:i=0}){const a=p({lines:t,lineHeight:e,width:r,align:n});return g({rects:a,padding:o,cornerRadius:i})}({lines:JSON.parse(JSON.stringify(rt)),cornerRadius:o.backgroundCornerRadius*(o.a.fontSize*ft*.5),lineHeight:ft*o.a.fontSize,padding:o.backgroundPadding*(o.a.fontSize*ft*.5),width:o.a.width,align:o.align}):"",[o.backgroundEnabled,o.curveEnabled,o.backgroundCornerRadius,o.a.fontSize,o.a.height,ft,o.backgroundPadding,o.a.width,o.align,rt]),xt=L();let vt=0;o.curveEnabled||("middle"===o.verticalAlign?vt=(o.a.height-rt.length*ft*o.a.fontSize)/2:"bottom"===o.verticalAlign&&(vt=o.a.height-rt.length*ft*o.a.fontSize));const wt=o.curveEnabled?R(o.a.width,o.a.height,o.curvePower,o.a.fontSize):"",yt=at?'"'+o.fontFamily+'"':et===o.fontFamily?"Arial":'"'+et+'"',St=O(it);return r(e,{children:[t(a,{ref:H,x:o.a.x,y:o.a.y,rotation:o.a.rotation,hideInExport:!o.showInExport,listening:!1,visible:o.backgroundEnabled,opacity:o.backgroundOpacity*dt,data:mt,fill:o.backgroundColor,offsetY:-vt}),t(a,{data:wt,stroke:d.stroke,strokeWidth:1,x:o.a.x,y:o.a.y,rotation:o.a.rotation,visible:!1}),t(s,Object.assign({ref:A,visible:o.curveEnabled,data:wt,text:it||o.placeholder,listening:!1,align:"center",textBaseline:"middle",direction:St},gt,pt,{strokeWidth:o.strokeWidth,lineJoin:F(o.strokeLineJoin),fillAfterStrokeEnabled:!0,fontSize:o.a.fontSize,fontFamily:`"${o.fontFamily}", "${et}"`,fontStyle:o.fontStyle+" "+o.fontWeight,textDecoration:o.textDecoration.trim(),letterSpacing:o.letterSpacing*o.a.fontSize,x:o.a.x,y:o.a.y,rotation:o.a.rotation,opacity:o._editModeEnabled?.3:dt,hideInExport:!o.showInExport,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity})),t(l,Object.assign({ref:E,id:o.selectable?o.id:void 0,name:o.selectable?"element":"",hideInExport:!o.showInExport,editModeEnabled:o._editModeEnabled,x:o.a.x,y:o.a.y,rotation:o.a.rotation,width:o.a.width,height:o.a.height,text:it||o.placeholder,direction:St},gt,pt,{lineJoin:F(o.strokeLineJoin),strokeWidth:o.strokeWidth,fillAfterStrokeEnabled:!0,fontSize:o.a.fontSize,fontFamily:yt,fontStyle:o.fontStyle+" "+o.fontWeight,textDecoration:o.textDecoration,align:o.align,verticalAlign:o.verticalAlign,draggable:xt?o.draggable&&G:o.draggable,preventDefault:!xt||G,opacity:o.curveEnabled?0:dt,visible:!o._editModeEnabled,ellipsis:"ellipsis"===z.textOverflow,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity,lineHeight:ft,letterSpacing:o.letterSpacing*o.a.fontSize,listening:!!o.selectable&&ht,onDragStart:()=>{_(!0)},onDragMove:t=>{o.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{_(!1),o.set({x:t.target.x(),y:t.target.y()})},onClick:ut,onTap:ut,onTransformStart:()=>{var t,e;N(!0);const r=E.current;V.current=r.height(),q.current=r.rotation(),Z.current=r.height();const n=null===(t=r.getStage())||void 0===t?void 0:t.findOne("Transformer");U.current=null!==(e=null==n?void 0:n.getActiveAnchor())&&void 0!==e?e:""},onTransform:t=>{var e,r,n;const i=t.target;null===(e=H.current)||void 0===e||e.setAttrs({x:i.x(),y:i.y(),rotation:i.rotation(),scale:i.scale()});const a=(null===(r=i.getStage())||void 0===r?void 0:r.findOne("Transformer")).getActiveAnchor();if("middle-left"===a||"middle-right"===a){const t=i.scaleX(),e=i.width()*t,r=o.a.fontSize;let n=e;e<r&&(n=r,st.current&&i.position(st.current)),i.width(n),i.scaleX(1),i.scaleY(1);let a=lt();if("ellipsis"===z.textOverflow){a=V.current}else{const t=Math.max(a,V.current);i.height(t),o.set({height:i.height()})}const l=z.textVerticalResizeEnabled?Math.max(a,V.current):lt();o.set({x:i.x(),width:i.width(),rotation:i.rotation(),height:l}),i.skewX(0),i.skewY(0),ot()}if("top-center"===a||"bottom-center"===a){const e="resize"===z.textOverflow?lt():ft*o.a.fontSize,r=t.target.height()*t.target.scaleY();if(r<e){if(t.target.height(e),st.current){if("top-center"===U.current){const r=q.current*Math.PI/180,n=Z.current-e;t.target.x(st.current.x-n*Math.sin(r)),t.target.y(st.current.y+n*Math.cos(r))}else{t.target.position(st.current)}}}else{t.target.height(r)}t.target.scaleY(1),t.target.scaleX(1),t.target.rotation(q.current),t.target.skewX(0),t.target.skewY(0),Z.current=Math.max(e,r)}st.current=t.target.position();const l=t.target.scaleX();null===(n=H.current)||void 0===n||n.setAttrs({scaleX:1,scaleY:1}),t.target.scaleX(1),t.target.scaleY(1),o.set({fontSize:o.a.fontSize*l,width:t.target.width()*l,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),height:t.target.height()*l,shadowBlur:o.shadowBlur*l,shadowOffsetX:o.shadowOffsetX*l,shadowOffsetY:o.shadowOffsetY*l,strokeWidth:o.strokeWidth*l})},onTransformEnd:t=>{var e;const r=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),o.set(Object.assign(Object.assign({},S(o,o.fontSize*r)),{width:Math.ceil(t.target.width()*r),x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),height:t.target.height()*r})),null===(e=H.current)||void 0===e||e.setAttrs({scaleX:1,scaleY:1}),N(!1)}})),W&&o.contentEditable&&t(i,{x:o.a.x,y:o.a.y,rotation:o.a.rotation,children:t($,{textNodeRef:E,element:o,selectAll:D,cursorPosition:ct.current,onBlur:()=>{o.set(b(o)),o.toggleEditMode(!1)}})})]})});
@@ -1 +1 @@
1
- import t from"react";import*as i from"../utils/gradient.js";import r from"konva";export const useColor=(o,a,n)=>{var e;return void 0===a&&(a=null!==(e=o.fill)&&void 0!==e?e:""),void 0===n&&(n="fill"),t.useMemo(()=>{if(!i.isGradient(a)){return{[n]:a}}const{stops:t,rotation:e}=i.parseColor(a),l=o.a.width/2,s=o.a.height/2,d=(e%180+180)%180,h=d>45&&d<135?o.a.width:o.a.height,f=r.Util.degToRad(e)-Math.PI/2,G=[];return t.forEach(({offset:t,color:i})=>{G.push(t,i)}),"fill"===n?{fillLinearGradientStartPointX:l-h/2*Math.cos(f),fillLinearGradientStartPointY:s-h/2*Math.sin(f),fillLinearGradientColorStops:G,fillLinearGradientEndPointX:l+h/2*Math.cos(f),fillLinearGradientEndPointY:s+h/2*Math.sin(f),fill:t[1].color,fillPriority:"linear-gradient"}:{strokeLinearGradientStartPointX:l-h/2*Math.cos(f),strokeLinearGradientStartPointY:s-h/2*Math.sin(f),strokeLinearGradientColorStops:G,strokeLinearGradientEndPointX:l+h/2*Math.cos(f),strokeLinearGradientEndPointY:s+h/2*Math.sin(f)}},[a,o.width,o.height])};
1
+ import t from"react";import*as i from"@polotno/core/gradient";import r from"konva";export const useColor=(o,a,n)=>{var e;return void 0===a&&(a=null!==(e=o.fill)&&void 0!==e?e:""),void 0===n&&(n="fill"),t.useMemo(()=>{if(!i.isGradient(a)){return{[n]:a}}const{stops:t,rotation:e}=i.parseColor(a),l=o.a.width/2,s=o.a.height/2,d=(e%180+180)%180,h=d>45&&d<135?o.a.width:o.a.height,f=r.Util.degToRad(e)-Math.PI/2,c=[];return t.forEach(({offset:t,color:i})=>{c.push(t,i)}),"fill"===n?{fillLinearGradientStartPointX:l-h/2*Math.cos(f),fillLinearGradientStartPointY:s-h/2*Math.sin(f),fillLinearGradientColorStops:c,fillLinearGradientEndPointX:l+h/2*Math.cos(f),fillLinearGradientEndPointY:s+h/2*Math.sin(f),fill:t[1].color,fillPriority:"linear-gradient"}:{strokeLinearGradientStartPointX:l-h/2*Math.cos(f),strokeLinearGradientStartPointY:s-h/2*Math.sin(f),strokeLinearGradientColorStops:c,strokeLinearGradientEndPointX:l+h/2*Math.cos(f),strokeLinearGradientEndPointY:s+h/2*Math.sin(f)}},[a,o.width,o.height])};
@@ -1 +1 @@
1
- import e from"react";import{nodeAutorun as r}from"../utils/mobx.js";import{Input as t,UrlSource as n,BufferSource as u,CanvasSink as a,ALL_FORMATS as i}from"mediabunny";import{incrementLoader as c,triggerLoadError as s}from"../utils/loader.js";import{polotnoError as o}from"../utils/errors.js";import{getElementTimeRange as l,getVideoRestMs as d}from"../utils/timeline.js";const f=.05;export const useMediabunnyVideo=(m,p,g)=>{const[h,v]=e.useState({input:null,videoSink:null,duration:0,isReady:!1,error:null});e.useRef(h).current=h;const w=e.useRef(0),b=e.useRef(null),y=e.useRef(null),T=e.useRef(null),R=e.useRef(null),k=e.useRef(null),E=e.useRef(null),S=e.useRef(!1),$=e.useRef(null),x=e.useRef([]),O=e.useRef(null),I=e.useRef(!1),[,j]=e.useReducer(e=>e+1,0);return e.useEffect(()=>{if(!g){return}let e=!0;const r=++w.current;let l=null;return(async()=>{try{if(!e||r!==w.current){return}l=c(`mediabunny init ${m.id}`);const s=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")}const t=e.slice(r+1),n=atob(t),u=new Uint8Array(n.length);for(let a=0;a<n.length;a++){u[a]=n.charCodeAt(a)}return u.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)}(m.src);if(!e||r!==w.current){return void(l&&(l(),l=null))}const d=new t({source:s,formats:i}),f=await d.computeDuration(),p=await d.getPrimaryVideoTrack();if(!p){throw o("VIDEO_FAILED","No video track found",{reason:"no-video-track"})}if(null===p.codec){throw o("VIDEO_FAILED","Unsupported video codec",{reason:"unsupported-codec"})}if(!await p.canDecode()){throw o("VIDEO_FAILED","Unable to decode the video track",{reason:"cannot-decode"})}const g=await p.canBeTransparent(),h=new a(p,{poolSize:5,fit:"contain",alpha:g});if(!e||r!==w.current){return d.dispose(),void(l&&(l(),l=null))}l&&(l(),l=null),v(e=>Object.assign(Object.assign({},e),{input:d,videoSink:h,duration:f,isReady:!0,error:null}))}catch(d){if(console.error("Failed to initialize mediabunny:",d),l&&(l(),l=null),e&&r===w.current){const e=`Failed to initialize mediabunny for video ${m.id}: ${d}`;s(o("VIDEO_FAILED",e,Object.assign({reason:"load"},null==d?void 0:d.details),d)),v(e=>Object.assign(Object.assign({},e),{error:String(d),isReady:!1}))}}})(),()=>{e=!1,l&&(l(),l=null)}},[m.src,g]),e.useEffect(()=>()=>{y.current&&(y.current.return(),y.current=null),b.current&&(b.current(),b.current=null),T.current=null,R.current=null,k.current=null,S.current=!1,$.current=null,x.current=[],O.current=null,I.current=!1,v({input:null,videoSink:null,duration:0,isReady:!1,error:null})},[g]),e.useEffect(()=>{if(!g||!h.isReady||!h.videoSink){return}const e=++w.current,t="string"==typeof m.src?m.src.slice(0,120):String(m.src),n=(e,r={},n="debug")=>{let u="";try{u=JSON.stringify(Object.assign(Object.assign({},r),{timeCalc:E.current}))}catch(i){u=`[unserializable extras: ${String(i)}]`}const a=`mediabunny event=${e} elementId=${m.id} targetTime=${k.current} duration=${h.duration} lastFrameTimestamp=${R.current} hasIterator=${Boolean(y.current)} prefetchSize=${x.current.length} srcHint=${t} extras=${u}`;"error"===n?console.error(a):"warn"===n?console.warn(a):console.debug(a)},u=e=>{const r=h.duration||0;if(!r||!Number.isFinite(r)){return e}const t=r>f?r-f:r;return Math.max(0,Math.min(e,t))},a=e=>{const r=h.duration||0;return!(!r||!Number.isFinite(r))&&r-e<=.050001000000000004},i=e=>{let r=T.current;r&&r.width===e.canvas.width&&r.height===e.canvas.height||(r||(r=document.createElement("canvas"),T.current=r),r.width=e.canvas.width,r.height=e.canvas.height);const t=r.getContext("2d");t&&(t.clearRect(0,0,r.width,r.height),t.drawImage(e.canvas,0,0)),R.current=e.timestamp},s=e=>{const r=y.current;r&&(I.current||(I.current=!0,O.current=(async()=>{try{for(;x.current.length<4&&e===w.current;){const t=await r.next();if(e!==w.current){return}if(t.done||!t.value){break}x.current.push({timestamp:t.value.timestamp,frame:t.value})}}catch(t){}finally{I.current=!1,O.current=null}})()))},o=e=>{const r=x.current;for(let t=0;t<r.length;t++){if(Math.abs(r[t].timestamp-e)<f){const e=r[t];return x.current=r.slice(t+1),e}}return null},v=()=>{x.current=[]},D=async(e,r,t=0)=>{const c=u(e),l=(e=>{const r=R.current;return null===r||e<r-f||e>r+.5})(c)?"seek":"iterate";try{const t=h.videoSink,u=R.current;if(null!==u&&Math.abs(u-c)<f){return void(k.current=e)}const m=o(c);if(m){return i(m.frame),k.current=e,s(r),void j()}if(O.current){await O.current;const t=o(c);if(t){return i(t.frame),k.current=e,s(r),void j()}}if(v(),"seek"===l){y.current&&(await y.current.return(),y.current=null);const u=t.canvases(c);y.current=u;const o=await u.next();if(r!==w.current){return void(y.current&&(await y.current.return(),y.current=null))}if(o.done||!o.value){if(a(c)||n("iterator_exhausted",{mode:l,requestedTargetTime:e,clampedTargetTime:c},"warn"),r===w.current&&!a(c)){try{y.current&&(await y.current.return(),y.current=null),v();const n=t.canvases(c);y.current=n;const u=await n.next();!u.done&&u.value&&(i(u.value),s(r),k.current=e,j())}catch(d){}}return}i(o.value),s(r)}else{const u=y.current;if(!u){return}let o=!1;for(;r===w.current;){const m=await u.next();if(r!==w.current){break}if(m.done||!m.value){if(a(c)||n("iterator_exhausted",{mode:l,requestedTargetTime:e,clampedTargetTime:c},"warn"),!o&&!a(c)){o=!0;try{y.current&&(await y.current.return(),y.current=null),v();const e=t.canvases(c);y.current=e;const n=await e.next();if(r!==w.current){break}if(n.done||!n.value){break}i(n.value),s(r);break}catch(d){break}}break}const p=m.value;if(i(p),Math.abs(p.timestamp-c)<f){s(r);break}if(p.timestamp>c){s(r);break}}}k.current=e,j()}catch(m){const u=m instanceof Error?{name:m.name,message:m.message,stack:m.stack}:{message:String(m)},a=m instanceof Error?`${m.name}: ${m.message}`:String(m),i=a.includes("Unsupported configuration")||a.includes("isConfigSupported")||a.includes("OperationError");if(n("frame_process_failed",{mode:l,requestedTargetTime:e,clampedTargetTime:c,unsupportedConfigAttempt:t,isUnsupportedConfig:i,error:u},"error"),i&&t<1){try{y.current&&(await y.current.return(),y.current=null),v(),O.current=null,I.current=!1,R.current=null,await D(e,r,t+1)}catch(d){}}}},F=r(m,()=>{const r=h.videoSink,t=h.duration;if(!r||!t){return}const n=m.startTime*t*1e3,a=t*(m.endTime-m.startTime)*1e3,{start:i}=l(m.animations,m.page.duration),s=d(p.currentTime,m.page.startTime,i,a,n,m.speed),o=s/1e3,f=u(o);E.current={pageStartTime:m.page.startTime,storeCurrentTime:p.currentTime,offsetMs:n,durationMs:a,restMs:s,targetTime:o,clampedTargetTime:f,startTime:m.startTime,endTime:m.endTime,videoDuration:t},((e,r)=>{S.current?$.current=e:(S.current=!0,b.current||(b.current=c(`mediabunny video frame ${m.id}`)),(async()=>{let t=e;for(;null!==t&&r===w.current;){await D(t,r),t=$.current,$.current=null}b.current&&(b.current(),b.current=null),S.current=!1})())})(f,e)});return()=>{F(),w.current++,b.current&&(b.current(),b.current=null)}},[g,h.isReady,h.videoSink,h.duration,p,m]),g&&h.isReady?T.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,CanvasSink as a,ALL_FORMATS as i}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";const f=.05;export const useMediabunnyVideo=(m,p,g)=>{const[h,v]=e.useState({input:null,videoSink:null,duration:0,isReady:!1,error:null});e.useRef(h).current=h;const w=e.useRef(0),b=e.useRef(null),y=e.useRef(null),T=e.useRef(null),R=e.useRef(null),k=e.useRef(null),E=e.useRef(null),S=e.useRef(!1),$=e.useRef(null),x=e.useRef([]),O=e.useRef(null),I=e.useRef(!1),[,D]=e.useReducer(e=>e+1,0);return e.useEffect(()=>{if(!g){return}let e=!0;const r=++w.current;let l=null;return(async()=>{try{if(!e||r!==w.current){return}l=c(`mediabunny init ${m.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")}const t=e.slice(r+1),n=atob(t),u=new Uint8Array(n.length);for(let a=0;a<n.length;a++){u[a]=n.charCodeAt(a)}return u.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)}(m.src);if(!e||r!==w.current){return void(l&&(l(),l=null))}const d=new t({source:o,formats:i}),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 g=await p.canBeTransparent(),h=new a(p,{poolSize:5,fit:"contain",alpha:g});if(!e||r!==w.current){return d.dispose(),void(l&&(l(),l=null))}l&&(l(),l=null),v(e=>Object.assign(Object.assign({},e),{input:d,videoSink:h,duration:f,isReady:!0,error:null}))}catch(d){if(console.error("Failed to initialize mediabunny:",d),l&&(l(),l=null),e&&r===w.current){const e=`Failed to initialize mediabunny for video ${m.id}: ${d}`;o(s("VIDEO_FAILED",e,Object.assign({reason:"load"},null==d?void 0:d.details),d)),v(e=>Object.assign(Object.assign({},e),{error:String(d),isReady:!1}))}}})(),()=>{e=!1,l&&(l(),l=null)}},[m.src,g]),e.useEffect(()=>()=>{y.current&&(y.current.return(),y.current=null),b.current&&(b.current(),b.current=null),T.current=null,R.current=null,k.current=null,S.current=!1,$.current=null,x.current=[],O.current=null,I.current=!1,v({input:null,videoSink:null,duration:0,isReady:!1,error:null})},[g]),e.useEffect(()=>{if(!g||!h.isReady||!h.videoSink){return}const e=++w.current,t="string"==typeof m.src?m.src.slice(0,120):String(m.src),n=(e,r={},n="debug")=>{let u="";try{u=JSON.stringify(Object.assign(Object.assign({},r),{timeCalc:E.current}))}catch(i){u=`[unserializable extras: ${String(i)}]`}const a=`mediabunny event=${e} elementId=${m.id} targetTime=${k.current} duration=${h.duration} lastFrameTimestamp=${R.current} hasIterator=${Boolean(y.current)} prefetchSize=${x.current.length} srcHint=${t} extras=${u}`;"error"===n?console.error(a):"warn"===n?console.warn(a):console.debug(a)},u=e=>{const r=h.duration||0;if(!r||!Number.isFinite(r)){return e}const t=r>f?r-f:r;return Math.max(0,Math.min(e,t))},a=e=>{const r=h.duration||0;return!(!r||!Number.isFinite(r))&&r-e<=.050001000000000004},i=e=>{let r=T.current;r&&r.width===e.canvas.width&&r.height===e.canvas.height||(r||(r=document.createElement("canvas"),T.current=r),r.width=e.canvas.width,r.height=e.canvas.height);const t=r.getContext("2d");t&&(t.clearRect(0,0,r.width,r.height),t.drawImage(e.canvas,0,0)),R.current=e.timestamp},o=e=>{const r=y.current;r&&(I.current||(I.current=!0,O.current=(async()=>{try{for(;x.current.length<4&&e===w.current;){const t=await r.next();if(e!==w.current){return}if(t.done||!t.value){break}x.current.push({timestamp:t.value.timestamp,frame:t.value})}}catch(t){}finally{I.current=!1,O.current=null}})()))},s=e=>{const r=x.current;for(let t=0;t<r.length;t++){if(Math.abs(r[t].timestamp-e)<f){const e=r[t];return x.current=r.slice(t+1),e}}return null},v=()=>{x.current=[]},F=async(e,r,t=0)=>{const c=u(e),l=(e=>{const r=R.current;return null===r||e<r-f||e>r+.5})(c)?"seek":"iterate";try{const t=h.videoSink,u=R.current;if(null!==u&&Math.abs(u-c)<f){return void(k.current=e)}const m=s(c);if(m){return i(m.frame),k.current=e,o(r),void D()}if(O.current){await O.current;const t=s(c);if(t){return i(t.frame),k.current=e,o(r),void D()}}if(v(),"seek"===l){y.current&&(await y.current.return(),y.current=null);const u=t.canvases(c);y.current=u;const s=await u.next();if(r!==w.current){return void(y.current&&(await y.current.return(),y.current=null))}if(s.done||!s.value){if(a(c)||n("iterator_exhausted",{mode:l,requestedTargetTime:e,clampedTargetTime:c},"warn"),r===w.current&&!a(c)){try{y.current&&(await y.current.return(),y.current=null),v();const n=t.canvases(c);y.current=n;const u=await n.next();!u.done&&u.value&&(i(u.value),o(r),k.current=e,D())}catch(d){}}return}i(s.value),o(r)}else{const u=y.current;if(!u){return}let s=!1;for(;r===w.current;){const m=await u.next();if(r!==w.current){break}if(m.done||!m.value){if(a(c)||n("iterator_exhausted",{mode:l,requestedTargetTime:e,clampedTargetTime:c},"warn"),!s&&!a(c)){s=!0;try{y.current&&(await y.current.return(),y.current=null),v();const e=t.canvases(c);y.current=e;const n=await e.next();if(r!==w.current){break}if(n.done||!n.value){break}i(n.value),o(r);break}catch(d){break}}break}const p=m.value;if(i(p),Math.abs(p.timestamp-c)<f){o(r);break}if(p.timestamp>c){o(r);break}}}k.current=e,D()}catch(m){const u=m instanceof Error?{name:m.name,message:m.message,stack:m.stack}:{message:String(m)},a=m instanceof Error?`${m.name}: ${m.message}`:String(m),i=a.includes("Unsupported configuration")||a.includes("isConfigSupported")||a.includes("OperationError");if(n("frame_process_failed",{mode:l,requestedTargetTime:e,clampedTargetTime:c,unsupportedConfigAttempt:t,isUnsupportedConfig:i,error:u},"error"),i&&t<1){try{y.current&&(await y.current.return(),y.current=null),v(),O.current=null,I.current=!1,R.current=null,await F(e,r,t+1)}catch(d){}}}},j=r(m,()=>{const r=h.videoSink,t=h.duration;if(!r||!t){return}const n=m.startTime*t*1e3,a=t*(m.endTime-m.startTime)*1e3,{start:i}=l(m.animations,m.page.duration),o=d(p.currentTime,m.page.startTime,i,a,n,m.speed),s=o/1e3,f=u(s);E.current={pageStartTime:m.page.startTime,storeCurrentTime:p.currentTime,offsetMs:n,durationMs:a,restMs:o,targetTime:s,clampedTargetTime:f,startTime:m.startTime,endTime:m.endTime,videoDuration:t},((e,r)=>{S.current?$.current=e:(S.current=!0,b.current||(b.current=c(`mediabunny video frame ${m.id}`)),(async()=>{let t=e;for(;null!==t&&r===w.current;){await F(t,r),t=$.current,$.current=null}b.current&&(b.current(),b.current=null),S.current=!1})())})(f,e)});return()=>{j(),w.current++,b.current&&(b.current(),b.current=null)}},[g,h.isReady,h.videoSink,h.duration,p,m]),g&&h.isReady?T.current:null};
@@ -6,7 +6,7 @@ export declare const useCornerRadiusAndCrop: (element: VideoElementType, image:
6
6
  y: number;
7
7
  width: number;
8
8
  height: number;
9
- }, pixelRatio: number, cornerRadius?: number, skipDownscale?: boolean) => readonly [HTMLVideoElement | HTMLCanvasElement | undefined, () => void];
9
+ }, pixelRatio: number, cornerRadius?: number, skipDownscale?: boolean) => readonly [HTMLCanvasElement | HTMLVideoElement | undefined, () => void];
10
10
  type Props = {
11
11
  store: StoreType;
12
12
  element: VideoElementType;
@@ -1 +1 @@
1
- import{jsx as e,jsxs as t,Fragment as r}from"react/jsx-runtime";import i from"react";import{observer as o}from"mobx-react-lite";import{nodeAutorun as n}from"../utils/mobx.js";import{Arc as a,Group as d,Image as h,Rect as s,Text as l,Transformer as c}from"react-konva";import{ROLES as u}from"../model/store.js";import g from"use-image";import m from"konva";import{Portal as f}from"react-konva-utils";import{useWorkspaceStyle as p}from"./workspace-style.js";import{incrementLoader as v,triggerLoadError as w}from"../utils/loader.js";import{polotnoError as x}from"../utils/errors.js";import*as M from"../utils/svg.js";import{flags as y}from"../utils/flags.js";import{useFilteredSource as E}from"./use-filtered-source.js";import{useEvent as b}from"../hooks/use-event.js";import{useFadeIn as L}from"./use-fadein.js";import{isTouchDevice as T}from"../utils/screen.js";import{useMediabunnyVideo as C}from"./use-mediabunny-video.js";import{getElementTimeRange as R,getVideoRestMs as I}from"../utils/timeline.js";function S(){return document.createElement("canvas")}const k=new window.Image;k.src=M.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 H=new window.Image;H.src=M.svgToURL('\n <svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path opacity="0.6" d="M14 19L14 5C14 3.89543 14.8954 3 16 3L17 3C18.1046 3 19 3.89543 19 5L19 19C19 20.1046 18.1046 21 17 21L16 21C14.8954 21 14 20.1046 14 19Z" fill="white"/>\n <path opacity="0.6" d="M10 19L10 5C10 3.89543 9.10457 3 8 3L7 3C5.89543 3 5 3.89543 5 5L5 19C5 20.1046 5.89543 21 7 21L8 21C9.10457 21 10 20.1046 10 19Z" fill="white"/>\n <path d="M14 19L14 5C14 3.89543 14.8954 3 16 3L17 3C18.1046 3 19 3.89543 19 5L19 19C19 20.1046 18.1046 21 17 21L16 21C14.8954 21 14 20.1046 14 19Z" stroke="#323232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n <path d="M10 19L10 5C10 3.89543 9.10457 3 8 3L7 3C5.89543 3 5 3.89543 5 5L5 19C5 20.1046 5.89543 21 7 21L8 21C9.10457 21 10 20.1046 10 19Z" stroke="#323232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n');export const useCornerRadiusAndCrop=(e,t,r,o,n=0,a=!1)=>{var d,h;const s=Math.floor(Math.max(e.width*o,1)),l=Math.floor(Math.max(e.height*o,1)),c=Math.min(n*o,s/2,l/2),u=Math.max(e.width/r.width,e.height/r.height)*o,g=(null===(d=e.page)||void 0===d?void 0:d._exportingOrRendering)&&y.imageDownScalingEnabled&&u<1&&!a,f=t instanceof HTMLVideoElement?t.videoWidth:null==t?void 0:t.width,p=t instanceof HTMLVideoElement?t.videoHeight:null==t?void 0:t.height,v=0===r.x&&0===r.y&&r.width===f&&r.height===p,w=i.useMemo(()=>{if(t&&f&&p){return v&&0===c&&!g?void 0:S()}},[t,c,g,v,f,p]),x=()=>{if(!w||!t){return}w.width=s,w.height=l;const e=w.getContext("2d");if(!e){return}c&&(e.beginPath(),e.moveTo(c,0),e.lineTo(s-c,0),e.arc(s-c,c,c,3*Math.PI/2,0,!1),e.lineTo(s,l-c),e.arc(s-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());const i=g?function(e,t){var r,i;const o=S(),n=e instanceof HTMLVideoElement?e.videoWidth:e.width,a=e instanceof HTMLVideoElement?e.videoHeight:e.height;o.width=n,o.height=a,null===(r=o.getContext("2d"))||void 0===r||r.drawImage(e,0,0,o.width,o.height);const d=function(e,t,r,i,o,n,a){for(var d=new ImageData(t,r),h=new Int32Array(e.data.buffer),s=e.width,l=new Int32Array(d.data.buffer),c=d.width,u=t/n,g=r/a,m=Math.round(1/u),f=Math.round(1/g),p=m*f,v=0;v<d.height;v++){for(var w=0;w<c;w++){for(var x=0+Math.round(w/u)+(0+Math.round(v/g))*s,M=0,y=0,E=0,b=0,L=0;L<f;L++){for(var T=0;T<m;T++){var C=h[x+T+L*s];M+=C<<24>>>24,y+=C<<16>>>24,E+=C<<8>>>24,b+=C>>>24}}M=Math.round(M/p),y=Math.round(y/p),E=Math.round(E/p),b=Math.round(b/p),l[w+v*c]=b<<24|E<<16|y<<8|M}}return d}(o.getContext("2d").getImageData(0,0,o.width,o.height),Math.floor(o.width*t),Math.floor(o.height*t),0,0,o.width,o.height);return o.width=Math.floor(o.width*t),o.height=Math.floor(o.height*t),null===(i=o.getContext("2d"))||void 0===i||i.putImageData(d,0,0),o}(t,u):t,o=g?{x:Math.floor(r.x*u),y:Math.floor(r.y*u),width:Math.floor(r.width*u),height:Math.floor(r.height*u)}:r;e.drawImage(i,o.x,o.y,o.width,o.height,0,0,w.width,w.height)};return i.useLayoutEffect(()=>{x()},[w,e.width,e.height,r.x,r.y,r.width,r.height,n,o,a,null===(h=e.page)||void 0===h?void 0:h._exportingOrRendering,g]),i.useEffect(()=>()=>{w&&"CANVAS"===w.nodeName&&m.Util.releaseCanvas(w)},[w]),[w||t,x]};const W=S(),X=o(({element:r})=>{const o=Math.min(30,r.width/4,r.height/4),n=i.useRef(null);i.useEffect(()=>{const e=n.current;if(!e){return}const t=new m.Animation(t=>{e.rotate(((null==t?void 0:t.timeDiff)||0)/2)},e.getLayer());return t.start(),()=>{t.stop()}});const{mediaLoadingStyle:h}=p();return t(d,{x:r.a.x,y:r.a.y,rotation:r.a.rotation,listening:!1,opacity:r.a.opacity,hideInExport:!r.showInExport,children:[e(s,{width:r.width,height:r.height,fill:h.fill}),e(a,{ref:n,x:r.width/2,y:r.height/2,fill:h.textFill,outerRadius:Math.abs(o),innerRadius:Math.max(1,o-5),angle:270})]})}),Y=o(({element:r})=>{const{mediaErrorStyle:i}=p(),o=Math.max(10,Math.min(30,r.width/25));return t(d,{x:r.a.x,y:r.a.y,rotation:r.a.rotation,listening:!1,opacity:r.a.opacity,hideInExport:!r.showInExport,children:[e(s,{width:r.width,height:r.height,fill:i.fill}),e(l,{text:"Can not load the video...",fontSize:o,width:r.width,height:r.height,align:"center",fill:i.textFill,verticalAlign:"middle",padding:5})]})});let A=function(e,t,r){const o=i.useRef("loading"),n=i.useRef(void 0),[a,d]=i.useState(0),h=i.useRef(void 0),s=i.useRef(void 0),l=i.useRef(void 0);return h.current===e&&s.current===t&&l.current===r||(o.current="loading",n.current=void 0,h.current=e,s.current=t,l.current=r),i.useLayoutEffect(function(){if(e){var i=document.createElement("video");return i.addEventListener("canplay",a),i.addEventListener("error",h),t&&(i.crossOrigin=t),r&&(i.referrerPolicy=r),i.src=e,i.load(),function(){i.removeEventListener("canplay",a),i.removeEventListener("error",h)}}function a(){o.current="loaded",n.current=i,n.current.currentTime=0,d(Math.random()),n.current.removeEventListener("canplay",a)}function h(e){var t;const r=4===i.readyState,a=i.buffered&&i.buffered.length>0&&i.buffered.end(i.buffered.length-1)/i.duration*100>=100;if(r&&a){return}const h=e.message||(null===(t=i.error)||void 0===t?void 0:t.message)||"Unknown error",s=new Error("Video failed to load: "+h);console.error(s),o.current="failed",n.current=void 0,d(Math.random())}},[e,t,r]),[n.current,o.current]};export const setVideoLoaderHook=e=>{A=e};function O(e){return 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=v(a)),"loading"!==e&&n(),"failed"===e&&w(x("VIDEO_FAILED",a,{src:i,elementId:r,reason:"load"}))},[e])};export const VideoElement=o(({element:o,store:a})=>{var l,p,w;const[x,y]=i.useState(!1),P=i.useRef(null),_=i.useRef(null),j=o.isSelected,[V,D]=i.useState(!1),[z,B]=A(o.src,"anonymous"),[U,F]=i.useState(!1),N=a.activePage===o.page,Z=(null===(l=o.page)||void 0===l?void 0:l._exportingOrRendering)&&"loaded"===B,$=C(o,a,Z);useLoader(B,o.src,o.id),z&&(z.playsInline=!0);const q=((e,t,r)=>{const o=i.useMemo(()=>{var i,o;const{flipX:n,flipY:a}=e,d="svg"===e.type||e.src.indexOf("data:image/svg+xml")>=0||e.src.indexOf(".svg")>=0,h=navigator.userAgent.toLowerCase().indexOf("firefox")>-1;if(!(n||a||h&&d)){return t}if(!t){return null}const s=t instanceof HTMLVideoElement?t.videoWidth:null==t?void 0:t.width,l=t instanceof HTMLVideoElement?t.videoHeight:null==t?void 0:t.height;if(!s||!l){return null}const c=S();let u=1;"svg"===e.type&&(u=Math.max(e.width/s*r,e.height/l*r)),c.width=Math.max(s*u,1),c.height=Math.max(l*u,1);let g=n?-c.width:0,m=a?-c.height:0;return null===(i=c.getContext("2d"))||void 0===i||i.scale(n?-1:1,a?-1:1),null===(o=c.getContext("2d"))||void 0===o||o.drawImage(t,g,m,c.width,c.height),c},[e.flipX,e.flipY,t,e.width,e.height,r]);return i.useEffect(()=>()=>{o&&"CANVAS"===o.nodeName&&m.Util.releaseCanvas(o)},[o]),o})(o,z,a._elementsPixelRatio),G=Z&&$||q||W,[J=W,K]=E(o,G);i.useEffect(()=>{z&&a.history.ignore(()=>{o.set({duration:1e3*z.duration})})},[z]),i.useEffect(()=>{var e;if(!z){return}const t=a.animatedElementsIds,r=(!t.length||t.includes(o.id))&&a.isPlaying;if(!N||!r&&!V){return void z.pause()}V&&(z.muted=!1,z.currentTime=o.startTime*z.duration,z.play());const i=new m.Animation(()=>{Me()},null===(e=P.current)||void 0===e?void 0:e.getLayer());i.start();const n=()=>{D(!1),z.currentTime=o.startTime*z.duration},d=()=>{z.currentTime>=o.endTime*z.duration&&(z.pause(),z.currentTime=o.startTime*z.duration,D(!1))};return z.addEventListener("ended",n),z.addEventListener("timeupdate",d),()=>{z.pause(),i.stop(),z.removeEventListener("ended",n),z.removeEventListener("timeupdate",d)}},[z,V,a.isPlaying,N]),i.useEffect(()=>{z&&(z.volume=o.volume)},[z,o.volume]),i.useEffect(()=>{z&&(z.playbackRate=o.speed,z.preservesPitch=!1)},[z,o.speed]);const Q=i.useRef(null);i.useEffect(()=>{const e=n(o,()=>{var e,t;if(z){if(Z&&$){return Me(),void a.currentTime}const r=a.animatedElementsIds;if(r.length&&!r.includes(o.id)){return}const i=a.activePage===o.page,n=a.currentTime>=o.page.startTime&&a.currentTime<o.page.startTime+o.page.duration,d=o.startTime*z.duration*1e3,h=z.duration*(o.endTime-o.startTime)*1e3,{start:s,end:l}=R(o.animations,o.page.duration),c=(a.currentTime||o.page.startTime)-o.page.startTime,u=n?I(a.currentTime,o.page.startTime,s,h,d,o.speed):0,g=u/1e3,m=n&&c>=s&&c<l;V||(z.muted=!m,m&&a.isPlaying&&i?z.paused?(z.currentTime=g,z.play()):Math.abs(1e3*z.currentTime-u)>500&&(z.currentTime=g):(z.paused||z.pause(),g!==z.currentTime&&(z.currentTime=g),!O(z)&&!a.isPlaying&&!Q.current&&(Q.current=v(`video ${o.id}`)))),Me(),null===(t=null===(e=P.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()}});return()=>{e(),Q.current&&(Q.current(),Q.current=null)}},[a,z,Z,$,V]),i.useEffect(()=>{var e,t;if(!z){return}if(Z){return null===(e=Q.current)||void 0===e||e.call(Q),void(Q.current=null)}const r=()=>{var e,t,r;!O(z)&&(null===(e=o.page)||void 0===e?void 0:e._exportingOrRendering)||Q.current&&(Me(),null===(r=null===(t=P.current)||void 0===t?void 0:t.getLayer())||void 0===r||r.batchDraw(),Q.current(),Q.current=null)};let i;return(null===(t=o.page)||void 0===t?void 0:t._exportingOrRendering)&&(i=setInterval(r,20)),z.addEventListener("timeupdate",r),z.addEventListener("canplay",r),()=>{clearInterval(i),z.removeEventListener("timeupdate",r),z.removeEventListener("canplay",r)}},[null===(p=o.page)||void 0===p?void 0:p._exportingOrRendering,z,o.id,v,Z]);let{cropX:ee,cropY:te,cropWidth:re,cropHeight:ie}=o;"loaded"!==B&&(ee=te=0,re=ie=1);const oe=(ne=J)instanceof HTMLVideoElement?ne.videoWidth:(null==ne?void 0:ne.width)||0;var ne;const ae=(e=>e instanceof HTMLVideoElement?e.videoHeight:(null==e?void 0:e.height)||0)(J),de=oe*re,he=ae*ie,se=o.width/o.height;let le,ce;const ue=de/he,ge="svg"===o.type;ge?(le=de,ce=he):se>=ue?(le=de,ce=de/se):(le=he*se,ce=he);const me={x:oe*ee,y:ae*te,width:le,height:ce},fe=null!==(w=o.cornerRadius)&&void 0!==w?w:0,[pe,ve]=useCornerRadiusAndCrop(o,J,me,a._elementsPixelRatio,fe,!0);let[we,xe]=((e,t,r,o)=>{const n=(e=>{const[t,r]=i.useState(e);return i.useEffect(()=>{(async()=>{const i=await async function(e){if(!(e.indexOf("data:image/svg+xml")>=0||e.indexOf(".svg")>=0)){return e}const t=await M.urlToString(e),r=M.fixSize(t);return M.svgToURL(r)}(e);i!==t&&r(i)})()},[e]),t})(e.clipSrc||""),[a,d]=g(n,"anonymous"),h=e.clipSrc?d:"loaded";useLoader(h,e.clipSrc,e.id);const s=i.useMemo(()=>{if(t&&a){return S()}},[t,a]);function l(){var i;if(!a){return}const o=t instanceof HTMLVideoElement?t.videoWidth:null==t?void 0:t.width,n=t instanceof HTMLVideoElement?t.videoHeight:null==t?void 0:t.height;if(!t||!o||!n){return}if(!a||!a.width||!a.height){return}if(!s){return}const d=S(),h=Math.max(e.width/a.width*r,e.height/a.height*r);d.width=a.width*h,d.height=a.height*h,null===(i=d.getContext("2d"))||void 0===i||i.drawImage(a,0,0,d.width,d.height),s.width=Math.max(o,1),s.height=Math.max(n,1);const l=s.getContext("2d");l&&(l.save(),l.drawImage(d,0,0,o,n),m.Util.releaseCanvas(d),l.globalCompositeOperation="source-in",l.drawImage(t,0,0,s.width,s.height),l.restore())}return i.useLayoutEffect(()=>{l()},[s,t,a,e.width,e.height,r,...o]),[e.clipSrc&&a?s:t,l]})(o,pe,a._elementsPixelRatio,[me,fe,a._elementsPixelRatio]);const Me=b(()=>{var e,t;K(),ve(),xe(),null===(t=null===(e=P.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()});i.useEffect(()=>{Me()});const ye=Math.max(o.width/le,o.height/ce);i.useEffect(()=>{var e;if(!o._cropModeEnabled){return}const t=null===(e=P.current)||void 0===e?void 0:e.getStage();function r(e){o._cropModeEnabled&&e.target!==_.current&&o.toggleCropMode(!1)}function i(e){o._cropModeEnabled&&e.target.parentNode!==(null==t?void 0:t.content)&&o.toggleCropMode(!1)}return document.body.addEventListener("click",i),null==t||t.on("click",r),null==t||t.on("tap",r),()=>{document.body.removeEventListener("click",i),document.body.removeEventListener("touchstart",i),null==t||t.off("click",r),null==t||t.off("click",r)}},[o._cropModeEnabled]);const Ee=i.useRef(null),be=i.useRef(null),Le=i.useRef(null);i.useLayoutEffect(()=>{o._cropModeEnabled&&(be.current.nodes([Ee.current]),Le.current.nodes([_.current]))},[o._cropModeEnabled]);const Te=e=>{Math.round(e.target.x())>0&&(e.target.x(0),e.target.scaleX(1)),Math.round(e.target.y())>0&&(e.target.y(0),e.target.scaleY(1));const t=e.target.width()*e.target.scaleX(),r=e.target.height()*e.target.scaleY(),i=Math.min(1,le/t),n=Math.min(1,ce/r),a=1-i,d=Math.min(a,Math.max(0,Math.round(-e.target.x())/t)),h=1-n,s=Math.min(h,Math.max(0,Math.round(-e.target.y())/r));e.target.setAttrs({x:-d*oe,y:-s*ae,scaleX:1,scaleY:1}),o.set({cropX:d,cropY:s,cropWidth:i,cropHeight:n})},Ce=()=>{"svg"!==o.type&&o.contentEditable&&setTimeout(()=>{o.toggleCropMode(!0)})},Re="loading"===B,Ie="failed"===B,Se=!Re&&!Ie,ke=i.useRef({cropX:0,cropY:0,cropWidth:0,cropHeight:0}),He=Se?o.a.opacity:0;L(P,He);const We=o.selectable||a.role===u.ADMIN,Xe=T();return e(r,{children:t(d,{onMouseEnter:()=>F(!0),onMouseLeave:()=>F(!1),children:[Re&&e(X,{element:o}),Ie&&e(Y,{element:o}),e(h,{ref:P,name:"element",id:o.id,image:we,x:o.a.x,y:o.a.y,width:o.a.width||1,height:o.a.height||1,rotation:o.a.rotation,opacity:He,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity,customCrop:me,listening:We,draggable:Xe?o.draggable&&j:o.draggable,preventDefault:!Xe||j,hideInExport:!o.showInExport,onDragMove:e=>{o.set({x:e.target.x(),y:e.target.y()})},onDragEnd:e=>{o.set({x:e.target.x(),y:e.target.y()})},onDblClick:Ce,onDblTap:Ce,onTransformStart:()=>{y(!0),ke.current={cropX:o.cropX,cropY:o.cropY,cropWidth:o.cropWidth,cropHeight:o.cropHeight}},onTransform:e=>{var t;const r=e.currentTarget,i=Math.abs(r.scaleX()-1)<1e-7?1:r.scaleX(),n=Math.abs(r.scaleY()-1)<1e-7?1:r.scaleY();r.scaleX(1),r.scaleY(1);const a=null===(t=e.target.getStage())||void 0===t?void 0:t.findOne("Transformer"),d=1-le/oe,h=Math.min(d,Math.max(0,o.cropX)),s=1-ce/ae,l=Math.min(s,Math.max(0,o.cropY)),c=a.getActiveAnchor(),u=!(c.indexOf("middle")>=0||c.indexOf("center")>=0),g=!u&&i<1&&ke.current.cropHeight>ce/ae;let m=u?o.cropWidth:o.cropWidth*i;g&&(m=o.cropWidth);const f=!u&&n<1&&ke.current.cropWidth>le/oe;let p=u?o.cropHeight:o.cropHeight*n;f&&(p=o.cropHeight),ge&&(m=o.cropWidth,p=o.cropHeight),o.set({cropX:h,cropY:l,x:r.x(),y:r.y(),width:r.width()*i,height:r.height()*n,rotation:e.target.rotation(),cropWidth:Math.min(m,1-h),cropHeight:Math.min(p,1-l)})},onTransformEnd:e=>{const t=e.currentTarget;o.set({width:t.width(),height:t.height(),x:t.x(),y:t.y(),rotation:e.target.rotation(),cropWidth:le/oe,cropHeight:ce/ae}),y(!1)}}),e(s,{x:o.a.x,y:o.a.y,width:Math.max(o.a.width-o.borderSize,0),height:Math.max(o.a.height-o.borderSize,0),opacity:He,offsetX:-o.borderSize/2,offsetY:-o.borderSize/2,stroke:o.borderColor,strokeWidth:o.borderSize,listening:!1,visible:!!o.borderSize,rotation:o.rotation,cornerRadius:Math.max(0,fe-o.borderSize),hideInExport:!o.showInExport}),!a.isPlaying&&e(h,{image:V?U||Xe?H:void 0:k,x:o.a.x,y:o.a.y,offsetX:-o.a.width/2+15/a.scale,offsetY:-o.a.height/2+15/a.scale,rotation:o.a.rotation,width:30/a.scale,height:30/a.scale,hideInExport:!0,onClick:()=>D(!V),onTap:()=>D(!V)}),o._cropModeEnabled&&t(f,{selector:".page-abs-container",enabled:!0,children:[e(s,{x:-window.innerWidth/a.scale,y:-window.innerWidth/a.scale,width:window.innerWidth/a.scale*3,height:window.innerWidth/a.scale*3,fill:"rgba(0,0,0,0.3)"}),e(h,{listening:!1,image:we,x:o.a.x,y:o.a.y,width:o.a.width,height:o.a.height,rotation:o.a.rotation,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur}),t(d,{x:o.a.x,y:o.a.y,rotation:o.a.rotation,scaleX:ye,scaleY:ye,children:[e(h,{image:J,ref:_,width:oe,height:ae,opacity:.4,draggable:!0,x:-o.cropX*oe,y:-o.cropY*ae,onDragMove:Te,onTransform:Te}),e(c,{ref:Le,anchorSize:20,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],boundBoxFunc:(e,t)=>t.width<5||t.height<5?e:t,rotateEnabled:!1,borderEnabled:!1,anchorCornerRadius:10,anchorStrokeWidth:2,borderStrokeWidth:2}),e(s,{width:le,height:ce,ref:Ee,listening:!1,onTransform:e=>{e.target.x()<-o.cropX*oe-1e-9&&(e.target.x(-o.cropX*oe),e.target.scaleX(1)),e.target.y()<-o.cropY*ae-1e-9&&(e.target.y(-o.cropY*ae),e.target.scaleY(1));const t=Math.min(1,Math.max(0,o.cropX+e.target.x()/oe)),r=Math.min(1,Math.max(0,e.target.y()/ae+o.cropY)),i=e.target.width()*e.target.scaleX(),n=e.target.height()*e.target.scaleY(),a=Math.min(1-t,i/oe),d=Math.min(1-r,n/ae),h=e.target.getAbsolutePosition(e.target.getParent().getParent());e.target.scale({x:1,y:1}),e.target.position({x:0,y:0}),o.set({x:h.x,y:h.y,cropX:t,cropY:r,cropWidth:a,cropHeight:d,width:Math.min(i*ye,oe*(1-t)*ye),height:Math.min(n*ye,ae*(1-r)*ye)})}}),e(c,{ref:be,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],boundBoxFunc:(e,t)=>t.width<5||t.height<5?e:t,keepRatio:!1,rotateEnabled:!1,anchorFill:"rgb(240, 240, 240)",anchorStrokeWidth:2,borderStrokeWidth:2,visible:o.resizable})]})]})]})})});
1
+ import{jsx as e,jsxs as t,Fragment as r}from"react/jsx-runtime";import i from"react";import{observer as o}from"mobx-react-lite";import{nodeAutorun as n}from"../utils/mobx.js";import{Arc as a,Group as d,Image as h,Rect as s,Text as l,Transformer as c}from"react-konva";import{ROLES as u}from"../model/store.js";import g from"use-image";import m from"konva";import{Portal as f}from"react-konva-utils";import{useWorkspaceStyle as p}from"./workspace-style.js";import{incrementLoader as v,triggerLoadError as w}from"../utils/loader.js";import{polotnoError as x}from"@polotno/core/errors";import{getCropRect as M}from"@polotno/core/image";import*as y from"@polotno/core/svg";import{flags as E}from"../utils/flags.js";import{roundEnabledPx as b,isCornerAnchor as L,scaledBoxStyleAttrs as T,roundedBoxStyleAttrs as C}from"../utils/px.js";import{useFilteredSource as S}from"./use-filtered-source.js";import{useEvent as R}from"../hooks/use-event.js";import{useFadeIn as I}from"./use-fadein.js";import{isTouchDevice as k}from"../utils/screen.js";import{useMediabunnyVideo as H}from"./use-mediabunny-video.js";import{getElementTimeRange as W,getVideoRestMs as X}from"../utils/timeline.js";function Y(){return document.createElement("canvas")}const O=new window.Image;O.src=y.svgToURL('\n <svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path opacity="0.6" d="M4 5.49683V18.5032C4 20.05 5.68077 21.0113 7.01404 20.227L18.0694 13.7239C19.384 12.9506 19.384 11.0494 18.0694 10.2761L7.01404 3.77296C5.68077 2.98869 4 3.95 4 5.49683Z" fill="white"/>\n <path d="M4 5.49683V18.5032C4 20.05 5.68077 21.0113 7.01404 20.227L18.0694 13.7239C19.384 12.9506 19.384 11.0494 18.0694 10.2761L7.01404 3.77296C5.68077 2.98869 4 3.95 4 5.49683Z" stroke="#323232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n');const j=new window.Image;j.src=y.svgToURL('\n <svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path opacity="0.6" d="M14 19L14 5C14 3.89543 14.8954 3 16 3L17 3C18.1046 3 19 3.89543 19 5L19 19C19 20.1046 18.1046 21 17 21L16 21C14.8954 21 14 20.1046 14 19Z" fill="white"/>\n <path opacity="0.6" d="M10 19L10 5C10 3.89543 9.10457 3 8 3L7 3C5.89543 3 5 3.89543 5 5L5 19C5 20.1046 5.89543 21 7 21L8 21C9.10457 21 10 20.1046 10 19Z" fill="white"/>\n <path d="M14 19L14 5C14 3.89543 14.8954 3 16 3L17 3C18.1046 3 19 3.89543 19 5L19 19C19 20.1046 18.1046 21 17 21L16 21C14.8954 21 14 20.1046 14 19Z" stroke="#323232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n <path d="M10 19L10 5C10 3.89543 9.10457 3 8 3L7 3C5.89543 3 5 3.89543 5 5L5 19C5 20.1046 5.89543 21 7 21L8 21C9.10457 21 10 20.1046 10 19Z" stroke="#323232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n');export const useCornerRadiusAndCrop=(e,t,r,o,n=0,a=!1)=>{var d,h;const s=Math.floor(Math.max(e.width*o,1)),l=Math.floor(Math.max(e.height*o,1)),c=Math.min(n*o,s/2,l/2),u=Math.max(e.width/r.width,e.height/r.height)*o,g=(null===(d=e.page)||void 0===d?void 0:d._exportingOrRendering)&&E.imageDownScalingEnabled&&u<1&&!a,f=t instanceof HTMLVideoElement?t.videoWidth:null==t?void 0:t.width,p=t instanceof HTMLVideoElement?t.videoHeight:null==t?void 0:t.height,v=0===r.x&&0===r.y&&r.width===f&&r.height===p,w=i.useMemo(()=>{if(t&&f&&p){return v&&0===c&&!g?void 0:Y()}},[t,c,g,v,f,p]),x=()=>{if(!w||!t){return}w.width=s,w.height=l;const e=w.getContext("2d");if(!e){return}c&&(e.beginPath(),e.moveTo(c,0),e.lineTo(s-c,0),e.arc(s-c,c,c,3*Math.PI/2,0,!1),e.lineTo(s,l-c),e.arc(s-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());const i=g?function(e,t){var r,i;const o=Y(),n=e instanceof HTMLVideoElement?e.videoWidth:e.width,a=e instanceof HTMLVideoElement?e.videoHeight:e.height;o.width=n,o.height=a,null===(r=o.getContext("2d"))||void 0===r||r.drawImage(e,0,0,o.width,o.height);const d=function(e,t,r,i,o,n,a){for(var d=new ImageData(t,r),h=new Int32Array(e.data.buffer),s=e.width,l=new Int32Array(d.data.buffer),c=d.width,u=t/n,g=r/a,m=Math.round(1/u),f=Math.round(1/g),p=m*f,v=0;v<d.height;v++){for(var w=0;w<c;w++){for(var x=0+Math.round(w/u)+(0+Math.round(v/g))*s,M=0,y=0,E=0,b=0,L=0;L<f;L++){for(var T=0;T<m;T++){var C=h[x+T+L*s];M+=C<<24>>>24,y+=C<<16>>>24,E+=C<<8>>>24,b+=C>>>24}}M=Math.round(M/p),y=Math.round(y/p),E=Math.round(E/p),b=Math.round(b/p),l[w+v*c]=b<<24|E<<16|y<<8|M}}return d}(o.getContext("2d").getImageData(0,0,o.width,o.height),Math.floor(o.width*t),Math.floor(o.height*t),0,0,o.width,o.height);return o.width=Math.floor(o.width*t),o.height=Math.floor(o.height*t),null===(i=o.getContext("2d"))||void 0===i||i.putImageData(d,0,0),o}(t,u):t,o=g?{x:Math.floor(r.x*u),y:Math.floor(r.y*u),width:Math.floor(r.width*u),height:Math.floor(r.height*u)}:r;e.drawImage(i,o.x,o.y,o.width,o.height,0,0,w.width,w.height)};return i.useLayoutEffect(()=>{x()},[w,e.width,e.height,r.x,r.y,r.width,r.height,n,o,a,null===(h=e.page)||void 0===h?void 0:h._exportingOrRendering,g]),i.useEffect(()=>()=>{w&&"CANVAS"===w.nodeName&&m.Util.releaseCanvas(w)},[w]),[w||t,x]};const A=Y(),P=o(({element:r})=>{const o=Math.min(30,r.width/4,r.height/4),n=i.useRef(null);i.useEffect(()=>{const e=n.current;if(!e){return}const t=new m.Animation(t=>{e.rotate(((null==t?void 0:t.timeDiff)||0)/2)},e.getLayer());return t.start(),()=>{t.stop()}});const{mediaLoadingStyle:h}=p();return t(d,{x:r.a.x,y:r.a.y,rotation:r.a.rotation,listening:!1,opacity:r.a.opacity,hideInExport:!r.showInExport,children:[e(s,{width:r.width,height:r.height,fill:h.fill}),e(a,{ref:n,x:r.width/2,y:r.height/2,fill:h.textFill,outerRadius:Math.abs(o),innerRadius:Math.max(1,o-5),angle:270})]})}),_=o(({element:r})=>{const{mediaErrorStyle:i}=p(),o=Math.max(10,Math.min(30,r.width/25));return t(d,{x:r.a.x,y:r.a.y,rotation:r.a.rotation,listening:!1,opacity:r.a.opacity,hideInExport:!r.showInExport,children:[e(s,{width:r.width,height:r.height,fill:i.fill}),e(l,{text:"Can not load the video...",fontSize:o,width:r.width,height:r.height,align:"center",fill:i.textFill,verticalAlign:"middle",padding:5})]})});let V=function(e,t,r){const o=i.useRef("loading"),n=i.useRef(void 0),[a,d]=i.useState(0),h=i.useRef(void 0),s=i.useRef(void 0),l=i.useRef(void 0);return h.current===e&&s.current===t&&l.current===r||(o.current="loading",n.current=void 0,h.current=e,s.current=t,l.current=r),i.useLayoutEffect(function(){if(e){var i=document.createElement("video");return i.addEventListener("canplay",a),i.addEventListener("error",h),t&&(i.crossOrigin=t),r&&(i.referrerPolicy=r),i.src=e,i.load(),function(){i.removeEventListener("canplay",a),i.removeEventListener("error",h)}}function a(){o.current="loaded",n.current=i,n.current.currentTime=0,d(Math.random()),n.current.removeEventListener("canplay",a)}function h(e){var t;const r=4===i.readyState,a=i.buffered&&i.buffered.length>0&&i.buffered.end(i.buffered.length-1)/i.duration*100>=100;if(r&&a){return}const h=e.message||(null===(t=i.error)||void 0===t?void 0:t.message)||"Unknown error",s=new Error("Video failed to load: "+h);console.error(s),o.current="failed",n.current=void 0,d(Math.random())}},[e,t,r]),[n.current,o.current]};export const setVideoLoaderHook=e=>{V=e};function D(e){return 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=v(a)),"loading"!==e&&n(),"failed"===e&&w(x("VIDEO_FAILED",a,{src:i,elementId:r,reason:"load"}))},[e])};export const VideoElement=o(({element:o,store:a})=>{var l,p,w;const[x,E]=i.useState(!1),z=i.useRef(null),B=i.useRef(null),U=o.isSelected,[F,N]=i.useState(!1),[Z,$]=V(o.src,"anonymous"),[q,G]=i.useState(!1),J=a.activePage===o.page,K=(null===(l=o.page)||void 0===l?void 0:l._exportingOrRendering)&&"loaded"===$,Q=H(o,a,K);useLoader($,o.src,o.id),Z&&(Z.playsInline=!0);const ee=((e,t,r)=>{const o=i.useMemo(()=>{var i,o;const{flipX:n,flipY:a}=e,d="svg"===e.type||e.src.indexOf("data:image/svg+xml")>=0||e.src.indexOf(".svg")>=0,h=navigator.userAgent.toLowerCase().indexOf("firefox")>-1;if(!(n||a||h&&d)){return t}if(!t){return null}const s=t instanceof HTMLVideoElement?t.videoWidth:null==t?void 0:t.width,l=t instanceof HTMLVideoElement?t.videoHeight:null==t?void 0:t.height;if(!s||!l){return null}const c=Y();let u=1;"svg"===e.type&&(u=Math.max(e.width/s*r,e.height/l*r)),c.width=Math.max(s*u,1),c.height=Math.max(l*u,1);let g=n?-c.width:0,m=a?-c.height:0;return null===(i=c.getContext("2d"))||void 0===i||i.scale(n?-1:1,a?-1:1),null===(o=c.getContext("2d"))||void 0===o||o.drawImage(t,g,m,c.width,c.height),c},[e.flipX,e.flipY,t,e.width,e.height,r]);return i.useEffect(()=>()=>{o&&"CANVAS"===o.nodeName&&m.Util.releaseCanvas(o)},[o]),o})(o,Z,a._elementsPixelRatio),te=K&&Q||ee||A,[re=A,ie]=S(o,te);i.useEffect(()=>{Z&&a.history.ignore(()=>{o.set({duration:1e3*Z.duration})})},[Z]),i.useEffect(()=>{var e;if(!Z){return}const t=a.animatedElementsIds,r=(!t.length||t.includes(o.id))&&a.isPlaying;if(!J||!r&&!F){return void Z.pause()}F&&(Z.muted=!1,Z.currentTime=o.startTime*Z.duration,Z.play());const i=new m.Animation(()=>{ye()},null===(e=z.current)||void 0===e?void 0:e.getLayer());i.start();const n=()=>{N(!1),Z.currentTime=o.startTime*Z.duration},d=()=>{Z.currentTime>=o.endTime*Z.duration&&(Z.pause(),Z.currentTime=o.startTime*Z.duration,N(!1))};return Z.addEventListener("ended",n),Z.addEventListener("timeupdate",d),()=>{Z.pause(),i.stop(),Z.removeEventListener("ended",n),Z.removeEventListener("timeupdate",d)}},[Z,F,a.isPlaying,J]),i.useEffect(()=>{Z&&(Z.volume=o.volume)},[Z,o.volume]),i.useEffect(()=>{Z&&(Z.playbackRate=o.speed,Z.preservesPitch=!1)},[Z,o.speed]);const oe=i.useRef(null);i.useEffect(()=>{const e=n(o,()=>{var e,t;if(Z){if(K&&Q){return ye(),void a.currentTime}const r=a.animatedElementsIds;if(r.length&&!r.includes(o.id)){return}const i=a.activePage===o.page,n=a.currentTime>=o.page.startTime&&a.currentTime<o.page.startTime+o.page.duration,d=o.startTime*Z.duration*1e3,h=Z.duration*(o.endTime-o.startTime)*1e3,{start:s,end:l}=W(o.animations,o.page.duration),c=(a.currentTime||o.page.startTime)-o.page.startTime,u=n?X(a.currentTime,o.page.startTime,s,h,d,o.speed):0,g=u/1e3,m=n&&c>=s&&c<l;F||(Z.muted=!m,m&&a.isPlaying&&i?Z.paused?(Z.currentTime=g,Z.play()):Math.abs(1e3*Z.currentTime-u)>500&&(Z.currentTime=g):(Z.paused||Z.pause(),g!==Z.currentTime&&(Z.currentTime=g),!D(Z)&&!a.isPlaying&&!oe.current&&(oe.current=v(`video ${o.id}`)))),ye(),null===(t=null===(e=z.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()}});return()=>{e(),oe.current&&(oe.current(),oe.current=null)}},[a,Z,K,Q,F]),i.useEffect(()=>{var e,t;if(!Z){return}if(K){return null===(e=oe.current)||void 0===e||e.call(oe),void(oe.current=null)}const r=()=>{var e,t,r;!D(Z)&&(null===(e=o.page)||void 0===e?void 0:e._exportingOrRendering)||oe.current&&(ye(),null===(r=null===(t=z.current)||void 0===t?void 0:t.getLayer())||void 0===r||r.batchDraw(),oe.current(),oe.current=null)};let i;return(null===(t=o.page)||void 0===t?void 0:t._exportingOrRendering)&&(i=setInterval(r,20)),Z.addEventListener("timeupdate",r),Z.addEventListener("canplay",r),()=>{clearInterval(i),Z.removeEventListener("timeupdate",r),Z.removeEventListener("canplay",r)}},[null===(p=o.page)||void 0===p?void 0:p._exportingOrRendering,Z,o.id,v,K]);let{cropX:ne,cropY:ae,cropWidth:de,cropHeight:he}=o;"loaded"!==$&&(ne=ae=0,de=he=1);const se=(le=re)instanceof HTMLVideoElement?le.videoWidth:(null==le?void 0:le.width)||0;var le;const ce=(e=>e instanceof HTMLVideoElement?e.videoHeight:(null==e?void 0:e.height)||0)(re),ue=M({type:o.type,cropX:ne,cropY:ae,cropWidth:de,cropHeight:he,width:o.width,height:o.height},{width:se,height:ce}),ge=ue.width,me=ue.height,fe="svg"===o.type,pe=null!==(w=o.cornerRadius)&&void 0!==w?w:0,[ve,we]=useCornerRadiusAndCrop(o,re,ue,a._elementsPixelRatio,pe,!0);let[xe,Me]=((e,t,r,o)=>{const n=(e=>{const[t,r]=i.useState(e);return i.useEffect(()=>{(async()=>{const i=await async function(e){if(!(e.indexOf("data:image/svg+xml")>=0||e.indexOf(".svg")>=0)){return e}const t=await y.urlToString(e),r=y.fixSize(t);return y.svgToURL(r)}(e);i!==t&&r(i)})()},[e]),t})(e.clipSrc||""),[a,d]=g(n,"anonymous"),h=e.clipSrc?d:"loaded";useLoader(h,e.clipSrc,e.id);const s=i.useMemo(()=>{if(t&&a){return Y()}},[t,a]);function l(){var i;if(!a){return}const o=t instanceof HTMLVideoElement?t.videoWidth:null==t?void 0:t.width,n=t instanceof HTMLVideoElement?t.videoHeight:null==t?void 0:t.height;if(!t||!o||!n){return}if(!a||!a.width||!a.height){return}if(!s){return}const d=Y(),h=Math.max(e.width/a.width*r,e.height/a.height*r);d.width=a.width*h,d.height=a.height*h,null===(i=d.getContext("2d"))||void 0===i||i.drawImage(a,0,0,d.width,d.height),s.width=Math.max(o,1),s.height=Math.max(n,1);const l=s.getContext("2d");l&&(l.save(),l.drawImage(d,0,0,o,n),m.Util.releaseCanvas(d),l.globalCompositeOperation="source-in",l.drawImage(t,0,0,s.width,s.height),l.restore())}return i.useLayoutEffect(()=>{l()},[s,t,a,e.width,e.height,r,...o]),[e.clipSrc&&a?s:t,l]})(o,ve,a._elementsPixelRatio,[ue,pe,a._elementsPixelRatio]);const ye=R(()=>{var e,t;ie(),we(),Me(),null===(t=null===(e=z.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()});i.useEffect(()=>{ye()});const Ee=Math.max(o.width/ge,o.height/me);i.useEffect(()=>{var e;if(!o._cropModeEnabled){return}const t=null===(e=z.current)||void 0===e?void 0:e.getStage();function r(e){o._cropModeEnabled&&e.target!==B.current&&o.toggleCropMode(!1)}function i(e){o._cropModeEnabled&&e.target.parentNode!==(null==t?void 0:t.content)&&o.toggleCropMode(!1)}return document.body.addEventListener("click",i),null==t||t.on("click",r),null==t||t.on("tap",r),()=>{document.body.removeEventListener("click",i),document.body.removeEventListener("touchstart",i),null==t||t.off("click",r),null==t||t.off("click",r)}},[o._cropModeEnabled]);const be=i.useRef(null),Le=i.useRef(null),Te=i.useRef(null);i.useLayoutEffect(()=>{o._cropModeEnabled&&(Le.current.nodes([be.current]),Te.current.nodes([B.current]))},[o._cropModeEnabled]);const Ce=e=>{Math.round(e.target.x())>0&&(e.target.x(0),e.target.scaleX(1)),Math.round(e.target.y())>0&&(e.target.y(0),e.target.scaleY(1));const t=e.target.width()*e.target.scaleX(),r=e.target.height()*e.target.scaleY(),i=Math.min(1,ge/t),n=Math.min(1,me/r),a=1-i,d=Math.min(a,Math.max(0,Math.round(-e.target.x())/t)),h=1-n,s=Math.min(h,Math.max(0,Math.round(-e.target.y())/r));e.target.setAttrs({x:-d*se,y:-s*ce,scaleX:1,scaleY:1}),o.set({cropX:d,cropY:s,cropWidth:i,cropHeight:n})},Se=()=>{"svg"!==o.type&&o.contentEditable&&setTimeout(()=>{o.toggleCropMode(!0)})},Re="loading"===$,Ie="failed"===$,ke=!Re&&!Ie,He=i.useRef({cropX:0,cropY:0,cropWidth:0,cropHeight:0}),We=ke?o.a.opacity:0;I(z,We);const Xe=o.selectable||a.role===u.ADMIN,Ye=k();return e(r,{children:t(d,{onMouseEnter:()=>G(!0),onMouseLeave:()=>G(!1),children:[Re&&e(P,{element:o}),Ie&&e(_,{element:o}),e(h,{ref:z,name:"element",id:o.id,image:xe,x:o.a.x,y:o.a.y,width:o.a.width||1,height:o.a.height||1,rotation:o.a.rotation,opacity:We,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity,customCrop:ue,listening:Xe,draggable:Ye?o.draggable&&U:o.draggable,preventDefault:!Ye||U,hideInExport:!o.showInExport,onDragMove:e=>{o.set({x:e.target.x(),y:e.target.y()})},onDragEnd:e=>{o.set({x:e.target.x(),y:e.target.y()})},onDblClick:Se,onDblTap:Se,onTransformStart:()=>{E(!0),He.current={cropX:o.cropX,cropY:o.cropY,cropWidth:o.cropWidth,cropHeight:o.cropHeight}},onTransform:e=>{var t,r;const i=e.currentTarget,n=Math.abs(i.scaleX()-1)<1e-7?1:i.scaleX(),a=Math.abs(i.scaleY()-1)<1e-7?1:i.scaleY();i.scaleX(1),i.scaleY(1);const d=null===(t=e.target.getStage())||void 0===t?void 0:t.findOne("Transformer"),h=1-ge/se,s=Math.min(h,Math.max(0,o.cropX)),l=1-me/ce,c=Math.min(l,Math.max(0,o.cropY)),u=L(null!==(r=d.getActiveAnchor())&&void 0!==r?r:""),g=!u&&n<1&&He.current.cropHeight>me/ce;let m=u?o.cropWidth:o.cropWidth*n;g&&(m=o.cropWidth);const f=!u&&a<1&&He.current.cropWidth>ge/se;let p=u?o.cropHeight:o.cropHeight*a;f&&(p=o.cropHeight),fe&&(m=o.cropWidth,p=o.cropHeight);const v=u?Math.min(n,a):1;o.set(Object.assign({cropX:s,cropY:c,x:i.x(),y:i.y(),width:i.width()*n,height:i.height()*a,rotation:e.target.rotation(),cropWidth:Math.min(m,1-s),cropHeight:Math.min(p,1-c)},1!==v&&Object.assign(Object.assign({},T(o,v)),{borderSize:o.borderSize*v})))},onTransformEnd:e=>{const t=e.currentTarget;o.set(Object.assign(Object.assign({width:t.width(),height:t.height(),x:t.x(),y:t.y(),rotation:e.target.rotation(),cropWidth:ge/se,cropHeight:me/ce},C(o)),{borderSize:b(o.borderSize)})),E(!1)}}),e(s,{x:o.a.x,y:o.a.y,width:Math.max(o.a.width-o.borderSize,0),height:Math.max(o.a.height-o.borderSize,0),opacity:We,offsetX:-o.borderSize/2,offsetY:-o.borderSize/2,stroke:o.borderColor,strokeWidth:o.borderSize,listening:!1,visible:!!o.borderSize,rotation:o.rotation,cornerRadius:Math.max(0,pe-o.borderSize),hideInExport:!o.showInExport}),!a.isPlaying&&e(h,{image:F?q||Ye?j:void 0:O,x:o.a.x,y:o.a.y,offsetX:-o.a.width/2+15/a.scale,offsetY:-o.a.height/2+15/a.scale,rotation:o.a.rotation,width:30/a.scale,height:30/a.scale,hideInExport:!0,onClick:()=>N(!F),onTap:()=>N(!F)}),o._cropModeEnabled&&t(f,{selector:".page-abs-container",enabled:!0,children:[e(s,{x:-window.innerWidth/a.scale,y:-window.innerWidth/a.scale,width:window.innerWidth/a.scale*3,height:window.innerWidth/a.scale*3,fill:"rgba(0,0,0,0.3)"}),e(h,{listening:!1,image:xe,x:o.a.x,y:o.a.y,width:o.a.width,height:o.a.height,rotation:o.a.rotation,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur}),t(d,{x:o.a.x,y:o.a.y,rotation:o.a.rotation,scaleX:Ee,scaleY:Ee,children:[e(h,{image:re,ref:B,width:se,height:ce,opacity:.4,draggable:!0,x:-o.cropX*se,y:-o.cropY*ce,onDragMove:Ce,onTransform:Ce}),e(c,{ref:Te,anchorSize:20,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],boundBoxFunc:(e,t)=>t.width<5||t.height<5?e:t,rotateEnabled:!1,borderEnabled:!1,anchorCornerRadius:10,anchorStrokeWidth:2,borderStrokeWidth:2}),e(s,{width:ge,height:me,ref:be,listening:!1,onTransform:e=>{e.target.x()<-o.cropX*se-1e-9&&(e.target.x(-o.cropX*se),e.target.scaleX(1)),e.target.y()<-o.cropY*ce-1e-9&&(e.target.y(-o.cropY*ce),e.target.scaleY(1));const t=Math.min(1,Math.max(0,o.cropX+e.target.x()/se)),r=Math.min(1,Math.max(0,e.target.y()/ce+o.cropY)),i=e.target.width()*e.target.scaleX(),n=e.target.height()*e.target.scaleY(),a=Math.min(1-t,i/se),d=Math.min(1-r,n/ce),h=e.target.getAbsolutePosition(e.target.getParent().getParent());e.target.scale({x:1,y:1}),e.target.position({x:0,y:0}),o.set({x:h.x,y:h.y,cropX:t,cropY:r,cropWidth:a,cropHeight:d,width:Math.min(i*Ee,se*(1-t)*Ee),height:Math.min(n*Ee,ce*(1-r)*Ee)})}}),e(c,{ref:Le,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],boundBoxFunc:(e,t)=>t.width<5||t.height<5?e:t,keepRatio:!1,rotateEnabled:!1,anchorFill:"rgb(240, 240, 240)",anchorStrokeWidth:2,borderStrokeWidth:2,visible:o.resizable})]})]})]})})});
@@ -9,7 +9,7 @@ import { FigureElementType } from './figure-model.js';
9
9
  import { GifElementType } from './gif-model.js';
10
10
  import { TableElementType } from './table-model.js';
11
11
  export declare const forEveryChild: (node: any, cb: any) => void;
12
- export declare const forEveryNode: (node: any, cb: any) => void;
12
+ export { forEveryNode } from '@polotno/core/for-every-node';
13
13
  export declare function zIndexOps(self: {
14
14
  children: any;
15
15
  }): {
@@ -1677,4 +1677,3 @@ export declare const TYPES_MAP: {
1677
1677
  };
1678
1678
  export declare function registerShapeModel(defaultAttributes: any, extendFunc?: any): void;
1679
1679
  export type GroupElementType = Instance<typeof GroupElement>;
1680
- export {};
@@ -1 +1 @@
1
- var e=this&&this.__rest||function(e,t){var o={};for(var i in e){Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(o[i]=e[i])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++){t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(o[i[r]]=e[i[r]])}}return o};import{detach as t,isAlive as o,types as i}from"mobx-state-tree";import{nanoid as r}from"nanoid";import{Node as n}from"./node-model.js";import{Animation as s,Shape as l}from"./shape-model.js";import{animate as a}from"../utils/animations.js";import{polotnoError as d}from"../utils/errors.js";import{getPlayheadLocalTime as c}from"../utils/timeline.js";import{getCenter as p,getTotalClientRect as h}from"../utils/math.js";import{TextElement as y}from"./text-model.js";import{ImageElement as m}from"./image-model.js";import{VideoElement as f}from"./video-model.js";import{LineElement as u}from"./line-model.js";import{SVGElement as g}from"./svg-model.js";import{FigureElement as E}from"./figure-model.js";import{GifElement as b}from"./gif-model.js";import{TableElement as v}from"./table-model.js";export const forEveryChild=(e,t)=>{if(e.children){for(const o of e.children){if(!0===t(o)){break}forEveryChild(o,t)}}};export const forEveryNode=(e,t)=>{if(e.children){for(const o of e.children){if(!0===t(o)){break}forEveryNode(o,t)}}if(e.cells){for(const o of e.cells){if(!0===t(o)){break}}}};export function zIndexOps(e){const o=(t,o,i)=>{const r=t.map(t=>e.children.findIndex(e=>e.id===t)).filter(e=>-1!==e).sort((e,t)=>(t-e)*o);for(const n of r){const r=e.children[n+o];!r||t.indexOf(r.id)>=0||i(n)}},i=(e,t)=>{let i=!1;return o(e,t,()=>{i=!0}),i},r=(i,r)=>{o(i,r,o=>{const i=e.children[o];t(i),e.children.splice(o+r,0,i)})},n=(t,o)=>{const i=[],r=[];e.children.forEach(e=>{(t.indexOf(e.id)>=0?i:r).push(e)}),e.children.replace(o?r.concat(i):i.concat(r))};return{canMoveElementsUp:e=>i(e,1),canMoveElementsTop:e=>i(e,1),canMoveElementsDown:e=>i(e,-1),canMoveElementsBottom:e=>i(e,-1),moveElementsUp(e){r(e,1)},moveElementsDown(e){r(e,-1)},moveElementsTop(e){n(e,!0)},moveElementsBottom(e){n(e,!1)},setElementZIndex(o,i){const r=e.children.find(e=>e.id===o);r&&(t(r),e.children.remove(r),e.children.splice(i,0,r))}}}const x=[...new Array(20)].map((e,t)=>i.late(()=>S[t]));export const ElementTypes=i.union({dispatcher:e=>{const t=TYPES_MAP[e.type];if(!t){const t=`Unknown element type: "${e.type}"`;throw d("DESIGN_INVALID",t,{errors:[{path:"type",message:t}],knownTypes:Object.keys(TYPES_MAP)})}return t}},g,y,m,u,f,E,b,v,i.late(()=>GroupElement),...x);const w=Object.freeze({x:0,y:0,offsetX:0,offsetY:0,scaleX:1,scaleY:1,rotation:0,opacity:1});function j(e){return 1===e?w:Object.assign(Object.assign({},w),{opacity:e})}const O={x:0,y:0,width:0,height:0,rotation:0,opacity:1,fontSize:0,cropX:0,cropY:0,cropWidth:1,cropHeight:1},P=(e,t)=>"number"==typeof e&&isFinite(e)?e:t;function C(e,t,o,i){O.x=e.x,O.y=e.y,O.width=e.width,O.height=e.height,O.opacity=i;const r=a({element:O,animation:t,dTime:o})||{},n=P(r.width,e.width),s=P(r.height,e.height);return{x:P(r.x,e.x),y:P(r.y,e.y),width:n>0?n:e.width,height:s>0?s:e.height,rotation:P(r.rotation,0),opacity:P(r.opacity,i)}}export const GroupElement=n.named("Group").props({type:"group",children:i.array(ElementTypes),animations:i.array(s)}).views(e=>({get draggable(){let t=!0;return forEveryChild(e,e=>{e.draggable||(t=!1)}),t},get resizable(){let t=!0;return forEveryChild(e,e=>{e.resizable||(t=!1)}),t},get contentEditable(){let t=!0;return forEveryChild(e,e=>{e.contentEditable||(t=!1)}),t},get styleEditable(){let t=!0;return forEveryChild(e,e=>{e.styleEditable||(t=!1)}),t},get locked(){let t=!0;return forEveryChild(e,e=>{e.locked||(t=!1)}),t},get _restingBbox(){const t=[];if(forEveryChild(e,e=>{var o,i,r;if("group"===e.type){return}const n=e.width,s=e.height;!n||!s||n<=0||s<=0||t.push({x:null!==(o=e.x)&&void 0!==o?o:0,y:null!==(i=e.y)&&void 0!==i?i:0,width:n,height:s,rotation:null!==(r=e.rotation)&&void 0!==r?r:0})}),!t.length){return null}const o=h(t);return o.width<=0||o.height<=0?null:{x:o.x,y:o.y,width:o.width,height:o.height}},get a(){if(!o(e)){return w}const t=c(e);if(null===t){return j(e.opacity)}if(e.store.isEditingPaused&&this.isSelectedDirectly){return j(e.opacity)}const i=e.page,r=e.store.animatedElementsIds;if(r.length&&!r.includes(e.id)){return j(e.opacity)}let n,s,l;for(const o of e.animations){o.enabled&&("enter"===o.type?n=o:"exit"===o.type?s=o:"loop"===o.type&&(l=o))}const a=!!n&&t<n.delay,d=!!n&&t>=n.delay&&t<=n.delay+n.duration,h=!a&&!d&&!!s&&t>=i.duration-s.duration-s.delay&&t<=i.duration-s.delay,y=!!s&&t>=i.duration-s.delay;if(!(a||d||h||y||l)){return j(e.opacity)}const m=this._restingBbox;if(!m){return j(e.opacity)}let f={x:m.x,y:m.y,width:m.width,height:m.height,rotation:0,opacity:e.opacity};a&&(f.opacity=0),d&&(f=C(m,n,t-n.delay,e.opacity)),h&&(f=C(m,s,t-(i.duration-s.duration-s.delay),e.opacity)),y&&(f.opacity=0),l&&(f=C(f,l,t,f.opacity));const u=p(f);return{x:u.x,y:u.y,offsetX:m.x+m.width/2,offsetY:m.y+m.height/2,scaleX:f.width/m.width,scaleY:f.height/m.height,rotation:f.rotation,opacity:f.opacity}},get isSelectedDirectly(){return!!o(e)&&e.store.selectedElements.indexOf(e)>=0&&e.selectable},get active(){return!0}})).actions(t=>Object.assign(Object.assign({set(o){var{draggable:i,contentEditable:r,styleEditable:n,resizable:s}=o,l=e(o,["draggable","contentEditable","styleEditable","resizable"]);void 0!==i&&forEveryChild(t,e=>{e.set({draggable:i})}),void 0!==r&&forEveryChild(t,e=>{e.set({contentEditable:r})}),void 0!==n&&forEveryChild(t,e=>{e.set({styleEditable:n})}),void 0!==s&&forEveryChild(t,e=>{e.set({resizable:s})}),Object.assign(t,l)},addElement(e,{skipSelect:o=!1}={}){const i=TYPES_MAP[e.type];if(!i){return void console.error("Can not find model with type "+e.type)}e.children&&e.children.forEach(e=>{e.id=e.id||r(10)});const n=i.create(Object.assign({id:r(10)},e));return t.children.push(n),n.selectable&&!o&&t.store.selectElements([n.id]),n}},zIndexOps(t)),{setAnimation(e,o){const i=t.animations.find(t=>t.type===e);i?Object.assign(i,o):t.animations.push(Object.assign({type:e},o))}}));const S=[];export const TYPES_MAP={svg:g,text:y,image:m,group:GroupElement,line:u,video:f,figure:E,gif:b,table:v};export function registerShapeModel(e,t){const o=e.type;if(!o){throw new Error('You must pass "type" attribute to custom model.')}let i=l.named(o).props(e);t&&(i=t(i)),TYPES_MAP[o]=i,S.push(i)}
1
+ var e=this&&this.__rest||function(e,t){var o={};for(var i in e){Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(o[i]=e[i])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++){t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(o[i[r]]=e[i[r]])}}return o};import{detach as t,isAlive as o,types as i}from"mobx-state-tree";import{nanoid as r}from"nanoid";import{Node as n}from"./node-model.js";import{Animation as s,Shape as l}from"./shape-model.js";import{animate as a}from"../utils/animations.js";import{polotnoError as d}from"@polotno/core/errors";import{getPlayheadLocalTime as c}from"../utils/timeline.js";import{getCenter as p,getTotalClientRect as h}from"../utils/math.js";import{TextElement as y}from"./text-model.js";import{ImageElement as m}from"./image-model.js";import{VideoElement as f}from"./video-model.js";import{LineElement as u}from"./line-model.js";import{SVGElement as g}from"./svg-model.js";import{FigureElement as E}from"./figure-model.js";import{GifElement as b}from"./gif-model.js";import{TableElement as v}from"./table-model.js";export const forEveryChild=(e,t)=>{if(e.children){for(const o of e.children){if(!0===t(o)){break}forEveryChild(o,t)}}};export{forEveryNode}from"@polotno/core/for-every-node";export function zIndexOps(e){const o=(t,o,i)=>{const r=t.map(t=>e.children.findIndex(e=>e.id===t)).filter(e=>-1!==e).sort((e,t)=>(t-e)*o);for(const n of r){const r=e.children[n+o];!r||t.indexOf(r.id)>=0||i(n)}},i=(e,t)=>{let i=!1;return o(e,t,()=>{i=!0}),i},r=(i,r)=>{o(i,r,o=>{const i=e.children[o];t(i),e.children.splice(o+r,0,i)})},n=(t,o)=>{const i=[],r=[];e.children.forEach(e=>{(t.indexOf(e.id)>=0?i:r).push(e)}),e.children.replace(o?r.concat(i):i.concat(r))};return{canMoveElementsUp:e=>i(e,1),canMoveElementsTop:e=>i(e,1),canMoveElementsDown:e=>i(e,-1),canMoveElementsBottom:e=>i(e,-1),moveElementsUp(e){r(e,1)},moveElementsDown(e){r(e,-1)},moveElementsTop(e){n(e,!0)},moveElementsBottom(e){n(e,!1)},setElementZIndex(o,i){const r=e.children.find(e=>e.id===o);r&&(t(r),e.children.remove(r),e.children.splice(i,0,r))}}}const x=[...new Array(20)].map((e,t)=>i.late(()=>S[t]));export const ElementTypes=i.union({dispatcher:e=>{const t=TYPES_MAP[e.type];if(!t){const t=`Unknown element type: "${e.type}"`;throw d("DESIGN_INVALID",t,{errors:[{path:"type",message:t}],knownTypes:Object.keys(TYPES_MAP)})}return t}},g,y,m,u,f,E,b,v,i.late(()=>GroupElement),...x);const w=Object.freeze({x:0,y:0,offsetX:0,offsetY:0,scaleX:1,scaleY:1,rotation:0,opacity:1});function j(e){return 1===e?w:Object.assign(Object.assign({},w),{opacity:e})}const O={x:0,y:0,width:0,height:0,rotation:0,opacity:1,fontSize:0,cropX:0,cropY:0,cropWidth:1,cropHeight:1},P=(e,t)=>"number"==typeof e&&isFinite(e)?e:t;function C(e,t,o,i){O.x=e.x,O.y=e.y,O.width=e.width,O.height=e.height,O.opacity=i;const r=a({element:O,animation:t,dTime:o})||{},n=P(r.width,e.width),s=P(r.height,e.height);return{x:P(r.x,e.x),y:P(r.y,e.y),width:n>0?n:e.width,height:s>0?s:e.height,rotation:P(r.rotation,0),opacity:P(r.opacity,i)}}export const GroupElement=n.named("Group").props({type:"group",children:i.array(ElementTypes),animations:i.array(s)}).views(e=>({get draggable(){let t=!0;return forEveryChild(e,e=>{e.draggable||(t=!1)}),t},get resizable(){let t=!0;return forEveryChild(e,e=>{e.resizable||(t=!1)}),t},get contentEditable(){let t=!0;return forEveryChild(e,e=>{e.contentEditable||(t=!1)}),t},get styleEditable(){let t=!0;return forEveryChild(e,e=>{e.styleEditable||(t=!1)}),t},get locked(){let t=!0;return forEveryChild(e,e=>{e.locked||(t=!1)}),t},get _restingBbox(){const t=[];if(forEveryChild(e,e=>{var o,i,r;if("group"===e.type){return}const n=e.width,s=e.height;!n||!s||n<=0||s<=0||t.push({x:null!==(o=e.x)&&void 0!==o?o:0,y:null!==(i=e.y)&&void 0!==i?i:0,width:n,height:s,rotation:null!==(r=e.rotation)&&void 0!==r?r:0})}),!t.length){return null}const o=h(t);return o.width<=0||o.height<=0?null:{x:o.x,y:o.y,width:o.width,height:o.height}},get a(){if(!o(e)){return w}const t=c(e);if(null===t){return j(e.opacity)}if(e.store.isEditingPaused&&this.isSelectedDirectly){return j(e.opacity)}const i=e.page,r=e.store.animatedElementsIds;if(r.length&&!r.includes(e.id)){return j(e.opacity)}let n,s,l;for(const o of e.animations){o.enabled&&("enter"===o.type?n=o:"exit"===o.type?s=o:"loop"===o.type&&(l=o))}const a=!!n&&t<n.delay,d=!!n&&t>=n.delay&&t<=n.delay+n.duration,h=!a&&!d&&!!s&&t>=i.duration-s.duration-s.delay&&t<=i.duration-s.delay,y=!!s&&t>=i.duration-s.delay;if(!(a||d||h||y||l)){return j(e.opacity)}const m=this._restingBbox;if(!m){return j(e.opacity)}let f={x:m.x,y:m.y,width:m.width,height:m.height,rotation:0,opacity:e.opacity};a&&(f.opacity=0),d&&(f=C(m,n,t-n.delay,e.opacity)),h&&(f=C(m,s,t-(i.duration-s.duration-s.delay),e.opacity)),y&&(f.opacity=0),l&&(f=C(f,l,t,f.opacity));const u=p(f);return{x:u.x,y:u.y,offsetX:m.x+m.width/2,offsetY:m.y+m.height/2,scaleX:f.width/m.width,scaleY:f.height/m.height,rotation:f.rotation,opacity:f.opacity}},get isSelectedDirectly(){return!!o(e)&&e.store.selectedElements.indexOf(e)>=0&&e.selectable},get active(){return!0}})).actions(t=>Object.assign(Object.assign({set(o){var{draggable:i,contentEditable:r,styleEditable:n,resizable:s}=o,l=e(o,["draggable","contentEditable","styleEditable","resizable"]);void 0!==i&&forEveryChild(t,e=>{e.set({draggable:i})}),void 0!==r&&forEveryChild(t,e=>{e.set({contentEditable:r})}),void 0!==n&&forEveryChild(t,e=>{e.set({styleEditable:n})}),void 0!==s&&forEveryChild(t,e=>{e.set({resizable:s})}),Object.assign(t,l)},addElement(e,{skipSelect:o=!1}={}){const i=TYPES_MAP[e.type];if(!i){return void console.error("Can not find model with type "+e.type)}e.children&&e.children.forEach(e=>{e.id=e.id||r(10)});const n=i.create(Object.assign({id:r(10)},e));return t.children.push(n),n.selectable&&!o&&t.store.selectElements([n.id]),n}},zIndexOps(t)),{setAnimation(e,o){const i=t.animations.find(t=>t.type===e);i?Object.assign(i,o):t.animations.push(Object.assign({type:e},o))}}));const S=[];export const TYPES_MAP={svg:g,text:y,image:m,group:GroupElement,line:u,video:f,figure:E,gif:b,table:v};export function registerShapeModel(e,t){const o=e.type;if(!o){throw new Error('You must pass "type" attribute to custom model.')}let i=l.named(o).props(e);t&&(i=t(i)),TYPES_MAP[o]=i,S.push(i)}
package/model/store.js CHANGED
@@ -1 +1 @@
1
- var e=this&&this.__rest||function(e,t){var i={};for(var o in e){Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(i[o]=e[o])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(e);n<o.length;n++){t.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(e,o[n])&&(i[o[n]]=e[o[n]])}}return i};import{applySnapshot as t,cast as i,destroy as o,detach as n,getSnapshot as a,onSnapshot as s,setLivelinessChecking as r,types as l}from"mobx-state-tree";import{UndoManager as d}from"./history.js";import{nanoid as p}from"nanoid";import c from"konva";import{computed as g}from"mobx";import{ZERO_BLEED as m}from"@polotno/schema";import{downloadFile as u}from"../utils/download.js";import{getJsPDF as f}from"../utils/pdf.js";import{createGIF as h}from"../utils/gif-lib.js";import{validateKey as b,setKey as y}from"../utils/validate-key.js";import*as v from"../utils/fonts.js";import{flags as P}from"../utils/flags.js";import{addDpiMetadataToImage as w}from"../utils/image-dpi.js";import{nodeToCanvas as E}from"../utils/canvas.js";import{whenLoaded as x}from"../utils/loader.js";import{polotnoError as I}from"../utils/errors.js";import{pxToUnit as T}from"../utils/unit.js";import{deepEqual as _}from"../utils/deep-equal.js";import{waitTillAvailable as O}from"../utils/wait.js";import{jsonToHTML as k}from"../utils/to-html.js";import{jsonToSVG as S}from"../utils/to-svg.js";import{Page as j}from"./page-model.js";import{forEveryChild as R,forEveryNode as F}from"./group-model.js";import{Audio as A}from"./audio-model.js";r("ignore");export const Font=l.model("Font",{fontFamily:l.string,url:l.optional(l.string,""),styles:l.frozen()}).preProcessSnapshot(e=>Object.assign(Object.assign({},e),{fontFamily:e.fontFamily||e.name}));export const ROLES={ADMIN:"admin",VIEWER:"viewer"};export const Store=l.model("Store",{role:"",pages:l.array(j),fonts:l.array(Font),audios:l.array(A),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:l.optional(l.enumeration("UnitType",["pt","mm","cm","in","px"]),"px"),dpi:72,schemaVersion:4,bleedVisible:!1,rulesVisible:!1,distanceGuidesVisible:!1,timingPreview:l.optional(l.enumeration("TimingPreview",["all","playhead"]),"all"),openedSidePanel:"",previousOpenedSidePanel:"",custom:l.frozen(),tool:l.optional(l.enumeration("Tool",["selection","draw","pan","text","eraser"]),"selection"),toolOptions:l.optional(l.model({brushType:l.optional(l.enumeration("BrushType",["brush","highlighter"]),"brush"),strokeWidth:l.optional(l.number,5),stroke:l.optional(l.string,"#000000"),opacity:l.optional(l.number,1)}),{}),selectedElementsIds:l.array(l.string),animatedElementsIds:l.array(l.string),history:l.optional(d,{targetPath:"../pages"}),_elementsPixelRatio:Math.min(2,"undefined"!=typeof window&&window.devicePixelRatio||1),_activePageId:"",_selectedPagesIds:l.array(l.string),_forceShowCredit:!1,_validated:!1}).views(e=>{const t=g(()=>{const t={};return F({children:e.pages},e=>(t[e.id]=e,!1)),t},{keepAlive:!0});return{get _idsMap(){return t.get()}}}).views(e=>({get _bleedVisible(){return console.warn("store._bleedVisible is deprecated. Please use store.bleedVisible instead."),e.bleedVisible},get selectedElements(){return e.selectedElementsIds.map(t=>e._idsMap[t]).filter(e=>!!e)},get children(){return e.pages},get selectedShapes(){const e=[];return R({children:this.selectedElements},t=>{"group"!==t.type&&e.push(t)}),e},get activePage(){return e.pages.slice().find(t=>t.id===e._activePageId)||(e.pages.length?e.pages[0]:null)},get selectedPages(){return e._selectedPagesIds.map(t=>e.pages.find(e=>e.id===t))},get duration(){let t=0;return e.pages.forEach(e=>{t+=e.duration}),t},pageAtTime(t){for(const i of e.pages){if(t>=i.startTime&&t<i.startTime+i.duration){return i}}return e.pages.length&&t>=this.duration?e.pages[e.pages.length-1]:null},get effectiveTime(){if(e.isPlaying){return e.currentTime}const t=this.activePage;return t&&this.pageAtTime(e.currentTime)!==t?t.startTime:e.currentTime},get playheadAccurate(){return e.isPlaying||"playhead"===e.timingPreview},get isEditingPaused(){var t;return!e.isPlaying&&!(null===(t=this.activePage)||void 0===t?void 0:t._exportingOrRendering)},get _hasCroppedImages(){return this.find(e=>"image"===e.type&&e._cropModeEnabled)},find(t){let i;return F({children:e.pages},e=>{if(!i&&t(e)){return i=e,!0}}),i},getElementById:t=>e._idsMap[t]})).actions(r=>{let l=0,d=null,g=!1;const y={afterCreate(){r.history.canUndo},setCurrentTime(e){r.currentTime=e},_togglePlaying(e=!r.isPlaying){r.isPlaying=e},play({animatedElementsIds:e=[],startTime:t=0,currentTime:o=0,endTime:n=r.duration,repeat:a=!1}={}){o&&(console.warn("currentTime property of store.play() is deprecated. Please use startTime instead."),t=o),r.animatedElementsIds=i(e),r.currentTime=t,r.isPlaying=!0,l=Date.now(),d=n,g=a,requestAnimationFrame(()=>y.seek())},checkActivePage(){const e=r.pageAtTime(r.currentTime);e&&y.selectPage(e.id)},seek(){if(!r.isPlaying){return}const e=Date.now(),t=e-l;l=e,r.currentTime+=t;const i=d||r.duration;r.currentTime>=i&&!g&&(r.currentTime=i),y.checkActivePage(),r.isPlaying&&r.currentTime<i?requestAnimationFrame(()=>y.seek()):r.isPlaying&&g?(r.currentTime=0,requestAnimationFrame(()=>y.seek())):y.pause()},pause(){r.isPlaying=!1,r.animatedElementsIds=i([])},stop(){y.pause(),r.currentTime=0,y.checkActivePage()},__(){r._validated||(b(r._forceShowCredit),r._validated=!0)},set(e){Object.assign(r,e)},setUnit({unit:e,dpi:t}){r.unit=e||r.unit,r.dpi=t||r.dpi},setRole(e){r.role=e},setTool(e){r.tool=e},setToolOptions(e){Object.assign(r.toolOptions,e)},addPage(e){const t=j.create(Object.assign({id:p(10)},e));return r.pages.push(t),r._activePageId=t.id,t},selectPage(e){r._activePageId=e,1===r._selectedPagesIds.length&&(r._selectedPagesIds=i([e]))},selectPages(e){r._selectedPagesIds=i(e),1===r._selectedPagesIds.length&&(r._activePageId=r._selectedPagesIds[0])},selectElements(e){const t=e.map(e=>r.getElementById(e)).filter(e=>!!e);t.sort((e,t)=>{var i,o,n,a;return(null!==(o=null===(i=e.parent)||void 0===i?void 0:i.children.indexOf(e))&&void 0!==o?o:0)-(null!==(a=null===(n=t.parent)||void 0===n?void 0:n.children.indexOf(t))&&void 0!==a?a:0)}),r.selectedElementsIds=i(t.map(e=>e.id))},toggleBleed(e){r.bleedVisible=null!=e?e:!r.bleedVisible},toggleRulers(e){r.rulesVisible=null!=e?e:!r.rulesVisible},setTimingPreview(e){r.timingPreview=e},toggleDistanceGuides(e){r.distanceGuidesVisible=null!=e?e:!r.distanceGuidesVisible},openSidePanel(e){r.openedSidePanel!==e&&(r.previousOpenedSidePanel=r.openedSidePanel,r.openedSidePanel=e)},restoreSidePanel(){const e=r.previousOpenedSidePanel;e&&e!==r.openedSidePanel?r.openedSidePanel=e:r.openedSidePanel="photos"},setScale(e){r.scale=e},_setScaleToFit(e){r.scaleToFit=e},setElementsPixelRatio(e){r._elementsPixelRatio=e},setSize(e,t,i){r.pages.forEach(o=>{o.setSize({width:e,height:t,useMagic:i,softChange:!0})}),r.width=e,r.height=t},setPageZIndex(e,t){const i=r.pages.find(t=>t.id===e);i&&(n(i),r.pages.remove(i),r.pages.splice(t,0,i))},deletePages(e){const t=r.pages.indexOf(r.activePage);e.forEach(e=>{const t=r.pages.find(t=>t.id===e);o(t)});const n=Math.min(r.pages.length-1,t),a=r.pages[n];a&&(r._activePageId=a.id),r.selectedElementsIds=i(r.selectedElementsIds.filter(e=>r.getElementById(e)))},groupElements(e,t={}){const o=e.map(e=>r.getElementById(e)).filter(e=>!!e);if(!o.length){return}const a=o[0].parent;if(!a){return}if(!o.every(e=>e.parent===a)){return void console.warn("store.groupElements: refusing to group elements that do not share a parent. Pass ids whose elements all live under the same page or the same group.")}o.forEach(e=>n(e));const s=a.children.reduce((e,t)=>{var i;if("group"===t.type){const o=null===(i=t.name)||void 0===i?void 0:i.match(/group-(\d+)/);if(o){const t=parseInt(o[1],10);return Math.max(e,t)}}return e},0),l=Object.assign({id:p(10),name:`group-${s+1}`,children:o,type:"group"},t);return a.children.push(l),r.selectedElementsIds=i([l.id]),a.children.find(e=>e.id===l.id)},ungroupElements(e){const t=e.map(e=>r.getElementById(e)),o=[];t.forEach(e=>{if(e&&"group"===e.type){const t=e.parent;if(!t){return}const i=t.children.indexOf(e);e.children.forEach(e=>{o.push(e.id)}),e.children.slice().forEach(e=>{n(e),t.children.push(e)}),t.children.splice(i,1)}}),r.selectedElementsIds=i(o)},deleteElements(e){const t=[];r.find(i=>(e.includes(i.id)&&t.push(i),!1)),t.forEach(e=>{o(e)}),r.selectedElementsIds=i(r.selectedElementsIds.filter(e=>r.getElementById(e)))},on(e,t){if("change"===e){let e=y.toJSON();return s(r,i=>{const o=y.toJSON();!_(e,o)&&(e=o,t(o))})}},async _toCanvas({pixelRatio:e,ignoreBackground:t,pageId:i,mimeType:o,includeBleed:n,_skipTimeout:a,quickMode:s=!1,_exportCanvases:l}={}){var d;const p=e||1;i=i||(null===(d=r.pages[0])||void 0===d?void 0:d.id);const g=r.pages.find(e=>e.id===i);if(!g){throw I("EXPORT_FAILED",`No page for export with id ${i}`,{reason:"page-not-found",pageId:i,availablePageIds:r.pages.map(e=>e.id)})}const u=r._elementsPixelRatio;p>r._elementsPixelRatio&&y.setElementsPixelRatio(p),s?null==g||g.set({_forceMount:!0}):null==g||g.set({_exporting:!0});const f=await O(()=>{const e=c.stages.filter(e=>e.getAttr("pageId")===i);return 0===e.length?null:e});if(!f){throw null==g||g.set({_forceMount:!1,_exporting:!1}),y.setElementsPixelRatio(u),I("EXPORT_FAILED",`Export is failed. Can not find stage for page ${i}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`,{reason:"workspace-not-mounted",pageId:i})}f.length>1&&console.error(`Polotno error: Detected several canvas elements for page "${i}" in the document. This is not supported and will lead to incorrect export. Make sure to use unique ids for all pages and make sure you unmount <Workspace /> when it is not needed.`);const h=f[0];await y.waitLoading({_skipTimeout:a});const b=h.findOne(".page-container");if(!b){throw y.setElementsPixelRatio(u),null==g||g.set({_forceMount:!1,_exporting:!1}),I("EXPORT_FAILED","Export is failed. Canvas was unmounted.",{reason:"unmounted-during-export",pageId:i})}const v=h.position();h.position({x:0,y:0}),h.find("Transformer").forEach(e=>{e.setAttr("oldVisible",e.visible()),e.visible(!1)}),b.find(".page-background").forEach(e=>e.shadowEnabled(!1)),b.find(".page-background").forEach(e=>e.strokeEnabled(!1)),b.find(".highlighter").forEach(e=>e.visible(!1));const P=b.findOne(".page-background-group"),w=P.clip();P.clip({x:null,y:null,width:null,height:null});const x=b.findOne(".elements-container"),T=x.clip();x.clip({x:null,y:null,width:null,height:null});const _=b.find(e=>!e.visible()&&e.getAttr("editModeEnabled")&&!e.getAttr("hideInExport"));_.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.show()});const k=b.find(e=>e.getAttr("hideInExport"));k.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.hide()}),t&&b.find(".page-background").forEach(e=>e.hide());const S=n?g.computedBleed:m;let j=S.left,R=S.top;!r.bleedVisible&&n||(r.bleedVisible||n?r.bleedVisible&&n?(j=0,R=0):r.bleedVisible&&!n&&(j=-g.computedBleed.left,R=-g.computedBleed.top):(j=0,R=0));const F=g.computedWidth+S.left+S.right,A=g.computedHeight+S.top+S.bottom,C=b.scale();b.scale({x:1,y:1});const V=E(b,{x:b.x()-j,y:b.y()-R,width:F,height:A,pixelRatio:p,sceneCanvas:null==l?void 0:l.sceneCanvas,bufferCanvas:null==l?void 0:l.bufferCanvas});b.scale(C);const L=V._canvas;if("image/jpeg"===o){const e=L.getContext("2d");e.save(),e.globalCompositeOperation="destination-over",e.fillStyle="white",e.fillRect(0,0,L.width,L.height),e.restore()}return t&&b.find(".page-background").forEach(e=>e.show()),k.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),_.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),b.find(".page-background").forEach(e=>e.shadowEnabled(!0)),b.find(".page-background").forEach(e=>e.strokeEnabled(!0)),h.find("Transformer").forEach(e=>{e.visible(e.getAttr("oldVisible"))}),b.find(".highlighter").forEach(e=>e.visible(!0)),P.clip(w),x.clip(T),h.position(v),null==g||g.set({_exporting:!1,_forceMount:!1}),await Promise.resolve(),y.setElementsPixelRatio(u),L},async toDataURL(t={}){var{mimeType:i,quality:o,dpi:n,dpiMetadata:a="auto"}=t,s=e(t,["mimeType","quality","dpi","dpiMetadata"]);const l=await y._toCanvas(Object.assign({mimeType:i},s)),d=i||"image/png",p=l.toDataURL(d,o);c.Util.releaseCanvas(l);const g=null!=n?n:r.dpi;return"image/png"!==d&&"image/jpeg"!==d||"never"===a||"auto"===a&&72===g?p:w(p,d,g)},async toBlob(t={}){var{mimeType:i,quality:o}=t,n=e(t,["mimeType","quality"]);const a=await y._toCanvas(Object.assign({mimeType:i},n)),s=await new Promise(e=>{a.toBlob(e,i,o)});return c.Util.releaseCanvas(a),s},async saveAsImage(t={}){var{fileName:i}=t,o=e(t,["fileName"]);const n=(o.mimeType||"image/png").split("/")[1];u(await y.toDataURL(o),i||"polotno."+n)},async _toPDF(e){const t=e.dpi||r.dpi,i=e.parallel||1,o=e.unit||("px"===r.unit?"mm":r.unit),n=e.pixelRatio||1,a=e.pageIds||(e.pageId?[e.pageId]:r.pages.map(e=>e.id)),s=r.pages.filter(e=>a.includes(e.id)),l=await f(),d=e=>T({px:e,unit:o,dpi:t}),p=e.cropMarkSize||0,c=d(p),g=s[0]||{},u=e.includeBleed&&g.computedBleed||m,h=d(g.computedWidth+u.left+u.right+2*c),b=d(g.computedHeight+u.top+u.bottom+2*c);var v=new l({unit:o,orientation:h>b?"landscape":"portrait",format:[h,b],compress:!0,putOnlyUsedFonts:!0});v.deletePage(1);const P=((e,t)=>{const i=[];for(let o=0;o<e.length;o+=t){i.push(e.slice(o,o+t))}return i})(s,i);let w=0;for(const r of P){const t=r.map(async t=>{const i=e.includeBleed?t.computedBleed:m,o=t.computedWidth+i.left+i.right+2*p,s=t.computedHeight+i.top+i.bottom+2*p,r=d(o),l=d(s);let c=0,g=n;for(;c<10;){c+=1;const d=await y.toDataURL(Object.assign(Object.assign({},e),{pageId:t.id,pixelRatio:g,dpiMetadata:"never"}));if(d.length>20){return g!==n&&console.error(`Polotno can not export PDF with current settings. Quality is automatically reduced. pixelRatio was reduced to ${parseFloat(g.toFixed(3))}.`),e.onProgress&&e.onProgress(++w/a.length*.9),{url:d,width:r,height:l,widthPx:o,heightPx:s,cb:i}}g*=.8}});(await Promise.all(t)).filter(e=>void 0!==e).forEach(({url:e,width:t,height:i,widthPx:n,heightPx:a,cb:s})=>{v.addPage([t,i],t>i?"landscape":"portrait");const r=v.getCurrentPageInfo();var l;switch(o){case"pt":l=1;break;case"mm":l=72/25.4;break;case"cm":l=72/2.54;break;case"in":l=72;break;case"px":l=.75;break;default:throw I("EXPORT_FAILED","Invalid unit: "+o,{reason:"invalid-options",option:"unit",value:o})}if(r.pageContext.cropBox={bottomLeftX:0,bottomLeftY:0,topRightX:t*l,topRightY:i*l},r.pageContext.artBox={bottomLeftX:d(p+s.left)*l,bottomLeftY:d(p+s.bottom)*l,topRightX:d(n-p-s.right)*l,topRightY:d(a-p-s.top)*l},r.pageContext.bleedBox={bottomLeftX:d(p+s.left)*l,bottomLeftY:d(p+s.bottom)*l,topRightX:d(n-p-s.right)*l,topRightY:d(a-p-s.top)*l},c){v.setLineWidth(d(1));const e=c+d(s.left),o=c+d(s.right),n=c+d(s.top),a=c+d(s.bottom);v.line(e,0,e,c),v.line(0,n,c,n),v.line(t-o,0,t-o,c),v.line(t,n,t-c,n),v.line(0,i-a,c,i-a),v.line(e,i,e,i-c),v.line(t,i-a,t-c,i-a),v.line(t-o,i,t-o,i-c)}v.addImage(e,c,c,t-2*c,i-2*c,void 0,"FAST")})}return v},toPDFDataURL:async e=>(await y._toPDF(Object.assign({mimeType:"image/jpeg"},e))).output("datauristring"),async toGIFDataURL(e={}){const t=e.pixelRatio||1,i=e.pageIds||(e.pageId?[e.pageId]:r.pages.map(e=>e.id)),o=r.pages.filter(e=>i.includes(e.id));if(!o.length){throw I("EXPORT_FAILED","No pages found for GIF export",{reason:"page-not-found",pageId:e.pageId,availablePageIds:r.pages.map(e=>e.id)})}const n=o[0],a=await h({width:n.computedWidth*t,height:n.computedHeight*t}),s=1e3/(e.fps||10);for(const l of o){const e=Math.max(1,Math.floor(l.duration/s));for(let i=0;i<e;i++){const e=l.startTime+i*s||1;y.setCurrentTime(e);for(const t of r.pages){t.set({_rendering:t.id===l.id})}const o=await y._toCanvas({pixelRatio:t,pageId:l.id,_skipTimeout:!0});a.addFrame(o.getContext("2d"),{delay:s,copy:!0})}}for(const l of r.pages){l.set({_rendering:!1})}return y.stop(),a.render(),new Promise(e=>{a.on("finished",function(t){!function(e,t){var i=new FileReader;i.onload=function(e){t(e.target.result)},i.readAsDataURL(e)}(t,e)})})},async saveAsGIF(t={}){var{fileName:i}=t,o=e(t,["fileName"]);const n=await y.toGIFDataURL(o);u(n,i||"polotno.gif")},async toHTML({elementHook:e}={}){const t=y.toJSON();return k({json:t,elementHook:e})},async saveAsHTML({fileName:e,elementHook:t}={}){const i=await y.toHTML({elementHook:t}),o="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(i)));u(o,e||"polotno.html")},async toSVG({elementHook:e,pageId:t,fontEmbedding:i="inline"}={fontEmbedding:"inline"}){var o;const n=y.toJSON();t=t||(null===(o=n.pages[0])||void 0===o?void 0:o.id);const a=n.pages.find(e=>e.id===t);return S({json:Object.assign(Object.assign({},n),{pages:a?[a]:[]}),elementHook:e,fontEmbedding:i})},async saveAsSVG({fileName:e,elementHook:t,pageId:i,fontEmbedding:o="inline"}={}){const n=await y.toSVG({elementHook:t,pageId:i,fontEmbedding:o}),a="data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(n)));u(a,e||"polotno.svg")},async saveAsPDF(t={}){var{fileName:i}=t,o=e(t,["fileName"]);(await y._toPDF(Object.assign({mimeType:"image/jpeg"},o))).save(i||"polotno.pdf")},async waitLoading({_skipTimeout:e=!1}={}){e||await new Promise(e=>setTimeout(e,50)),await x()},toJSON:()=>({width:r.width,height:r.height,fonts:a(r.fonts),pages:a(r.pages),audios:a(r.audios),unit:r.unit,dpi:r.dpi,custom:r.custom,schemaVersion:r.schemaVersion}),loadJSON(e,i=!1){var o,n,s;const l="boolean"==typeof i?i:null!==(o=null==i?void 0:i.keepHistory)&&void 0!==o&&o,d="boolean"!=typeof i&&null!==(n=null==i?void 0:i.modernizeTextBackground)&&void 0!==n&&n,p=JSON.parse(JSON.stringify(e)),c=p.schemaVersion||0;c<1&&(P.htmlRenderEnabled||P.renderTagTextEnabled)&&F({children:p.pages},e=>{if("text"===e.type){const t=16,i=e.letterSpacing*t;e.letterSpacing=i/e.fontSize}}),c<2&&F({children:p.pages},e=>{e.filters&&Object.keys(e.filters).forEach(t=>{if(["warm","cold","natural"].includes(t)){return}const i=e.filters[t];i&&"number"==typeof i.intensity&&(i.intensity=i.intensity/100)})}),c<3&&(P.htmlRenderEnabled||P.renderTagTextEnabled)&&!d&&F({children:p.pages},e=>{"text"===e.type&&e.backgroundEnabled&&(e.legacyBackground=!0)}),delete p.schemaVersion;const g=r.activePage?r.pages.indexOf(r.activePage):0;let m=null===(s=p.pages[g]||p.pages[0])||void 0===s?void 0:s.id;p._activePageId=m;const u=Object.assign({},a(r));Object.assign(u,p),u.history=l?a(r.history):{history:[],undoIdx:-1,targetPath:""},t(r,u)},clear({keepHistory:e=!1}={}){const t=r.pages.map(e=>e.id);y.deletePages(t),r.custom=null,e||r.history.clear()},addFont(e){y.removeFont(e.fontFamily),r.fonts.push(e)},removeFont(e){r.fonts.filter(t=>t.fontFamily===e).forEach(e=>o(e))},addAudio(e){const t=A.create(Object.assign({id:p(10)},e));r.audios.push(t)},removeAudio(e){const t=r.audios.find(t=>t.id===e);t&&r.audios.remove(t)},async loadFont(e,t,i,o){const n=r.fonts.find(t=>t.fontFamily===e)||v.globalFonts.find(t=>t.fontFamily===e);let a=[{fontStyle:"normal",fontWeight:"normal"},{fontStyle:"normal",fontWeight:"bold"}];return n?(n.styles&&(a=n.styles.map(e=>({fontStyle:e.fontStyle||"normal",fontWeight:e.fontWeight||"normal"}))),v.injectCustomFont(n)):v.injectGoogleFont(e),t&&i&&!a.some(e=>e.fontStyle===t&&e.fontWeight===i)&&a.push({fontStyle:t,fontWeight:i}),Promise.all(a.map(t=>v.loadFont(e,t.fontStyle,t.fontWeight,o)))},validate:e=>Store.validate(e,[{path:"",type:Store}]).map(e=>({path:"store"+e.context.map(e=>e.path).join("."),message:e.message}))};return y});export function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){return y(e),Store.create({_forceShowCredit:t})}export default createStore;
1
+ var e=this&&this.__rest||function(e,t){var i={};for(var o in e){Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(i[o]=e[o])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(e);n<o.length;n++){t.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(e,o[n])&&(i[o[n]]=e[o[n]])}}return i};import{applySnapshot as t,cast as i,destroy as o,detach as n,getSnapshot as a,onSnapshot as s,setLivelinessChecking as r,types as l}from"mobx-state-tree";import{UndoManager as d}from"./history.js";import{nanoid as p}from"nanoid";import c from"konva";import{computed as g}from"mobx";import{ZERO_BLEED as m}from"@polotno/schema";import{downloadFile as u}from"../utils/download.js";import{getJsPDF as f}from"../utils/pdf.js";import{createGIF as h}from"../utils/gif-lib.js";import{validateKey as b,setKey as v}from"../utils/validate-key.js";import*as y from"../utils/fonts.js";import{flags as P}from"../utils/flags.js";import{addDpiMetadataToImage as w}from"../utils/image-dpi.js";import{nodeToCanvas as x}from"../utils/canvas.js";import{whenLoaded as E}from"../utils/loader.js";import{polotnoError as I}from"@polotno/core/errors";import{pxToUnit as T}from"../utils/unit.js";import{deepEqual as _}from"../utils/deep-equal.js";import{waitTillAvailable as S}from"../utils/wait.js";import{jsonToHTML as O}from"@polotno/html-export";import{jsonToSVG as k}from"@polotno/svg-export";import{warnOnceDeprecated as j}from"../utils/deprecation.js";import{Page as R}from"./page-model.js";import{forEveryChild as F,forEveryNode as A}from"./group-model.js";import{Audio as V}from"./audio-model.js";r("ignore");export const Font=l.model("Font",{fontFamily:l.string,url:l.optional(l.string,""),styles:l.frozen()}).preProcessSnapshot(e=>Object.assign(Object.assign({},e),{fontFamily:e.fontFamily||e.name}));export const ROLES={ADMIN:"admin",VIEWER:"viewer"};export const Store=l.model("Store",{role:"",pages:l.array(R),fonts:l.array(Font),audios:l.array(V),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:l.optional(l.enumeration("UnitType",["pt","mm","cm","in","px"]),"px"),dpi:72,schemaVersion:4,bleedVisible:!1,rulesVisible:!1,distanceGuidesVisible:!1,timingPreview:l.optional(l.enumeration("TimingPreview",["all","playhead"]),"all"),openedSidePanel:"",previousOpenedSidePanel:"",custom:l.frozen(),tool:l.optional(l.enumeration("Tool",["selection","draw","pan","text","eraser"]),"selection"),toolOptions:l.optional(l.model({brushType:l.optional(l.enumeration("BrushType",["brush","highlighter"]),"brush"),strokeWidth:l.optional(l.number,5),stroke:l.optional(l.string,"#000000"),opacity:l.optional(l.number,1)}),{}),selectedElementsIds:l.array(l.string),animatedElementsIds:l.array(l.string),history:l.optional(d,{targetPath:"../pages"}),_elementsPixelRatio:Math.min(2,"undefined"!=typeof window&&window.devicePixelRatio||1),_activePageId:"",_selectedPagesIds:l.array(l.string),_forceShowCredit:!1,_validated:!1}).views(e=>{const t=g(()=>{const t={};return A({children:e.pages},e=>(t[e.id]=e,!1)),t},{keepAlive:!0});return{get _idsMap(){return t.get()}}}).views(e=>({get _bleedVisible(){return console.warn("store._bleedVisible is deprecated. Please use store.bleedVisible instead."),e.bleedVisible},get selectedElements(){return e.selectedElementsIds.map(t=>e._idsMap[t]).filter(e=>!!e)},get children(){return e.pages},get selectedShapes(){const e=[];return F({children:this.selectedElements},t=>{"group"!==t.type&&e.push(t)}),e},get activePage(){return e.pages.slice().find(t=>t.id===e._activePageId)||(e.pages.length?e.pages[0]:null)},get selectedPages(){return e._selectedPagesIds.map(t=>e.pages.find(e=>e.id===t))},get duration(){let t=0;return e.pages.forEach(e=>{t+=e.duration}),t},pageAtTime(t){for(const i of e.pages){if(t>=i.startTime&&t<i.startTime+i.duration){return i}}return e.pages.length&&t>=this.duration?e.pages[e.pages.length-1]:null},get effectiveTime(){if(e.isPlaying){return e.currentTime}const t=this.activePage;return t&&this.pageAtTime(e.currentTime)!==t?t.startTime:e.currentTime},get playheadAccurate(){return e.isPlaying||"playhead"===e.timingPreview},get isEditingPaused(){var t;return!e.isPlaying&&!(null===(t=this.activePage)||void 0===t?void 0:t._exportingOrRendering)},get _hasCroppedImages(){return this.find(e=>"image"===e.type&&e._cropModeEnabled)},find(t){let i;return A({children:e.pages},e=>{if(!i&&t(e)){return i=e,!0}}),i},getElementById:t=>e._idsMap[t]})).actions(r=>{let l=0,d=null,g=!1;const v={afterCreate(){r.history.canUndo},setCurrentTime(e){r.currentTime=e},_togglePlaying(e=!r.isPlaying){r.isPlaying=e},play({animatedElementsIds:e=[],startTime:t=0,currentTime:o=0,endTime:n=r.duration,repeat:a=!1}={}){o&&(console.warn("currentTime property of store.play() is deprecated. Please use startTime instead."),t=o),r.animatedElementsIds=i(e),r.currentTime=t,r.isPlaying=!0,l=Date.now(),d=n,g=a,requestAnimationFrame(()=>v.seek())},checkActivePage(){const e=r.pageAtTime(r.currentTime);e&&v.selectPage(e.id)},seek(){if(!r.isPlaying){return}const e=Date.now(),t=e-l;l=e,r.currentTime+=t;const i=d||r.duration;r.currentTime>=i&&!g&&(r.currentTime=i),v.checkActivePage(),r.isPlaying&&r.currentTime<i?requestAnimationFrame(()=>v.seek()):r.isPlaying&&g?(r.currentTime=0,requestAnimationFrame(()=>v.seek())):v.pause()},pause(){r.isPlaying=!1,r.animatedElementsIds=i([])},stop(){v.pause(),r.currentTime=0,v.checkActivePage()},__(){r._validated||(b(r._forceShowCredit),r._validated=!0)},set(e){Object.assign(r,e)},setUnit({unit:e,dpi:t}){r.unit=e||r.unit,r.dpi=t||r.dpi},setRole(e){r.role=e},setTool(e){r.tool=e},setToolOptions(e){Object.assign(r.toolOptions,e)},addPage(e){const t=R.create(Object.assign({id:p(10)},e));return r.pages.push(t),r._activePageId=t.id,t},selectPage(e){r._activePageId=e,1===r._selectedPagesIds.length&&(r._selectedPagesIds=i([e]))},selectPages(e){r._selectedPagesIds=i(e),1===r._selectedPagesIds.length&&(r._activePageId=r._selectedPagesIds[0])},selectElements(e){const t=e.map(e=>r.getElementById(e)).filter(e=>!!e);t.sort((e,t)=>{var i,o,n,a;return(null!==(o=null===(i=e.parent)||void 0===i?void 0:i.children.indexOf(e))&&void 0!==o?o:0)-(null!==(a=null===(n=t.parent)||void 0===n?void 0:n.children.indexOf(t))&&void 0!==a?a:0)}),r.selectedElementsIds=i(t.map(e=>e.id))},toggleBleed(e){r.bleedVisible=null!=e?e:!r.bleedVisible},toggleRulers(e){r.rulesVisible=null!=e?e:!r.rulesVisible},setTimingPreview(e){r.timingPreview=e},toggleDistanceGuides(e){r.distanceGuidesVisible=null!=e?e:!r.distanceGuidesVisible},openSidePanel(e){r.openedSidePanel!==e&&(r.previousOpenedSidePanel=r.openedSidePanel,r.openedSidePanel=e)},restoreSidePanel(){const e=r.previousOpenedSidePanel;e&&e!==r.openedSidePanel?r.openedSidePanel=e:r.openedSidePanel="photos"},setScale(e){r.scale=e},_setScaleToFit(e){r.scaleToFit=e},setElementsPixelRatio(e){r._elementsPixelRatio=e},setSize(e,t,i){r.pages.forEach(o=>{o.setSize({width:e,height:t,useMagic:i,softChange:!0})}),r.width=e,r.height=t},setPageZIndex(e,t){const i=r.pages.find(t=>t.id===e);i&&(n(i),r.pages.remove(i),r.pages.splice(t,0,i))},deletePages(e){const t=r.pages.indexOf(r.activePage);e.forEach(e=>{const t=r.pages.find(t=>t.id===e);o(t)});const n=Math.min(r.pages.length-1,t),a=r.pages[n];a&&(r._activePageId=a.id),r.selectedElementsIds=i(r.selectedElementsIds.filter(e=>r.getElementById(e)))},groupElements(e,t={}){const o=e.map(e=>r.getElementById(e)).filter(e=>!!e);if(!o.length){return}const a=o[0].parent;if(!a){return}if(!o.every(e=>e.parent===a)){return void console.warn("store.groupElements: refusing to group elements that do not share a parent. Pass ids whose elements all live under the same page or the same group.")}o.forEach(e=>n(e));const s=a.children.reduce((e,t)=>{var i;if("group"===t.type){const o=null===(i=t.name)||void 0===i?void 0:i.match(/group-(\d+)/);if(o){const t=parseInt(o[1],10);return Math.max(e,t)}}return e},0),l=Object.assign({id:p(10),name:`group-${s+1}`,children:o,type:"group"},t);return a.children.push(l),r.selectedElementsIds=i([l.id]),a.children.find(e=>e.id===l.id)},ungroupElements(e){const t=e.map(e=>r.getElementById(e)),o=[];t.forEach(e=>{if(e&&"group"===e.type){const t=e.parent;if(!t){return}const i=t.children.indexOf(e);e.children.forEach(e=>{o.push(e.id)}),e.children.slice().forEach(e=>{n(e),t.children.push(e)}),t.children.splice(i,1)}}),r.selectedElementsIds=i(o)},deleteElements(e){const t=[];r.find(i=>(e.includes(i.id)&&t.push(i),!1)),t.forEach(e=>{o(e)}),r.selectedElementsIds=i(r.selectedElementsIds.filter(e=>r.getElementById(e)))},on(e,t){if("change"===e){let e=v.toJSON();return s(r,i=>{const o=v.toJSON();!_(e,o)&&(e=o,t(o))})}},async _toCanvas({pixelRatio:e,ignoreBackground:t,pageId:i,mimeType:o,includeBleed:n,_skipTimeout:a,quickMode:s=!1,_exportCanvases:l}={}){var d;const p=e||1;i=i||(null===(d=r.pages[0])||void 0===d?void 0:d.id);const g=r.pages.find(e=>e.id===i);if(!g){throw I("EXPORT_FAILED",`No page for export with id ${i}`,{reason:"page-not-found",pageId:i,availablePageIds:r.pages.map(e=>e.id)})}const u=r._elementsPixelRatio;p>r._elementsPixelRatio&&v.setElementsPixelRatio(p),s?null==g||g.set({_forceMount:!0}):null==g||g.set({_exporting:!0});const f=await S(()=>{const e=c.stages.filter(e=>e.getAttr("pageId")===i);return 0===e.length?null:e});if(!f){throw null==g||g.set({_forceMount:!1,_exporting:!1}),v.setElementsPixelRatio(u),I("EXPORT_FAILED",`Export is failed. Can not find stage for page ${i}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`,{reason:"workspace-not-mounted",pageId:i})}f.length>1&&console.error(`Polotno error: Detected several canvas elements for page "${i}" in the document. This is not supported and will lead to incorrect export. Make sure to use unique ids for all pages and make sure you unmount <Workspace /> when it is not needed.`);const h=f[0];await v.waitLoading({_skipTimeout:a});const b=h.findOne(".page-container");if(!b){throw v.setElementsPixelRatio(u),null==g||g.set({_forceMount:!1,_exporting:!1}),I("EXPORT_FAILED","Export is failed. Canvas was unmounted.",{reason:"unmounted-during-export",pageId:i})}const y=h.position();h.position({x:0,y:0}),h.find("Transformer").forEach(e=>{e.setAttr("oldVisible",e.visible()),e.visible(!1)}),b.find(".page-background").forEach(e=>e.shadowEnabled(!1)),b.find(".page-background").forEach(e=>e.strokeEnabled(!1)),b.find(".highlighter").forEach(e=>e.visible(!1));const P=b.findOne(".page-background-group"),w=P.clip();P.clip({x:null,y:null,width:null,height:null});const E=b.findOne(".elements-container"),T=E.clip();E.clip({x:null,y:null,width:null,height:null});const _=b.find(e=>!e.visible()&&e.getAttr("editModeEnabled")&&!e.getAttr("hideInExport"));_.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.show()});const O=b.find(e=>e.getAttr("hideInExport"));O.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.hide()}),t&&b.find(".page-background").forEach(e=>e.hide());const k=n?g.computedBleed:m;let j=k.left,R=k.top;!r.bleedVisible&&n||(r.bleedVisible||n?r.bleedVisible&&n?(j=0,R=0):r.bleedVisible&&!n&&(j=-g.computedBleed.left,R=-g.computedBleed.top):(j=0,R=0));const F=g.computedWidth+k.left+k.right,A=g.computedHeight+k.top+k.bottom,V=b.scale();b.scale({x:1,y:1});const C=x(b,{x:b.x()-j,y:b.y()-R,width:F,height:A,pixelRatio:p,sceneCanvas:null==l?void 0:l.sceneCanvas,bufferCanvas:null==l?void 0:l.bufferCanvas});b.scale(V);const L=C._canvas;if("image/jpeg"===o){const e=L.getContext("2d");e.save(),e.globalCompositeOperation="destination-over",e.fillStyle="white",e.fillRect(0,0,L.width,L.height),e.restore()}return t&&b.find(".page-background").forEach(e=>e.show()),O.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),_.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),b.find(".page-background").forEach(e=>e.shadowEnabled(!0)),b.find(".page-background").forEach(e=>e.strokeEnabled(!0)),h.find("Transformer").forEach(e=>{e.visible(e.getAttr("oldVisible"))}),b.find(".highlighter").forEach(e=>e.visible(!0)),P.clip(w),E.clip(T),h.position(y),null==g||g.set({_exporting:!1,_forceMount:!1}),await Promise.resolve(),v.setElementsPixelRatio(u),L},async toDataURL(t={}){var{mimeType:i,quality:o,dpi:n,dpiMetadata:a="auto"}=t,s=e(t,["mimeType","quality","dpi","dpiMetadata"]);const l=await v._toCanvas(Object.assign({mimeType:i},s)),d=i||"image/png",p=l.toDataURL(d,o);c.Util.releaseCanvas(l);const g=null!=n?n:r.dpi;return"image/png"!==d&&"image/jpeg"!==d||"never"===a||"auto"===a&&72===g?p:w(p,d,g)},async toBlob(t={}){var{mimeType:i,quality:o}=t,n=e(t,["mimeType","quality"]);const a=await v._toCanvas(Object.assign({mimeType:i},n)),s=await new Promise(e=>{a.toBlob(e,i,o)});return c.Util.releaseCanvas(a),s},async saveAsImage(t={}){var{fileName:i}=t,o=e(t,["fileName"]);const n=(o.mimeType||"image/png").split("/")[1];u(await v.toDataURL(o),i||"polotno."+n)},async _toPDF(e){const t=e.dpi||r.dpi,i=e.parallel||1,o=e.unit||("px"===r.unit?"mm":r.unit),n=e.pixelRatio||1,a=e.pageIds||(e.pageId?[e.pageId]:r.pages.map(e=>e.id)),s=r.pages.filter(e=>a.includes(e.id)),l=await f(),d=e=>T({px:e,unit:o,dpi:t}),p=e.cropMarkSize||0,c=d(p),g=s[0]||{},u=e.includeBleed&&g.computedBleed||m,h=d(g.computedWidth+u.left+u.right+2*c),b=d(g.computedHeight+u.top+u.bottom+2*c);var y=new l({unit:o,orientation:h>b?"landscape":"portrait",format:[h,b],compress:!0,putOnlyUsedFonts:!0});y.deletePage(1);const P=((e,t)=>{const i=[];for(let o=0;o<e.length;o+=t){i.push(e.slice(o,o+t))}return i})(s,i);let w=0;for(const r of P){const t=r.map(async t=>{const i=e.includeBleed?t.computedBleed:m,o=t.computedWidth+i.left+i.right+2*p,s=t.computedHeight+i.top+i.bottom+2*p,r=d(o),l=d(s);let c=0,g=n;for(;c<10;){c+=1;const d=await v.toDataURL(Object.assign(Object.assign({},e),{pageId:t.id,pixelRatio:g,dpiMetadata:"never"}));if(d.length>20){return g!==n&&console.error(`Polotno can not export PDF with current settings. Quality is automatically reduced. pixelRatio was reduced to ${parseFloat(g.toFixed(3))}.`),e.onProgress&&e.onProgress(++w/a.length*.9),{url:d,width:r,height:l,widthPx:o,heightPx:s,cb:i}}g*=.8}});(await Promise.all(t)).filter(e=>void 0!==e).forEach(({url:e,width:t,height:i,widthPx:n,heightPx:a,cb:s})=>{y.addPage([t,i],t>i?"landscape":"portrait");const r=y.getCurrentPageInfo();var l;switch(o){case"pt":l=1;break;case"mm":l=72/25.4;break;case"cm":l=72/2.54;break;case"in":l=72;break;case"px":l=.75;break;default:throw I("EXPORT_FAILED","Invalid unit: "+o,{reason:"invalid-options",option:"unit",value:o})}if(r.pageContext.cropBox={bottomLeftX:0,bottomLeftY:0,topRightX:t*l,topRightY:i*l},r.pageContext.artBox={bottomLeftX:d(p+s.left)*l,bottomLeftY:d(p+s.bottom)*l,topRightX:d(n-p-s.right)*l,topRightY:d(a-p-s.top)*l},r.pageContext.bleedBox={bottomLeftX:d(p+s.left)*l,bottomLeftY:d(p+s.bottom)*l,topRightX:d(n-p-s.right)*l,topRightY:d(a-p-s.top)*l},c){y.setLineWidth(d(1));const e=c+d(s.left),o=c+d(s.right),n=c+d(s.top),a=c+d(s.bottom);y.line(e,0,e,c),y.line(0,n,c,n),y.line(t-o,0,t-o,c),y.line(t,n,t-c,n),y.line(0,i-a,c,i-a),y.line(e,i,e,i-c),y.line(t,i-a,t-c,i-a),y.line(t-o,i,t-o,i-c)}y.addImage(e,c,c,t-2*c,i-2*c,void 0,"FAST")})}return y},toPDFDataURL:async e=>(await v._toPDF(Object.assign({mimeType:"image/jpeg"},e))).output("datauristring"),async toGIFDataURL(e={}){const t=e.pixelRatio||1,i=e.pageIds||(e.pageId?[e.pageId]:r.pages.map(e=>e.id)),o=r.pages.filter(e=>i.includes(e.id));if(!o.length){throw I("EXPORT_FAILED","No pages found for GIF export",{reason:"page-not-found",pageId:e.pageId,availablePageIds:r.pages.map(e=>e.id)})}const n=o[0],a=await h({width:n.computedWidth*t,height:n.computedHeight*t}),s=1e3/(e.fps||10);for(const l of o){const e=Math.max(1,Math.floor(l.duration/s));for(let i=0;i<e;i++){const e=l.startTime+i*s||1;v.setCurrentTime(e);for(const t of r.pages){t.set({_rendering:t.id===l.id})}const o=await v._toCanvas({pixelRatio:t,pageId:l.id,_skipTimeout:!0});a.addFrame(o.getContext("2d"),{delay:s,copy:!0})}}for(const l of r.pages){l.set({_rendering:!1})}return v.stop(),a.render(),new Promise(e=>{a.on("finished",function(t){!function(e,t){var i=new FileReader;i.onload=function(e){t(e.target.result)},i.readAsDataURL(e)}(t,e)})})},async saveAsGIF(t={}){var{fileName:i}=t,o=e(t,["fileName"]);const n=await v.toGIFDataURL(o);u(n,i||"polotno.gif")},async toHTML({elementHook:e}={}){j("store.toHTML","store.toHTML()/saveAsHTML() are deprecated: install @polotno/html-export and call jsonToHTML(store.toJSON()) instead");const t=v.toJSON();return O(t,{elementHook:e,textOverflow:P.textOverflow,textSplitAllowed:P.textSplitAllowed})},async saveAsHTML({fileName:e,elementHook:t}={}){const i=await v.toHTML({elementHook:t}),o="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(i)));u(o,e||"polotno.html")},async toSVG({elementHook:e,pageId:t,fontEmbedding:i="inline"}={fontEmbedding:"inline"}){var o;j("store.toSVG","store.toSVG()/saveAsSVG() are deprecated: install @polotno/svg-export and call jsonToSVG(store.toJSON()) instead");const n=v.toJSON();t=t||(null===(o=n.pages[0])||void 0===o?void 0:o.id);const a=n.pages.find(e=>e.id===t);return k(Object.assign(Object.assign({},n),{pages:a?[a]:[]}),{elementHook:e,fontEmbedding:i})},async saveAsSVG({fileName:e,elementHook:t,pageId:i,fontEmbedding:o="inline"}={}){const n=await v.toSVG({elementHook:t,pageId:i,fontEmbedding:o}),a="data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(n)));u(a,e||"polotno.svg")},async saveAsPDF(t={}){var{fileName:i}=t,o=e(t,["fileName"]);(await v._toPDF(Object.assign({mimeType:"image/jpeg"},o))).save(i||"polotno.pdf")},async waitLoading({_skipTimeout:e=!1}={}){e||await new Promise(e=>setTimeout(e,50)),await E()},toJSON:()=>({width:r.width,height:r.height,fonts:a(r.fonts),pages:a(r.pages),audios:a(r.audios),unit:r.unit,dpi:r.dpi,custom:r.custom,schemaVersion:r.schemaVersion}),loadJSON(e,i=!1){var o,n,s;const l="boolean"==typeof i?i:null!==(o=null==i?void 0:i.keepHistory)&&void 0!==o&&o,d="boolean"!=typeof i&&null!==(n=null==i?void 0:i.modernizeTextBackground)&&void 0!==n&&n,p=JSON.parse(JSON.stringify(e)),c=p.schemaVersion||0;c<1&&(P.htmlRenderEnabled||P.renderTagTextEnabled)&&A({children:p.pages},e=>{if("text"===e.type){const t=16,i=e.letterSpacing*t;e.letterSpacing=i/e.fontSize}}),c<2&&A({children:p.pages},e=>{e.filters&&Object.keys(e.filters).forEach(t=>{if(["warm","cold","natural"].includes(t)){return}const i=e.filters[t];i&&"number"==typeof i.intensity&&(i.intensity=i.intensity/100)})}),c<3&&(P.htmlRenderEnabled||P.renderTagTextEnabled)&&!d&&A({children:p.pages},e=>{"text"===e.type&&e.backgroundEnabled&&(e.legacyBackground=!0)}),delete p.schemaVersion;const g=r.activePage?r.pages.indexOf(r.activePage):0;let m=null===(s=p.pages[g]||p.pages[0])||void 0===s?void 0:s.id;p._activePageId=m;const u=Object.assign({},a(r));Object.assign(u,p),u.history=l?a(r.history):{history:[],undoIdx:-1,targetPath:""},t(r,u)},clear({keepHistory:e=!1}={}){const t=r.pages.map(e=>e.id);v.deletePages(t),r.custom=null,e||r.history.clear()},addFont(e){v.removeFont(e.fontFamily),r.fonts.push(e)},removeFont(e){r.fonts.filter(t=>t.fontFamily===e).forEach(e=>o(e))},addAudio(e){const t=V.create(Object.assign({id:p(10)},e));r.audios.push(t)},removeAudio(e){const t=r.audios.find(t=>t.id===e);t&&r.audios.remove(t)},async loadFont(e,t,i,o){const n=r.fonts.find(t=>t.fontFamily===e)||y.globalFonts.find(t=>t.fontFamily===e);let a=[{fontStyle:"normal",fontWeight:"normal"},{fontStyle:"normal",fontWeight:"bold"}];return n?(n.styles&&(a=n.styles.map(e=>({fontStyle:e.fontStyle||"normal",fontWeight:e.fontWeight||"normal"}))),y.injectCustomFont(n)):y.injectGoogleFont(e),t&&i&&!a.some(e=>e.fontStyle===t&&e.fontWeight===i)&&a.push({fontStyle:t,fontWeight:i}),Promise.all(a.map(t=>y.loadFont(e,t.fontStyle,t.fontWeight,o)))},validate:e=>Store.validate(e,[{path:"",type:Store}]).map(e=>({path:"store"+e.context.map(e=>e.path).join("."),message:e.message}))};return v});export function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){return v(e),Store.create({_forceShowCredit:t})}export default createStore;