polotno 4.23.0 → 4.24.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.
@@ -1 +1 @@
1
- import{isAlive as e}from"mobx-state-tree";import{applyFiltersToCanvas as t,getFilterAttrs as r}from"@polotno/core/filters";import{hasPixelFilters as i}from"@polotno/core/pixel-filters";export{getEffectiveBlurRadius,getElementBlurRadius}from"@polotno/core/filters";export function getFilterAttrs(e,t={enabled:e.blurEnabled,radius:e.blurRadius}){return r(e,e.filters.entries(),t)}export function hasActiveFilters(e){return i(e,e.filters.keys())}export function applyFiltersToCanvas(r,i){e(i)&&t(r,i,i.filters.entries())}export function getFiltersDepsKey(t){if(!e(t)){return""}const r=[];return t.filters.forEach((e,t)=>{r.push(t+":"+e.intensity)}),[t.brightnessEnabled&&t.brightness,t.blurEnabled&&t.blurRadius,t.sepiaEnabled,t.grayscaleEnabled,...r].join("|")}export function applyFilter(t,r){var i;if(!t||!e(r)){return}const s={enabled:r.a.blurEnabled,radius:r.a.blurRadius},l=getFilterAttrs(r,s),n={};s.enabled&&"text"===r.type&&r.lineHeight<1&&(n.offset=r.fontSize),t.setAttrs(l),l.filters.length?t.cache(Object.assign(Object.assign({},n),{pixelRatio:r.store._elementsPixelRatio})):t.clearCache(),null===(i=t.getLayer())||void 0===i||i.batchDraw()}
1
+ import{isAlive as e}from"mobx-state-tree";import{applyFiltersToCanvas as t,getFilterAttrs as r,textFilterCacheOffset as i}from"@polotno/core/filters";import{hasPixelFilters as l}from"@polotno/core/pixel-filters";export{getEffectiveBlurRadius,getElementBlurRadius}from"@polotno/core/filters";export function getFilterAttrs(e,t={enabled:e.blurEnabled,radius:e.blurRadius}){return r(e,e.filters.entries(),t)}export function hasActiveFilters(e){return l(e,e.filters.keys())}export function applyFiltersToCanvas(r,i){e(i)&&t(r,i,i.filters.entries())}export function getFiltersDepsKey(t){if(!e(t)){return""}const r=[];return t.filters.forEach((e,t)=>{r.push(t+":"+e.intensity)}),[t.brightnessEnabled&&t.brightness,t.blurEnabled&&t.blurRadius,t.sepiaEnabled,t.grayscaleEnabled,...r].join("|")}export function applyFilter(t,r){var l;if(!t||!e(r)){return}const s={enabled:r.a.blurEnabled,radius:r.a.blurRadius},n=getFilterAttrs(r,s),a="text"===r.type?r:null,o=a?i({blurEnabled:s.enabled,blurRadius:s.radius,lineHeight:a.lineHeight,fontSize:a.fontSize}):0;t.setAttrs(n),n.filters.length?t.cache({offset:o,pixelRatio:r.store._elementsPixelRatio}):t.clearCache(),null===(l=t.getLayer())||void 0===l||l.batchDraw()}
@@ -1,4 +1,4 @@
1
- export { BAND_ROWS, drawReduced, forceDownscaleEngine, loadDownscaleKernel, planBands, setDownscaleBandRows, resampleCanvas, shouldResample, sourceSize, RESAMPLE_PIXEL_BUDGET, type AxisFilter, type DownscaleEngine, type SourceRegion, } from '@polotno/core/downscale';
1
+ export { BAND_ROWS, drawImageWindow, drawReduced, forceDownscaleEngine, loadDownscaleKernel, planBands, setDownscaleBandRows, resampleCanvas, shouldResample, sourceSize, RESAMPLE_PIXEL_BUDGET, type AxisFilter, type DownscaleEngine, type SourceRegion, } from '@polotno/core/downscale';
2
2
  export declare function exportKernelEnabled(page: {
3
3
  _exporting?: boolean;
4
4
  _rendering?: boolean;
@@ -1 +1 @@
1
- import{flags as e}from"../utils/flags.js";export{BAND_ROWS,drawReduced,forceDownscaleEngine,loadDownscaleKernel,planBands,setDownscaleBandRows,resampleCanvas,shouldResample,sourceSize,RESAMPLE_PIXEL_BUDGET}from"@polotno/core/downscale";export function exportKernelEnabled(n){return Boolean(null==n?void 0:n._exporting)&&!(null==n?void 0:n._rendering)&&e.imageDownScalingEnabled}
1
+ import{flags as e}from"../utils/flags.js";export{BAND_ROWS,drawImageWindow,drawReduced,forceDownscaleEngine,loadDownscaleKernel,planBands,setDownscaleBandRows,resampleCanvas,shouldResample,sourceSize,RESAMPLE_PIXEL_BUDGET}from"@polotno/core/downscale";export function exportKernelEnabled(n){return Boolean(null==n?void 0:n._exporting)&&!(null==n?void 0:n._rendering)&&e.imageDownScalingEnabled}
package/canvas/hotkeys.js CHANGED
@@ -1 +1 @@
1
- import{ROLES as e}from"../model/store.js";import{copyToEvent as t,cutToEvent as o,escapeText as l,pasteFromEvent as n,insertTextElement as r}from"../utils/clipboard.js";import{duplicateElements as i}from"../utils/duplicate.js";import{alignBottom as c,alignCenter as a,alignLeft as s,alignMiddle as d,alignRight as u,alignTop as f}from"../utils/alignment.js";import{richTextToPlainText as p}from"@polotno/core/text";const v="rgba(191, 191, 191, 100)";function y(e){if(1!==e.selectedElements.length){return null}const t=e.selectedElements[0];return"table"!==t.type?null:t}function h(e,t,o){const l=e.visibleCellAt(t,o);l&&e.focusCell(l.id)}function m(e,t,o){const l=e.rows*e.cols,n=t.row*e.cols+t.col;for(let r=1;r<=l;r++){const t=((n+o*r)%l+l)%l,i=e.getCell(Math.floor(t/e.cols),t%e.cols);if(i&&!i.mergedInto){return i}}}function g(e=document.querySelector(".polotno-workspace-container")){var t;const o=document.activeElement,l=null==o?void 0:o.closest(".polotno-workspace-container"),n=!!l&&l!==e,r="INPUT"===(null==o?void 0:o.tagName)||"TEXTAREA"===(null==o?void 0:o.tagName)||!!(null==o?void 0:o.isContentEditable),i=!(!o||!(null==e?void 0:e.contains(o))),c=document.activeElement===e||i;return{workspaceContainer:e,otherWorkspace:n,activeIsEditable:r,activeIsInsideWorkspace:i,isWorkspaceActive:c,hasOutsideTextSelection:!c&&((null===(t=window.getSelection())||void 0===t?void 0:t.toString().length)||0)>0}}export function getWorkspaceEventScope(t,o){if(t.role===e.VIEWER){return{handle:!1,table:null}}const l=g(o);if(l.otherWorkspace||l.activeIsEditable||l.hasOutsideTextSelection){return{handle:!1,table:null}}const n=y(t);return{handle:!0,table:n&&n._focusedCellIds.length>0&&!n._editingCellId?n:null}}export function handleHotkey(t,o,l){var n,p,w,E,k,D,C,x,K,b,A;if(o.role===e.VIEWER){return}const R=g(l);if(R.otherWorkspace){return}const T=R.activeIsEditable&&!R.activeIsInsideWorkspace,S=y(o);if(!T&&S&&function(e,t,o){const l=t._focusedCellIds.length>0,n=!!t._editingCellId;if(!l&&!n){return!1}if(n){if("Escape"===e.key){return e.preventDefault(),t.exitCellEdit(),!0}if("Tab"===e.key){e.preventDefault();const o=t.editingCell;t.exitCellEdit();const l=o&&m(t,o,e.shiftKey?-1:1);return l&&t.enterCellEdit(l.id),!0}return!0}if("Escape"===e.key){return e.preventDefault(),t.clearCellFocus(),!0}const r=t.focusedCells[0],i=r&&t.visibleCellAt(r.row,r.col);if(!i){return!1}const{row:c,col:a}=i;if("Enter"===e.key){return e.preventDefault(),t.enterCellEdit(i.id),!0}if("Tab"===e.key){e.preventDefault();const o=m(t,i,e.shiftKey?-1:1);return o&&t.focusCell(o.id),!0}if("ArrowRight"===e.key||"ArrowLeft"===e.key||"ArrowDown"===e.key||"ArrowUp"===e.key){if(e.preventDefault(),e.shiftKey){const o=function(e){const t=e.cells.find(t=>t.id===e._anchorCellId);if(!t){return null}const o=e.focusedCells;if(o.length<=1){return{row:t.row,col:t.col}}let l=1/0,n=-1,r=1/0,i=-1;for(const c of o){c.row<l&&(l=c.row),c.row>n&&(n=c.row),c.col<r&&(r=c.col),c.col>i&&(i=c.col)}return{row:t.row===l?n:l,col:t.col===r?i:r}}(t)||{row:c,col:a};let l=o.row,n=o.col;"ArrowRight"===e.key&&(n=Math.min(o.col+1,t.cols-1)),"ArrowLeft"===e.key&&(n=Math.max(o.col-1,0)),"ArrowDown"===e.key&&(l=Math.min(o.row+1,t.rows-1)),"ArrowUp"===e.key&&(l=Math.max(o.row-1,0)),t.focusCellRange(l,n)}else{"ArrowRight"===e.key&&h(t,c,Math.min(a+i.colSpan,t.cols-1)),"ArrowLeft"===e.key&&h(t,c,Math.max(a-1,0)),"ArrowDown"===e.key&&h(t,Math.min(c+i.rowSpan,t.rows-1),a),"ArrowUp"===e.key&&h(t,Math.max(c-1,0),a)}return!0}const s=e.ctrlKey||e.metaKey;if(!(s||e.shiftKey||e.altKey||"Delete"!==e.key&&"Backspace"!==e.key)){return e.preventDefault(),t.focusedCells.forEach(e=>{e.set({text:""})}),!0}if(s&&e.shiftKey&&!e.altKey&&"Equal"===e.code){e.preventDefault();const l=t.getFocusedCellRange(),n=l?l.maxRow+1:c+1;return o.history.transaction(()=>{t.addRow(n)}),!0}if(s&&e.shiftKey&&e.altKey&&"Equal"===e.code){e.preventDefault();const l=t.getFocusedCellRange(),n=l?l.maxCol+1:a+1;return o.history.transaction(()=>{t.addColumn(n)}),!0}if(s&&!e.shiftKey&&"Backspace"===e.code){const l=t.getFocusedCellRange();if(l&&0===l.minCol&&l.maxCol===t.cols-1&&t.rows>1){return e.preventDefault(),o.history.transaction(()=>{t.removeRowRange(l.minRow,l.maxRow)}),!0}}if(s&&e.shiftKey&&"Backspace"===e.code){const l=t.getFocusedCellRange();if(l&&0===l.minRow&&l.maxRow===t.rows-1&&t.cols>1){return e.preventDefault(),o.history.transaction(()=>{t.removeColumnRange(l.minCol,l.maxCol)}),!0}}return s&&"KeyA"===e.code?(e.preventDefault(),t.cells.forEach(e=>{t.focusCell(e.id,!0)}),!0):!s||"z"!==e.key.toLowerCase()&&"y"!==e.key.toLowerCase()}(t,S,o)){return}if(R.activeIsEditable){return}if(R.hasOutsideTextSelection){return}if(o.activeTool&&"crop"!==o.activeTool.name&&"Escape"===t.key&&R.isWorkspaceActive){return t.preventDefault(),void o._closeImageTool("discard")}if("Alt"===t.key){const e=R.workspaceContainer;return void((R.isWorkspaceActive||o.distanceGuidesVisible||e&&e.matches(":hover"))&&t.preventDefault())}if("Escape"===t.key||"Enter"===t.key){const e=o._hasCroppedImages;if(e&&("Escape"===t.key||R.isWorkspaceActive)){return t.preventDefault(),void("Escape"===t.key?e.cancelCropMode():(null===(n=o.activeTool)||void 0===n?void 0:n.pending)||e.toggleCropMode(!1))}}const W=o.selectedElements.filter(e=>e.removable).map(e=>e.id),I=!!o.activeTool&&"crop"!==o.activeTool.name;46!==t.keyCode&&8!==t.keyCode||I||o.deleteElements(W);const M=t.ctrlKey||t.metaKey,L=t.shiftKey,P=t.altKey;if("Escape"===t.key){return t.preventDefault(),void("draw"===o.tool?o.setTool("selection"):o.selectElements([]))}if(M&&!L&&"z"===t.key.toLowerCase()){return t.preventDefault(),void o.history.undo()}if(M&&(L&&"z"===t.key.toLowerCase()||"y"===t.key.toLowerCase())){return t.preventDefault(),void o.history.redo()}if(M&&"KeyA"===t.code){t.preventDefault();const e=null===(p=o.activePage)||void 0===p?void 0:p.children.filter(e=>e.selectable),l=(null==e?void 0:e.map(e=>e.id))||[];o.selectElements(l)}if(M&&("Equal"===t.code||"Minus"===t.code)){return t.preventDefault(),void o.setScale(o.scale+("Equal"===t.code?.1:-.1))}if(!I&&!o.selectedShapes.some(e=>"pendingEdit"in e&&e.pendingEdit)){if("ArrowDown"===t.code){t.preventDefault();const e=t.shiftKey?10:1;o.selectedShapes.forEach(t=>{t.draggable&&t.set({y:t.y+e})})}if("ArrowUp"===t.code){t.preventDefault();const e=t.shiftKey?10:1;o.selectedShapes.forEach(t=>{t.draggable&&t.set({y:t.y-e})})}if("ArrowLeft"===t.code){t.preventDefault();const e=t.shiftKey?10:1;o.selectedShapes.forEach(t=>{t.draggable&&t.set({x:t.x-e})})}if("ArrowRight"===t.code){t.preventDefault();const e=t.shiftKey?10:1;o.selectedShapes.forEach(t=>{t.draggable&&t.set({x:t.x+e})})}if(M&&"KeyG"===t.code){t.preventDefault();const e=o.selectedElements[0];if(e&&"group"===e.type){const t=e;o.ungroupElements([t.id])}else{o.groupElements(o.selectedElements.map(e=>e.id))}}if(M&&"KeyD"===t.code&&(t.preventDefault(),i(o.selectedElements,o)),"KeyT"!==t.code||M||(t.preventDefault(),r(o,"Sample Text",{fontFamily:"Roboto"})),"KeyR"===t.code&&!M){t.preventDefault();const e={type:"figure",x:o.width/4,y:o.height/4,width:300,height:300,fill:v,stroke:"#0c0c0c",strokeWidth:0,subType:"rect"};null===(w=o.activePage)||void 0===w||w.addElement(e)}if("KeyL"===t.code&&!M){t.preventDefault();const e=(null!==(K=null===(E=o.activePage)||void 0===E?void 0:E.computedWidth)&&void 0!==K?K:0)/3,l={type:"line",x:(null!==(b=null===(k=o.activePage)||void 0===k?void 0:k.computedWidth)&&void 0!==b?b:0)/2-e/2,y:(null!==(A=null===(D=o.activePage)||void 0===D?void 0:D.computedHeight)&&void 0!==A?A:0)/2,width:e,color:v};null===(C=o.activePage)||void 0===C||C.addElement(l)}if("KeyO"===t.code&&!M){t.preventDefault(),t.preventDefault();const e={type:"figure",x:o.width/4,y:o.height/4,width:300,height:300,fill:v,stroke:"#0c0c0c",strokeWidth:0,subType:"circle"};null===(x=o.activePage)||void 0===x||x.addElement(e)}P&&("KeyA"===t.code&&(t.preventDefault(),s(o)),"KeyD"===t.code&&(t.preventDefault(),u(o)),"KeyS"===t.code&&(t.preventDefault(),c(o)),"KeyW"===t.code&&(t.preventDefault(),f(o)),"KeyV"===t.code&&(t.preventDefault(),d(o)),"KeyH"===t.code&&(t.preventDefault(),a(o))),"BracketRight"===t.code&&(t.preventDefault(),o.selectedElements.forEach(e=>M?e.moveUp():e.moveTop())),"BracketLeft"===t.code&&(t.preventDefault(),o.selectedElements.forEach(e=>M?e.moveDown():e.moveBottom()))}}function w(e,t){const o=e.focusedCells.map(e=>p(e.text)).join("\n");t.clipboardData.setData("text/plain",o||" "),t.preventDefault()}export function handleCopyEvent(e,o,l){const n=getWorkspaceEventScope(o,l);n.handle&&e.clipboardData&&(n.table?w(n.table,e):t(o,e))}export function handleCutEvent(e,t,l){const n=getWorkspaceEventScope(t,l);if(n.handle&&e.clipboardData){if(n.table){const o=n.table;return w(o,e),void t.history.transaction(()=>{o.focusedCells.forEach(e=>e.set({text:""}))})}o(t,e)}}export function handlePasteEvent(e,t,o){const r=getWorkspaceEventScope(t,o);if(!r.handle){return}const i=r.table;n(t,e,{onText:i?e=>{var t;return null===(t=i.focusedCells[0])||void 0===t?void 0:t.set({text:l(e)})}:void 0})}
1
+ import{ROLES as e}from"../model/store.js";import{copyToEvent as t,cutToEvent as o,escapeText as l,pasteFromEvent as n,insertTextElement as r}from"../utils/clipboard.js";import{duplicateElements as a}from"../utils/duplicate.js";import{alignBottom as c,alignCenter as i,alignLeft as s,alignMiddle as d,alignRight as u,alignTop as f}from"../utils/alignment.js";import{richTextToPlainText as p}from"@polotno/core/text";const v="rgba(191, 191, 191, 100)";function y(e){if(1!==e.selectedElements.length){return null}const t=e.selectedElements[0];return"table"!==t.type?null:t}function h(e,t,o){const l=e.visibleCellAt(t,o);l&&e.focusCell(l.id)}function m(e,t,o){const l=e.rows*e.cols,n=t.row*e.cols+t.col;for(let r=1;r<=l;r++){const t=((n+o*r)%l+l)%l,a=e.getCell(Math.floor(t/e.cols),t%e.cols);if(a&&!a.mergedInto){return a}}}function g(e=document.querySelector(".polotno-workspace-container")){var t;const o=document.activeElement,l=null==o?void 0:o.closest(".polotno-workspace-container"),n=!!l&&l!==e,r="INPUT"===(null==o?void 0:o.tagName)||"TEXTAREA"===(null==o?void 0:o.tagName)||!!(null==o?void 0:o.isContentEditable),a=!(!o||!(null==e?void 0:e.contains(o))),c=document.activeElement===e||a;return{workspaceContainer:e,otherWorkspace:n,activeIsEditable:r,activeIsInsideWorkspace:a,isWorkspaceActive:c,hasOutsideTextSelection:!c&&((null===(t=window.getSelection())||void 0===t?void 0:t.toString().length)||0)>0}}export function getWorkspaceEventScope(t,o){if(t.role===e.VIEWER){return{handle:!1,table:null}}const l=g(o);if(l.otherWorkspace||l.activeIsEditable||l.hasOutsideTextSelection){return{handle:!1,table:null}}const n=y(t);return{handle:!0,table:n&&n._focusedCellIds.length>0&&!n._editingCellId?n:null}}export function handleHotkey(t,o,l){var n,p,w,k,E,D,C,x,K,b,A;if(o.role===e.VIEWER){return}const R=g(l);if(R.otherWorkspace){return}const T=R.activeIsEditable&&!R.activeIsInsideWorkspace,S=y(o);if(!T&&S&&function(e,t,o){const l=t._focusedCellIds.length>0,n=!!t._editingCellId;if(!l&&!n){return!1}if(n){if("Escape"===e.key){return e.preventDefault(),t.exitCellEdit(),!0}if("Tab"===e.key){e.preventDefault();const o=t.editingCell;t.exitCellEdit();const l=o&&m(t,o,e.shiftKey?-1:1);return l&&t.enterCellEdit(l.id),!0}return!0}if("Escape"===e.key){return e.preventDefault(),t.clearCellFocus(),!0}const r=t.focusedCells[0],a=r&&t.visibleCellAt(r.row,r.col);if(!a){return!1}const{row:c,col:i}=a;if("Enter"===e.key){return e.preventDefault(),t.enterCellEdit(a.id),!0}if("Tab"===e.key){e.preventDefault();const o=m(t,a,e.shiftKey?-1:1);return o&&t.focusCell(o.id),!0}if("ArrowRight"===e.key||"ArrowLeft"===e.key||"ArrowDown"===e.key||"ArrowUp"===e.key){if(e.preventDefault(),e.shiftKey){const o=function(e){const t=e.cells.find(t=>t.id===e._anchorCellId);if(!t){return null}const o=e.focusedCells;if(o.length<=1){return{row:t.row,col:t.col}}let l=1/0,n=-1,r=1/0,a=-1;for(const c of o){c.row<l&&(l=c.row),c.row>n&&(n=c.row),c.col<r&&(r=c.col),c.col>a&&(a=c.col)}return{row:t.row===l?n:l,col:t.col===r?a:r}}(t)||{row:c,col:i};let l=o.row,n=o.col;"ArrowRight"===e.key&&(n=Math.min(o.col+1,t.cols-1)),"ArrowLeft"===e.key&&(n=Math.max(o.col-1,0)),"ArrowDown"===e.key&&(l=Math.min(o.row+1,t.rows-1)),"ArrowUp"===e.key&&(l=Math.max(o.row-1,0)),t.focusCellRange(l,n)}else{"ArrowRight"===e.key&&h(t,c,Math.min(i+a.colSpan,t.cols-1)),"ArrowLeft"===e.key&&h(t,c,Math.max(i-1,0)),"ArrowDown"===e.key&&h(t,Math.min(c+a.rowSpan,t.rows-1),i),"ArrowUp"===e.key&&h(t,Math.max(c-1,0),i)}return!0}const s=e.ctrlKey||e.metaKey;if(!(s||e.shiftKey||e.altKey||"Delete"!==e.key&&"Backspace"!==e.key)){return e.preventDefault(),t.focusedCells.forEach(e=>{e.set({text:""})}),!0}if(s&&e.shiftKey&&!e.altKey&&"Equal"===e.code){e.preventDefault();const l=t.getFocusedCellRange(),n=l?l.maxRow+1:c+1;return o.history.transaction(()=>{t.addRow(n)}),!0}if(s&&e.shiftKey&&e.altKey&&"Equal"===e.code){e.preventDefault();const l=t.getFocusedCellRange(),n=l?l.maxCol+1:i+1;return o.history.transaction(()=>{t.addColumn(n)}),!0}if(s&&!e.shiftKey&&"Backspace"===e.code){const l=t.getFocusedCellRange();if(l&&0===l.minCol&&l.maxCol===t.cols-1&&t.rows>1){return e.preventDefault(),o.history.transaction(()=>{t.removeRowRange(l.minRow,l.maxRow)}),!0}}if(s&&e.shiftKey&&"Backspace"===e.code){const l=t.getFocusedCellRange();if(l&&0===l.minRow&&l.maxRow===t.rows-1&&t.cols>1){return e.preventDefault(),o.history.transaction(()=>{t.removeColumnRange(l.minCol,l.maxCol)}),!0}}return s&&"KeyA"===e.code?(e.preventDefault(),t.cells.forEach(e=>{t.focusCell(e.id,!0)}),!0):!s||"z"!==e.key.toLowerCase()&&"y"!==e.key.toLowerCase()}(t,S,o)){return}if(R.activeIsEditable){return}if(R.hasOutsideTextSelection){return}if(o.activeTool&&"crop"!==o.activeTool.name&&"Escape"===t.key&&R.isWorkspaceActive){return t.preventDefault(),void o._closeImageTool("discard")}if("Alt"===t.key){const e=R.workspaceContainer;return void((R.isWorkspaceActive||o.distanceGuidesVisible||e&&e.matches(":hover"))&&t.preventDefault())}if("Escape"===t.key||"Enter"===t.key){const e=o._hasCroppedImages;if(e&&("Escape"===t.key||R.isWorkspaceActive)){return t.preventDefault(),void("Escape"===t.key?e.cancelCropMode():(null===(n=o.activeTool)||void 0===n?void 0:n.pending)||e.toggleCropMode(!1))}}const W=o.selectedElements.filter(e=>e.removable).map(e=>e.id),I=!!o.activeTool&&"crop"!==o.activeTool.name;46!==t.keyCode&&8!==t.keyCode||I||o.deleteElements(W);const M=t.ctrlKey||t.metaKey,L=t.shiftKey,P=t.altKey;if("Escape"===t.key){return t.preventDefault(),void("draw"===o.tool?o.setTool("selection"):o.selectElements([]))}if(M&&!L&&"z"===t.key.toLowerCase()){return t.preventDefault(),void o.history.undo()}if(M&&(L&&"z"===t.key.toLowerCase()||"y"===t.key.toLowerCase())){return t.preventDefault(),void o.history.redo()}if(M&&"KeyA"===t.code){t.preventDefault();const e=null===(p=o.activePage)||void 0===p?void 0:p.children.filter(e=>e.selectable),l=(null==e?void 0:e.map(e=>e.id))||[];o.selectElements(l)}const F="Equal"===t.code||"NumpadAdd"===t.code||"="===t.key||"+"===t.key,_="Minus"===t.code||"NumpadSubtract"===t.code||"-"===t.key;if(M&&(F||_)){t.preventDefault();const e=Math.max(5,o.scaleToFit),l=Math.max(Math.min(.1,o.scaleToFit),.01),n=o.scale+(F?.1:-.1);return void o.setScale(Math.min(e,Math.max(l,n)))}if(!I&&!o.selectedShapes.some(e=>"pendingEdit"in e&&e.pendingEdit)){if("ArrowDown"===t.code){t.preventDefault();const e=t.shiftKey?10:1;o.selectedShapes.forEach(t=>{t.draggable&&t.set({y:t.y+e})})}if("ArrowUp"===t.code){t.preventDefault();const e=t.shiftKey?10:1;o.selectedShapes.forEach(t=>{t.draggable&&t.set({y:t.y-e})})}if("ArrowLeft"===t.code){t.preventDefault();const e=t.shiftKey?10:1;o.selectedShapes.forEach(t=>{t.draggable&&t.set({x:t.x-e})})}if("ArrowRight"===t.code){t.preventDefault();const e=t.shiftKey?10:1;o.selectedShapes.forEach(t=>{t.draggable&&t.set({x:t.x+e})})}if(M&&"KeyG"===t.code){t.preventDefault();const e=o.selectedElements[0];if(e&&"group"===e.type){const t=e;o.ungroupElements([t.id])}else{o.groupElements(o.selectedElements.map(e=>e.id))}}if(M&&"KeyD"===t.code&&(t.preventDefault(),a(o.selectedElements,o)),"KeyT"!==t.code||M||(t.preventDefault(),r(o,"Sample Text",{fontFamily:"Roboto"})),"KeyR"===t.code&&!M){t.preventDefault();const e={type:"figure",x:o.width/4,y:o.height/4,width:300,height:300,fill:v,stroke:"#0c0c0c",strokeWidth:0,subType:"rect"};null===(w=o.activePage)||void 0===w||w.addElement(e)}if("KeyL"===t.code&&!M){t.preventDefault();const e=(null!==(K=null===(k=o.activePage)||void 0===k?void 0:k.computedWidth)&&void 0!==K?K:0)/3,l={type:"line",x:(null!==(b=null===(E=o.activePage)||void 0===E?void 0:E.computedWidth)&&void 0!==b?b:0)/2-e/2,y:(null!==(A=null===(D=o.activePage)||void 0===D?void 0:D.computedHeight)&&void 0!==A?A:0)/2,width:e,color:v};null===(C=o.activePage)||void 0===C||C.addElement(l)}if("KeyO"===t.code&&!M){t.preventDefault(),t.preventDefault();const e={type:"figure",x:o.width/4,y:o.height/4,width:300,height:300,fill:v,stroke:"#0c0c0c",strokeWidth:0,subType:"circle"};null===(x=o.activePage)||void 0===x||x.addElement(e)}P&&("KeyA"===t.code&&(t.preventDefault(),s(o)),"KeyD"===t.code&&(t.preventDefault(),u(o)),"KeyS"===t.code&&(t.preventDefault(),c(o)),"KeyW"===t.code&&(t.preventDefault(),f(o)),"KeyV"===t.code&&(t.preventDefault(),d(o)),"KeyH"===t.code&&(t.preventDefault(),i(o))),"BracketRight"===t.code&&(t.preventDefault(),o.selectedElements.forEach(e=>M?e.moveUp():e.moveTop())),"BracketLeft"===t.code&&(t.preventDefault(),o.selectedElements.forEach(e=>M?e.moveDown():e.moveBottom()))}}function w(e,t){const o=e.focusedCells.map(e=>p(e.text)).join("\n");t.clipboardData.setData("text/plain",o||" "),t.preventDefault()}export function handleCopyEvent(e,o,l){const n=getWorkspaceEventScope(o,l);n.handle&&e.clipboardData&&(n.table?w(n.table,e):t(o,e))}export function handleCutEvent(e,t,l){const n=getWorkspaceEventScope(t,l);if(n.handle&&e.clipboardData){if(n.table){const o=n.table;return w(o,e),void t.history.transaction(()=>{o.focusedCells.forEach(e=>e.set({text:""}))})}o(t,e)}}export function handlePasteEvent(e,t,o){const r=getWorkspaceEventScope(t,o);if(!r.handle){return}const a=r.table;n(t,e,{onText:a?e=>{var t;return null===(t=a.focusedCells[0])||void 0===t?void 0:t.set({text:l(e)})}:void 0})}
@@ -1 +1 @@
1
- import{Fragment as t,jsx as e,jsxs as o}from"react/jsx-runtime";import r from"react";import{toDisplayColor as i}from"@polotno/core/color";import{elementOpacity as n}from"./paint-opacity.js";import{observer as a}from"mobx-react-lite";import{Group as s,Image as l,Path as c,Rect as d}from"react-konva";import{activeAnchorOf as f,scaledFontSizeAttrs as h,roundedFontSizeAttrs as u,roundedTextDecorationAttrs as g,roundedGeometryPx as m,roundedPosition as p,textMinResizeWidth as x,transformScale as b}from"../utils/px.js";import y from"konva";import{isAlive as w}from"mobx-state-tree";import{nodeAutorun as S}from"../utils/mobx.js";import{flags as v}from"../utils/flags.js";import{textOverflowOf as E}from"../utils/text-sizing.js";import{layoutTextSizing as z,legacyTextOverflow as k,renderTagLayoutAt as O,resolveTextSizing as j}from"@polotno/core/text-sizing";import{applyFilter as F}from"./apply-filters.js";import{getLineHeight as M,useFontFamiliesLoader as R,usePrevious as Y}from"./text-element.js";import{getCurvePath as X}from"@polotno/core/text-html";import{useColor as C,withDisplayTextPaints as I}from"./use-color.js";import{useWorkspaceStyle as A}from"./workspace-style.js";import{detectSize as P,detectLineRects as $,htmlToCanvas as T}from"../utils/html2canvas.js";import{generateBackgroundShapeFromRects as W}from"@polotno/core/background-shape";import{useFadeIn as B}from"./use-fadein.js";import{Html as H}from"react-konva-utils";import{incrementLoader as _,triggerLoadError as D}from"../utils/loader.js";import{removeTags as L}from"@polotno/core/text";import{cssFontFamily as J}from"@polotno/core/fonts";import{shadowCastByBackground as N}from"@polotno/core/filters";import*as q from"../utils/fonts.js";import{isTouchDevice as V}from"../utils/screen.js";import{getLimitedFontSize as G}from"./text-element/max-font-size.js";import{AutoDeleteEmptyText as K}from"./text-element/auto-delete-empty-text.js";import{useLegacyPaddingWarning as Q}from"./text-element/legacy-padding-warning.js";import{useDelayer as U}from"./use-delayer.js";import{geckoRtlOverhangCss as Z,getHtml as tt,letterSpacingOverhang as et,OVERHANG_PROPERTY as ot,textLayoutWidth as rt}from"@polotno/core/text-html";import{hasMeasuredHeight as it,resolveTextBoxHeight as nt}from"@polotno/core/text-types";import{normalizeRichTextHtml as at,extractFontFamiliesFromHtml as st,scaleRichTextFontSizesInHtml as lt}from"../utils/rich-text-html.js";import{RichEditor as ct,RichTextContainer as dt,applyOpacityToColor as ft,quillRef as ht,createQuill as ut,setQuillContent as gt,setQuillFormats as mt,syncQuillFormatState as pt,setCursorFromCoords as xt}from"./rich-editor.js";export{ht as quillRef,ut as createQuill,gt as setQuillContent,mt as setQuillFormats,pt as syncQuillFormatState,xt as setCursorFromCoords};function bt(t){const e=document.createElement("canvas"),o=e.getContext("2d");return null==o||o.drawImage(t,0,0,e.width,e.height),function(t){return!function(t){const e=t.getContext("2d").getImageData(0,0,t.width,t.height).data;for(let o=0;o<e.length;o+=4){if(0!==e[o+3]){return!0}}return!1}(t)}(e)}const yt=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),wt=navigator.userAgent.includes("Firefox");export const HTMLElement=a(({element:a,store:ht})=>{var ut,gt,mt;const{textOverflowIndicatorStyle:pt}=A(),xt=r.useRef(null),[St,vt]=r.useState(),[Et,zt]=r.useState(!1),[kt,Ot]=r.useState(!1),jt=r.useRef(a.height);Q(a);const Ft=a.fontSize/3,Mt=rt(a.a.width,a.letterSpacing,a.fontSize)+2*Ft,{textVerticalResizeEnabled:Rt}=v,Yt=Y(a.fontFamily),Xt=r.useMemo(()=>at(a.text,{fontSize:a.fontSize,fontFamily:a.fontFamily}),[a.text,a.fontSize,a.fontFamily]),Ct=r.useMemo(()=>[...new Set([a.fontFamily,...st(Xt)])].filter(Boolean),[a.fontFamily,Xt]),[It]=R(ht,Ct,a.fontStyle,a.fontWeight,a.text||a.placeholder),At=a._editModeEnabled,Pt=At&&!(null===(ut=a.page)||void 0===ut?void 0:ut._exporting);B(xt);const $t=It?a.fontFamily:Yt!==a.fontFamily?Yt:"Arial",Tt=C(a).fill,Wt=tt(I(a),{fontFamily:$t,color:Tt,textOverflow:E(a)}),Bt=function(t,e){return e&&/dir="rtl"|direction: rtl/.test(t)?`<div class="polotno-overhang" style="${ot}: ${e}px">${t}</div><style>${Z(".polotno-overhang [dir]:not(.polotno-overhang [dir] [dir])")}</style>`:t}(Wt,et(a.letterSpacing,a.fontSize)),Ht=r.useRef([]),_t=r.useRef(!0),[,Dt]=r.useReducer(t=>t+1,0);r.useEffect(()=>{const t=Ht.current;t.length>0&&(Ht.current=[],t.forEach(t=>t()))}),r.useEffect(()=>()=>{_t.current=!1;const t=Ht.current;t.length>0&&(Ht.current=[],t.forEach(t=>t()))},[]);let{width:Lt,height:Jt}=function(t,e,o){return r.useMemo(()=>P(t),[t,e.width,o])}(Bt,a,It);r.useEffect(()=>{if(!It){return}const t=(t,e,o,r)=>{const i=_(`text ${a.id}`),n=()=>{ht.history.ignore(t,e,o).then(()=>{_t.current?(Ht.current.push(i),Dt()):i()})};r?queueMicrotask(n):n()};if(a.curveEnabled&&Math.abs(Lt-a.width)>1&&!Et&&t(()=>{if(w(a)&&Math.abs(Lt-a.width)>1){const t=a.x+a.width/2;a.set({width:Lt,x:t-Lt/2})}},!1,!0),!it(a)){return void t(()=>{w(a)&&(it(a)||a.set({height:Jt}))},void 0,void 0,!0)}const e=k(E(a));if("change-font-size"!==e||Et||At||a.curveEnabled){"resize"===e&&(Rt&&a.height<Jt&&!Et&&t(()=>{w(a)&&a.set({height:Jt})},!1,!0),Rt||a.height===Jt||Et||t(()=>{w(a)&&a.set({height:Jt})},!1,!0))}else{const o=z({element:a,sizing:j({text:a.text,width:a.width,height:a.height,fontSize:a.fontSize,maxLines:a.maxLines,curveEnabled:a.curveEnabled},{textOverflow:e,textSplitAllowed:v.textSplitAllowed}),layoutAt:O(a,{getHtmlOptions:{fontFamily:a.fontFamily}})});o.fontSize!==a.fontSize?t(()=>{if(!w(a)){return}const t=h(a,o.fontSize);o.text!==a.text&&(t.text=o.text),a.set(t)},!1,!0):a.height!==Jt&&(Rt&&a.height<Jt?t(()=>{w(a)&&a.set({height:Jt})},!1,!0):Rt||t(()=>{w(a)&&a.set({height:Jt})},!1,!0))}});const Nt=r.useMemo(()=>{const t={lastArgs:null,lastResult:null};return async function(e){return t.lastArgs&&t.lastResult&&(o=t.lastArgs,r=e,JSON.stringify(o)===JSON.stringify(r))||(t.lastResult=await T(e),t.lastArgs=Object.assign({},e)),t.lastResult;var o,r}},[]),qt=r.useRef(0),Vt=r.useRef(null);r.useEffect(()=>{Et||Pt||(async()=>{qt.current++;const t=qt.current;let e=_(`text ${a.id} ${t}`);Vt.current&&Vt.current(),Vt.current=e,Ot(!0);let o=null;const r=yt?5:1;for(let n=0;n<r;n++){const e=n>0?Nt:T;try{if(o=await e({skipCache:n>0,html:Bt,width:Lt||a.width||1,height:nt(a,Jt)||1,fontFamily:$t,fontFamilies:st(Bt),resolveFont:t=>ht.fonts.find(e=>e.fontFamily===t)||q.globalFonts.find(e=>e.fontFamily===t),padding:Ft,pixelRatio:ht._elementsPixelRatio,font:ht.fonts.find(t=>t.fontFamily===$t)||q.globalFonts.find(t=>t.fontFamily===$t)}),t!==qt.current){return}if((yt||wt)&&o&&bt(o)){await new Promise(t=>setTimeout(t,50*(n+1)));continue}break}catch(i){console.error(i),D(`Error rendering rich text with id ${a.id}`);break}}o?vt(o):e?(e(),e=null):console.error("Finish function is called twice!"),Ot(!1)})()},[Bt,Et,Jt,Pt,$t,a.height,ht._elementsPixelRatio,It]);const[Gt,Kt]=U(kt,300),[Qt]=U(Et,300,!0),Ut=Qt||Gt;r.useEffect(()=>{var t;if(!Ut){return S(a,()=>{const t=xt.current;F(t,a)})}null===(t=xt.current)||void 0===t||t.clearCache()},[St,Ut,a.shadowColor,a.shadowOffsetX,a.shadowOffsetY,a.shadowOpacity]),r.useEffect(()=>{St&&!kt&&Vt.current&&(Vt.current(),Vt.current=null)},[St,kt]),r.useLayoutEffect(()=>{if(!It){return}if(!a.curveEnabled){return}const t=new y.TextPath({data:X(a.a.width,a.a.height,a.curvePower,a.a.fontSize),text:L(a.text),letterSpacing:a.letterSpacing*a.a.fontSize,fontSize:a.a.fontSize,fontFamily:J(a.fontFamily),fontWeight:a.fontWeight,fontStyle:a.fontStyle,align:"center",textBaseline:"middle",fill:a.fill}),e=t.getSelfRect().width;if(e){const t=e-a.a.width,o=a.a.rotation*Math.PI/180,r=-t/2*Math.cos(o),i=-t/2*Math.sin(o);queueMicrotask(()=>{w(a)&&a.set({width:e,x:a.a.x+r,y:a.a.y+i})})}t.destroy()},[It,a.curveEnabled,a.curvePower,a.text,a.fontSize,a.fontFamily,a.fontWeight,a.fontStyle,a.letterSpacing]),r.useEffect(()=>()=>{Vt.current&&Vt.current()},[]);const Zt=nt(a,Jt);let te=0;"middle"===a.verticalAlign&&(te=(Zt-Jt)/2),"bottom"===a.verticalAlign&&(te=Zt-Jt);const ee=M({fontLoaded:It,fontFamily:a.fontFamily,fontSize:a.fontSize,lineHeight:a.lineHeight}),oe=a.backgroundPadding*(a.fontSize*ee*.5),re=a.backgroundCornerRadius*(a.fontSize*ee*.5),ie=r.useMemo(()=>{if(!a.backgroundEnabled&&!a.borderSize||a.curveEnabled||"box"===a.backgroundShape){return""}const t=$(Wt);if(0===t.length){return""}const e=t.map(t=>({left:t.left+Ft,right:t.right+Ft,top:t.top+Ft,bottom:t.bottom+Ft}));return W({rects:e,padding:oe,cornerRadius:re})},[a.backgroundEnabled,a.borderSize,a.curveEnabled,a.backgroundShape,Wt,It,oe,re,Ft]),ne=V(),ae=X(a.a.width,Jt,a.curvePower,a.fontSize),se=r.useRef(null),le=r.useRef(a.width),ce=r.useRef(""),de=r.useRef(0),fe=r.useRef(0),he=r.useRef(null),ue=At&&a.strokeWidth>0&&!a.curveEnabled,ge=Lt>0?Mt/(Lt+2*Ft):1,me=a.shadowEnabled&&!N(a),pe={shadowEnabled:a.shadowEnabled&&(N(a)||a.borderSize>0),shadowBlur:a.shadowBlur,shadowOffsetX:a.shadowOffsetX,shadowOffsetY:a.shadowOffsetY,shadowColor:i(a.shadowColor),shadowOpacity:a.shadowOpacity};return o(t,{children:[e(K,{element:a,store:ht}),a.curveEnabled||"box"===a.backgroundShape?e(d,Object.assign({x:a.a.x,y:a.a.y,offsetX:oe/ge,offsetY:oe/ge,rotation:a.a.rotation,scaleX:ge,scaleY:ge,hideInExport:!a.showInExport,listening:!1,visible:a.backgroundEnabled||a.borderSize>0,opacity:n(a),fillEnabled:a.backgroundEnabled,fill:ft(a.backgroundColor,a.backgroundOpacity),strokeEnabled:a.borderSize>0,stroke:i(a.borderColor),strokeWidth:a.borderSize,width:a.width+2*oe,height:Zt+2*oe,cornerRadius:re},pe)):e(c,Object.assign({name:"html-background",x:a.a.x,y:a.a.y,offsetX:Ft/ge,offsetY:(Ft-te)/ge,rotation:a.a.rotation,scaleX:ge,scaleY:ge,hideInExport:!a.showInExport,listening:!1,visible:(a.backgroundEnabled||a.borderSize>0)&&ie.length>0,opacity:n(a),fillEnabled:a.backgroundEnabled,fill:ft(a.backgroundColor,a.backgroundOpacity),strokeEnabled:a.borderSize>0,stroke:i(a.borderColor),strokeWidth:a.borderSize,lineJoin:re>0?"round":"miter",data:ie},pe)),e(c,{x:a.a.x,y:a.a.y,rotation:a.a.rotation,data:ae,stroke:pt.stroke,strokeWidth:1,visible:!1}),e(d,{ref:xt,name:"element",x:a.a.x,y:a.a.y,listening:a.selectable,rotation:a.a.rotation,width:a.a.width,height:a.a.height,visible:!Ut,draggable:ne?a.draggable&&a.isSelected:a.draggable,preventDefault:!ne||a.isSelected,opacity:At?0:n(a),hideInExport:!a.showInExport,onDragMove:t=>{a.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{a.set(p(t.target))},id:a.id,onDblClick:t=>{a.contentEditable&&(he.current={x:t.evt.clientX,y:t.evt.clientY},a.toggleEditMode(!0))},onDblTap:t=>{var e;if(a.contentEditable){const o=null===(e=t.evt.changedTouches)||void 0===e?void 0:e[0];he.current=o?{x:o.clientX,y:o.clientY}:null,a.toggleEditMode(!0)}},onTransformStart:t=>{zt(!0),jt.current=a.height,le.current=a.width,se.current=t.target.position(),ce.current=f(t.target),de.current=a.a.rotation,fe.current=a.height},onTransform:t=>{const e=t.target,o=ce.current,r="middle-left"===o||"middle-right"===o,i="top-center"===o||"bottom-center"===o,n=b(e.scaleX());if(r){const t=e.width()*n,o=x(le.current,a.fontSize);let r=t;t<o&&(r=o,se.current&&e.position(se.current)),e.width(r),e.scaleX(1),e.scaleY(1);const i=tt(Object.assign(Object.assign({},a.toJSON()),{width:r}),{fontFamily:$t,color:Tt,textOverflow:E(a)}),s=P(i).height,l=v.textVerticalResizeEnabled?Math.max(s,jt.current):s;e.height(l),a.set({width:e.width(),height:l,x:e.x(),y:e.y()})}else if(i){const t="resize"===E(a),o="number"==typeof a.lineHeight?a.lineHeight:1,r=t?Jt:o*a.fontSize,i=e.height()*e.scaleY();if(i<r){if(e.height(r),se.current){if("top-center"===ce.current){const t=de.current*Math.PI/180,o=fe.current-r;e.x(se.current.x-o*Math.sin(t)),e.y(se.current.y+o*Math.cos(t))}else{e.position(se.current)}}}else{e.height(i)}e.scaleY(1),e.scaleX(1),fe.current=Math.max(r,i),a.set({x:e.x(),y:e.y(),height:e.height(),rotation:e.rotation()})}else{e.scaleX(1),e.scaleY(1),a.set({fontSize:a.fontSize*n,letterSpacing:a.letterSpacing,width:e.width()*n,x:e.x(),y:e.y(),rotation:e.rotation(),height:e.height()*n,shadowBlur:a.shadowBlur*n,shadowOffsetX:a.shadowOffsetX*n,shadowOffsetY:a.shadowOffsetY*n,strokeWidth:a.strokeWidth*n,borderSize:a.borderSize*n,text:lt(a.text,n)})}se.current=t.target.position()},onTransformEnd:t=>{zt(!1),Ot(!0);const e=b(t.target.scaleX());t.target.scaleX(1),t.target.scaleY(1),a.set(Object.assign(Object.assign({},u(a,a.fontSize*e)),{width:m(t.target.width()*e),x:m(t.target.x()),y:m(t.target.y()),rotation:m(t.target.rotation()),text:lt(a.text,e)}))}}),e(l,Object.assign({ref:xt,image:St,x:a.a.x,y:a.a.y,offsetX:Ft,offsetY:Ft-te,listening:!1,rotation:a.a.rotation,width:Mt,height:Mt*((null!==(gt=null==St?void 0:St.height)&&void 0!==gt?gt:0)/((null==St?void 0:St.width)||1)||1),visible:!Ut&&!At,opacity:n(a)},pe,{shadowEnabled:me,hideInExport:!a.showInExport,editModeEnabled:a._editModeEnabled||Et||Ut})),(Ut&&!At||ue)&&e(s,{x:a.a.x,y:a.a.y,rotation:a.a.rotation,offsetY:-te,children:e(H,{divProps:{style:{pointerEvents:"none"}},children:e(dt,{dangerouslySetInnerHTML:{__html:Bt},style:{pointerEvents:"none",opacity:a.a.opacity,textShadow:me?`${a.shadowOffsetX}px ${a.shadowOffsetY}px ${a.shadowBlur}px ${ft(a.shadowColor,null!==(mt=a.shadowOpacity)&&void 0!==mt?mt:1)}`:void 0}})})}),At&&e(s,{x:a.a.x,y:a.a.y,rotation:a.a.rotation,offsetY:-te,children:e(H,{divProps:{style:{zIndex:20}},children:e(ct,{element:a,onChange:t=>{const e=G({oldText:L(a.text),newText:L(t),element:a});a.set(Object.assign({text:t},h(a,e)))},onBlur:t=>{w(a)&&(a.set(g(a)),a.toggleEditMode(!1),Kt(!0))},clickCoords:he.current})})})]})});
1
+ import{Fragment as t,jsx as e,jsxs as o}from"react/jsx-runtime";import r from"react";import{toDisplayColor as i}from"@polotno/core/color";import{elementOpacity as n}from"./paint-opacity.js";import{observer as a}from"mobx-react-lite";import{Group as s,Image as l,Path as c,Rect as d}from"react-konva";import{activeAnchorOf as f,scaledFontSizeAttrs as h,roundedFontSizeAttrs as u,roundedTextDecorationAttrs as g,roundedGeometryPx as m,roundedPosition as p,textMinResizeWidth as x,transformScale as b}from"../utils/px.js";import y from"konva";import{isAlive as w}from"mobx-state-tree";import{nodeAutorun as S}from"../utils/mobx.js";import{flags as v}from"../utils/flags.js";import{textOverflowOf as E}from"../utils/text-sizing.js";import{layoutTextSizing as z,legacyTextOverflow as k,renderTagLayoutAt as O,resolveTextSizing as j}from"@polotno/core/text-sizing";import{applyFilter as F}from"./apply-filters.js";import{getLineHeight as M,useFontFamiliesLoader as R,usePrevious as Y}from"./text-element.js";import{getCurvePath as X}from"@polotno/core/text-html";import{useColor as C,withDisplayTextPaints as I}from"./use-color.js";import{useWorkspaceStyle as P}from"./workspace-style.js";import{detectSize as $,detectLineRects as T,htmlToCanvas as A}from"../utils/html2canvas.js";import{generateBackgroundShapeFromRects as W}from"@polotno/core/background-shape";import{useFadeIn as B}from"./use-fadein.js";import{Html as H}from"react-konva-utils";import{incrementLoader as _,triggerLoadError as D}from"../utils/loader.js";import{removeTags as L}from"@polotno/core/text";import{cssFontFamily as J}from"@polotno/core/fonts";import{shadowCastByBackground as N}from"@polotno/core/filters";import*as q from"../utils/fonts.js";import{isTouchDevice as V}from"../utils/screen.js";import{getLimitedFontSize as G}from"./text-element/max-font-size.js";import{AutoDeleteEmptyText as K}from"./text-element/auto-delete-empty-text.js";import{useLegacyPaddingWarning as Q}from"./text-element/legacy-padding-warning.js";import{useDelayer as U}from"./use-delayer.js";import{geckoRtlOverhangCss as Z,getHtml as tt,letterSpacingOverhang as et,OVERHANG_PROPERTY as ot,textLayoutWidth as rt}from"@polotno/core/text-html";import{hasMeasuredHeight as it,resolveTextBoxHeight as nt}from"@polotno/core/text-types";import{normalizeRichTextHtml as at,extractFontFamiliesFromHtml as st,scaleRichTextFontSizesInHtml as lt}from"../utils/rich-text-html.js";import{RichEditor as ct,RichTextContainer as dt,applyOpacityToColor as ft,quillRef as ht,createQuill as ut,setQuillContent as gt,setQuillFormats as mt,syncQuillFormatState as pt,setCursorFromCoords as xt}from"./rich-editor.js";import{isFirefox as bt,isWebKit as yt}from"../utils/engine.js";export{ht as quillRef,ut as createQuill,gt as setQuillContent,mt as setQuillFormats,pt as syncQuillFormatState,xt as setCursorFromCoords};function wt(t){const e=document.createElement("canvas"),o=e.getContext("2d");return null==o||o.drawImage(t,0,0,e.width,e.height),function(t){return!function(t){const e=t.getContext("2d").getImageData(0,0,t.width,t.height).data;for(let o=0;o<e.length;o+=4){if(0!==e[o+3]){return!0}}return!1}(t)}(e)}export const HTMLElement=a(({element:a,store:ht})=>{var ut,gt,mt;const{textOverflowIndicatorStyle:pt}=P(),xt=r.useRef(null),[St,vt]=r.useState(),[Et,zt]=r.useState(!1),[kt,Ot]=r.useState(!1),jt=r.useRef(a.height);Q(a);const Ft=a.fontSize/3,Mt=rt(a.a.width,a.letterSpacing,a.fontSize)+2*Ft,{textVerticalResizeEnabled:Rt}=v,Yt=Y(a.fontFamily),Xt=r.useMemo(()=>at(a.text,{fontSize:a.fontSize,fontFamily:a.fontFamily}),[a.text,a.fontSize,a.fontFamily]),Ct=r.useMemo(()=>[...new Set([a.fontFamily,...st(Xt)])].filter(Boolean),[a.fontFamily,Xt]),[It]=R(ht,Ct,a.fontStyle,a.fontWeight,a.text||a.placeholder),Pt=a._editModeEnabled,$t=Pt&&!(null===(ut=a.page)||void 0===ut?void 0:ut._exporting);B(xt);const Tt=It?a.fontFamily:Yt!==a.fontFamily?Yt:"Arial",At=C(a).fill,Wt=tt(I(a),{fontFamily:Tt,color:At,textOverflow:E(a)}),Bt=function(t,e){return e&&/dir="rtl"|direction: rtl/.test(t)?`<div class="polotno-overhang" style="${ot}: ${e}px">${t}</div><style>${Z(".polotno-overhang [dir]:not(.polotno-overhang [dir] [dir])")}</style>`:t}(Wt,et(a.letterSpacing,a.fontSize)),Ht=r.useRef([]),_t=r.useRef(!0),[,Dt]=r.useReducer(t=>t+1,0);r.useEffect(()=>{const t=Ht.current;t.length>0&&(Ht.current=[],t.forEach(t=>t()))}),r.useEffect(()=>()=>{_t.current=!1;const t=Ht.current;t.length>0&&(Ht.current=[],t.forEach(t=>t()))},[]);let{width:Lt,height:Jt}=function(t,e,o){return r.useMemo(()=>$(t),[t,e.width,o])}(Bt,a,It);r.useEffect(()=>{if(!It){return}const t=(t,e,o,r)=>{const i=_(`text ${a.id}`),n=()=>{ht.history.ignore(t,e,o).then(()=>{_t.current?(Ht.current.push(i),Dt()):i()})};r?queueMicrotask(n):n()};if(a.curveEnabled&&Math.abs(Lt-a.width)>1&&!Et&&t(()=>{if(w(a)&&Math.abs(Lt-a.width)>1){const t=a.x+a.width/2;a.set({width:Lt,x:t-Lt/2})}},!1,!0),!it(a)){return void t(()=>{w(a)&&(it(a)||a.set({height:Jt}))},void 0,void 0,!0)}const e=k(E(a));if("change-font-size"!==e||Et||Pt||a.curveEnabled){"resize"===e&&(Rt&&a.height<Jt&&!Et&&t(()=>{w(a)&&a.set({height:Jt})},!1,!0),Rt||a.height===Jt||Et||t(()=>{w(a)&&a.set({height:Jt})},!1,!0))}else{const o=z({element:a,sizing:j({text:a.text,width:a.width,height:a.height,fontSize:a.fontSize,maxLines:a.maxLines,curveEnabled:a.curveEnabled},{textOverflow:e,textSplitAllowed:v.textSplitAllowed}),layoutAt:O(a,{getHtmlOptions:{fontFamily:a.fontFamily}})});o.fontSize!==a.fontSize?t(()=>{if(!w(a)){return}const t=h(a,o.fontSize);o.text!==a.text&&(t.text=o.text),a.set(t)},!1,!0):a.height!==Jt&&(Rt&&a.height<Jt?t(()=>{w(a)&&a.set({height:Jt})},!1,!0):Rt||t(()=>{w(a)&&a.set({height:Jt})},!1,!0))}});const Nt=r.useMemo(()=>{const t={lastArgs:null,lastResult:null};return async function(e){return t.lastArgs&&t.lastResult&&(o=t.lastArgs,r=e,JSON.stringify(o)===JSON.stringify(r))||(t.lastResult=await A(e),t.lastArgs=Object.assign({},e)),t.lastResult;var o,r}},[]),qt=r.useRef(0),Vt=r.useRef(null);r.useEffect(()=>{Et||$t||(async()=>{qt.current++;const t=qt.current;let e=_(`text ${a.id} ${t}`);Vt.current&&Vt.current(),Vt.current=e,Ot(!0);let o=null;const r=yt()?5:1;for(let n=0;n<r;n++){const e=n>0?Nt:A;try{if(o=await e({skipCache:n>0,html:Bt,width:Lt||a.width||1,height:nt(a,Jt)||1,fontFamily:Tt,fontFamilies:st(Bt),resolveFont:t=>ht.fonts.find(e=>e.fontFamily===t)||q.globalFonts.find(e=>e.fontFamily===t),padding:Ft,pixelRatio:ht._elementsPixelRatio,font:ht.fonts.find(t=>t.fontFamily===Tt)||q.globalFonts.find(t=>t.fontFamily===Tt)}),t!==qt.current){return}if((yt()||bt())&&o&&wt(o)){await new Promise(t=>setTimeout(t,50*(n+1)));continue}break}catch(i){console.error(i),D(`Error rendering rich text with id ${a.id}`);break}}o?vt(o):e?(e(),e=null):console.error("Finish function is called twice!"),Ot(!1)})()},[Bt,Et,Jt,$t,Tt,a.height,ht._elementsPixelRatio,It]);const[Gt,Kt]=U(kt,300),[Qt]=U(Et,300,!0),Ut=Qt||Gt;r.useEffect(()=>{var t;if(!Ut){return S(a,()=>{const t=xt.current;F(t,a)})}null===(t=xt.current)||void 0===t||t.clearCache()},[St,Ut,a.shadowColor,a.shadowOffsetX,a.shadowOffsetY,a.shadowOpacity]),r.useEffect(()=>{St&&!kt&&Vt.current&&(Vt.current(),Vt.current=null)},[St,kt]),r.useLayoutEffect(()=>{if(!It){return}if(!a.curveEnabled){return}const t=new y.TextPath({data:X(a.a.width,a.a.height,a.curvePower,a.a.fontSize),text:L(a.text),letterSpacing:a.letterSpacing*a.a.fontSize,fontSize:a.a.fontSize,fontFamily:J(a.fontFamily),fontWeight:a.fontWeight,fontStyle:a.fontStyle,align:"center",textBaseline:"middle",fill:a.fill}),e=t.getSelfRect().width;if(e){const t=e-a.a.width,o=a.a.rotation*Math.PI/180,r=-t/2*Math.cos(o),i=-t/2*Math.sin(o);queueMicrotask(()=>{w(a)&&a.set({width:e,x:a.a.x+r,y:a.a.y+i})})}t.destroy()},[It,a.curveEnabled,a.curvePower,a.text,a.fontSize,a.fontFamily,a.fontWeight,a.fontStyle,a.letterSpacing]),r.useEffect(()=>()=>{Vt.current&&Vt.current()},[]);const Zt=nt(a,Jt);let te=0;"middle"===a.verticalAlign&&(te=(Zt-Jt)/2),"bottom"===a.verticalAlign&&(te=Zt-Jt);const ee=M({fontLoaded:It,fontFamily:a.fontFamily,fontSize:a.fontSize,lineHeight:a.lineHeight}),oe=a.backgroundPadding*(a.fontSize*ee*.5),re=a.backgroundCornerRadius*(a.fontSize*ee*.5),ie=r.useMemo(()=>{if(!a.backgroundEnabled&&!a.borderSize||a.curveEnabled||"box"===a.backgroundShape){return""}const t=T(Wt);if(0===t.length){return""}const e=t.map(t=>({left:t.left+Ft,right:t.right+Ft,top:t.top+Ft,bottom:t.bottom+Ft}));return W({rects:e,padding:oe,cornerRadius:re})},[a.backgroundEnabled,a.borderSize,a.curveEnabled,a.backgroundShape,Wt,It,oe,re,Ft]),ne=V(),ae=X(a.a.width,Jt,a.curvePower,a.fontSize),se=r.useRef(null),le=r.useRef(a.width),ce=r.useRef(""),de=r.useRef(0),fe=r.useRef(0),he=r.useRef(null),ue=Pt&&a.strokeWidth>0&&!a.curveEnabled,ge=Lt>0?Mt/(Lt+2*Ft):1,me=a.shadowEnabled&&!N(a),pe={shadowEnabled:a.shadowEnabled&&(N(a)||a.borderSize>0),shadowBlur:a.shadowBlur,shadowOffsetX:a.shadowOffsetX,shadowOffsetY:a.shadowOffsetY,shadowColor:i(a.shadowColor),shadowOpacity:a.shadowOpacity};return o(t,{children:[e(K,{element:a,store:ht}),a.curveEnabled||"box"===a.backgroundShape?e(d,Object.assign({x:a.a.x,y:a.a.y,offsetX:oe/ge,offsetY:oe/ge,rotation:a.a.rotation,scaleX:ge,scaleY:ge,hideInExport:!a.showInExport,listening:!1,visible:a.backgroundEnabled||a.borderSize>0,opacity:n(a),fillEnabled:a.backgroundEnabled,fill:ft(a.backgroundColor,a.backgroundOpacity),strokeEnabled:a.borderSize>0,stroke:i(a.borderColor),strokeWidth:a.borderSize,width:a.width+2*oe,height:Zt+2*oe,cornerRadius:re},pe)):e(c,Object.assign({name:"html-background",x:a.a.x,y:a.a.y,offsetX:Ft/ge,offsetY:(Ft-te)/ge,rotation:a.a.rotation,scaleX:ge,scaleY:ge,hideInExport:!a.showInExport,listening:!1,visible:(a.backgroundEnabled||a.borderSize>0)&&ie.length>0,opacity:n(a),fillEnabled:a.backgroundEnabled,fill:ft(a.backgroundColor,a.backgroundOpacity),strokeEnabled:a.borderSize>0,stroke:i(a.borderColor),strokeWidth:a.borderSize,lineJoin:re>0?"round":"miter",data:ie},pe)),e(c,{x:a.a.x,y:a.a.y,rotation:a.a.rotation,data:ae,stroke:pt.stroke,strokeWidth:1,visible:!1}),e(d,{ref:xt,name:"element",x:a.a.x,y:a.a.y,listening:a.selectable,rotation:a.a.rotation,width:a.a.width,height:a.a.height,visible:!Ut,draggable:ne?a.draggable&&a.isSelected:a.draggable,preventDefault:!ne||a.isSelected,opacity:Pt?0:n(a),hideInExport:!a.showInExport,onDragMove:t=>{a.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{a.set(p(t.target))},id:a.id,onDblClick:t=>{a.contentEditable&&(he.current={x:t.evt.clientX,y:t.evt.clientY},a.toggleEditMode(!0))},onDblTap:t=>{var e;if(a.contentEditable){const o=null===(e=t.evt.changedTouches)||void 0===e?void 0:e[0];he.current=o?{x:o.clientX,y:o.clientY}:null,a.toggleEditMode(!0)}},onTransformStart:t=>{zt(!0),jt.current=a.height,le.current=a.width,se.current=t.target.position(),ce.current=f(t.target),de.current=a.a.rotation,fe.current=a.height},onTransform:t=>{const e=t.target,o=ce.current,r="middle-left"===o||"middle-right"===o,i="top-center"===o||"bottom-center"===o,n=b(e.scaleX());if(r){const t=e.width()*n,o=x(le.current,a.fontSize);let r=t;t<o&&(r=o,se.current&&e.position(se.current)),e.width(r),e.scaleX(1),e.scaleY(1);const i=tt(Object.assign(Object.assign({},a.toJSON()),{width:r}),{fontFamily:Tt,color:At,textOverflow:E(a)}),s=$(i).height,l=v.textVerticalResizeEnabled?Math.max(s,jt.current):s;e.height(l),a.set({width:e.width(),height:l,x:e.x(),y:e.y()})}else if(i){const t="resize"===E(a),o="number"==typeof a.lineHeight?a.lineHeight:1,r=t?Jt:o*a.fontSize,i=e.height()*e.scaleY();if(i<r){if(e.height(r),se.current){if("top-center"===ce.current){const t=de.current*Math.PI/180,o=fe.current-r;e.x(se.current.x-o*Math.sin(t)),e.y(se.current.y+o*Math.cos(t))}else{e.position(se.current)}}}else{e.height(i)}e.scaleY(1),e.scaleX(1),fe.current=Math.max(r,i),a.set({x:e.x(),y:e.y(),height:e.height(),rotation:e.rotation()})}else{e.scaleX(1),e.scaleY(1),a.set({fontSize:a.fontSize*n,letterSpacing:a.letterSpacing,width:e.width()*n,x:e.x(),y:e.y(),rotation:e.rotation(),height:e.height()*n,shadowBlur:a.shadowBlur*n,shadowOffsetX:a.shadowOffsetX*n,shadowOffsetY:a.shadowOffsetY*n,strokeWidth:a.strokeWidth*n,borderSize:a.borderSize*n,text:lt(a.text,n)})}se.current=t.target.position()},onTransformEnd:t=>{zt(!1),Ot(!0);const e=b(t.target.scaleX());t.target.scaleX(1),t.target.scaleY(1),a.set(Object.assign(Object.assign({},u(a,a.fontSize*e)),{width:m(t.target.width()*e),x:m(t.target.x()),y:m(t.target.y()),rotation:m(t.target.rotation()),text:lt(a.text,e)}))}}),e(l,Object.assign({ref:xt,image:St,x:a.a.x,y:a.a.y,offsetX:Ft,offsetY:Ft-te,listening:!1,rotation:a.a.rotation,width:Mt,height:Mt*((null!==(gt=null==St?void 0:St.height)&&void 0!==gt?gt:0)/((null==St?void 0:St.width)||1)||1),visible:!Ut&&!Pt,opacity:n(a)},pe,{shadowEnabled:me,hideInExport:!a.showInExport,editModeEnabled:a._editModeEnabled||Et||Ut})),(Ut&&!Pt||ue)&&e(s,{x:a.a.x,y:a.a.y,rotation:a.a.rotation,offsetY:-te,children:e(H,{divProps:{style:{pointerEvents:"none"}},children:e(dt,{dangerouslySetInnerHTML:{__html:Bt},style:{pointerEvents:"none",opacity:a.a.opacity,textShadow:me?`${a.shadowOffsetX}px ${a.shadowOffsetY}px ${a.shadowBlur}px ${ft(a.shadowColor,null!==(mt=a.shadowOpacity)&&void 0!==mt?mt:1)}`:void 0}})})}),Pt&&e(s,{x:a.a.x,y:a.a.y,rotation:a.a.rotation,offsetY:-te,children:e(H,{divProps:{style:{zIndex:20}},children:e(ct,{element:a,onChange:t=>{const e=G({oldText:L(a.text),newText:L(t),element:a});a.set(Object.assign({text:t},h(a,e)))},onBlur:t=>{w(a)&&(a.set(g(a)),a.toggleEditMode(!1),Kt(!0))},clickCoords:he.current})})})]})});
@@ -1 +1 @@
1
- import{Fragment as e,jsx as t,jsxs as r}from"react/jsx-runtime";import o from"react";import{toDisplayColor as i}from"@polotno/core/color";import{animatedShadow as a}from"./animated-shadow.js";import{observer as n}from"mobx-react-lite";import{isAlive as s}from"mobx-state-tree";import{Image as d,Rect as h}from"react-konva";import{ROLES as c}from"../model/store.js";import l from"./use-image.js";import u from"konva";import{ErrorPlaceholder as g,LoadingPlaceholder as m}from"./media-placeholders.js";import{incrementLoader as p,triggerLoadError as f}from"../utils/loader.js";import{polotnoError as v}from"@polotno/core/errors";import{getBorderInset as w,getCropRect as x,mayBeUnsizedSvg as y}from"@polotno/core/image";import{elementOpacity as M,paintOpacity as S}from"./paint-opacity.js";import*as b from"@polotno/core/svg";import{trySetCanvasSize as E}from"../utils/canvas.js";import{roundedPosition as I}from"../utils/px.js";import{useMediaResize as C}from"./media-resize.js";import{useFilteredSource as j}from"./use-filtered-source.js";import{useOffscreenCanvas as R}from"./use-offscreen-canvas.js";import{useFadeIn as z}from"./use-fadein.js";import{useAnimatedBlur as D}from"./use-animated-blur.js";import{PlacedNode as O}from"./placed-node.js";import{isTouchDevice as k}from"../utils/screen.js";import{useDelayer as L}from"./use-delayer.js";import{useColor as _}from"./use-color.js";import{commitCropSource as T,cropDraftWriter as A,CropOverlay as X}from"./crop-overlay.js";import{ImageToolControls as Y}from"./image-tool-controls.js";import{drawReduced as W,exportKernelEnabled as H,shouldResample as P}from"./downscale.js";import{alignToPixelGrid as N,coversWholeSource as U,displayRatio as F,maskCompositeSize as G,MAX_ELEMENT_BUFFER as $,svgSourceRatio as q}from"@polotno/core/image-buffer";export{G as maskCompositeSize,q as svgSourceRatio};const J=(e,t,r)=>F(e.a,t,r),Q=new Map,V=new Map;let B=0;const K=e=>{const t=Q.get(e);return void 0!==t&&(Q.delete(e),Q.set(e,t)),t},Z=(e,t)=>{const r=e.length+t.length;if(!(r>4e6||Q.has(e))){Q.set(e,t),B+=r;for(const[e,t]of Q){if(B<=16e6){break}Q.delete(e),B-=e.length+t.length}}},ee=(e,t)=>e+"\n"+JSON.stringify((null==t?void 0:t.size)?[...t]:[]),te=new Map,re=new Map,oe=e=>b.isSvgUrl(e)||!0===te.get(e),ie=e=>"svg"===e.type||oe(e.a.src||""),ae=(e,t,r,i)=>{const[a,n]=o.useState(""),s=!t&&!!r&&"loaded"===i&&!e.startsWith("data:")&&!te.has(e)&&a!==e&&y(r);return o.useEffect(()=>{if(!s){return}let t=!0;return(e=>{let t=re.get(e);return t||(t=b.fetchSvgText(e).then(t=>{null!==t&&Z(ee(e),b.prepareSvgSource(t)),te.set(e,null!==t)}).catch(()=>{}).finally(()=>re.delete(e)),re.set(e,t)),t})(e).then(()=>{t&&n(e)}),()=>{t=!1}},[s,e]),s?"loading":i},ne=(e,t,r)=>{const[,i]=o.useReducer(e=>e+1,0),a=t&&e?ee(e,r):"",n=o.useRef("loading"),s=o.useRef(""),d=o.useRef(a);if(d.current!==a&&(d.current=a,n.current="loading"),a&&"loading"===n.current){const e=K(a);void 0!==e&&(s.current=e,n.current="loaded")}return o.useEffect(()=>{if(!a||"loaded"===n.current){return}let t=!1;return((e,t)=>{const r=ee(e,t),o=K(r);if(void 0!==o){return Promise.resolve(o)}let i=V.get(r);if(!i){const o=(null==t?void 0:t.size)?new Map(t):null;i=b.urlToString(e).then(e=>b.prepareSvgSource(e,o)),V.set(r,i),i.then(e=>Z(r,e),()=>{}).finally(()=>V.delete(r))}return i})(e,r).then(e=>{t||(s.current=e,n.current="loaded",i())},()=>{t||(s.current="",n.current="failed",i())}),()=>{t=!0}},[a]),a?[s.current,n.current]:[e,"loaded"]};export const useSizeFixer=e=>ne(e,oe(e))[0]||e;function se(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}const de=e=>{if(e.flipX||e.flipY||e.maskSrc){return!0}const t=navigator.userAgent.toLowerCase();return(t.indexOf("firefox")>-1||/^((?!chrome|android).)*safari/i.test(t))&&ie(e)},he=(e,t,r)=>Math.max(t,Math.min(r,e));export const useCornerRadiusAndCrop=(e,t,r,i,a=0,n=!1,s=!0,d=0,h)=>{var c;const l=$,g=$,m=h.aligned?he(h.deviceWidth,1,l):Math.floor(he(e.a.width*i,1,l)),p=h.aligned?he(h.deviceHeight,1,g):Math.floor(he(e.a.height*i,1,g)),f=Math.min(a*i,m/2,p/2),v=Math.min(d*i,m/2,p/2),w=J(e,r,i),x=H(e.page)&&!n&&(P(w,m,p)||h.aligned),y=U(r,t),M=o.useMemo(()=>{if(t&&t.width&&t.height){return!y||0!==f||x||v?document.createElement("canvas"):void 0}},[t,f,x,y,v]);return o.useLayoutEffect(()=>{var o;if(!M||!t){return}E(M,m,p);const i=M.getContext("2d");if(i){if((null===(o=e.page)||void 0===o?void 0:o._exportingOrRendering)&&(i.imageSmoothingQuality="high"),(f||v)&&(i.beginPath(),i.roundRect(v,v,m-2*v,p-2*v,Math.max(0,f-v)),i.clip()),x){const e=M.width===m&&M.height===p&&h.aligned;return void W(i,t,r,M.width,M.height,{x:e?h.phaseX:0,y:e?h.phaseY:0,width:e?h.spanX:M.width,height:e?h.spanY:M.height})}i.drawImage(t,r.x,r.y,r.width,r.height,0,0,M.width,M.height)}},[M,e.a.width,e.a.height,r.x,r.y,r.width,r.height,a,i,n,null===(c=e.page)||void 0===c?void 0:c._exportingOrRendering,x,h.phaseX,h.phaseY,v]),o.useEffect(()=>()=>{M&&"CANVAS"===M.nodeName&&u.Util.releaseCanvas(M)},[M]),M||t};const ce=document.createElement("canvas");let le=l;export const setImageLoaderHook=e=>{le=e};export const useCanvasImage=(e,t)=>le(e,t);export const useSizedImage=e=>{const[t,r]=ne(e,oe(e)),[o,i]=useCanvasImage(t,"anonymous"),a=ae(e,oe(e),o,i);return[o,"loaded"===r?a:r]};export const useClipImage=e=>{const[t,r]=useSizedImage(e),i=o.useRef(void 0);return e&&"failed"!==r?t&&(i.current=t):i.current=void 0,[e&&"failed"!==r?t||i.current:void 0,r]};export const useImageLoader=(e,t="",r="")=>{const i=o.useRef(void 0),a=()=>{var e;null===(e=i.current)||void 0===e||e.call(i),i.current=void 0};o.useEffect(()=>a,[]),o.useLayoutEffect(()=>{const o=t.slice(0,200),n=`image with id ${r} url: ${o}`;"loading"!==e||i.current||(i.current=p(n)),"loading"!==e&&a(),"failed"===e&&f(v("IMAGE_FAILED",n,{src:o,elementId:r,reason:"load"}))},[e])};export const ImageElement=n(({element:n,store:l})=>{var p,f,v,y,b;const[W,P]=o.useState(!1),F=o.useRef(null),$=k(),Q=n.a.src,V=ie(n),[B,K]=ne(Q,V,n.colorsReplace),[Z,ee]=le(B,"anonymous"),te="loaded"===K?ee:K,re=ae(Q,V,Z,te),oe=!!Q;useImageLoader(oe?re:"loaded",Q,n.id);const he=(null===(p=n.page)||void 0===p?void 0:p._exportingOrRendering)||!de(n)?1:Math.max(1,l.scale),ue=l._elementsPixelRatio*he,ge=(({image:e,status:t})=>{const r=o.useRef(void 0);return o.useEffect(()=>{r.current=e||r.current},[e]),"failed"!==t?r.current:void 0})({image:Z,status:re}),me=((e,t,r)=>{const o=ie(e)&&t?q({cropWidth:e.a.cropWidth,cropHeight:e.a.cropHeight,width:e.a.width,height:e.a.height},t,r):1,{flipX:i,flipY:a}=e,n=de(e),s=R(n&&!!(t&&t.width&&t.height),e=>{var r,n;if(!t){return}E(e,Math.max(t.width*o,1),Math.max(t.height*o,1));let s=i?-e.width:0,d=a?-e.height:0;null===(r=e.getContext("2d"))||void 0===r||r.scale(i?-1:1,a?-1:1),null===(n=e.getContext("2d"))||void 0===n||n.drawImage(t,s,d,e.width,e.height)},[i,a,t,o]);return n?s:t})(n,Z||ge,ue),pe=((e,t)=>{const[r,i]=useSizedImage(e.maskSrc||""),a=e.maskSrc?i:"loaded";return useImageLoader(a,e.maskSrc||"",e.id),o.useMemo(()=>{if(!r){return t}if(!t||!t.width||!t.height){return t}const{width:o,height:i}=G(t,{width:e.a.width,height:e.a.height,stretchEnabled:e.stretchEnabled}),a=document.createElement("canvas");a.width=o,a.height=i;const n=a.getContext("2d");if(!n){return t}n.drawImage(t,0,0,o,i,0,0,o,i),n.globalCompositeOperation="source-in";const s=function(e,t){const r=t.width/t.height;let o,i;return r>=e.width/e.height?(o=e.width,i=e.width/r):(o=e.height*r,i=e.height),{x:(e.width-o)/2,y:(e.height-i)/2,width:o,height:i}}(r,e);return n.drawImage(r,s.x,s.y,s.width,s.height,0,0,o,i),a},[t,r,e.a.width,e.a.height,e.stretchEnabled])})(n,me)||ce,[fe=ce]=j(n,pe);o.useLayoutEffect(()=>{"loaded"===re&&n._setSourceSize({width:fe.width,height:fe.height},Q)},[n,Q,re,fe.width,fe.height]);let{cropX:ve,cropY:we,cropWidth:xe,cropHeight:ye}=n.a;"loaded"!==ee&&(ve=we=0,xe=ye=1);const Me=x({stretchEnabled:n.stretchEnabled,fit:n.a.fit,focus:n.focus,cropX:ve,cropY:we,cropWidth:xe,cropHeight:ye,width:n.a.width,height:n.a.height},fe),Se=Me.width,be=Me.height,Ee=null!==(b=n.cornerRadius)&&void 0!==b?b:0,Ie=w({borderSize:n.borderSize,borderColor:i(n.borderColor),width:n.a.width,height:n.a.height,opacity:S(n)}),Ce=!(!Ee&&!Ie&&!n.clipSrc&&U(Me,fe)),je=(null===(f=n.page)||void 0===f?void 0:f._exportingOrRendering)||!Ce?1:Math.min(2,l.scale),Re=l._elementsPixelRatio*je,ze=W||n._cropModeEnabled||"svg"===n.type,De=H(n.page)&&0===n.a.rotation&&"group"!==(null===(v=n.parent)||void 0===v?void 0:v.type)&&!ze,Oe=((e,t,r,o)=>N(e.a,t,r,o))(n,Re,J(n,Me,Re),De);let ke=((e,t,r,i)=>{const[a,n]=useClipImage(e.clipSrc||""),s=e.clipSrc?n:"loaded";useImageLoader(s,e.clipSrc,e.id);const d=o.useMemo(()=>{if(t&&a){return document.createElement("canvas")}},[t,a]);return o.useLayoutEffect(()=>{var o;if(!a){return}if(!t||!t.width||!t.height){return}if(!a||!a.width||!a.height){return}if(!d){return}const i=document.createElement("canvas"),n=Math.max(e.a.width/a.width*r,e.a.height/a.height*r);E(i,Math.min(1e4,Math.max(a.width*n,1)),Math.min(1e4,Math.max(a.height*n,1))),null===(o=i.getContext("2d"))||void 0===o||o.drawImage(a,0,0,i.width,i.height),E(d,Math.min(1e4,Math.max(t.width,Math.ceil(e.a.width*r),1)),Math.min(1e4,Math.max(t.height,Math.ceil(e.a.height*r),1)));const s=d.getContext("2d");s&&(s.save(),s.drawImage(i,0,0,d.width,d.height),u.Util.releaseCanvas(i),s.globalCompositeOperation="source-in",s.drawImage(t,0,0,d.width,d.height),s.restore())},[d,t,a,e.a.width,e.a.height,r,...i]),o.useEffect(()=>()=>{d&&u.Util.releaseCanvas(d)},[d]),e.clipSrc&&a?d:t})(n,useCornerRadiusAndCrop(n,fe,Me,Re,Ee,ze,!0,Ie,Oe),Re,[Me,Ee,Re]);var Le=o.useRef(null),_e=o.useRef(0),Te=o.useRef(!1);const Ae=()=>{var e;n._cropEnabled&&!n.pendingEdit&&(null===(e=l.activeTool)||void 0===e?void 0:e.elementId)!==n.id&&setTimeout(()=>{s(n)&&n.toggleCropMode(!0)})},Xe=ie(n)&&ge,Ye=oe&&"loading"===te&&!Xe,[We]=L(Ye,100,!1,!1),He="failed"===re,Pe=!We&&!He,Ne=C(n,Me,"loaded"===ee?fe:void 0,P),Ue=Pe?M(n):0;z(F,Ue),D(F,n,ke);const Fe=n.selectable||l.role===c.ADMIN,Ge=_(n,n.borderColor,"stroke",n.borderSize/2);return r(e,{children:[We&&t(m,{element:n}),He&&t(g,{element:n,text:"Can not load the image..."}),t(O,Object.assign({as:d,nodeRef:F,element:n,name:"element",id:n.id,image:ke},Oe.position,{width:Oe.width||1,height:Oe.height||1,opacity:Ue},a(n),{customCrop:Me,listening:Fe,draggable:!n.pendingEdit&&(null===(y=l.activeTool)||void 0===y?void 0:y.elementId)!==n.id&&($?n.draggable&&n.isSelected:n.draggable),preventDefault:!$||n.isSelected,hideInExport:!n.showInExport,onDragMove:e=>{n.set({x:e.target.x(),y:e.target.y()})},onDragEnd:e=>{n.set(I(e.target))},onDblClick:Ae,onDblTap:Ae},Ne)),!!n.borderSize&&t(O,Object.assign({as:h,element:n},Oe.position,{width:Math.max(Oe.width-n.borderSize,0),height:Math.max(Oe.height-n.borderSize,0),opacity:Ue,offsetX:-n.borderSize/2,offsetY:-n.borderSize/2},Ge,{strokeWidth:n.borderSize,listening:!1,cornerRadius:Math.max(0,Ee-n.borderSize),hideInExport:!n.showInExport})),n._cropModeEnabled&&"loaded"===re&&t(X,{element:n,store:l,previewImage:ke,sourceImage:fe,sourceWidth:fe.width,sourceHeight:fe.height,crop:Me,onSourceTouchMove:e=>{e.evt.preventDefault();const t=e.target.getStage().getPointersPositions();var r=t[0],o=t[1];const i=e.target;if(r&&!o&&!i.isDragging()&&Te.current&&(i.startDrag(),Te.current=!1),r&&o){u.hitOnDragEnabled=!0,i.isDragging()&&(Te.current=!0,i.stopDrag());const t=e.target.getAbsoluteTransform().copy();t.invert();var a={x:r.x,y:r.y},s={x:o.x,y:o.y};if(!Le.current){return void(Le.current=se(a,s))}var d=se(a,s),h=function(e,t){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}(a,s);_e.current||(_e.current=h);const v=i.position();var c={x:d.x-v.x,y:d.y-v.y},g=h/_e.current;i.scaleX(g),i.scaleY(g);const w=t.point(d),x=t.point(Le.current);var m=w.x-x.x,p=w.y-x.y,f={x:Math.min(0,d.x-c.x*g+m),y:Math.min(0,d.y-c.y*g+p)};i.position(f),_e.current=h,Le.current=d,(e=>{T(e,n,A(n,l),fe.width,fe.height,Se,be)})(e)}},onSourceTouchEnd:e=>{_e.current=0,Le.current=null,u.hitOnDragEnabled=!1}}),"image"===n.type&&t(Y,{element:n,store:l})]})});
1
+ import{Fragment as e,jsx as t,jsxs as r}from"react/jsx-runtime";import o from"react";import{toDisplayColor as i}from"@polotno/core/color";import{animatedShadow as a}from"./animated-shadow.js";import{observer as n}from"mobx-react-lite";import{isAlive as s}from"mobx-state-tree";import{Image as d,Rect as h}from"react-konva";import{ROLES as c}from"../model/store.js";import l from"./use-image.js";import u from"konva";import{ErrorPlaceholder as g,LoadingPlaceholder as m}from"./media-placeholders.js";import{incrementLoader as p,triggerLoadError as f}from"../utils/loader.js";import{polotnoError as v}from"@polotno/core/errors";import{getBorderInset as w,getCropRect as x,mayBeUnsizedSvg as y}from"@polotno/core/image";import{elementOpacity as M,paintOpacity as S}from"./paint-opacity.js";import*as b from"@polotno/core/svg";import{trySetCanvasSize as E}from"../utils/canvas.js";import{roundedPosition as I}from"../utils/px.js";import{useMediaResize as C}from"./media-resize.js";import{useFilteredSource as j}from"./use-filtered-source.js";import{useOffscreenCanvas as R}from"./use-offscreen-canvas.js";import{useFadeIn as z}from"./use-fadein.js";import{useAnimatedBlur as D}from"./use-animated-blur.js";import{PlacedNode as k}from"./placed-node.js";import{isTouchDevice as O}from"../utils/screen.js";import{useDelayer as _}from"./use-delayer.js";import{useColor as L}from"./use-color.js";import{commitCropSource as T,cropDraftWriter as X,CropOverlay as Y}from"./crop-overlay.js";import{ImageToolControls as A}from"./image-tool-controls.js";import{drawImageWindow as W,drawReduced as H,exportKernelEnabled as P,shouldResample as N}from"./downscale.js";import{alignToPixelGrid as U,coversWholeSource as F,displayRatio as G,maskCompositeSize as $,MAX_ELEMENT_BUFFER as q,svgSourceRatio as J}from"@polotno/core/image-buffer";import{isFirefox as Q,isWebKit as V}from"../utils/engine.js";export{$ as maskCompositeSize,J as svgSourceRatio};const B=(e,t,r)=>G(e.a,t,r),K=new Map,Z=new Map;let ee=0;const te=e=>{const t=K.get(e);return void 0!==t&&(K.delete(e),K.set(e,t)),t},re=(e,t)=>{const r=e.length+t.length;if(!(r>4e6||K.has(e))){K.set(e,t),ee+=r;for(const[e,t]of K){if(ee<=16e6){break}K.delete(e),ee-=e.length+t.length}}},oe=(e,t)=>e+"\n"+JSON.stringify((null==t?void 0:t.size)?[...t]:[]),ie=new Map,ae=new Map,ne=e=>b.isSvgUrl(e)||!0===ie.get(e),se=e=>"svg"===e.type||ne(e.a.src||""),de=(e,t,r,i)=>{const[a,n]=o.useState(""),s=!t&&!!r&&"loaded"===i&&!e.startsWith("data:")&&!ie.has(e)&&a!==e&&y(r);return o.useEffect(()=>{if(!s){return}let t=!0;return(e=>{let t=ae.get(e);return t||(t=b.fetchSvgText(e).then(t=>{null!==t&&re(oe(e),b.prepareSvgSource(t)),ie.set(e,null!==t)}).catch(()=>{}).finally(()=>ae.delete(e)),ae.set(e,t)),t})(e).then(()=>{t&&n(e)}),()=>{t=!1}},[s,e]),s?"loading":i},he=(e,t,r)=>{const[,i]=o.useReducer(e=>e+1,0),a=t&&e?oe(e,r):"",n=o.useRef("loading"),s=o.useRef(""),d=o.useRef(a);if(d.current!==a&&(d.current=a,n.current="loading"),a&&"loading"===n.current){const e=te(a);void 0!==e&&(s.current=e,n.current="loaded")}return o.useEffect(()=>{if(!a||"loaded"===n.current){return}let t=!1;return((e,t)=>{const r=oe(e,t),o=te(r);if(void 0!==o){return Promise.resolve(o)}let i=Z.get(r);if(!i){const o=(null==t?void 0:t.size)?new Map(t):null;i=b.urlToString(e).then(e=>b.prepareSvgSource(e,o)),Z.set(r,i),i.then(e=>re(r,e),()=>{}).finally(()=>Z.delete(r))}return i})(e,r).then(e=>{t||(s.current=e,n.current="loaded",i())},()=>{t||(s.current="",n.current="failed",i())}),()=>{t=!0}},[a]),a?[s.current,n.current]:[e,"loaded"]};export const useSizeFixer=e=>he(e,ne(e))[0]||e;function ce(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}const le=e=>!!(e.flipX||e.flipY||e.maskSrc)||(Q()||V())&&se(e),ue=(e,t,r)=>Math.max(t,Math.min(r,e));export const useCornerRadiusAndCrop=(e,t,r,i,a=0,n=!1,s=!0,d=0,h)=>{var c;const l=q,g=q,m=h.aligned?ue(h.deviceWidth,1,l):Math.floor(ue(e.a.width*i,1,l)),p=h.aligned?ue(h.deviceHeight,1,g):Math.floor(ue(e.a.height*i,1,g)),f=Math.min(a*i,m/2,p/2),v=Math.min(d*i,m/2,p/2),w=B(e,r,i),x=P(e.page)&&!n&&(N(w,m,p)||h.aligned),y=F(r,t),M=o.useMemo(()=>{if(t&&t.width&&t.height){return!y||0!==f||x||v?document.createElement("canvas"):void 0}},[t,f,x,y,v]);return o.useLayoutEffect(()=>{var o;if(!M||!t){return}E(M,m,p);const i=M.getContext("2d");if(i){if((null===(o=e.page)||void 0===o?void 0:o._exportingOrRendering)&&(i.imageSmoothingQuality="high"),(f||v)&&(i.beginPath(),i.roundRect(v,v,m-2*v,p-2*v,Math.max(0,f-v)),i.clip()),x){const e=M.width===m&&M.height===p&&h.aligned;return void H(i,t,r,M.width,M.height,{x:e?h.phaseX:0,y:e?h.phaseY:0,width:e?h.spanX:M.width,height:e?h.spanY:M.height})}W(i,t,r,{x:0,y:0,width:M.width,height:M.height})}},[M,e.a.width,e.a.height,r.x,r.y,r.width,r.height,a,i,n,null===(c=e.page)||void 0===c?void 0:c._exportingOrRendering,x,h.phaseX,h.phaseY,v]),o.useEffect(()=>()=>{M&&"CANVAS"===M.nodeName&&u.Util.releaseCanvas(M)},[M]),M||t};const ge=document.createElement("canvas");let me=l;export const setImageLoaderHook=e=>{me=e};export const useCanvasImage=(e,t)=>me(e,t);export const useSizedImage=e=>{const[t,r]=he(e,ne(e)),[o,i]=useCanvasImage(t,"anonymous"),a=de(e,ne(e),o,i);return[o,"loaded"===r?a:r]};export const useClipImage=e=>{const[t,r]=useSizedImage(e),i=o.useRef(void 0);return e&&"failed"!==r?t&&(i.current=t):i.current=void 0,[e&&"failed"!==r?t||i.current:void 0,r]};export const useImageLoader=(e,t="",r="")=>{const i=o.useRef(void 0),a=()=>{var e;null===(e=i.current)||void 0===e||e.call(i),i.current=void 0};o.useEffect(()=>a,[]),o.useLayoutEffect(()=>{const o=t.slice(0,200),n=`image with id ${r} url: ${o}`;"loading"!==e||i.current||(i.current=p(n)),"loading"!==e&&a(),"failed"===e&&f(v("IMAGE_FAILED",n,{src:o,elementId:r,reason:"load"}))},[e])};export const ImageElement=n(({element:n,store:l})=>{var p,f,v,y,b;const[W,H]=o.useState(!1),N=o.useRef(null),G=O(),q=n.a.src,Q=se(n),[V,K]=he(q,Q,n.colorsReplace),[Z,ee]=me(V,"anonymous"),te="loaded"===K?ee:K,re=de(q,Q,Z,te),oe=!!q;useImageLoader(oe?re:"loaded",q,n.id);const ie=(null===(p=n.page)||void 0===p?void 0:p._exportingOrRendering)||!le(n)?1:Math.max(1,l.scale),ae=l._elementsPixelRatio*ie,ne=(({image:e,status:t})=>{const r=o.useRef(void 0);return o.useEffect(()=>{r.current=e||r.current},[e]),"failed"!==t?r.current:void 0})({image:Z,status:re}),ue=((e,t,r)=>{const o=se(e)&&t?J({cropWidth:e.a.cropWidth,cropHeight:e.a.cropHeight,width:e.a.width,height:e.a.height},t,r):1,{flipX:i,flipY:a}=e,n=le(e),s=R(n&&!!(t&&t.width&&t.height),e=>{var r,n;if(!t){return}E(e,Math.max(t.width*o,1),Math.max(t.height*o,1));let s=i?-e.width:0,d=a?-e.height:0;null===(r=e.getContext("2d"))||void 0===r||r.scale(i?-1:1,a?-1:1),null===(n=e.getContext("2d"))||void 0===n||n.drawImage(t,s,d,e.width,e.height)},[i,a,t,o]);return n?s:t})(n,Z||ne,ae),pe=((e,t)=>{const[r,i]=useSizedImage(e.maskSrc||""),a=e.maskSrc?i:"loaded";return useImageLoader(a,e.maskSrc||"",e.id),o.useMemo(()=>{if(!r){return t}if(!t||!t.width||!t.height){return t}const{width:o,height:i}=$(t,{width:e.a.width,height:e.a.height,stretchEnabled:e.stretchEnabled}),a=document.createElement("canvas");a.width=o,a.height=i;const n=a.getContext("2d");if(!n){return t}n.drawImage(t,0,0,o,i,0,0,o,i),n.globalCompositeOperation="source-in";const s=function(e,t){const r=t.width/t.height;let o,i;return r>=e.width/e.height?(o=e.width,i=e.width/r):(o=e.height*r,i=e.height),{x:(e.width-o)/2,y:(e.height-i)/2,width:o,height:i}}(r,e);return n.drawImage(r,s.x,s.y,s.width,s.height,0,0,o,i),a},[t,r,e.a.width,e.a.height,e.stretchEnabled])})(n,ue)||ge,[fe=ge]=j(n,pe);o.useLayoutEffect(()=>{"loaded"===re&&n._setSourceSize({width:fe.width,height:fe.height},q)},[n,q,re,fe.width,fe.height]);let{cropX:ve,cropY:we,cropWidth:xe,cropHeight:ye}=n.a;"loaded"!==ee&&(ve=we=0,xe=ye=1);const Me=x({stretchEnabled:n.stretchEnabled,fit:n.a.fit,focus:n.focus,cropX:ve,cropY:we,cropWidth:xe,cropHeight:ye,width:n.a.width,height:n.a.height},fe),Se=Me.width,be=Me.height,Ee=null!==(b=n.cornerRadius)&&void 0!==b?b:0,Ie=w({borderSize:n.borderSize,borderColor:i(n.borderColor),width:n.a.width,height:n.a.height,opacity:S(n)}),Ce=!(!Ee&&!Ie&&!n.clipSrc&&F(Me,fe)),je=(null===(f=n.page)||void 0===f?void 0:f._exportingOrRendering)||!Ce?1:Math.min(2,l.scale),Re=l._elementsPixelRatio*je,ze=W||n._cropModeEnabled||"svg"===n.type,De=P(n.page)&&0===n.a.rotation&&"group"!==(null===(v=n.parent)||void 0===v?void 0:v.type)&&!ze,ke=((e,t,r,o)=>U(e.a,t,r,o))(n,Re,B(n,Me,Re),De);let Oe=((e,t,r,i)=>{const[a,n]=useClipImage(e.clipSrc||""),s=e.clipSrc?n:"loaded";useImageLoader(s,e.clipSrc,e.id);const d=o.useMemo(()=>{if(t&&a){return document.createElement("canvas")}},[t,a]);return o.useLayoutEffect(()=>{var o;if(!a){return}if(!t||!t.width||!t.height){return}if(!a||!a.width||!a.height){return}if(!d){return}const i=document.createElement("canvas"),n=Math.max(e.a.width/a.width*r,e.a.height/a.height*r);E(i,Math.min(1e4,Math.max(a.width*n,1)),Math.min(1e4,Math.max(a.height*n,1))),null===(o=i.getContext("2d"))||void 0===o||o.drawImage(a,0,0,i.width,i.height),E(d,Math.min(1e4,Math.max(t.width,Math.ceil(e.a.width*r),1)),Math.min(1e4,Math.max(t.height,Math.ceil(e.a.height*r),1)));const s=d.getContext("2d");s&&(s.save(),s.drawImage(i,0,0,d.width,d.height),u.Util.releaseCanvas(i),s.globalCompositeOperation="source-in",s.drawImage(t,0,0,d.width,d.height),s.restore())},[d,t,a,e.a.width,e.a.height,r,...i]),o.useEffect(()=>()=>{d&&u.Util.releaseCanvas(d)},[d]),e.clipSrc&&a?d:t})(n,useCornerRadiusAndCrop(n,fe,Me,Re,Ee,ze,!0,Ie,ke),Re,[Me,Ee,Re]);var _e=o.useRef(null),Le=o.useRef(0),Te=o.useRef(!1);const Xe=()=>{var e;n._cropEnabled&&!n.pendingEdit&&(null===(e=l.activeTool)||void 0===e?void 0:e.elementId)!==n.id&&setTimeout(()=>{s(n)&&n.toggleCropMode(!0)})},Ye=se(n)&&ne,Ae=oe&&"loading"===te&&!Ye,[We]=_(Ae,100,!1,!1),He="failed"===re,Pe=!We&&!He,Ne=C(n,Me,"loaded"===ee?fe:void 0,H),Ue=Pe?M(n):0;z(N,Ue),D(N,n,Oe);const Fe=n.selectable||l.role===c.ADMIN,Ge=L(n,n.borderColor,"stroke",n.borderSize/2);return r(e,{children:[We&&t(m,{element:n}),He&&t(g,{element:n,text:"Can not load the image..."}),t(k,Object.assign({as:d,nodeRef:N,element:n,name:"element",id:n.id,image:Oe},ke.position,{width:ke.width||1,height:ke.height||1,opacity:Ue},a(n),{customCrop:Me,listening:Fe,draggable:!n.pendingEdit&&(null===(y=l.activeTool)||void 0===y?void 0:y.elementId)!==n.id&&(G?n.draggable&&n.isSelected:n.draggable),preventDefault:!G||n.isSelected,hideInExport:!n.showInExport,onDragMove:e=>{n.set({x:e.target.x(),y:e.target.y()})},onDragEnd:e=>{n.set(I(e.target))},onDblClick:Xe,onDblTap:Xe},Ne)),!!n.borderSize&&t(k,Object.assign({as:h,element:n},ke.position,{width:Math.max(ke.width-n.borderSize,0),height:Math.max(ke.height-n.borderSize,0),opacity:Ue,offsetX:-n.borderSize/2,offsetY:-n.borderSize/2},Ge,{strokeWidth:n.borderSize,listening:!1,cornerRadius:Math.max(0,Ee-n.borderSize),hideInExport:!n.showInExport})),n._cropModeEnabled&&"loaded"===re&&t(Y,{element:n,store:l,previewImage:Oe,sourceImage:fe,sourceWidth:fe.width,sourceHeight:fe.height,crop:Me,onSourceTouchMove:e=>{e.evt.preventDefault();const t=e.target.getStage().getPointersPositions();var r=t[0],o=t[1];const i=e.target;if(r&&!o&&!i.isDragging()&&Te.current&&(i.startDrag(),Te.current=!1),r&&o){u.hitOnDragEnabled=!0,i.isDragging()&&(Te.current=!0,i.stopDrag());const t=e.target.getAbsoluteTransform().copy();t.invert();var a={x:r.x,y:r.y},s={x:o.x,y:o.y};if(!_e.current){return void(_e.current=ce(a,s))}var d=ce(a,s),h=function(e,t){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}(a,s);Le.current||(Le.current=h);const v=i.position();var c={x:d.x-v.x,y:d.y-v.y},g=h/Le.current;i.scaleX(g),i.scaleY(g);const w=t.point(d),x=t.point(_e.current);var m=w.x-x.x,p=w.y-x.y,f={x:Math.min(0,d.x-c.x*g+m),y:Math.min(0,d.y-c.y*g+p)};i.position(f),Le.current=h,_e.current=d,(e=>{T(e,n,X(n,l),fe.width,fe.height,Se,be)})(e)}},onSourceTouchEnd:e=>{Le.current=0,_e.current=null,u.hitOnDragEnabled=!1}}),"image"===n.type&&t(A,{element:n,store:l})]})});
@@ -1 +1 @@
1
- var t=this&&this.__rest||function(t,e){var o={};for(var i in t){Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(o[i]=t[i])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(t);r<i.length;r++){e.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(t,i[r])&&(o[i[r]]=t[i[r]])}}return o};import{Fragment as e,jsx as o,jsxs as i}from"react/jsx-runtime";import{elementOpacity as r}from"./paint-opacity.js";import n from"react";import{observer as s}from"mobx-react-lite";import{Group as a,Path as l,Rect as c,Shape as d}from"react-konva";import{nodeAutorun as u}from"../utils/mobx.js";import{isAlive as h}from"mobx-state-tree";import{Html as f}from"react-konva-utils";import{drawLayout as g}from"render-tag";import{drawTextOnPathLayout as m}from"render-tag/path";import{activeAnchorOf as p,isCornerAnchor as b,isRotateAnchor as x,scaledFontSizeAttrs as v,scaledFontSizeBounds as w,roundedFontSizeAttrs as y,roundedTextDecorationAttrs as j,scaledStyleAttrs as O,roundedGeometryPx as z,roundedPosition as E,paddedTextMinResizeWidth as S,roundedTextPaddingAttrs as M,transformScale as R}from"../utils/px.js";import{flags as k}from"../utils/flags.js";import{editorTextSizing as X,textOverflowOf as Y,textResizeFloorFontSize as C}from"../utils/text-sizing.js";import{curvedBoxWidth as P,layoutAsSized as T,layoutCurvedTextSizing as F,layoutTextSizing as I,renderTagLayoutAt as A}from"@polotno/core/text-sizing";import{curveLayoutAt as B}from"@polotno/core/curve-glyphs";import{applyFilter as H}from"./apply-filters.js";import{getLineHeight as L}from"./text-element.js";import{liveFitScale as $,useRenderTagSource as D}from"./text-element/render-tag-source.js";import{getHtml as _,getCurveTextHeight as J,letterSpacingOverhang as N}from"@polotno/core/text-html";import{withDisplayTextPaints as U}from"./use-color.js";import{toDisplayColor as V}from"@polotno/core/color";import{animatedShadow as q}from"./animated-shadow.js";import{detectSize as W}from"@polotno/core/measure-html";import{generateBackgroundShapeFromRects as G,trimTrailingLetterSpace as K}from"@polotno/core/background-shape";import{useFadeIn as Q}from"./use-fadein.js";import{incrementLoader as Z}from"../utils/loader.js";import{removeTags as tt}from"@polotno/core/text";import{shadowCastByBackground as et}from"@polotno/core/filters";import{applyOpacityToColor as ot}from"@polotno/core/svg";import{isTouchDevice as it}from"../utils/screen.js";import{getLimitedFontSize as rt}from"./text-element/max-font-size.js";import{scaleRichTextFontSizesInHtml as nt}from"../utils/rich-text-html.js";import{RichEditor as st}from"./rich-editor.js";import{PlacedNode as at}from"./placed-node.js";import{AutoDeleteEmptyText as lt}from"./text-element/auto-delete-empty-text.js";import{wrapHtmlForRenderTag as ct}from"@polotno/core/reset-style";import{hasMeasuredHeight as dt,resolveTextBoxHeight as ut,textBackgroundRadius as ht,textBackgroundSpread as ft,textContentElement as gt,textOuterHeight as mt,textPadding as pt}from"@polotno/core/text-types";import{TEXT_PRESETS as bt,WIPE_DIRECTION as xt}from"@polotno/core/animation-presets";import{textUnitState as vt}from"../utils/animations.js";export{ct as wrapHtmlForRenderTag};function wt(t,e){return t!==e&&(!k.textVerticalResizeEnabled||t<e)}const yt=({opacity:t,y:e,scale:o,blur:i,from:r,to:n,shift:s})=>t>=1&&!e&&1===o&&!i&&r<=0&&n>=1&&!s;export const RenderTagElement=s(({element:s,store:ct})=>{var jt,Ot,zt,Et,St,Mt,Rt,kt,Xt,Yt,Ct;const Pt=n.useRef(null),Tt=n.useRef(null),[Ft,It]=n.useState(!1),At=n.useRef(s.height),Bt=n.useRef(null),Ht=it(),{textVerticalResizeEnabled:Lt}=k,{fontLoaded:$t,fontFamily:Dt,color:_t,isPlaceholder:Jt,normalizedSourceText:Nt,getHtmlOptions:Ut}=D(s,ct),Vt=s._editModeEnabled;Q(Pt);const qt=Jt?.6:r(s),Wt=_(U(s),Ut),Gt=s.width||1,Kt=(t,e)=>A(U(t),{getHtmlOptions:Ut,textUnits:e}),Qt=Y(s),Zt=X(s),te=s.curveEnabled,ee=pt(s),oe=JSON.stringify(Zt),ie="fixed"===Zt.box?s.height:0,re=Ft?Bt.current:null,ne=n.useMemo(()=>{if(re){return re.sized}const t=s.filled.text,e=Jt?Object.assign(Object.assign({},s),{text:Nt}):void 0!==t&&t!==s.text?Object.assign(Object.assign({},s),{text:t}):s;try{return te?Object.assign({curved:!0},F({element:e,sizing:Zt,layoutAt:B(U(s),{getHtmlOptions:{fontFamily:Dt,color:_t,text:Nt,textIsNormalized:!0}})})):Object.assign({curved:!1},I({element:gt(e),sizing:Zt,layoutAt:Kt(gt(s))}))}catch(o){return console.error("render-tag layout failed:",o),null}},[Wt,Gt,$t,te,oe,ie,s.curvePower,s.fontSize,s.width,s.paddingTop,s.paddingRight,s.paddingBottom,s.paddingLeft,re]),se=null!==(jt=null==re?void 0:re.width)&&void 0!==jt?jt:Gt,ae=re?s.width/re.width:1,le=!1===(null==ne?void 0:ne.curved)?ne.layout:null,ce=(null==ne?void 0:ne.curved)?ne.layout:null,de=s.a.text,ue=s.a.textUnits,he=ue?bt[ue.animation.name].unit:void 0,fe=n.useMemo(()=>{var t;const e="string"==typeof de&&de!==(null!==(t=s.filled.text)&&void 0!==t?t:s.text);if(!1!==(null==ne?void 0:ne.curved)||Jt||!e&&!he){return le}try{const t=gt(s);return T({element:e?Object.assign(Object.assign({},t),{text:de}):t,sized:ne,sizing:Zt,layoutAt:Kt(t,he)})}catch(o){return console.error("render-tag layout failed:",o),le}},[le,de,he]),ge=ue&&(null==fe?void 0:fe.textUnits),me=n.useMemo(()=>{if(!ue||!ge){return null}const t=ge.map((t,e)=>vt(ue,e,ge.length)),e=e=>!t[e]||yt(t[e]);return t.map((t,o)=>({state:t,slice:yt(t)&&e(o-1)&&e(o+1)}))},[ue,ge]),pe=null!==(Ot=null==ne?void 0:ne.fontSize)&&void 0!==Ot?Ot:s.fontSize,be=null!==(zt=null==ne?void 0:ne.scale)&&void 0!==zt?zt:1,xe=N(s.letterSpacing,pe),ve=null!==(Et=null==re?void 0:re.overhang)&&void 0!==Et?Et:xe,we=L({fontLoaded:$t,fontFamily:s.fontFamily,fontSize:pe,lineHeight:s.lineHeight}),ye=te?0:Math.max(null!==(St=null==le?void 0:le.height)&&void 0!==St?St:0,pe*we),je=te?ye:mt(s,ye),Oe=ce?ce.bounds:null,ze=Oe?(s.width-Oe.width)/2-Oe.x:0,Ee=n.useMemo(()=>{var t;if(ce&&Oe){const t=ce.paintBounds;return Object.assign(Object.assign({},t),{x:t.x+ze,y:t.y-Oe.y})}const e=null!==(t=null==fe?void 0:fe.paintBounds)&&void 0!==t?t:null;return e&&ge?{x:e.x-pe,y:e.y-pe,width:e.width+2*pe,height:e.height+2*pe}:e},[fe,ce,Oe,ze,ge,pe]),Se=n.useMemo(()=>fe?fe.lines.map(t=>K({left:t.bounds.x,right:t.bounds.x+t.bounds.width,top:t.bounds.y,bottom:t.bounds.y+t.bounds.height},ve)):[],[fe,ve]),Me=n.useRef([]),Re=n.useRef(null),ke=n.useRef(!0),[,Xe]=n.useReducer(t=>t+1,0);n.useEffect(()=>{const t=Me.current;t.length>0&&(Me.current=[],t.forEach(t=>t()))});const Ye=n.useCallback((t,e,o,i)=>{const r=Z(`text ${s.id}`),n=()=>{ct.history.ignore(t,e,o).then(()=>{ke.current?(Me.current.push(r),Xe()):r()})};i?queueMicrotask(n):n()},[s.id,ct]),Ce=n.useCallback(t=>{const e=null!==Re.current;Re.current=t,e||Ye(()=>{const t=Re.current;Re.current=null,h(s)&&wt(s.height,t)&&s.set({height:t})},!1,!0)},[s,Ye]),Pe=n.useRef(ne);Pe.current=ne,n.useEffect(()=>{if(!$t){return}if(!le){return}if(!dt(s)){return void Ye(()=>{h(s)&&(dt(s)||s.set({height:je}))},void 0,void 0,!0)}if(ct.isPlaying){return}const t=wt(s.height,je),e=()=>Ce(je);if(void 0===s.filled.text||"change-font-size"!==Qt){if("change-font-size"!==Qt||Ft||Vt||s.curveEnabled){"resize"===Qt&&t&&!Ft&&e()}else if(ne&&ne.fontSize!==s.fontSize){const{fontSize:t,text:e}=ne;Ye(()=>{if(!h(s)){return}if(Pe.current!==ne||"change-font-size"!==Y(s)||s._editModeEnabled){return}const o=v(s,t);Jt||e===s.text||(o.text=e),s.set(o)},!1,!0)}else{t&&e()}}}),n.useEffect(()=>()=>{ke.current=!1;const t=Me.current;t.length>0&&(Me.current=[],t.forEach(t=>t()))},[]),n.useLayoutEffect(()=>{if(!$t||!s.curveEnabled||Ft){return}if(!Oe||!Oe.width){return}const t=t=>t&&Lt?Math.max(t,Oe.height):Oe.height,e=t=>P(Zt,{width:t},Oe.width);Math.abs(e(s.width)-s.width)<1&&Math.abs(t(s.height)-s.height)<1||Ye(()=>{if(!h(s)){return}const o=e(s.width),i=o-s.width,r=t(s.height),n=r-s.height;if(Math.abs(i)<1&&Math.abs(n)<1){return}const a=s.a.rotation*Math.PI/180,l=-i/2*Math.cos(a),c=-i/2*Math.sin(a);s.set({width:o,height:r,x:s.a.x+l,y:s.a.y+c})},!1,!0,!0)},[$t,s.curveEnabled,Qt,Oe,Ft,Lt,Ye]),n.useEffect(()=>u(s,()=>{const t=Pt.current;t&&H(t,s)}),[fe,ce,s.a.width,s.a.height,ue,s.a.shadowColor,s.a.shadowOffsetX,s.a.shadowOffsetY,s.a.shadowOpacity]);const Te=ut(s,je),Fe=te||!$t||Ft||ct.isPlaying||"resize"!==Qt?s.a.height:Lt?Math.max(s.a.height,je):je,Ie=ut(gt(s),ye);let Ae=0;te||"middle"!==s.verticalAlign?te||"bottom"!==s.verticalAlign||(Ae=Ie-ye*ae):Ae=(Ie-ye*ae)/2;const Be=null!==(Mt=null==re?void 0:re.backgroundPadding)&&void 0!==Mt?Mt:ft(s,we),He=null!==(Rt=null==re?void 0:re.backgroundCornerRadius)&&void 0!==Rt?Rt:ht(s,we),Le=s.backgroundEnabled||s.borderSize>0,$e="box"===s.backgroundShape,De=n.useMemo(()=>!Le||s.curveEnabled||$e||0===Se.length?"":G({rects:Se,padding:Be,cornerRadius:He}),[Le,s.curveEnabled,$e,Se,Be,He]),_e=n.useRef(null),Je=n.useRef(s.width),Ne=n.useRef(null),Ue=n.useRef(null),Ve=n.useRef(""),qe=n.useRef(0),We=n.useRef(0),Ge=n.useRef({fontSize:s.fontSize}),Ke=s.width>0?s.a.width/s.width:1,Qe=Ke*ae,Ze=ee.left&&ae>0?ee.left/ae:0,to=ee.top&&ae>0?ee.top/ae:0,eo=q(s),oo=null!==(kt=null==re?void 0:re.shadow)&&void 0!==kt?kt:{shadowBlur:eo.shadowBlur*be,shadowOffsetX:eo.shadowOffsetX*be,shadowOffsetY:eo.shadowOffsetY*be},io=Object.assign(Object.assign({},oo),{shadowColor:eo.shadowColor,shadowOpacity:eo.shadowOpacity}),ro=Object.assign(Object.assign({},io),{shadowEnabled:eo.shadowEnabled&&Le});return i(e,{children:[o(lt,{element:s,store:ct}),Le?s.curveEnabled||$e?o(at,Object.assign({as:c,element:s,offsetX:Be/Ke,offsetY:Be/Ke,scaleX:Qe,scaleY:Qe,hideInExport:!s.showInExport,listening:!1,opacity:qt,fillEnabled:s.backgroundEnabled,fill:ot(s.backgroundColor,s.backgroundOpacity),strokeEnabled:s.borderSize>0,stroke:V(s.borderColor),strokeWidth:null!==(Xt=null==re?void 0:re.borderSize)&&void 0!==Xt?Xt:s.borderSize},ro,{width:se+2*Be,height:(null!==(Yt=null==re?void 0:re.boxHeight)&&void 0!==Yt?Yt:Te)+2*Be,cornerRadius:He})):o(at,Object.assign({as:l,element:s,name:"rendertag-background",offsetX:Ze?-Ze:void 0,offsetY:-(to+Ae/Qe),scaleX:Qe,scaleY:Qe,hideInExport:!s.showInExport,listening:!1,visible:De.length>0,opacity:qt,fillEnabled:s.backgroundEnabled,fill:ot(s.backgroundColor,s.backgroundOpacity),strokeEnabled:s.borderSize>0,stroke:V(s.borderColor),strokeWidth:null!==(Ct=null==re?void 0:re.borderSize)&&void 0!==Ct?Ct:s.borderSize,lineJoin:He>0?"round":"miter"},ro,{data:De})):null,o(at,Object.assign({as:d,nodeRef:Pt,element:s,selfRectFunc:Ee?()=>Ee:void 0,name:"rendertag-text",scaleX:Qe,scaleY:Qe,offsetX:Ze&&Qe>0?-Ze:void 0,offsetY:Qe>0?-(to+Ae/Qe):0,width:se,height:Math.max(s.height,ye),listening:!1,visible:!Vt&&!!(te?ce:le),editModeEnabled:Vt,opacity:qt,shadowEnabled:eo.shadowEnabled&&!et(s)},io,{hideInExport:!s.showInExport,sceneFunc:(t,e)=>{const o=t._context;if(o){try{if(te){if(!ce||!Oe){return}o.save(),o.translate(ze,-Oe.y),m({layout:ce,ctx:o}),o.restore()}else{if(!fe){return}g({layout:fe,width:se,ctx:o,pixelRatio:1,paintTextUnit:me?t=>{const{state:e,slice:o}=me[t.unit.index];(({unit:t,ctx:e,draw:o},{opacity:i,y:r,scale:n,blur:s,from:a,to:l,direction:c,shift:d},u,h)=>{if(!(i<=0||n<=0||l<=a)){if(a>0||l<1||d){const{vertical:o,low:i,high:r,forward:n}=((t,e,o)=>{var i;const r=e?xt[e]:void 0,n="y"===(null==r?void 0:r.axis);let s=n?t.y:t.x,a=s+(n?t.height:t.width);if(n||o){for(const l of t.fragments){s=Math.min(s,n?l.paintTop:l.paintLeft),a=Math.max(a,n?l.paintBottom:l.paintRight)}}return{vertical:n,low:s,high:a,forward:r?r.forward:"rtl"!==(null===(i=t.fragments[0])||void 0===i?void 0:i.direction)}})(t,c,0!==d),s=r-i,[h,f]=n?[a,l]:[1-l,1-a],g=h<=0&&!d?i-u:i+h*s,m=f>=1&&!d?r+u:i+f*s;e.beginPath(),o?e.rect(t.x-u,g,t.width+2*u,m-g):e.rect(g,t.y-u,m-g,t.height+2*u),e.clip();const p=d*s*(n?1:-1);o?e.translate(0,p):e.translate(p,0)}if(e.globalAlpha*=i,r&&e.translate(0,r*u),1!==n){const o=t.x+t.width/2,i=t.y+t.height/2;e.translate(o,i),e.scale(n,n),e.translate(-o,-i)}if(s>0){const t=e.getTransform(),o=Math.sqrt(Math.abs(t.a*t.d-t.b*t.c));e.filter=`blur(${s*u*o}px)`}o({slice:h})}})(t,e,pe,o)}:void 0})}}catch(i){console.error("render-tag draw failed:",i)}}}})),o(at,{as:c,nodeRef:Tt,element:s,name:"element",listening:s.selectable,width:s.a.width,height:Fe,visible:!Vt,draggable:Ht?s.draggable&&s.isSelected:s.draggable,preventDefault:!Ht||s.isSelected,opacity:0,hideInExport:!0,id:s.id,onDragMove:t=>{s.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{s.set(E(t.target))},onDblClick:t=>{s.contentEditable&&(Ue.current={x:t.evt.clientX,y:t.evt.clientY},s.toggleEditMode(!0))},onDblTap:t=>{var e;if(s.contentEditable){const o=null===(e=t.evt.changedTouches)||void 0===e?void 0:e[0];Ue.current=o?{x:o.clientX,y:o.clientY}:null,s.toggleEditMode(!0)}},onTransformStart:t=>{At.current=s.height,Je.current=s.width,Ne.current=null,_e.current=t.target.position(),Ve.current=p(t.target),qe.current=s.a.rotation,We.current=s.height,Ge.current={fontSize:s.fontSize,minFontSize:s.minFontSize,maxFontSize:s.maxFontSize},Bt.current=!s.curveEnabled&&["top-left","top-right","bottom-left","bottom-right"].includes(Ve.current)?{sized:ne,width:Gt,boxHeight:Te,backgroundPadding:Be,backgroundCornerRadius:He,borderSize:s.borderSize,overhang:xe,shadow:oo}:null,It(!0)},onTransform:e=>{const o=e.target,i=Ve.current,r="middle-left"===i||"middle-right"===i,n="top-center"===i||"bottom-center"===i,a=R(o.scaleX());if(r){const e=o.width()*a;let i=Math.max(e,S(te?{}:s,Je.current,C(s)));const r=s.toJSON();let n=0;if("fit"===Qt){n=At.current}else if(s.curveEnabled){n=J(Object.assign(Object.assign({},r),{width:i}))}else{const{x:e,y:o,width:s,height:a}=r,l=t(r,["x","y","width","height"]),c=`${JSON.stringify(l)}|${Dt}|${$t}|${_t}`;if(Ne.current&&Ne.current.signature===c&&i<=Ne.current.width){i=Ne.current.width,n=Ne.current.height}else{const t=t=>{const e=gt(Object.assign(Object.assign({},r),{width:t}));try{return I({element:Object.assign(Object.assign({},e),{text:Nt}),sizing:Object.assign(Object.assign({},Zt),{fit:{mode:"off"},cutAtBox:!1}),layoutAt:Kt(e)}).layout}catch(jt){const o=_(e,Ut);return{height:W(o).height,lines:[]}}};let e=t(i);const o=Math.max(0,...e.lines.map(t=>t.bounds.x+t.bounds.width-xe)),s=ee.left+ee.right;o+s>i+.5&&o+s<=Je.current+.5&&(i=Math.min(Math.ceil(o)+s,Je.current),e=t(i),Ne.current={signature:c,width:i,height:e.height}),n=e.height}n+=ee.top+ee.bottom}i>e&&_e.current&&o.position(_e.current),o.width(i),o.scaleX(1),o.scaleY(1);let l=k.textVerticalResizeEnabled?Math.max(n,At.current):n;"ellipsis"!==Qt&&"fit"!==Qt||(l=At.current),o.height(l),s.set({width:o.width(),height:l,x:o.x(),y:o.y()})}else if(n){const t="resize"===Qt?te?(null==Oe?void 0:Oe.height)||s.fontSize:je:we*("fit"===Zt.fit.mode?Zt.fit.min:s.fontSize)+ee.top+ee.bottom,e=o.height()*o.scaleY();if(e<t){if(o.height(t),_e.current){if("top-center"===Ve.current){const e=qe.current*Math.PI/180,i=We.current-t;o.x(_e.current.x-i*Math.sin(e)),o.y(_e.current.y+i*Math.cos(e))}else{o.position(_e.current)}}}else{o.height(e)}o.scaleY(1),o.scaleX(1),We.current=Math.max(t,e),s.set({x:o.x(),y:o.y(),height:o.height(),rotation:o.rotation()})}else{o.scaleX(1),o.scaleY(1);const t=s.fontSize*a;s.set(Object.assign(Object.assign(Object.assign({},w(Ge.current,t/Ge.current.fontSize)),{letterSpacing:s.letterSpacing,width:o.width()*a,x:o.x(),y:o.y(),rotation:o.rotation(),height:o.height()*a}),O(s,a)))}_e.current=e.target.position()},onTransformEnd:t=>{Bt.current=null,It(!1);const e=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1);const o=y(s,s.fontSize*e),i=Ge.current,r=Ve.current;s.set(Object.assign(Object.assign(Object.assign({},o),b(r)&&!x(r)?Object.assign(Object.assign({},w(i,o.fontSize/i.fontSize,!0)),M(s)):{}),{width:z(t.target.width()*e),x:z(t.target.x()),y:z(t.target.y()),rotation:z(t.target.rotation()),text:nt(s.text,e)}))}}),Vt&&o(at,{as:a,element:s,offsetX:ee.left?-ee.left:void 0,offsetY:-(ee.top+Ae),children:o(f,{divProps:{style:{zIndex:20}},children:o(st,{element:s,fitScale:be,fitScaleFor:t=>te?be:$(gt(s),Zt,Ut,t,be),onChange:t=>{if("fit"===Qt){return void s.set({text:t})}const e=rt({oldText:tt(s.text),newText:tt(t),element:s});s.set(Object.assign({text:t},v(s,e)))},onBlur:()=>{h(s)&&(s.set(j(s)),s.toggleEditMode(!1))},clickCoords:Ue.current})})})]})});
1
+ var t=this&&this.__rest||function(t,e){var o={};for(var i in t){Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(o[i]=t[i])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(t);r<i.length;r++){e.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(t,i[r])&&(o[i[r]]=t[i[r]])}}return o};import{Fragment as e,jsx as o,jsxs as i}from"react/jsx-runtime";import{elementOpacity as r}from"./paint-opacity.js";import n from"react";import{observer as s}from"mobx-react-lite";import{Group as a,Path as l,Rect as c,Shape as d}from"react-konva";import{nodeAutorun as u}from"../utils/mobx.js";import{isAlive as h}from"mobx-state-tree";import{Html as f}from"react-konva-utils";import{drawLayout as g}from"render-tag";import{drawTextOnPathLayout as m}from"render-tag/path";import{activeAnchorOf as p,isCornerAnchor as b,isRotateAnchor as x,scaledFontSizeAttrs as v,scaledFontSizeBounds as y,roundedFontSizeAttrs as w,roundedTextDecorationAttrs as j,scaledStyleAttrs as O,roundedGeometryPx as z,roundedPosition as E,paddedTextMinResizeWidth as S,roundedTextPaddingAttrs as M,transformScale as R}from"../utils/px.js";import{flags as k}from"../utils/flags.js";import{editorTextSizing as X,textOverflowOf as Y,textResizeFloorFontSize as C}from"../utils/text-sizing.js";import{curvedBoxWidth as P,curveOrigin as T,layoutAsSized as F,layoutCurvedTextSizing as I,layoutTextSizing as A,renderTagLayoutAt as B}from"@polotno/core/text-sizing";import{curveLayoutAt as H}from"@polotno/core/curve-glyphs";import{applyFilter as L}from"./apply-filters.js";import{getLineHeight as $}from"./text-element.js";import{liveFitScale as D,useRenderTagSource as _}from"./text-element/render-tag-source.js";import{getHtml as J,getCurveTextHeight as N,letterSpacingOverhang as U}from"@polotno/core/text-html";import{withDisplayTextPaints as V}from"./use-color.js";import{toDisplayColor as q}from"@polotno/core/color";import{animatedShadow as W}from"./animated-shadow.js";import{detectSize as G}from"@polotno/core/measure-html";import{generateBackgroundShapeFromRects as K,trimTrailingLetterSpace as Q}from"@polotno/core/background-shape";import{useFadeIn as Z}from"./use-fadein.js";import{incrementLoader as tt}from"../utils/loader.js";import{removeTags as et}from"@polotno/core/text";import{shadowCastByBackground as ot}from"@polotno/core/filters";import{applyOpacityToColor as it}from"@polotno/core/svg";import{isTouchDevice as rt}from"../utils/screen.js";import{getLimitedFontSize as nt}from"./text-element/max-font-size.js";import{scaleRichTextFontSizesInHtml as st}from"../utils/rich-text-html.js";import{RichEditor as at}from"./rich-editor.js";import{PlacedNode as lt}from"./placed-node.js";import{AutoDeleteEmptyText as ct}from"./text-element/auto-delete-empty-text.js";import{wrapHtmlForRenderTag as dt}from"@polotno/core/reset-style";import{hasMeasuredHeight as ut,resolveTextBoxHeight as ht,textBackgroundRadius as ft,textBackgroundSpread as gt,textContentElement as mt,textOuterHeight as pt,textPadding as bt}from"@polotno/core/text-types";import{TEXT_PRESETS as xt,WIPE_DIRECTION as vt}from"@polotno/core/animation-presets";import{textUnitState as yt}from"../utils/animations.js";export{dt as wrapHtmlForRenderTag};function wt(t,e){return t!==e&&(!k.textVerticalResizeEnabled||t<e)}const jt=({opacity:t,y:e,scale:o,blur:i,from:r,to:n,shift:s})=>t>=1&&!e&&1===o&&!i&&r<=0&&n>=1&&!s;export const RenderTagElement=s(({element:s,store:dt})=>{var Ot,zt,Et,St,Mt,Rt,kt,Xt,Yt,Ct,Pt;const Tt=n.useRef(null),Ft=n.useRef(null),[It,At]=n.useState(!1),Bt=n.useRef(s.height),Ht=n.useRef(null),Lt=rt(),{textVerticalResizeEnabled:$t}=k,{fontLoaded:Dt,fontFamily:_t,color:Jt,isPlaceholder:Nt,normalizedSourceText:Ut,getHtmlOptions:Vt}=_(s,dt),qt=s._editModeEnabled;Z(Tt);const Wt=Nt?.6:r(s),Gt=J(V(s),Vt),Kt=s.width||1,Qt=(t,e)=>B(V(t),{getHtmlOptions:Vt,textUnits:e}),Zt=Y(s),te=X(s),ee=s.curveEnabled,oe=bt(s),ie=JSON.stringify(te),re="fixed"===te.box?s.height:0,ne=It?Ht.current:null,se=n.useMemo(()=>{if(ne){return ne.sized}const t=s.filled.text,e=Nt?Object.assign(Object.assign({},s),{text:Ut}):void 0!==t&&t!==s.text?Object.assign(Object.assign({},s),{text:t}):s;try{return ee?Object.assign({curved:!0},I({element:e,sizing:te,layoutAt:H(V(s),{getHtmlOptions:{fontFamily:_t,color:Jt,text:Ut,textIsNormalized:!0}})})):Object.assign({curved:!1},A({element:mt(e),sizing:te,layoutAt:Qt(mt(s))}))}catch(o){return console.error("render-tag layout failed:",o),null}},[Gt,Kt,Dt,ee,ie,re,s.curvePower,s.fontSize,s.width,s.paddingTop,s.paddingRight,s.paddingBottom,s.paddingLeft,ne]),ae=null!==(Ot=null==ne?void 0:ne.width)&&void 0!==Ot?Ot:Kt,le=ne?s.width/ne.width:1,ce=!1===(null==se?void 0:se.curved)?se.layout:null,de=(null==se?void 0:se.curved)?se.layout:null,ue=s.a.text,he=s.a.textUnits,fe=he?xt[he.animation.name].unit:void 0,ge=n.useMemo(()=>{var t;const e="string"==typeof ue&&ue!==(null!==(t=s.filled.text)&&void 0!==t?t:s.text);if(!1!==(null==se?void 0:se.curved)||Nt||!e&&!fe){return ce}try{const t=mt(s);return F({element:e?Object.assign(Object.assign({},t),{text:ue}):t,sized:se,sizing:te,layoutAt:Qt(t,fe)})}catch(o){return console.error("render-tag layout failed:",o),ce}},[ce,ue,fe]),me=he&&(null==ge?void 0:ge.textUnits),pe=n.useMemo(()=>{if(!he||!me){return null}const t=me.map((t,e)=>yt(he,e,me.length)),e=e=>!t[e]||jt(t[e]);return t.map((t,o)=>({state:t,slice:jt(t)&&e(o-1)&&e(o+1)}))},[he,me]),be=null!==(zt=null==se?void 0:se.fontSize)&&void 0!==zt?zt:s.fontSize,xe=null!==(Et=null==se?void 0:se.scale)&&void 0!==Et?Et:1,ve=U(s.letterSpacing,be),ye=null!==(St=null==ne?void 0:ne.overhang)&&void 0!==St?St:ve,we=$({fontLoaded:Dt,fontFamily:s.fontFamily,fontSize:be,lineHeight:s.lineHeight}),je=ee?0:Math.max(null!==(Mt=null==ce?void 0:ce.height)&&void 0!==Mt?Mt:0,be*we),Oe=ee?je:pt(s,je),ze=de?de.bounds:null,{x:Ee,y:Se}=ze?T(s.width,ze):{x:0,y:0},Me=n.useMemo(()=>{var t;if(de&&ze){const t=de.paintBounds;return Object.assign(Object.assign({},t),{x:t.x+Ee,y:t.y+Se})}const e=null!==(t=null==ge?void 0:ge.paintBounds)&&void 0!==t?t:null;return e&&me?{x:e.x-be,y:e.y-be,width:e.width+2*be,height:e.height+2*be}:e},[ge,de,ze,Ee,Se,me,be]),Re=n.useMemo(()=>ge?ge.lines.map(t=>Q({left:t.bounds.x,right:t.bounds.x+t.bounds.width,top:t.bounds.y,bottom:t.bounds.y+t.bounds.height},ye)):[],[ge,ye]),ke=n.useRef([]),Xe=n.useRef(null),Ye=n.useRef(!0),[,Ce]=n.useReducer(t=>t+1,0);n.useEffect(()=>{const t=ke.current;t.length>0&&(ke.current=[],t.forEach(t=>t()))});const Pe=n.useCallback((t,e,o,i)=>{const r=tt(`text ${s.id}`),n=()=>{dt.history.ignore(t,e,o).then(()=>{Ye.current?(ke.current.push(r),Ce()):r()})};i?queueMicrotask(n):n()},[s.id,dt]),Te=n.useCallback(t=>{const e=null!==Xe.current;Xe.current=t,e||Pe(()=>{const t=Xe.current;Xe.current=null,h(s)&&wt(s.height,t)&&s.set({height:t})},!1,!0)},[s,Pe]),Fe=n.useRef(se);Fe.current=se,n.useEffect(()=>{if(!Dt){return}if(!ce){return}if(!ut(s)){return void Pe(()=>{h(s)&&(ut(s)||s.set({height:Oe}))},void 0,void 0,!0)}if(dt.isPlaying){return}const t=wt(s.height,Oe),e=()=>Te(Oe);if(void 0===s.filled.text||"change-font-size"!==Zt){if("change-font-size"!==Zt||It||qt||s.curveEnabled){"resize"===Zt&&t&&!It&&e()}else if(se&&se.fontSize!==s.fontSize){const{fontSize:t,text:e}=se;Pe(()=>{if(!h(s)){return}if(Fe.current!==se||"change-font-size"!==Y(s)||s._editModeEnabled){return}const o=v(s,t);Nt||e===s.text||(o.text=e),s.set(o)},!1,!0)}else{t&&e()}}}),n.useEffect(()=>()=>{Ye.current=!1;const t=ke.current;t.length>0&&(ke.current=[],t.forEach(t=>t()))},[]),n.useLayoutEffect(()=>{if(!Dt||!s.curveEnabled||It){return}if(!ze||!ze.width){return}const t=t=>t&&$t?Math.max(t,ze.height):ze.height,e=t=>P(te,{width:t},ze.width);Math.abs(e(s.width)-s.width)<1&&Math.abs(t(s.height)-s.height)<1||Pe(()=>{if(!h(s)){return}const o=e(s.width),i=o-s.width,r=t(s.height),n=r-s.height;if(Math.abs(i)<1&&Math.abs(n)<1){return}const a=s.a.rotation*Math.PI/180,l=-i/2*Math.cos(a),c=-i/2*Math.sin(a);s.set({width:o,height:r,x:s.a.x+l,y:s.a.y+c})},!1,!0,!0)},[Dt,s.curveEnabled,Zt,ze,It,$t,Pe]),n.useEffect(()=>u(s,()=>{const t=Tt.current;t&&L(t,s)}),[ge,de,s.a.width,s.a.height,he,s.a.shadowColor,s.a.shadowOffsetX,s.a.shadowOffsetY,s.a.shadowOpacity]);const Ie=ht(s,Oe),Ae=ee||!Dt||It||dt.isPlaying||"resize"!==Zt?s.a.height:$t?Math.max(s.a.height,Oe):Oe,Be=ht(mt(s),je);let He=0;ee||"middle"!==s.verticalAlign?ee||"bottom"!==s.verticalAlign||(He=Be-je*le):He=(Be-je*le)/2;const Le=null!==(Rt=null==ne?void 0:ne.backgroundPadding)&&void 0!==Rt?Rt:gt(s,we),$e=null!==(kt=null==ne?void 0:ne.backgroundCornerRadius)&&void 0!==kt?kt:ft(s,we),De=s.backgroundEnabled||s.borderSize>0,_e="box"===s.backgroundShape,Je=n.useMemo(()=>!De||s.curveEnabled||_e||0===Re.length?"":K({rects:Re,padding:Le,cornerRadius:$e}),[De,s.curveEnabled,_e,Re,Le,$e]),Ne=n.useRef(null),Ue=n.useRef(s.width),Ve=n.useRef(null),qe=n.useRef(null),We=n.useRef(""),Ge=n.useRef(0),Ke=n.useRef(0),Qe=n.useRef({fontSize:s.fontSize}),Ze=s.width>0?s.a.width/s.width:1,to=Ze*le,eo=oe.left&&le>0?oe.left/le:0,oo=oe.top&&le>0?oe.top/le:0,io=W(s),ro=null!==(Xt=null==ne?void 0:ne.shadow)&&void 0!==Xt?Xt:{shadowBlur:io.shadowBlur*xe,shadowOffsetX:io.shadowOffsetX*xe,shadowOffsetY:io.shadowOffsetY*xe},no=Object.assign(Object.assign({},ro),{shadowColor:io.shadowColor,shadowOpacity:io.shadowOpacity}),so=Object.assign(Object.assign({},no),{shadowEnabled:io.shadowEnabled&&De});return i(e,{children:[o(ct,{element:s,store:dt}),De?s.curveEnabled||_e?o(lt,Object.assign({as:c,element:s,offsetX:Le/Ze,offsetY:Le/Ze,scaleX:to,scaleY:to,hideInExport:!s.showInExport,listening:!1,opacity:Wt,fillEnabled:s.backgroundEnabled,fill:it(s.backgroundColor,s.backgroundOpacity),strokeEnabled:s.borderSize>0,stroke:q(s.borderColor),strokeWidth:null!==(Yt=null==ne?void 0:ne.borderSize)&&void 0!==Yt?Yt:s.borderSize},so,{width:ae+2*Le,height:(null!==(Ct=null==ne?void 0:ne.boxHeight)&&void 0!==Ct?Ct:Ie)+2*Le,cornerRadius:$e})):o(lt,Object.assign({as:l,element:s,name:"rendertag-background",offsetX:eo?-eo:void 0,offsetY:-(oo+He/to),scaleX:to,scaleY:to,hideInExport:!s.showInExport,listening:!1,visible:Je.length>0,opacity:Wt,fillEnabled:s.backgroundEnabled,fill:it(s.backgroundColor,s.backgroundOpacity),strokeEnabled:s.borderSize>0,stroke:q(s.borderColor),strokeWidth:null!==(Pt=null==ne?void 0:ne.borderSize)&&void 0!==Pt?Pt:s.borderSize,lineJoin:$e>0?"round":"miter"},so,{data:Je})):null,o(lt,Object.assign({as:d,nodeRef:Tt,element:s,selfRectFunc:Me?()=>Me:void 0,name:"rendertag-text",scaleX:to,scaleY:to,offsetX:eo&&to>0?-eo:void 0,offsetY:to>0?-(oo+He/to):0,width:ae,height:Math.max(s.height,je),listening:!1,visible:!qt&&!!(ee?de:ce),editModeEnabled:qt,opacity:Wt,shadowEnabled:io.shadowEnabled&&!ot(s)},no,{hideInExport:!s.showInExport,sceneFunc:(t,e)=>{const o=t._context;if(o){try{if(ee){if(!de||!ze){return}o.save(),o.translate(Ee,Se),m({layout:de,ctx:o}),o.restore()}else{if(!ge){return}g({layout:ge,width:ae,ctx:o,pixelRatio:1,paintTextUnit:pe?t=>{const{state:e,slice:o}=pe[t.unit.index];(({unit:t,ctx:e,draw:o},{opacity:i,y:r,scale:n,blur:s,from:a,to:l,direction:c,shift:d},u,h)=>{if(!(i<=0||n<=0||l<=a)){if(a>0||l<1||d){const{vertical:o,low:i,high:r,forward:n}=((t,e,o)=>{var i;const r=e?vt[e]:void 0,n="y"===(null==r?void 0:r.axis);let s=n?t.y:t.x,a=s+(n?t.height:t.width);if(n||o){for(const l of t.fragments){s=Math.min(s,n?l.paintTop:l.paintLeft),a=Math.max(a,n?l.paintBottom:l.paintRight)}}return{vertical:n,low:s,high:a,forward:r?r.forward:"rtl"!==(null===(i=t.fragments[0])||void 0===i?void 0:i.direction)}})(t,c,0!==d),s=r-i,[h,f]=n?[a,l]:[1-l,1-a],g=h<=0&&!d?i-u:i+h*s,m=f>=1&&!d?r+u:i+f*s;e.beginPath(),o?e.rect(t.x-u,g,t.width+2*u,m-g):e.rect(g,t.y-u,m-g,t.height+2*u),e.clip();const p=d*s*(n?1:-1);o?e.translate(0,p):e.translate(p,0)}if(e.globalAlpha*=i,r&&e.translate(0,r*u),1!==n){const o=t.x+t.width/2,i=t.y+t.height/2;e.translate(o,i),e.scale(n,n),e.translate(-o,-i)}if(s>0){const t=e.getTransform(),o=Math.sqrt(Math.abs(t.a*t.d-t.b*t.c));e.filter=`blur(${s*u*o}px)`}o({slice:h})}})(t,e,be,o)}:void 0})}}catch(i){console.error("render-tag draw failed:",i)}}}})),o(lt,{as:c,nodeRef:Ft,element:s,name:"element",listening:s.selectable,width:s.a.width,height:Ae,visible:!qt,draggable:Lt?s.draggable&&s.isSelected:s.draggable,preventDefault:!Lt||s.isSelected,opacity:0,hideInExport:!0,id:s.id,onDragMove:t=>{s.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{s.set(E(t.target))},onDblClick:t=>{s.contentEditable&&(qe.current={x:t.evt.clientX,y:t.evt.clientY},s.toggleEditMode(!0))},onDblTap:t=>{var e;if(s.contentEditable){const o=null===(e=t.evt.changedTouches)||void 0===e?void 0:e[0];qe.current=o?{x:o.clientX,y:o.clientY}:null,s.toggleEditMode(!0)}},onTransformStart:t=>{Bt.current=s.height,Ue.current=s.width,Ve.current=null,Ne.current=t.target.position(),We.current=p(t.target),Ge.current=s.a.rotation,Ke.current=s.height,Qe.current={fontSize:s.fontSize,minFontSize:s.minFontSize,maxFontSize:s.maxFontSize},Ht.current=!s.curveEnabled&&["top-left","top-right","bottom-left","bottom-right"].includes(We.current)?{sized:se,width:Kt,boxHeight:Ie,backgroundPadding:Le,backgroundCornerRadius:$e,borderSize:s.borderSize,overhang:ve,shadow:ro}:null,At(!0)},onTransform:e=>{const o=e.target,i=We.current,r="middle-left"===i||"middle-right"===i,n="top-center"===i||"bottom-center"===i,a=R(o.scaleX());if(r){const e=o.width()*a;let i=Math.max(e,S(ee?{}:s,Ue.current,C(s)));const r=s.toJSON();let n=0;if("fit"===Zt){n=Bt.current}else if(s.curveEnabled){n=N(Object.assign(Object.assign({},r),{width:i}))}else{const{x:e,y:o,width:s,height:a}=r,l=t(r,["x","y","width","height"]),c=`${JSON.stringify(l)}|${_t}|${Dt}|${Jt}`;if(Ve.current&&Ve.current.signature===c&&i<=Ve.current.width){i=Ve.current.width,n=Ve.current.height}else{const t=t=>{const e=mt(Object.assign(Object.assign({},r),{width:t}));try{return A({element:Object.assign(Object.assign({},e),{text:Ut}),sizing:Object.assign(Object.assign({},te),{fit:{mode:"off"},cutAtBox:!1}),layoutAt:Qt(e)}).layout}catch(Ot){const o=J(e,Vt);return{height:G(o).height,lines:[]}}};let e=t(i);const o=Math.max(0,...e.lines.map(t=>t.bounds.x+t.bounds.width-ve)),s=oe.left+oe.right;o+s>i+.5&&o+s<=Ue.current+.5&&(i=Math.min(Math.ceil(o)+s,Ue.current),e=t(i),Ve.current={signature:c,width:i,height:e.height}),n=e.height}n+=oe.top+oe.bottom}i>e&&Ne.current&&o.position(Ne.current),o.width(i),o.scaleX(1),o.scaleY(1);let l=k.textVerticalResizeEnabled?Math.max(n,Bt.current):n;"ellipsis"!==Zt&&"fit"!==Zt||(l=Bt.current),o.height(l),s.set({width:o.width(),height:l,x:o.x(),y:o.y()})}else if(n){const t="resize"===Zt?ee?(null==ze?void 0:ze.height)||s.fontSize:Oe:we*("fit"===te.fit.mode?te.fit.min:s.fontSize)+oe.top+oe.bottom,e=o.height()*o.scaleY();if(e<t){if(o.height(t),Ne.current){if("top-center"===We.current){const e=Ge.current*Math.PI/180,i=Ke.current-t;o.x(Ne.current.x-i*Math.sin(e)),o.y(Ne.current.y+i*Math.cos(e))}else{o.position(Ne.current)}}}else{o.height(e)}o.scaleY(1),o.scaleX(1),Ke.current=Math.max(t,e),s.set({x:o.x(),y:o.y(),height:o.height(),rotation:o.rotation()})}else{o.scaleX(1),o.scaleY(1);const t=s.fontSize*a;s.set(Object.assign(Object.assign(Object.assign({},y(Qe.current,t/Qe.current.fontSize)),{letterSpacing:s.letterSpacing,width:o.width()*a,x:o.x(),y:o.y(),rotation:o.rotation(),height:o.height()*a}),O(s,a)))}Ne.current=e.target.position()},onTransformEnd:t=>{Ht.current=null,At(!1);const e=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1);const o=w(s,s.fontSize*e),i=Qe.current,r=We.current;s.set(Object.assign(Object.assign(Object.assign({},o),b(r)&&!x(r)?Object.assign(Object.assign({},y(i,o.fontSize/i.fontSize,!0)),M(s)):{}),{width:z(t.target.width()*e),x:z(t.target.x()),y:z(t.target.y()),rotation:z(t.target.rotation()),text:st(s.text,e)}))}}),qt&&o(lt,{as:a,element:s,offsetX:oe.left?-oe.left:void 0,offsetY:-(oe.top+He),children:o(f,{divProps:{style:{zIndex:20}},children:o(at,{element:s,fitScale:xe,fitScaleFor:t=>ee?xe:D(mt(s),te,Vt,t,xe),onChange:t=>{if("fit"===Zt){return void s.set({text:t})}const e=nt({oldText:et(s.text),newText:et(t),element:s});s.set(Object.assign({text:t},v(s,e)))},onBlur:()=>{h(s)&&(s.set(j(s)),s.toggleEditMode(!1))},clickCoords:qe.current})})})]})});
@@ -35,8 +35,10 @@ export type MarkerFont = {
35
35
  export declare function computeMarkerVars(element: MarkerFont): MarkerVars | null;
36
36
  export declare const RichTextContainer: any;
37
37
  export declare const setQuillFormats: (formats: string[]) => void;
38
+ type FormatShortcut = 'bold' | 'italic' | 'underline';
38
39
  export declare const createQuill: (node: any, options?: {
39
40
  placeholder?: string;
41
+ onFormatShortcut?: (toggle: FormatShortcut) => void;
40
42
  }) => Quill;
41
43
  export declare const setQuillContent: (quill: any, html: any) => void;
42
44
  export type RichEditorElement = TextElementType | TableCellType;
@@ -1,4 +1,4 @@
1
- var t=this&&this.__rest||function(t,e){var o={};for(var n in t){Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(o[n]=t[n])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(t);r<n.length;r++){e.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(t,n[r])&&(o[n[r]]=t[n[r]])}}return o};import{jsx as e}from"react/jsx-runtime";import o from"react";import n from"quill";import*as r from"mobx";import{nodeReaction as i}from"../utils/mobx.js";import{isAlive as l}from"mobx-state-tree";import{geckoRtlOverhangCss as s,getDir as a,getMeasureCtx as c,getQuillEditorHtml as d,letterSpacingOverhang as u,OVERHANG_PROPERTY as f,textLayoutWidth as p}from"@polotno/core/text-html";import{textContentBox as m}from"@polotno/core/text-types";import{quillHtmlToModelText as h,isQuillFormatMixed as g,isBoldWeight as b,detachNativeColorsInHtml as v,VARIABLE_TOKEN_CLASS as y}from"../utils/rich-text-html.js";import{variableTokens as x}from"@polotno/schema/variables";import{toDisplayColor as w}from"@polotno/core/color";import{LIST_INDENT_EM as k}from"@polotno/core/css-values";import{resetStyleContent as S,linkStyle as T,wrapHtmlForRenderTag as E}from"@polotno/core/reset-style";import{layout as q,lineBaselineOffset as C}from"render-tag";import{removeTags as L}from"@polotno/core/text";import{cssFontFamily as R}from"@polotno/core/fonts";import{isGradient as O,firstStopColor as F}from"@polotno/core/gradient";import{getOptimalCaretColor as $}from"./text-element/caret-color.js";import{visiblePlaceholder as N}from"./text-element/placeholder.js";import{registerQuillUnrestrictedFontFormats as z,PRESERVED_INLINE_STYLES as j,PRESERVED_BLOCK_STYLES as M,VARIABLE_TOKEN_FORMAT as D}from"./quill-font-formats.js";import{ALL_QUILL_MIXED_KEYS as P,setActiveTextEditor as A,updateActiveTextFormat as H,clearActiveTextEditor as I,getActiveTextEditor as Q}from"../utils/text-format-state.js";import _ from"../utils/styled.js";import{applyOpacityToColor as W}from"@polotno/core/svg";import{elementDropShadow as B,shadowCastByBackground as V}from"@polotno/core/filters";export{W as applyOpacityToColor};export const quillRef=r.observable({enabled:!1,currentFormat:{},pendingToolbarInteraction:!1,editor:r.observable.object({instance:null},{},{deep:!1})});const X=P;export function syncQuillFormatState(t,e){const o=e?t.getFormat(e):{},n=function(t,e){const o={};if(!e||e.length<=0){return o}const n=t.getContents(e.index,e.length);for(const r of X){g(n,r)&&(o[r]=!0)}return o}(t,e);r.runInAction(()=>{quillRef.currentFormat=o}),H(o,n,e)}const G="polotno-saved-selection";function Y(){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(G,new Highlight(e)),K()}function U(){"undefined"!=typeof CSS&&CSS.highlights&&CSS.highlights.delete(G)}function K(){setTimeout(()=>{"undefined"!=typeof CSS&&CSS.highlights&&CSS.highlights.has(G)&&(document.querySelector(".polotno-portal")||ut(document.activeElement)?K():U())},300)}if("undefined"!=typeof document&&"undefined"!=typeof CSS&&CSS.highlights&&!document.querySelector("[data-polotno-highlight]")){const ft=document.createElement("style");ft.setAttribute("data-polotno-highlight",""),ft.textContent=`::highlight(${G}) { background-color: Highlight; }`,document.head.appendChild(ft)}export function collectRTText(t,e){"text"===t.type?e.push(t):t.children.forEach(t=>collectRTText(t,e))}export function computeMarkerVars(t){var e,o,n;const r=t.fontSize;if(!r||r<=0){return null}const i=R(t.fontFamily),l=b(t.fontWeight)?700:400,s="italic"===t.fontStyle?"italic":"normal",a=c();a.fontKerning="normal",a.font=`${r}px ${i}`;const d=a.measureText("M"),u=(null!==(e=d.fontBoundingBoxAscent)&&void 0!==e?e:0)/r,f=(null!==(o=d.fontBoundingBoxDescent)&&void 0!==o?o:0)/r,p=`font-family:${i};font-size:${r}px;font-weight:${l};font-style:${s};line-height:${t.lineHeight};letter-spacing:${t.letterSpacing}em`,m=E(`<div style="${p}"><ul><li>x</li></ul><ol><li>x</li></ol></div>`);let h;try{h=q({html:m,width:Math.max(12*r,600)})}catch(L){return null}const g=[];collectRTText(h.layoutRoot,g);const v=g.find(t=>"•"===t.text),y=g.find(t=>/^\d/.test(t.text));if(!v){return null}const x=v.style.fontSize,w=v.x,S=v.y-C(x,x*u,x*f),T=k*r;return{bulletLeft:w,bulletTop:S,bulletFontSize:x,numberGap:y?Math.max(0,T-y.x-(null!==(n=y.width)&&void 0!==n?n:0)):0}}export const RichTextContainer=_("div",o.forwardRef)`
1
+ var t=this&&this.__rest||function(t,e){var o={};for(var n in t){Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(o[n]=t[n])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(t);r<n.length;r++){e.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(t,n[r])&&(o[n[r]]=t[n[r]])}}return o};import{jsx as e}from"react/jsx-runtime";import o from"react";import n from"quill";import*as r from"mobx";import{nodeReaction as i}from"../utils/mobx.js";import{isAlive as l}from"mobx-state-tree";import{geckoRtlOverhangCss as s,getDir as a,getMeasureCtx as c,getQuillEditorHtml as d,letterSpacingOverhang as u,OVERHANG_PROPERTY as f,textLayoutWidth as p}from"@polotno/core/text-html";import{textContentBox as m}from"@polotno/core/text-types";import{quillHtmlToModelText as h,isQuillFormatMixed as g,isBoldWeight as b,detachNativeColorsInHtml as v,VARIABLE_TOKEN_CLASS as y}from"../utils/rich-text-html.js";import{variableTokens as x}from"@polotno/schema/variables";import{toDisplayColor as w}from"@polotno/core/color";import{LIST_INDENT_EM as k}from"@polotno/core/css-values";import{resetStyleContent as S,linkStyle as T,wrapHtmlForRenderTag as E}from"@polotno/core/reset-style";import{layout as q,lineBaselineOffset as C}from"render-tag";import{removeTags as O}from"@polotno/core/text";import{cssFontFamily as L}from"@polotno/core/fonts";import{isGradient as R,firstStopColor as F}from"@polotno/core/gradient";import{getOptimalCaretColor as $}from"./text-element/caret-color.js";import{visiblePlaceholder as N}from"./text-element/placeholder.js";import{registerQuillUnrestrictedFontFormats as j,PRESERVED_INLINE_STYLES as z,PRESERVED_BLOCK_STYLES as M,VARIABLE_TOKEN_FORMAT as D}from"./quill-font-formats.js";import{ALL_QUILL_MIXED_KEYS as P,setActiveTextEditor as A,updateActiveTextFormat as H,clearActiveTextEditor as I,getActiveTextEditor as Q,getTextFormatState as _}from"../utils/text-format-state.js";import{formatToggle as W}from"../utils/text-format.js";import B from"../utils/styled.js";import{applyOpacityToColor as V}from"@polotno/core/svg";import{elementDropShadow as X,shadowCastByBackground as G}from"@polotno/core/filters";export{V as applyOpacityToColor};export const quillRef=r.observable({enabled:!1,currentFormat:{},pendingToolbarInteraction:!1,editor:r.observable.object({instance:null},{},{deep:!1})});const Y=P;export function syncQuillFormatState(t,e){const o=e?t.getFormat(e):{},n=function(t,e){const o={};if(!e||e.length<=0){return o}const n=t.getContents(e.index,e.length);for(const r of Y){g(n,r)&&(o[r]=!0)}return o}(t,e);r.runInAction(()=>{quillRef.currentFormat=o}),H(o,n,e)}const U="polotno-saved-selection";function K(){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(U,new Highlight(e)),Z()}function J(){"undefined"!=typeof CSS&&CSS.highlights&&CSS.highlights.delete(U)}function Z(){setTimeout(()=>{"undefined"!=typeof CSS&&CSS.highlights&&CSS.highlights.has(U)&&(document.querySelector(".polotno-portal")||pt(document.activeElement)?Z():J())},300)}if("undefined"!=typeof document&&"undefined"!=typeof CSS&&CSS.highlights&&!document.querySelector("[data-polotno-highlight]")){const mt=document.createElement("style");mt.setAttribute("data-polotno-highlight",""),mt.textContent=`::highlight(${U}) { background-color: Highlight; }`,document.head.appendChild(mt)}export function collectRTText(t,e){"text"===t.type?e.push(t):t.children.forEach(t=>collectRTText(t,e))}export function computeMarkerVars(t){var e,o,n;const r=t.fontSize;if(!r||r<=0){return null}const i=L(t.fontFamily),l=`font-family:${i};font-size:${r}px;font-weight:${b(t.fontWeight)?700:400};font-style:${"italic"===t.fontStyle?"italic":"normal"};line-height:${t.lineHeight};letter-spacing:${t.letterSpacing}em`,s=E(`<div style="${l}"><ul><li>x</li></ul><ol><li>x</li></ol></div>`);let a;try{a=q({html:s,width:Math.max(12*r,600)})}catch(x){return null}const d=[];collectRTText(a.layoutRoot,d);const u=d.find(t=>"•"===t.text),f=d.find(t=>/^\d/.test(t.text));if(!u){return null}const p=u.style.fontSize,m=u.x,h=c();h.fontKerning="normal",h.font=`${p}px ${i}`;const g=h.measureText("M"),v=u.y-C(p,null!==(e=g.fontBoundingBoxAscent)&&void 0!==e?e:0,null!==(o=g.fontBoundingBoxDescent)&&void 0!==o?o:0),y=k*r;return{bulletLeft:m,bulletTop:v,bulletFontSize:p,numberGap:f?Math.max(0,y-f.x-(null!==(n=f.width)&&void 0!==n?n:0)):0}}export const RichTextContainer=B("div",o.forwardRef)`
2
2
  .ql-editor {
3
3
  outline: none;
4
4
  /* anchor for the absolutely-positioned ::before placeholder below */
@@ -170,4 +170,4 @@ var t=this&&this.__rest||function(t,e){var o={};for(var n in t){Object.prototype
170
170
  .ql-editor [style*='background-clip'] {
171
171
  -webkit-text-stroke-width: 0;
172
172
  }
173
- `;const J=[...j,...M,"header"];let Z=["link","background","font-weight","color","gradient","font","italic","size","script","strike","underline","text-transform","indent","list","direction",...J];export const setQuillFormats=t=>{Z=t};let tt=!1;function et(){tt||(tt=!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 ot(t){return t?"700":"400"}const nt=n.import("delta"),rt="data-polotno-rich-text",it=["text-decoration-color","text-decoration-style","text-decoration-thickness"],lt=(t,e)=>{const{style:o}=t,n=o.textDecorationLine,r={};if(n.includes("underline")&&(r.underline=!0),n.includes("line-through")&&(r.strike=!0),!r.underline&&!r.strike){return e}for(const i of it){const t=o.getPropertyValue(i);t&&!/^(initial|currentcolor|solid|auto)$/i.test(t)&&(r[i]=t)}return e.ops.reduce((t,e)=>void 0===e.insert?t:t.insert(e.insert,Object.assign(Object.assign({},r),e.attributes)),new nt)};export const createQuill=(e,o)=>{z();const r=new n(e,{toolbar:!1,keyboard:!1,placeholder:(null==o?void 0:o.placeholder)||void 0,clipboard:{matchVisual:!1},formats:[...Z,D]});r.root.addEventListener("click",t=>{t.target instanceof Element&&t.target.closest("a")&&t.preventDefault()}),function(e){const o=e.format.bind(e),n=e.formatText.bind(e),r=e.getFormat.bind(e);e.format=(t,e,n)=>"bold"===t?(et(),o("font-weight",ot(e),n)):o(t,e,n),e.formatText=(e,o,r,i,l)=>{if(r&&"object"==typeof r){if("bold"in r){et();const{bold:l}=r,s=t(r,["bold"]);return n(e,o,Object.assign(Object.assign({},s),{"font-weight":ot(l)}),i)}return n(e,o,r,i)}return"bold"===r?(et(),n(e,o,"font-weight",ot(i),l)):n(e,o,r,i,l)},e.getFormat=(...t)=>{const e=r(...t);return e&&null!=e["font-weight"]&&!("bold"in e)&&(e.bold=b(e["font-weight"])),e}}(r);const i=(t,e)=>e.compose((new nt).retain(e.length(),{"font-weight":"700"}));r.clipboard.addMatcher("STRONG",i),r.clipboard.addMatcher("B",i),r.clipboard.addMatcher(Node.ELEMENT_NODE,lt);const l=r.clipboard,s=l.onPaste.bind(l);return l.onPaste=(t,e)=>{var o;if(null===(o=e.html)||void 0===o?void 0:o.includes(rt)){return ct(r,()=>s(t,e))}const n=l.convert;l.convert=(...t)=>((t,e)=>{for(const o of t.ops){if(o.attributes){for(const t of e){delete o.attributes[t]}}}return t})(n.apply(l,t),J);try{return s(t,e)}finally{l.convert=n}},r};const st=(t,e)=>e.insert(t.data),at=(t,e)=>{const o=e.ops[0];return parseFloat(t.style.textIndent)>0&&"string"==typeof(null==o?void 0:o.insert)&&o.insert.startsWith("\t")?e.compose((new nt).delete(1)):e};function ct(t,e){const{matchers:o}=t.clipboard,n=o.findIndex(([t])=>t===Node.TEXT_NODE),r=o[n];-1!==n&&(o[n]=[Node.TEXT_NODE,st]),o.push([Node.ELEMENT_NODE,at]);try{return e()}finally{o.pop(),-1!==n&&(o[n]=r)}}function dt(t){var e;const{ops:o}=t.getContents(),n=o.map(t=>"string"==typeof t.insert?t.insert:"").join(""),r=new Uint8Array(n.length);for(const{start:s,end:a}of x(n)){r.fill(1,s,a)}const i=[];let l=0;for(const s of o){const t="string"==typeof s.insert?s.insert.length:1,o=!!(null===(e=s.attributes)||void 0===e?void 0:e[D]);for(let e=l;e<l+t;e++){const t=1===r[e];if(t===o){continue}const n=i[i.length-1];n&&n.index+n.length===e&&n.mark===t?n.length++:i.push({index:e,length:1,mark:t})}l+=t}for(const s of i){t.formatText(s.index,s.length,D,s.mark,"silent")}}export const setQuillContent=(t,e)=>{const o=ct(t,()=>t.clipboard.convert({html:"<div class='ql-editor' style='outline: none;'>"+e+"<p><br></p></div>",text:""}));t.setContents(o),t.history.clear()};export const editorHtml=t=>d({text:v(t.text),width:t.width,fontSize:t.fontSize,fontFamily:t.fontFamily},t.fontFamily);export const RichEditor=({onBlur:t,onChange:n,element:s,clickCoords:c,initialCaret:d="start",fitScale:g=1,fitScaleFor:b})=>{const v=o.useRef(null),y=o.useRef(!1),x=o.useRef(g);x.current=g;const[k,S]=o.useState(null),T=null!=k?k:g,E=o.useRef(b);E.current=b;const q=t=>({width:p(m({width:s.a.width,paddingLeft:s.paddingLeft,paddingRight:s.paddingRight,curveEnabled:s.curveEnabled}).width/t,s.letterSpacing,s.fontSize),zoom:1!==t?t:void 0}),C=o.useRef(null),z=o.useRef(void 0),j=()=>`${s.text}\0${s.fontSize}\0${s.fontFamily}`,M=t=>h(t,{fontSize:s.fontSize,fontFamily:s.fontFamily}),D=t=>{setQuillContent(t,editorHtml(s)),C.current=M(t.root.innerHTML),z.current=j()},P=o.useRef(()=>{}),H=()=>{P.current(),t()};o.useLayoutEffect(()=>{let t,e,o=!1,i=null,a=null,u=null,f=null,p=null;const m=()=>{if(!o&&v.current){try{t=createQuill(v.current,{placeholder:N(s.placeholder)}),r.runInAction(()=>{quillRef.editor.instance=t}),quillRef.pendingToolbarInteraction=!1,window.__polotnoQuill=t,A({instance:t,store:s.store,element:s});const o=e=>{e&&syncQuillFormatState(t,e)},m=()=>{let e=t.root;if(e.querySelector(".ql-cursor")){e=e.cloneNode(!0);const t=e.querySelector(".ql-cursor");t.replaceWith(t.textContent.replace(/\uFEFF/g,""))}return M(e.innerHTML)},h=()=>{const t=E.current;t&&l(s)&&(t=>{const e=v.current;if(!e){return}const o=q(t);e.style.width=`${o.width}px`,e.style.zoom=void 0===o.zoom?"":String(o.zoom)})(t(m()))},g=()=>{var o,r;if(clearTimeout(e),e=void 0,!l(s)){return}const i=m();if(i===C.current){return}C.current=i,y.current=!0,n(i);const a=t.getContents(),c=s.fill;let d=null,u=!0;for(const t of a.ops){if("string"!=typeof t.insert||"\n"===t.insert){continue}if(null===(o=t.attributes)||void 0===o?void 0:o.gradient){u=!1;break}const e=(null===(r=t.attributes)||void 0===r?void 0:r.color)||c;if(null===d){d=e}else if(e!==d){u=!1;break}}u&&d&&d!==s.fill&&s.set({fill:d})};P.current=()=>{(void 0!==e||t.composition.isComposing)&&g()},t.on("text-change",()=>{const n=Q(),r=n&&n.instance===t?n.lastSelection:null;o(t.getSelection()||r),t.composition.isComposing||(dt(t),h()),void 0===e&&(e=setTimeout(g,10))}),t.on("selection-change",o),t.on("composition-start",()=>S(x.current)),t.on("composition-end",()=>{dt(t),h(),S(null)}),D(t);const b=v.current.closest(".polotno-workspace-inner"),w=null==b?void 0:b.scrollLeft,k=null==b?void 0:b.scrollTop,T="end"===d?t.getLength()-1:0;c?setCursorFromCoords(t,c,T):t.setSelection(T,0,"api"),b&&void 0!==w&&void 0!==k&&(b.scrollLeft=w,b.scrollTop=k);const L=t.root;f=t=>{const e=t.relatedTarget;(null==e?void 0:e.classList.contains("ql-clipboard"))||(ut(e)||quillRef.pendingToolbarInteraction?Y():setTimeout(()=>{quillRef.pendingToolbarInteraction||ut(document.activeElement)?Y():(U(),H())},0))},p=()=>{U()},L.addEventListener("blur",f),L.addEventListener("focus",p),i=L,a=e=>{var o,n;const r=t.getSelection();if(!r||0===r.length){return}const i=t.getText(r.index,r.length).replace(/\n$/,""),l=window.getSelection();let s="";if(l&&l.rangeCount>0){const t=l.getRangeAt(0);let e=t.cloneContents(),o=t.startContainer;o&&o.nodeType===Node.TEXT_NODE&&(o=o.parentNode);let n=t.endContainer;if(n&&n.nodeType===Node.TEXT_NODE&&(n=n.parentNode),o&&o===n){let t=o;for(;t&&t!==L&&t.nodeType===Node.ELEMENT_NODE;){const o=t.tagName;if("SPAN"!==o&&"EM"!==o&&"STRONG"!==o&&"U"!==o&&"S"!==o&&"A"!==o){break}const n=t.cloneNode(!1);n.appendChild(e),e=n,t=t.parentNode}}const r=document.createElement("div");r.appendChild(e),s=r.innerHTML}if(null===(o=e.clipboardData)||void 0===o||o.setData("text/plain",i),s){const t=`<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>\x3c!--StartFragment--\x3e<div ${rt} style="white-space: pre-wrap; overflow-wrap: break-word;">`+s+"</div>\x3c!--EndFragment--\x3e</body></html>";null===(n=e.clipboardData)||void 0===n||n.setData("text/html",t)}e.preventDefault()},u=e=>{a&&a(e);const o=t.getSelection();o&&o.length>0&&t.deleteText(o.index,o.length)},i.addEventListener("copy",a),i.addEventListener("cut",u)}catch(m){console.error("RichEditor init failed:",m)}}};return v.current?m():queueMicrotask(m),()=>{o=!0,P.current(),clearTimeout(e),i&&f&&i.removeEventListener("blur",f),i&&p&&i.removeEventListener("focus",p),U(),i&&a&&u&&(i.removeEventListener("copy",a),i.removeEventListener("cut",u)),r.runInAction(()=>{quillRef.editor.instance=null,quillRef.currentFormat={}}),I(t),delete window.__polotnoQuill}},[]),o.useEffect(()=>i(s,j,t=>{const e=quillRef.editor.instance;if(!e){return}if(y.current){return y.current=!1,void(z.current=t)}if(t===z.current){return}const o=e.getSelection();D(e),o&&(e.setSelection(o.index,o.length),syncQuillFormatState(e,e.getSelection()))},{fireImmediately:!0}),[]),o.useEffect(()=>i(s,()=>`${s.fontFamily}\0${s.fontSize}\0${s.fontWeight}\0${s.fontStyle}\0${s.lineHeight}\0${s.letterSpacing}\0${a(L(s.text))}`,()=>{const t=v.current;if(!t){return}const e="ltr"===a(L(s.text)),o=computeMarkerVars(s);o&&t.style.setProperty("--rt-number-gap",`${o.numberGap}px`),o&&e?(t.style.setProperty("--rt-bullet-left",`${o.bulletLeft}px`),t.style.setProperty("--rt-bullet-top",`${o.bulletTop}px`),t.style.setProperty("--rt-bullet-fs",`${o.bulletFontSize}px`),t.classList.add("rt-marker-geom")):t.classList.remove("rt-marker-geom")},{fireImmediately:!0}),[]),o.useEffect(()=>{window.addEventListener("blur",H);const t=t=>{var e;const o=t.target;"number"==typeof(null==o?void 0:o.nodeType)&&(null===(e=v.current)||void 0===e?void 0:e.contains(o))||ut(o)||quillRef.pendingToolbarInteraction||(U(),H())};return window.addEventListener("mousedown",t),window.addEventListener("touchstart",t),()=>{window.removeEventListener("blur",H),window.removeEventListener("mousedown",t),window.removeEventListener("touchstart",t)}},[]);const _=w(s.fill),W={color:_};_.indexOf("gradient")>=0&&(W["--polotno-gradient"]=_,W.color="transparent"),s.strokeWidth>0&&(W.WebkitTextStroke=`${s.strokeWidth}px ${F(s.stroke)}`,W.paintOrder="stroke fill");const X=O(s.fill)?F(s.fill):$(s),G=s.shadowEnabled&&!V(s);return e(RichTextContainer,{ref:v,style:Object.assign(Object.assign(Object.assign(Object.assign({},W),{fontSize:s.fontSize,fontFamily:R(s.fontFamily),fontWeight:s.fontWeight,fontStyle:s.fontStyle,"--polotno-text-decoration":s.textDecoration||"none",textTransform:s.textTransform}),q(T)),{[f]:u(s.letterSpacing,s.fontSize)+"px",lineHeight:s.lineHeight,letterSpacing:s.letterSpacing*s.fontSize+"px",textAlign:s.align,opacity:Math.max(s.a.opacity,.2),filter:G?B({shadowOffsetX:s.shadowOffsetX,shadowOffsetY:s.shadowOffsetY,shadowBlur:s.shadowBlur,shadowColor:s.shadowColor,shadowOpacity:s.shadowOpacity,rotation:s.a.rotation}):void 0,caretColor:X}),dir:a(L(s.text))})};function ut(t){const e=t;return!("function"!=typeof(null==e?void 0:e.closest)||!e.closest(".sketch-picker")&&!e.closest("[data-polotno-keep-focus]")&&!e.closest(".polotno-portal")&&!e.closest(".polotno-toolbar"))}export function setCursorFromCoords(t,e,o=0){if(!t||!e){return}const{x:r,y:i}=e;try{let e=null;if(document.caretRangeFromPoint){e=document.caretRangeFromPoint(r,i)}else if(document.caretPositionFromPoint){const t=document.caretPositionFromPoint(r,i);t&&(e=document.createRange(),e.setStart(t.offsetNode,t.offset))}if(e){const o=n.find(e.startContainer,!0);if(o){const n=o.offset(t.scroll)+e.startOffset;return void t.setSelection(n,0,"api")}}}catch(l){}t.setSelection(o,0,"api")}
173
+ `;const tt=[...z,...M,"header"];let et=["link","background","font-weight","color","gradient","font","italic","size","script","strike","underline","text-transform","indent","list","direction",...tt];export const setQuillFormats=t=>{et=t};let ot=!1;function nt(){ot||(ot=!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 rt(t){return t?"700":"400"}const it=n.import("delta"),lt="data-polotno-rich-text",st=["text-decoration-color","text-decoration-style","text-decoration-thickness"],at=(t,e)=>{const{style:o}=t,n=o.textDecorationLine,r={};if(n.includes("underline")&&(r.underline=!0),n.includes("line-through")&&(r.strike=!0),!r.underline&&!r.strike){return e}for(const i of st){const t=o.getPropertyValue(i);t&&!/^(initial|currentcolor|solid|auto)$/i.test(t)&&(r[i]=t)}return e.ops.reduce((t,e)=>void 0===e.insert?t:t.insert(e.insert,Object.assign(Object.assign({},r),e.attributes)),new it)};export const createQuill=(e,o)=>{j();const r=null==o?void 0:o.onFormatShortcut,i=new n(e,Object.assign(Object.assign({},r&&{modules:{keyboard:{bindings:Object.fromEntries(["bold","italic","underline"].map(t=>[t,{key:t[0],shortKey:!0,handler:()=>(r(t),!1)}]))}}}),{placeholder:(null==o?void 0:o.placeholder)||void 0,clipboard:{matchVisual:!1},formats:[...et,D]}));i.root.addEventListener("click",t=>{t.target instanceof Element&&t.target.closest("a")&&t.preventDefault()}),function(e){const o=e.format.bind(e),n=e.formatText.bind(e),r=e.getFormat.bind(e);e.format=(t,e,n)=>"bold"===t?(nt(),o("font-weight",rt(e),n)):o(t,e,n),e.formatText=(e,o,r,i,l)=>{if(r&&"object"==typeof r){if("bold"in r){nt();const{bold:l}=r,s=t(r,["bold"]);return n(e,o,Object.assign(Object.assign({},s),{"font-weight":rt(l)}),i)}return n(e,o,r,i)}return"bold"===r?(nt(),n(e,o,"font-weight",rt(i),l)):n(e,o,r,i,l)},e.getFormat=(...t)=>{const e=r(...t);return e&&null!=e["font-weight"]&&!("bold"in e)&&(e.bold=b(e["font-weight"])),e}}(i);const l=(t,e)=>e.compose((new it).retain(e.length(),{"font-weight":"700"}));i.clipboard.addMatcher("STRONG",l),i.clipboard.addMatcher("B",l),i.clipboard.addMatcher(Node.ELEMENT_NODE,at);const s=i.clipboard,a=s.onPaste.bind(s);return s.onPaste=(t,e)=>{var o;if(null===(o=e.html)||void 0===o?void 0:o.includes(lt)){return ut(i,()=>a(t,e))}const n=s.convert;s.convert=(...t)=>((t,e)=>{for(const o of t.ops){if(o.attributes){for(const t of e){delete o.attributes[t]}}}return t})(n.apply(s,t),tt);try{return a(t,e)}finally{s.convert=n}},i};const ct=(t,e)=>e.insert(t.data),dt=(t,e)=>{const o=e.ops[0];return parseFloat(t.style.textIndent)>0&&"string"==typeof(null==o?void 0:o.insert)&&o.insert.startsWith("\t")?e.compose((new it).delete(1)):e};function ut(t,e){const{matchers:o}=t.clipboard,n=o.findIndex(([t])=>t===Node.TEXT_NODE),r=o[n];-1!==n&&(o[n]=[Node.TEXT_NODE,ct]),o.push([Node.ELEMENT_NODE,dt]);try{return e()}finally{o.pop(),-1!==n&&(o[n]=r)}}function ft(t){var e;const{ops:o}=t.getContents(),n=o.map(t=>"string"==typeof t.insert?t.insert:"").join(""),r=new Uint8Array(n.length);for(const{start:s,end:a}of x(n)){r.fill(1,s,a)}const i=[];let l=0;for(const s of o){const t="string"==typeof s.insert?s.insert.length:1,o=!!(null===(e=s.attributes)||void 0===e?void 0:e[D]);for(let e=l;e<l+t;e++){const t=1===r[e];if(t===o){continue}const n=i[i.length-1];n&&n.index+n.length===e&&n.mark===t?n.length++:i.push({index:e,length:1,mark:t})}l+=t}for(const s of i){t.formatText(s.index,s.length,D,s.mark,"silent")}}export const setQuillContent=(t,e)=>{const o=ut(t,()=>t.clipboard.convert({html:"<div class='ql-editor' style='outline: none;'>"+e+"<p><br></p></div>",text:""}));t.setContents(o),t.history.clear()};export const editorHtml=t=>d({text:v(t.text),width:t.width,fontSize:t.fontSize,fontFamily:t.fontFamily},t.fontFamily);export const RichEditor=({onBlur:t,onChange:n,element:s,clickCoords:c,initialCaret:d="start",fitScale:g=1,fitScaleFor:b})=>{const v=o.useRef(null),y=o.useRef(!1),x=o.useRef(g);x.current=g;const[k,S]=o.useState(null),T=null!=k?k:g,E=o.useRef(b);E.current=b;const q=t=>({width:p(m({width:s.a.width,paddingLeft:s.paddingLeft,paddingRight:s.paddingRight,curveEnabled:s.curveEnabled}).width/t,s.letterSpacing,s.fontSize),zoom:1!==t?t:void 0}),C=o.useRef(null),j=o.useRef(void 0),z=()=>`${s.text}\0${s.fontSize}\0${s.fontFamily}`,M=t=>h(t,{fontSize:s.fontSize,fontFamily:s.fontFamily}),D=t=>{setQuillContent(t,editorHtml(s)),C.current=M(t.root.innerHTML),j.current=z()},P=o.useRef(()=>{}),H=()=>{P.current(),t()};o.useLayoutEffect(()=>{let t,e,o=!1,i=null,a=null,u=null,f=null,p=null;const m=()=>{if(!o&&v.current){try{t=createQuill(v.current,{placeholder:N(s.placeholder),onFormatShortcut:t=>{const e=_(s.store),{attrs:o,opts:n}=W(e.format,t);e.applyTextFormat(o,n)}}),r.runInAction(()=>{quillRef.editor.instance=t}),quillRef.pendingToolbarInteraction=!1,window.__polotnoQuill=t,A({instance:t,store:s.store,element:s});const o=e=>{e&&syncQuillFormatState(t,e)},m=()=>{let e=t.root;if(e.querySelector(".ql-cursor")){e=e.cloneNode(!0);const t=e.querySelector(".ql-cursor");t.replaceWith(t.textContent.replace(/\uFEFF/g,""))}return M(e.innerHTML)},h=()=>{const t=E.current;t&&l(s)&&(t=>{const e=v.current;if(!e){return}const o=q(t);e.style.width=`${o.width}px`,e.style.zoom=void 0===o.zoom?"":String(o.zoom)})(t(m()))},g=()=>{var o,r;if(clearTimeout(e),e=void 0,!l(s)){return}const i=m();if(i===C.current){return}C.current=i,y.current=!0,n(i);const a=t.getContents(),c=s.fill;let d=null,u=!0;for(const t of a.ops){if("string"!=typeof t.insert||"\n"===t.insert){continue}if(null===(o=t.attributes)||void 0===o?void 0:o.gradient){u=!1;break}const e=(null===(r=t.attributes)||void 0===r?void 0:r.color)||c;if(null===d){d=e}else if(e!==d){u=!1;break}}u&&d&&d!==s.fill&&s.set({fill:d})};P.current=()=>{(void 0!==e||t.composition.isComposing)&&g()},t.on("text-change",()=>{const n=Q(),r=n&&n.instance===t?n.lastSelection:null;o(t.getSelection()||r),t.composition.isComposing||(ft(t),h()),void 0===e&&(e=setTimeout(g,10))}),t.on("selection-change",o),t.on("composition-start",()=>S(x.current)),t.on("composition-end",()=>{ft(t),h(),S(null)}),D(t);const b=v.current.closest(".polotno-workspace-inner"),w=null==b?void 0:b.scrollLeft,k=null==b?void 0:b.scrollTop,T="end"===d?t.getLength()-1:0;c?setCursorFromCoords(t,c,T):t.setSelection(T,0,"api"),b&&void 0!==w&&void 0!==k&&(b.scrollLeft=w,b.scrollTop=k);const O=t.root;f=t=>{const e=t.relatedTarget;(null==e?void 0:e.classList.contains("ql-clipboard"))||(pt(e)||quillRef.pendingToolbarInteraction?K():setTimeout(()=>{quillRef.pendingToolbarInteraction||pt(document.activeElement)?K():(J(),H())},0))},p=()=>{J()},O.addEventListener("blur",f),O.addEventListener("focus",p),i=O,a=e=>{var o,n;const r=t.getSelection();if(!r||0===r.length){return}const i=t.getText(r.index,r.length).replace(/\n$/,""),l=window.getSelection();let s="";if(l&&l.rangeCount>0){const t=l.getRangeAt(0);let e=t.cloneContents(),o=t.startContainer;o&&o.nodeType===Node.TEXT_NODE&&(o=o.parentNode);let n=t.endContainer;if(n&&n.nodeType===Node.TEXT_NODE&&(n=n.parentNode),o&&o===n){let t=o;for(;t&&t!==O&&t.nodeType===Node.ELEMENT_NODE;){const o=t.tagName;if("SPAN"!==o&&"EM"!==o&&"STRONG"!==o&&"U"!==o&&"S"!==o&&"A"!==o){break}const n=t.cloneNode(!1);n.appendChild(e),e=n,t=t.parentNode}}const r=document.createElement("div");r.appendChild(e),s=r.innerHTML}if(null===(o=e.clipboardData)||void 0===o||o.setData("text/plain",i),s){const t=`<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>\x3c!--StartFragment--\x3e<div ${lt} style="white-space: pre-wrap; overflow-wrap: break-word;">`+s+"</div>\x3c!--EndFragment--\x3e</body></html>";null===(n=e.clipboardData)||void 0===n||n.setData("text/html",t)}e.preventDefault()},u=e=>{a&&a(e);const o=t.getSelection();o&&o.length>0&&t.deleteText(o.index,o.length)},i.addEventListener("copy",a),i.addEventListener("cut",u)}catch(m){console.error("RichEditor init failed:",m)}}};return v.current?m():queueMicrotask(m),()=>{o=!0,P.current(),clearTimeout(e),i&&f&&i.removeEventListener("blur",f),i&&p&&i.removeEventListener("focus",p),J(),i&&a&&u&&(i.removeEventListener("copy",a),i.removeEventListener("cut",u)),r.runInAction(()=>{quillRef.editor.instance=null,quillRef.currentFormat={}}),I(t),delete window.__polotnoQuill}},[]),o.useEffect(()=>i(s,z,t=>{const e=quillRef.editor.instance;if(!e){return}if(y.current){return y.current=!1,void(j.current=t)}if(t===j.current){return}const o=e.getSelection();D(e),o&&(e.setSelection(o.index,o.length),syncQuillFormatState(e,e.getSelection()))},{fireImmediately:!0}),[]),o.useEffect(()=>i(s,()=>`${s.fontFamily}\0${s.fontSize}\0${s.fontWeight}\0${s.fontStyle}\0${s.lineHeight}\0${s.letterSpacing}\0${a(O(s.text))}`,()=>{const t=v.current;if(!t){return}const e="ltr"===a(O(s.text)),o=computeMarkerVars(s);o&&t.style.setProperty("--rt-number-gap",`${o.numberGap}px`),o&&e?(t.style.setProperty("--rt-bullet-left",`${o.bulletLeft}px`),t.style.setProperty("--rt-bullet-top",`${o.bulletTop}px`),t.style.setProperty("--rt-bullet-fs",`${o.bulletFontSize}px`),t.classList.add("rt-marker-geom")):t.classList.remove("rt-marker-geom")},{fireImmediately:!0}),[]),o.useEffect(()=>{window.addEventListener("blur",H);const t=t=>{var e;const o=t.target;"number"==typeof(null==o?void 0:o.nodeType)&&(null===(e=v.current)||void 0===e?void 0:e.contains(o))||pt(o)||quillRef.pendingToolbarInteraction||(J(),H())};return window.addEventListener("mousedown",t),window.addEventListener("touchstart",t),()=>{window.removeEventListener("blur",H),window.removeEventListener("mousedown",t),window.removeEventListener("touchstart",t)}},[]);const B=w(s.fill),V={color:B};B.indexOf("gradient")>=0&&(V["--polotno-gradient"]=B,V.color="transparent"),s.strokeWidth>0&&(V.WebkitTextStroke=`${s.strokeWidth}px ${F(s.stroke)}`,V.paintOrder="stroke fill");const Y=R(s.fill)?F(s.fill):$(s),U=s.shadowEnabled&&!G(s);return e(RichTextContainer,{ref:v,style:Object.assign(Object.assign(Object.assign(Object.assign({},V),{fontSize:s.fontSize,fontFamily:L(s.fontFamily),fontWeight:s.fontWeight,fontStyle:s.fontStyle,"--polotno-text-decoration":s.textDecoration||"none",textTransform:s.textTransform}),q(T)),{[f]:u(s.letterSpacing,s.fontSize)+"px",lineHeight:s.lineHeight,letterSpacing:s.letterSpacing*s.fontSize+"px",textAlign:s.align,opacity:Math.max(s.a.opacity,.2),filter:U?X({shadowOffsetX:s.shadowOffsetX,shadowOffsetY:s.shadowOffsetY,shadowBlur:s.shadowBlur,shadowColor:s.shadowColor,shadowOpacity:s.shadowOpacity,rotation:s.a.rotation}):void 0,caretColor:Y}),dir:a(O(s.text))})};function pt(t){const e=t;return!("function"!=typeof(null==e?void 0:e.closest)||!e.closest(".sketch-picker")&&!e.closest("[data-polotno-keep-focus]")&&!e.closest(".polotno-portal")&&!e.closest(".polotno-toolbar"))}export function setCursorFromCoords(t,e,o=0){if(!t||!e){return}const{x:r,y:i}=e;try{let e=null;if(document.caretRangeFromPoint){e=document.caretRangeFromPoint(r,i)}else if(document.caretPositionFromPoint){const t=document.caretPositionFromPoint(r,i);t&&(e=document.createRange(),e.setStart(t.offsetNode,t.offset))}if(e){const o=n.find(e.startContainer,!0);if(o){const n=o.offset(t.scroll)+e.startOffset;return void t.setSelection(n,0,"api")}}}catch(l){}t.setSelection(o,0,"api")}
@@ -1 +1 @@
1
- import{Fragment as e,jsx as t,jsxs as r}from"react/jsx-runtime";import{elementOpacity as o}from"./paint-opacity.js";import i from"react";import{toDisplayColor as n}from"@polotno/core/color";import{animatedShadow as a}from"./animated-shadow.js";import{observer as s}from"mobx-react-lite";import{isAlive as d}from"mobx-state-tree";import{nodeAutorun as l}from"../utils/mobx.js";import{Group as c,Image as u,Rect as h}from"react-konva";import{ROLES as m}from"../model/store.js";import{DEFAULT_RETRIES as p,isDeterministicUrl as g,retryDelayMs as f}from"@polotno/core/retry";import v from"konva";import{ErrorPlaceholder as w,LoadingPlaceholder as x}from"./media-placeholders.js";import{incrementLoader as E,triggerLoadError as L}from"../utils/loader.js";import{polotnoError as M}from"@polotno/core/errors";import{getCropRect as y}from"@polotno/core/image";import*as C from"@polotno/core/svg";import{roundedPosition as b}from"../utils/px.js";import{useMediaResize as k}from"./media-resize.js";import{useFilteredSource as T}from"./use-filtered-source.js";import{useOffscreenCanvas as j}from"./use-offscreen-canvas.js";import{useEvent as I}from"../hooks/use-event.js";import{useFadeIn as R}from"./use-fadein.js";import{useAnimatedBlur as S}from"./use-animated-blur.js";import{isTouchDevice as P}from"../utils/screen.js";import{createPlayGate as _,playMedia as A}from"../utils/media.js";import{useMediabunnyVideo as V}from"./use-mediabunny-video.js";import{getElementTimeRange as D,getVideoRestMs as z,isHeldByPreview as F}from"../utils/timeline.js";import{drawReduced as O,exportKernelEnabled as H,shouldResample as U,sourceSize as Z}from"./downscale.js";import{trySetCanvasSize as W}from"../utils/canvas.js";import{useClipImage as X}from"./image-element.js";import{CropOverlay as Y,CROP_CORNER_ANCHORS as N}from"./crop-overlay.js";const q=new window.Image;q.src=C.svgToURL('\n <svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path opacity="0.6" d="M4 5.49683V18.5032C4 20.05 5.68077 21.0113 7.01404 20.227L18.0694 13.7239C19.384 12.9506 19.384 11.0494 18.0694 10.2761L7.01404 3.77296C5.68077 2.98869 4 3.95 4 5.49683Z" fill="white"/>\n <path d="M4 5.49683V18.5032C4 20.05 5.68077 21.0113 7.01404 20.227L18.0694 13.7239C19.384 12.9506 19.384 11.0494 18.0694 10.2761L7.01404 3.77296C5.68077 2.98869 4 3.95 4 5.49683Z" stroke="#323232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n');const $=new window.Image;$.src=C.svgToURL('\n <svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path opacity="0.6" d="M14 19L14 5C14 3.89543 14.8954 3 16 3L17 3C18.1046 3 19 3.89543 19 5L19 19C19 20.1046 18.1046 21 17 21L16 21C14.8954 21 14 20.1046 14 19Z" fill="white"/>\n <path opacity="0.6" d="M10 19L10 5C10 3.89543 9.10457 3 8 3L7 3C5.89543 3 5 3.89543 5 5L5 19C5 20.1046 5.89543 21 7 21L8 21C9.10457 21 10 20.1046 10 19Z" fill="white"/>\n <path d="M14 19L14 5C14 3.89543 14.8954 3 16 3L17 3C18.1046 3 19 3.89543 19 5L19 19C19 20.1046 18.1046 21 17 21L16 21C14.8954 21 14 20.1046 14 19Z" stroke="#323232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n <path d="M10 19L10 5C10 3.89543 9.10457 3 8 3L7 3C5.89543 3 5 3.89543 5 5L5 19C5 20.1046 5.89543 21 7 21L8 21C9.10457 21 10 20.1046 10 19Z" stroke="#323232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n');export const useFlip=(e,t)=>{const{flipX:r,flipY:o}=e,{width:i,height:n}=t?Z(t):{},a=e=>{if(!t){return}const i=e.getContext("2d");i&&(i.clearRect(0,0,e.width,e.height),i.save(),i.scale(r?-1:1,o?-1:1),i.drawImage(t,r?-e.width:0,o?-e.height:0,e.width,e.height),i.restore())},s=j((r||o)&&!!i&&!!n,e=>{i&&n&&(e.width=i,e.height=n,a(e))},[r,o,t,i,n]);return[s||t,()=>{s&&a(s)}]};export const useCornerRadiusAndCrop=(e,t,r,o,n=0,a=!1)=>{var s;const d=Math.floor(Math.max(e.a.width*o,1)),l=Math.floor(Math.max(e.a.height*o,1)),c=Math.min(n*o,d/2,l/2),u=Math.max(e.a.width/r.width,e.a.height/r.height)*o,h=H(e.page)&&!a&&U(u,d,l),{width:m,height:p}=t?Z(t):{},g=0===r.x&&0===r.y&&r.width===m&&r.height===p,f=i.useMemo(()=>{if(t&&m&&p){return g&&0===c&&!h?void 0:document.createElement("canvas")}},[t,c,h,g,m,p]),w=()=>{if(!f||!t){return}f.width=d,f.height=l;const e=f.getContext("2d");e&&(c&&(e.beginPath(),e.moveTo(c,0),e.lineTo(d-c,0),e.arc(d-c,c,c,3*Math.PI/2,0,!1),e.lineTo(d,l-c),e.arc(d-c,l-c,c,0,Math.PI/2,!1),e.lineTo(c,l),e.arc(c,l-c,c,Math.PI/2,Math.PI,!1),e.lineTo(0,c),e.arc(c,c,c,Math.PI,3*Math.PI/2,!1),e.clip()),h?O(e,t,r,f.width,f.height):e.drawImage(t,r.x,r.y,r.width,r.height,0,0,f.width,f.height))};return i.useLayoutEffect(()=>{w()},[f,e.a.width,e.a.height,r.x,r.y,r.width,r.height,n,o,a,null===(s=e.page)||void 0===s?void 0:s._exportingOrRendering,h]),i.useEffect(()=>()=>{f&&"CANVAS"===f.nodeName&&v.Util.releaseCanvas(f)},[f]),[f||t,w]};export const useClip=(e,t,r,o)=>{const[n,a]=X(e.clipSrc||""),s=e.clipSrc?a:"loaded";useLoader(s,e.clipSrc,e.id);const d=!!t&&!!n,l=i.useMemo(()=>d?{canvas:document.createElement("canvas"),mask:document.createElement("canvas"),width:0,height:0}:void 0,[d]),c=null==l?void 0:l.canvas;function u(){if(!l||!c||!t){return}const{width:o,height:i}=Z(t);if(!o||!i){return}const n=Math.min(1e4,Math.max(o,Math.ceil(e.a.width*r),1)),a=Math.min(1e4,Math.max(i,Math.ceil(e.a.height*r),1));c.width&&l.width===n&&l.height===a||(W(c,n,a),l.width=n,l.height=a);const s=c.getContext("2d");s&&(s.clearRect(0,0,c.width,c.height),s.save(),s.drawImage(t,0,0,c.width,c.height),s.globalCompositeOperation="destination-in",s.drawImage(l.mask,0,0,c.width,c.height),s.restore())}return i.useLayoutEffect(()=>{var t;if(!l||!(null==n?void 0:n.width)||!n.height){return}const o=Math.max(e.a.width/n.width*r,e.a.height/n.height*r);W(l.mask,Math.min(1e4,Math.max(n.width*o,1)),Math.min(1e4,Math.max(n.height*o,1))),null===(t=l.mask.getContext("2d"))||void 0===t||t.drawImage(n,0,0,l.mask.width,l.mask.height)},[l,n,e.a.width,e.a.height,r]),i.useLayoutEffect(()=>{u()},[l,t,n,e.a.width,e.a.height,r,...o]),i.useEffect(()=>()=>{l&&v.Util.releaseCanvas(l.canvas,l.mask)},[l]),[d?c:t,u]};const B=document.createElement("canvas");let G=function(e,t,r){const o=i.useRef("loading"),n=i.useRef(void 0),[a,s]=i.useState(0),d=i.useRef(void 0),l=i.useRef(void 0),c=i.useRef(void 0);return d.current===e&&l.current===t&&c.current===r||(o.current="loading",n.current=void 0,d.current=e,l.current=t,c.current=r),i.useLayoutEffect(()=>{if(!e){return}const i=g(e)?1:p;let a,d,l,c=0,u=!1,h=!1;const m=e=>{e&&(e.removeAttribute("src"),e.load())},v=()=>{c+=1;const p=document.createElement("video");function g(){u||(p.removeEventListener("canplay",g),h=!0,o.current="loaded",n.current=p,p.currentTime=0,s(Math.random()))}function w(e){var t;const r=4===p.readyState,l=p.buffered&&p.buffered.length>0&&p.buffered.end(p.buffered.length-1)/p.duration*100>=100;if(r&&l){return}if(u){return}if(!h&&c<i){return null==d||d(),m(p),void(a=setTimeout(v,f(c)))}const g=e.message||(null===(t=p.error)||void 0===t?void 0:t.message)||"Unknown error";console.error(new Error("Video failed to load: "+g)),o.current="failed",n.current=void 0,s(Math.random())}l=p,p.addEventListener("canplay",g),p.addEventListener("error",w),d=()=>{p.removeEventListener("canplay",g),p.removeEventListener("error",w)},t&&(p.crossOrigin=t),r&&(p.referrerPolicy=r),p.src=e,p.load()};return v(),()=>{u=!0,clearTimeout(a),null==d||d(),h||m(l)}},[e,t,r]),[n.current,o.current]};export const setVideoLoaderHook=e=>{G=e};function J(e){return!e.seeking&&e.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA}export const useLoader=(e,t,r)=>{const o=i.useRef(void 0),n=()=>{var e;null===(e=o.current)||void 0===e||e.call(o),o.current=void 0};i.useEffect(()=>n,[]),i.useLayoutEffect(()=>{const i=t.slice(0,200),a=`video with id ${r} url: ${i}`;"loading"!==e||o.current||(o.current=E(a)),"loading"!==e&&n(),"failed"===e&&L(M("VIDEO_FAILED",a,{src:i,elementId:r,reason:"load"}))},[e])};export const VideoElement=s(({element:s,store:p})=>{var g,f,L,M,C;const[j,O]=i.useState(!1),H=i.useRef(null),U=P(),[W,X]=i.useState(!1),[K,Q]=G(s.a.src,"anonymous"),[ee,te]=i.useState(!1),re=p.activePage===s.page,oe=(null===(g=s.page)||void 0===g?void 0:g._exportingOrRendering)&&"loaded"===Q,ie=V(s,p,oe);useLoader(Q,s.a.src,s.id),K&&(K.playsInline=!0);const ne=oe&&ie||K,[ae,se]=useFlip(s,ne),[de=B,le]=T(s,ae||B);i.useEffect(()=>{K&&p.history.ignore(()=>{s.set({duration:1e3*K.duration})})},[K]);const ce=i.useMemo(_,[K]);i.useEffect(()=>{var e;if(!K){return}const t=!F(s)&&p.isPlaying;if(!re||!t&&!W){return void K.pause()}W&&(K.muted=!1,K.currentTime=s.startTime*K.duration,A(K).then(e=>{"refused"===e&&X(!1)}));const r=new v.Animation(()=>{Te()},null===(e=H.current)||void 0===e?void 0:e.getLayer());r.start();const o=()=>{X(!1),K.currentTime=s.startTime*K.duration},i=()=>{K.currentTime>=s.endTime*K.duration&&(K.pause(),K.currentTime=s.startTime*K.duration,X(!1))};return K.addEventListener("ended",o),K.addEventListener("timeupdate",i),()=>{K.pause(),r.stop(),K.removeEventListener("ended",o),K.removeEventListener("timeupdate",i)}},[K,W,p.isPlaying,re]),i.useEffect(()=>{K&&(K.volume=s.volume)},[K,s.volume]),i.useEffect(()=>{K&&(K.playbackRate=s.speed,K.preservesPitch=!1)},[K,s.speed]);const ue=i.useRef(null);i.useEffect(()=>{const e=l(s,()=>{var e,t;if(K){if(oe&&ie){return Te(),void p.currentTime}if(F(s)){return}const r=p.activePage===s.page,o=s.page._mediaLocalTime,i=s.startTime*K.duration*1e3,n=K.duration*(s.endTime-s.startTime)*1e3,{start:a,end:d}=D(s.animations,s.page.duration),l=z(null!=o?o:0,0,a,n,i,s.speed,{windowEnd:d,frameMs:p._renderFrameMs,renderEnd:p._renderEndMs-s.page.startTime}),c=l/1e3,u=null!==o&&o>=a&&o<d;W||(K.muted=!u,u&&p.isPlaying&&r?K.paused?(K.currentTime=c,ce.play(K)):Math.abs(1e3*K.currentTime-l)>500&&(K.currentTime=c):(ce.reset(),K.paused||K.pause(),c!==K.currentTime&&(K.currentTime=c),!J(K)&&!p.isPlaying&&!ue.current&&(ue.current=E(`video ${s.id}`)))),Te(),null===(t=null===(e=H.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()}});return()=>{e(),ue.current&&(ue.current(),ue.current=null)}},[p,K,oe,ie,W]),i.useEffect(()=>{var e,t;if(!K){return}if(oe){return null===(e=ue.current)||void 0===e||e.call(ue),void(ue.current=null)}const r=()=>{var e;null===(e=ue.current)||void 0===e||e.call(ue),ue.current=null},o=()=>{J(K)&&(Te(),r())};let i,n;(null===(t=s.page)||void 0===t?void 0:t._exportingOrRendering)&&(i=setInterval(o,20)),K.addEventListener("timeupdate",o),K.addEventListener("canplay",o),K.addEventListener("seeked",o);const a=()=>{K.paused&&(Te(),J(K)&&r()),n=K.requestVideoFrameCallback(a)};return"requestVideoFrameCallback"in K&&(n=K.requestVideoFrameCallback(a)),()=>{clearInterval(i),void 0!==n&&K.cancelVideoFrameCallback(n),K.removeEventListener("timeupdate",o),K.removeEventListener("canplay",o),K.removeEventListener("seeked",o)}},[null===(f=s.page)||void 0===f?void 0:f._exportingOrRendering,K,s.id,E,oe]);let{cropX:he,cropY:me,cropWidth:pe,cropHeight:ge}=s.a;"loaded"!==Q&&(he=me=0,pe=ge=1);const{width:fe,height:ve}=Z(de),we=null!==(L=null==K?void 0:K.videoWidth)&&void 0!==L?L:0,xe=null!==(M=null==K?void 0:K.videoHeight)&&void 0!==M?M:0;i.useLayoutEffect(()=>{"loaded"===Q&&we>0&&xe>0&&s._setSourceSize({width:we,height:xe},s.a.src)},[s,s.a.src,Q,we,xe]);const Ee=y({fit:s.a.fit,focus:s.focus,stretchEnabled:s.stretchEnabled,cropX:he,cropY:me,cropWidth:pe,cropHeight:ge,width:s.a.width,height:s.a.height},{width:fe,height:ve}),Le=(Ee.width,Ee.height,null!==(C=s.cornerRadius)&&void 0!==C?C:0),[Me,ye]=useCornerRadiusAndCrop(s,de,Ee,p._elementsPixelRatio,Le,!0);let[Ce,be]=useClip(s,Me,p._elementsPixelRatio,[Ee,Le,p._elementsPixelRatio]);const ke=S(H,s,Ce),Te=I(()=>{var e,t;se(),le(),ye(),be(),ke(),null===(t=null===(e=H.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()});i.useEffect(()=>{Te()});const je=()=>{s._cropEnabled&&setTimeout(()=>{d(s)&&s.toggleCropMode(!0)})},Ie="loading"===Q,Re="failed"===Q,Se=!Ie&&!Re,Pe=k(s,Ee,"loaded"===Q?{width:fe,height:ve}:void 0,O),_e=Se?o(s):0;R(H,_e);const Ae=s.selectable||p.role===m.ADMIN;return t(e,{children:r(c,{onMouseEnter:()=>te(!0),onMouseLeave:()=>te(!1),children:[Ie&&t(x,{element:s}),Re&&t(w,{element:s,text:"Can not load the video..."}),t(u,Object.assign({ref:H,name:"element",id:s.id,image:Ce,x:s.a.x,y:s.a.y,width:s.a.width||1,height:s.a.height||1,rotation:s.a.rotation,opacity:_e},a(s),{customCrop:Ee,listening:Ae,draggable:U?s.draggable&&s.isSelected:s.draggable,preventDefault:!U||s.isSelected,hideInExport:!s.showInExport,onDragMove:e=>{s.set({x:e.target.x(),y:e.target.y()})},onDragEnd:e=>{s.set(b(e.target))},onDblClick:je,onDblTap:je},Pe)),!!s.borderSize&&t(h,{x:s.a.x,y:s.a.y,width:Math.max(s.a.width-s.borderSize,0),height:Math.max(s.a.height-s.borderSize,0),opacity:_e,offsetX:-s.borderSize/2,offsetY:-s.borderSize/2,stroke:n(s.borderColor),strokeWidth:s.borderSize,listening:!1,rotation:s.a.rotation,cornerRadius:Math.max(0,Le-s.borderSize),hideInExport:!s.showInExport}),!p.isPlaying&&t(u,{image:W?ee||U?$:void 0:q,x:s.a.x,y:s.a.y,offsetX:-s.a.width/2+15/p.scale,offsetY:-s.a.height/2+15/p.scale,rotation:s.a.rotation,width:30/p.scale,height:30/p.scale,hideInExport:!0,onClick:()=>X(!W),onTap:()=>X(!W)}),s._cropModeEnabled&&"loaded"===Q&&t(Y,{element:s,store:p,previewImage:Ce,sourceImage:de,sourceWidth:fe,sourceHeight:ve,crop:Ee,innerAnchors:N})]})})});
1
+ import{Fragment as e,jsx as t,jsxs as r}from"react/jsx-runtime";import{elementOpacity as i}from"./paint-opacity.js";import o from"react";import{toDisplayColor as n}from"@polotno/core/color";import{animatedShadow as a}from"./animated-shadow.js";import{observer as s}from"mobx-react-lite";import{isAlive as d}from"mobx-state-tree";import{nodeAutorun as l}from"../utils/mobx.js";import{Group as c,Image as u,Rect as h}from"react-konva";import{ROLES as m}from"../model/store.js";import{DEFAULT_RETRIES as p,isDeterministicUrl as f,retryDelayMs as g}from"@polotno/core/retry";import v from"konva";import{ErrorPlaceholder as w,LoadingPlaceholder as x}from"./media-placeholders.js";import{incrementLoader as E,triggerLoadError as L}from"../utils/loader.js";import{polotnoError as M}from"@polotno/core/errors";import{getCropRect as y}from"@polotno/core/image";import*as C from"@polotno/core/svg";import{roundedPosition as b}from"../utils/px.js";import{useMediaResize as k}from"./media-resize.js";import{useFilteredSource as T}from"./use-filtered-source.js";import{useOffscreenCanvas as j}from"./use-offscreen-canvas.js";import{useEvent as I}from"../hooks/use-event.js";import{useFadeIn as R}from"./use-fadein.js";import{useAnimatedBlur as S}from"./use-animated-blur.js";import{isTouchDevice as P}from"../utils/screen.js";import{createPlayGate as _,playMedia as A}from"../utils/media.js";import{useMediabunnyVideo as V}from"./use-mediabunny-video.js";import{getElementTimeRange as D,getVideoRestMs as z,isHeldByPreview as F}from"../utils/timeline.js";import{drawImageWindow as O,drawReduced as H,exportKernelEnabled as U,shouldResample as Z,sourceSize as W}from"./downscale.js";import{trySetCanvasSize as X}from"../utils/canvas.js";import{isWebKit as Y}from"../utils/engine.js";import{useClipImage as N}from"./image-element.js";import{CropOverlay as q,CROP_CORNER_ANCHORS as $}from"./crop-overlay.js";const B=new window.Image;B.src=C.svgToURL('\n <svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path opacity="0.6" d="M4 5.49683V18.5032C4 20.05 5.68077 21.0113 7.01404 20.227L18.0694 13.7239C19.384 12.9506 19.384 11.0494 18.0694 10.2761L7.01404 3.77296C5.68077 2.98869 4 3.95 4 5.49683Z" fill="white"/>\n <path d="M4 5.49683V18.5032C4 20.05 5.68077 21.0113 7.01404 20.227L18.0694 13.7239C19.384 12.9506 19.384 11.0494 18.0694 10.2761L7.01404 3.77296C5.68077 2.98869 4 3.95 4 5.49683Z" stroke="#323232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n');const G=new window.Image;G.src=C.svgToURL('\n <svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path opacity="0.6" d="M14 19L14 5C14 3.89543 14.8954 3 16 3L17 3C18.1046 3 19 3.89543 19 5L19 19C19 20.1046 18.1046 21 17 21L16 21C14.8954 21 14 20.1046 14 19Z" fill="white"/>\n <path opacity="0.6" d="M10 19L10 5C10 3.89543 9.10457 3 8 3L7 3C5.89543 3 5 3.89543 5 5L5 19C5 20.1046 5.89543 21 7 21L8 21C9.10457 21 10 20.1046 10 19Z" fill="white"/>\n <path d="M14 19L14 5C14 3.89543 14.8954 3 16 3L17 3C18.1046 3 19 3.89543 19 5L19 19C19 20.1046 18.1046 21 17 21L16 21C14.8954 21 14 20.1046 14 19Z" stroke="#323232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n <path d="M10 19L10 5C10 3.89543 9.10457 3 8 3L7 3C5.89543 3 5 3.89543 5 5L5 19C5 20.1046 5.89543 21 7 21L8 21C9.10457 21 10 20.1046 10 19Z" stroke="#323232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n');export const useFlip=(e,t)=>{const{flipX:r,flipY:i}=e,{width:o,height:n}=t?W(t):{},a=e=>{if(!t){return}const o=e.getContext("2d");o&&(o.clearRect(0,0,e.width,e.height),o.save(),o.scale(r?-1:1,i?-1:1),o.drawImage(t,r?-e.width:0,i?-e.height:0,e.width,e.height),o.restore())},s=j((r||i)&&!!o&&!!n,e=>{o&&n&&(e.width=o,e.height=n,a(e))},[r,i,t,o,n]);return[s||t,()=>{s&&a(s)}]};export const useCornerRadiusAndCrop=(e,t,r,i,n=0,a=!1)=>{var s;const d=Math.floor(Math.max(e.a.width*i,1)),l=Math.floor(Math.max(e.a.height*i,1)),c=Math.min(n*i,d/2,l/2),u=Math.max(e.a.width/r.width,e.a.height/r.height)*i,h=U(e.page)&&!a&&Z(u,d,l),{width:m,height:p}=t?W(t):{},f=0===r.x&&0===r.y&&r.width===m&&r.height===p,g=o.useMemo(()=>{if(t&&m&&p){return f&&0===c&&!h?void 0:document.createElement("canvas")}},[t,c,h,f,m,p]),w=()=>{if(!g||!t){return}g.width=d,g.height=l;const e=g.getContext("2d");e&&(c&&(e.beginPath(),e.moveTo(c,0),e.lineTo(d-c,0),e.arc(d-c,c,c,3*Math.PI/2,0,!1),e.lineTo(d,l-c),e.arc(d-c,l-c,c,0,Math.PI/2,!1),e.lineTo(c,l),e.arc(c,l-c,c,Math.PI/2,Math.PI,!1),e.lineTo(0,c),e.arc(c,c,c,Math.PI,3*Math.PI/2,!1),e.clip()),h?H(e,t,r,g.width,g.height):O(e,t,r,{x:0,y:0,width:g.width,height:g.height}))};return o.useLayoutEffect(()=>{w()},[g,e.a.width,e.a.height,r.x,r.y,r.width,r.height,n,i,a,null===(s=e.page)||void 0===s?void 0:s._exportingOrRendering,h]),o.useEffect(()=>()=>{g&&"CANVAS"===g.nodeName&&v.Util.releaseCanvas(g)},[g]),[g||t,w]};export const useClip=(e,t,r,i)=>{const[n,a]=N(e.clipSrc||""),s=e.clipSrc?a:"loaded";useLoader(s,e.clipSrc,e.id);const d=!!t&&!!n,l=o.useMemo(()=>d?{canvas:document.createElement("canvas"),mask:document.createElement("canvas"),width:0,height:0}:void 0,[d]),c=null==l?void 0:l.canvas;function u(){if(!l||!c||!t){return}const{width:i,height:o}=W(t);if(!i||!o){return}const n=Math.min(1e4,Math.max(i,Math.ceil(e.a.width*r),1)),a=Math.min(1e4,Math.max(o,Math.ceil(e.a.height*r),1));c.width&&l.width===n&&l.height===a||(X(c,n,a),l.width=n,l.height=a);const s=c.getContext("2d");s&&(s.clearRect(0,0,c.width,c.height),s.save(),s.drawImage(t,0,0,c.width,c.height),s.globalCompositeOperation="destination-in",s.drawImage(l.mask,0,0,c.width,c.height),s.restore())}return o.useLayoutEffect(()=>{var t;if(!l||!(null==n?void 0:n.width)||!n.height){return}const i=Math.max(e.a.width/n.width*r,e.a.height/n.height*r);X(l.mask,Math.min(1e4,Math.max(n.width*i,1)),Math.min(1e4,Math.max(n.height*i,1))),null===(t=l.mask.getContext("2d"))||void 0===t||t.drawImage(n,0,0,l.mask.width,l.mask.height)},[l,n,e.a.width,e.a.height,r]),o.useLayoutEffect(()=>{u()},[l,t,n,e.a.width,e.a.height,r,...i]),o.useEffect(()=>()=>{l&&v.Util.releaseCanvas(l.canvas,l.mask)},[l]),[d?c:t,u]};const J=document.createElement("canvas");let K=function(e,t,r){const i=o.useRef("loading"),n=o.useRef(void 0),[a,s]=o.useState(0),d=o.useRef(void 0),l=o.useRef(void 0),c=o.useRef(void 0);return d.current===e&&l.current===t&&c.current===r||(i.current="loading",n.current=void 0,d.current=e,l.current=t,c.current=r),o.useLayoutEffect(()=>{if(!e){return}const o=f(e)?1:p;let a,d,l,c=0,u=!1,h=!1;const m=e=>{e&&(e.removeAttribute("src"),e.load())},v=()=>{c+=1;const p=document.createElement("video");function f(){u||(p.removeEventListener("canplay",f),h=!0,i.current="loaded",n.current=p,p.currentTime=0,s(Math.random()))}function w(e){var t;const r=4===p.readyState,l=p.buffered&&p.buffered.length>0&&p.buffered.end(p.buffered.length-1)/p.duration*100>=100;if(r&&l){return}if(u){return}if(!h&&c<o){return null==d||d(),m(p),void(a=setTimeout(v,g(c)))}const f=e.message||(null===(t=p.error)||void 0===t?void 0:t.message)||"Unknown error";console.error(new Error("Video failed to load: "+f)),i.current="failed",n.current=void 0,s(Math.random())}l=p,p.addEventListener("canplay",f),p.addEventListener("error",w),d=()=>{p.removeEventListener("canplay",f),p.removeEventListener("error",w)},t&&(p.crossOrigin=t),r&&(p.referrerPolicy=r),p.src=e,p.load()};return v(),()=>{u=!0,clearTimeout(a),null==d||d(),h||m(l)}},[e,t,r]),[n.current,i.current]};export const setVideoLoaderHook=e=>{K=e};function Q(e){return!e.seeking&&e.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA}export const useLoader=(e,t,r)=>{const i=o.useRef(void 0),n=()=>{var e;null===(e=i.current)||void 0===e||e.call(i),i.current=void 0};o.useEffect(()=>n,[]),o.useLayoutEffect(()=>{const o=t.slice(0,200),a=`video with id ${r} url: ${o}`;"loading"!==e||i.current||(i.current=E(a)),"loading"!==e&&n(),"failed"===e&&L(M("VIDEO_FAILED",a,{src:o,elementId:r,reason:"load"}))},[e])};export const VideoElement=s(({element:s,store:p})=>{var f,g,L,M,C;const[j,O]=o.useState(!1),H=o.useRef(null),U=P(),[Z,X]=o.useState(!1),[N,ee]=K(s.a.src,"anonymous"),[te,re]=o.useState(!1),ie=p.activePage===s.page,oe=(null===(f=s.page)||void 0===f?void 0:f._exportingOrRendering)&&"loaded"===ee,ne=V(s,p,oe);useLoader(ee,s.a.src,s.id),N&&(N.playsInline=!0);const ae=oe&&ne||N,[se,de]=useFlip(s,ae),[le=J,ce]=T(s,se||J);o.useEffect(()=>{N&&p.history.ignore(()=>{s.set({duration:1e3*N.duration})})},[N]);const ue=o.useMemo(_,[N]);o.useEffect(()=>{var e;if(!N){return}const t=!F(s)&&p.isPlaying;if(!ie||!t&&!Z){return void N.pause()}Z&&(N.muted=!1,N.currentTime=s.startTime*N.duration,A(N).then(e=>{"refused"===e&&X(!1)}));const r=new v.Animation(()=>{je()},null===(e=H.current)||void 0===e?void 0:e.getLayer());r.start();const i=()=>{X(!1),N.currentTime=s.startTime*N.duration},o=()=>{N.currentTime>=s.endTime*N.duration&&(N.pause(),N.currentTime=s.startTime*N.duration,X(!1))};return N.addEventListener("ended",i),N.addEventListener("timeupdate",o),()=>{N.pause(),r.stop(),N.removeEventListener("ended",i),N.removeEventListener("timeupdate",o)}},[N,Z,p.isPlaying,ie]),o.useEffect(()=>{N&&(N.volume=s.volume)},[N,s.volume]),o.useEffect(()=>{N&&(N.playbackRate=s.speed,N.preservesPitch=!1)},[N,s.speed]);const he=o.useRef(null);o.useEffect(()=>{const e=l(s,()=>{var e,t;if(N){if(oe&&ne){return je(),void p.currentTime}if(F(s)){return}const r=p.activePage===s.page,i=s.page._mediaLocalTime,o=s.startTime*N.duration*1e3,n=N.duration*(s.endTime-s.startTime)*1e3,{start:a,end:d}=D(s.animations,s.page.duration),l=z(null!=i?i:0,0,a,n,o,s.speed,{windowEnd:d,frameMs:p._renderFrameMs,renderEnd:p._renderEndMs-s.page.startTime}),c=l/1e3,u=null!==i&&i>=a&&i<d;Z||(N.muted=!u,u&&p.isPlaying&&r?N.paused?(N.currentTime=c,ue.play(N)):Math.abs(1e3*N.currentTime-l)>500&&(N.currentTime=c):(ue.reset(),N.paused||N.pause(),c!==N.currentTime&&(N.currentTime=c),!Q(N)&&!p.isPlaying&&!he.current&&(he.current=E(`video ${s.id}`)))),je(),null===(t=null===(e=H.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()}});return()=>{e(),he.current&&(he.current(),he.current=null)}},[p,N,oe,ne,Z]),o.useEffect(()=>{var e,t;if(!N){return}if(oe){return null===(e=he.current)||void 0===e||e.call(he),void(he.current=null)}const r=()=>{var e;null===(e=he.current)||void 0===e||e.call(he),he.current=null},i=()=>{Q(N)&&(je(),r())};let o,n;(null===(t=s.page)||void 0===t?void 0:t._exportingOrRendering)&&(o=setInterval(i,20)),N.addEventListener("timeupdate",i),N.addEventListener("canplay",i),N.addEventListener("seeked",i);const a=()=>{N.paused&&(je(),Q(N)&&r()),n=N.requestVideoFrameCallback(a)};return"requestVideoFrameCallback"in N&&!Y()&&(n=N.requestVideoFrameCallback(a)),()=>{clearInterval(o),void 0!==n&&N.cancelVideoFrameCallback(n),N.removeEventListener("timeupdate",i),N.removeEventListener("canplay",i),N.removeEventListener("seeked",i)}},[null===(g=s.page)||void 0===g?void 0:g._exportingOrRendering,N,s.id,E,oe]);let{cropX:me,cropY:pe,cropWidth:fe,cropHeight:ge}=s.a;"loaded"!==ee&&(me=pe=0,fe=ge=1);const{width:ve,height:we}=W(le),xe=null!==(L=null==N?void 0:N.videoWidth)&&void 0!==L?L:0,Ee=null!==(M=null==N?void 0:N.videoHeight)&&void 0!==M?M:0;o.useLayoutEffect(()=>{"loaded"===ee&&xe>0&&Ee>0&&s._setSourceSize({width:xe,height:Ee},s.a.src)},[s,s.a.src,ee,xe,Ee]);const Le=y({fit:s.a.fit,focus:s.focus,stretchEnabled:s.stretchEnabled,cropX:me,cropY:pe,cropWidth:fe,cropHeight:ge,width:s.a.width,height:s.a.height},{width:ve,height:we}),Me=(Le.width,Le.height,null!==(C=s.cornerRadius)&&void 0!==C?C:0),[ye,Ce]=useCornerRadiusAndCrop(s,le,Le,p._elementsPixelRatio,Me,!0);let[be,ke]=useClip(s,ye,p._elementsPixelRatio,[Le,Me,p._elementsPixelRatio]);const Te=S(H,s,be),je=I(()=>{var e,t;de(),ce(),Ce(),ke(),Te(),null===(t=null===(e=H.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()});o.useEffect(()=>{je()});const Ie=()=>{s._cropEnabled&&setTimeout(()=>{d(s)&&s.toggleCropMode(!0)})},Re="loading"===ee,Se="failed"===ee,Pe=!Re&&!Se,_e=k(s,Le,"loaded"===ee?{width:ve,height:we}:void 0,O),Ae=Pe?i(s):0;R(H,Ae);const Ve=s.selectable||p.role===m.ADMIN;return t(e,{children:r(c,{onMouseEnter:()=>re(!0),onMouseLeave:()=>re(!1),children:[Re&&t(x,{element:s}),Se&&t(w,{element:s,text:"Can not load the video..."}),t(u,Object.assign({ref:H,name:"element",id:s.id,image:be,x:s.a.x,y:s.a.y,width:s.a.width||1,height:s.a.height||1,rotation:s.a.rotation,opacity:Ae},a(s),{customCrop:Le,listening:Ve,draggable:U?s.draggable&&s.isSelected:s.draggable,preventDefault:!U||s.isSelected,hideInExport:!s.showInExport,onDragMove:e=>{s.set({x:e.target.x(),y:e.target.y()})},onDragEnd:e=>{s.set(b(e.target))},onDblClick:Ie,onDblTap:Ie},_e)),!!s.borderSize&&t(h,{x:s.a.x,y:s.a.y,width:Math.max(s.a.width-s.borderSize,0),height:Math.max(s.a.height-s.borderSize,0),opacity:Ae,offsetX:-s.borderSize/2,offsetY:-s.borderSize/2,stroke:n(s.borderColor),strokeWidth:s.borderSize,listening:!1,rotation:s.a.rotation,cornerRadius:Math.max(0,Me-s.borderSize),hideInExport:!s.showInExport}),!p.isPlaying&&t(u,{image:Z?te||U?G:void 0:B,x:s.a.x,y:s.a.y,offsetX:-s.a.width/2+15/p.scale,offsetY:-s.a.height/2+15/p.scale,rotation:s.a.rotation,width:30/p.scale,height:30/p.scale,hideInExport:!0,onClick:()=>X(!Z),onTap:()=>X(!Z)}),s._cropModeEnabled&&"loaded"===ee&&t(q,{element:s,store:p,previewImage:be,sourceImage:le,sourceWidth:ve,sourceHeight:we,crop:Le,innerAnchors:$})]})})});
@@ -1 +1 @@
1
- import{getFlippedCropRect as t,loadImage as e,mayBeUnsizedSvg as i}from"@polotno/core/image";import{polotnoError as h}from"@polotno/core/errors";import{fetchSvgText as a,isSvgUrl as r,prepareSvgSource as o,urlToString as n}from"@polotno/core/svg";import{UNIT as c,matchesAspect as s}from"./geometry.js";export const WORKING_MAX_SIDE=4096;const w=(t,e,i)=>h("IMAGE_FAILED","This device could not prepare the image. Try a smaller image.",{reason:"raster-failed",stage:t,width:e.width,height:e.height},i);export function rasterCanvas(t,e){try{if(![t.width,t.height].every(t=>Number.isInteger(t)&&t>0&&t<=4096)){throw new Error("Invalid working dimensions")}const e=document.createElement("canvas");e.width=t.width,e.height=t.height;const i=e.getContext("2d");if(!i){throw new Error("Canvas 2D unavailable")}return{canvas:e,ctx:i}}catch(i){throw w(e,t,i)}}export async function encodeRaster(t,e){try{return await new Promise((e,i)=>t.toBlob(t=>t?e(t):i(new Error("PNG encoding failed")),"image/png"))}catch(i){throw w(e,t,i)}}export async function withBlobImage(t,i){const h=URL.createObjectURL(t);try{return await i(await e(h))}finally{URL.revokeObjectURL(h)}}export async function rasterizeImageInput(h,l=c){const g=r(h.src),d=g?o(await n(h.src)):h.src;let m=await e(d);if(!g&&i(m)){const t=await a(d).catch(()=>null);null!==t&&(m=await e(o(t)))}const f={width:m.naturalWidth,height:m.naturalHeight},p=t(h,f),u=Math.max(p.width,p.height)/Math.max(h.width,h.height),x=function(t){const e=Math.max(t.width,t.height);if(!Number.isFinite(e)||Math.min(t.width,t.height)<=0){throw w("compose",t)}for(let i=Math.min(4096,Math.ceil(e));i>0;i--){const h=i/e,a={width:Math.max(1,Math.round(t.width*h)),height:Math.max(1,Math.round(t.height*h))};if(s(a,t)){return a}}throw new RangeError("The image aspect cannot fit the working raster.")}({width:h.width*l.width*u,height:h.height*l.height*u}),{canvas:M,ctx:y}=rasterCanvas(x,"compose"),v=h.flipX?1-l.x-l.width:l.x,R=h.flipY?1-l.y-l.height:l.y;y.translate(h.flipX?x.width:0,h.flipY?x.height:0),y.scale(h.flipX?-1:1,h.flipY?-1:1);try{y.drawImage(m,p.x+v*p.width,p.y+R*p.height,l.width*p.width,l.height*p.height,0,0,x.width,x.height)}catch(I){throw w("compose",x,I)}return{image:await encodeRaster(M,"compose"),size:x}}export async function rectangleMask(t,e){const{canvas:i,ctx:h}=rasterCanvas(t,"mask");h.fillStyle="black",h.fillRect(0,0,t.width,t.height);const a=Math.max(0,Math.floor(e.x*t.width)),r=Math.max(0,Math.floor(e.y*t.height)),o=Math.min(t.width,Math.ceil((e.x+e.width)*t.width)),n=Math.min(t.height,Math.ceil((e.y+e.height)*t.height));return h.fillStyle="white",h.fillRect(a,r,o-a,n-r),encodeRaster(i,"mask")}
1
+ import{getFlippedCropRect as t,loadImage as e,mayBeUnsizedSvg as i}from"@polotno/core/image";import{polotnoError as h}from"@polotno/core/errors";import{drawImageWindow as a}from"@polotno/core/downscale";import{fetchSvgText as r,isSvgUrl as o,prepareSvgSource as n,urlToString as c}from"@polotno/core/svg";import{UNIT as s,matchesAspect as w}from"./geometry.js";export const WORKING_MAX_SIDE=4096;const l=(t,e,i)=>h("IMAGE_FAILED","This device could not prepare the image. Try a smaller image.",{reason:"raster-failed",stage:t,width:e.width,height:e.height},i);export function rasterCanvas(t,e){try{if(![t.width,t.height].every(t=>Number.isInteger(t)&&t>0&&t<=4096)){throw new Error("Invalid working dimensions")}const e=document.createElement("canvas");e.width=t.width,e.height=t.height;const i=e.getContext("2d");if(!i){throw new Error("Canvas 2D unavailable")}return{canvas:e,ctx:i}}catch(i){throw l(e,t,i)}}export async function encodeRaster(t,e){try{return await new Promise((e,i)=>t.toBlob(t=>t?e(t):i(new Error("PNG encoding failed")),"image/png"))}catch(i){throw l(e,t,i)}}export async function withBlobImage(t,i){const h=URL.createObjectURL(t);try{return await i(await e(h))}finally{URL.revokeObjectURL(h)}}export async function rasterizeImageInput(h,g=s){const d=o(h.src),m=d?n(await c(h.src)):h.src;let f=await e(m);if(!d&&i(f)){const t=await r(m).catch(()=>null);null!==t&&(f=await e(n(t)))}const p={width:f.naturalWidth,height:f.naturalHeight},u=t(h,p),x=Math.max(u.width,u.height)/Math.max(h.width,h.height),y=function(t){const e=Math.max(t.width,t.height);if(!Number.isFinite(e)||Math.min(t.width,t.height)<=0){throw l("compose",t)}for(let i=Math.min(4096,Math.ceil(e));i>0;i--){const h=i/e,a={width:Math.max(1,Math.round(t.width*h)),height:Math.max(1,Math.round(t.height*h))};if(w(a,t)){return a}}throw new RangeError("The image aspect cannot fit the working raster.")}({width:h.width*g.width*x,height:h.height*g.height*x}),{canvas:M,ctx:v}=rasterCanvas(y,"compose"),R=h.flipX?1-g.x-g.width:g.x,I=h.flipY?1-g.y-g.height:g.y;v.translate(h.flipX?y.width:0,h.flipY?y.height:0),v.scale(h.flipX?-1:1,h.flipY?-1:1);try{a(v,f,{x:u.x+R*u.width,y:u.y+I*u.height,width:g.width*u.width,height:g.height*u.height},{x:0,y:0,width:y.width,height:y.height})}catch(b){throw l("compose",y,b)}return{image:await encodeRaster(M,"compose"),size:y}}export async function rectangleMask(t,e){const{canvas:i,ctx:h}=rasterCanvas(t,"mask");h.fillStyle="black",h.fillRect(0,0,t.width,t.height);const a=Math.max(0,Math.floor(e.x*t.width)),r=Math.max(0,Math.floor(e.y*t.height)),o=Math.min(t.width,Math.ceil((e.x+e.width)*t.width)),n=Math.min(t.height,Math.ceil((e.y+e.height)*t.height));return h.fillStyle="white",h.fillRect(a,r,o-a,n-r),encodeRaster(i,"mask")}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "polotno",
3
- "version": "4.23.0",
3
+ "version": "4.24.0",
4
4
  "description": "Design editor SDK: embed a Canva-like editor, generate designs from templates and data, export PNG, PDF, and video in the browser or on a server.",
5
5
  "author": "Anton Lavrenov",
6
6
  "keywords": [
@@ -109,10 +109,10 @@
109
109
  "dependencies": {
110
110
  "@base-ui/react": "^1.9.0",
111
111
  "@lottiefiles/dotlottie-web": "0.83.2",
112
- "@polotno/core": "0.24.0",
113
- "@polotno/html-export": "0.14.0",
112
+ "@polotno/core": "0.25.0",
113
+ "@polotno/html-export": "0.14.1",
114
114
  "@polotno/schema": "0.15.0",
115
- "@polotno/svg-export": "0.15.0",
115
+ "@polotno/svg-export": "0.15.1",
116
116
  "class-variance-authority": "^0.7.1",
117
117
  "clsx": "^2.1.1",
118
118
  "gifuct-js": "^2.1.2",