// import React, { useCallback, useEffect, useMemo, useRef } from 'react';
// import PropTypes from 'prop-types';
// import { useDispatch } from 'react-redux';
// import { cloneDeep, flatten, forIn } from 'lodash';
 
// import withEditor from '../../../../HOCs/withEditor';
 
// import {
// selectCanvasContourSelectionBox,
// selectFirstSelectedObjType,
// selectMagicLinesType,
// selectPickerObjectID,
// selectPlayerIsPlaying,
// selectPlayerZoom,
// selectSelectedObjectIDs,
// selectShowTextEditor,
// } from '../../../../../store/selectors';
 
// import { useCurrentValue, useStoreCurrentValue, useThrottle } from '../../../../hooks';
 
// import {
// applyAdditionalTransformationAfterResize,
// calcResizeMagnetVector,
// checkAreAllObjectsTextOrShapes,
// draggableOnListeners,
// fixVideoDataCrop,
// getCursorPosition,
// getGeomParams,
// getGroupObjectParams,
// getLineInfo,
// getObjectGroupId,
// getObjectMagicPoints,
// getResizeObjectsUpdateResult,
// getScaleMatrix,
// getSelectionBox,
// isMobileOrTablet,
// removeCursorTrackTooltip,
// s3Replace,
// shouldBlockResizing,
// transformBoxPointsToView,
// } from '../../../../../utils';
 
// import {
// setSlideOrObjectId,
// switchCanvasHoverDisabledState,
// switchObjectsResizingState,
// updateCanvasContour,
// updateSlideObjectsThunk,
// } from '../../../../../actions';
 
// import {
// FIXED_ASPECT_RATIO_OBJECTS,
// OBJECT_SHAPE_TYPES,
// OBJECTS_WITH_CROP,
// OBJECTS_WITH_MOVE_CALLBACKS,
// } from '../../../../../constants';
 
// const PIVOT_INDEX_BY_POINT = {
// x1y1: 2, y1: 3, x2y1: 3, x2: 0, x2y2: 0, y2: 1, x1y2: 1, x1: 2,
// };
// const ACTIVE_INDEX_BY_POINT = {
// x1y1: 0, y1: 1, x2y1: 1, x2: 2, x2y2: 2, y2: 3, x1y2: 3, x1: 0,
// };
 
// /**
// * Detects resize inversion (dragged corner passed the pivot) in world coordinates.
// * Works for rotated boxes (e.g. group resize).
// * @returns {{ inverseX: boolean, inverseY: boolean }}
// */
// function getResizeInversion(initBox, currentBox, point) {
// const pivotIndex = PIVOT_INDEX_BY_POINT[point];
// const activeIndex = ACTIVE_INDEX_BY_POINT[point];
// if (pivotIndex === undefined || activeIndex === undefined) return { inverseX: false, inverseY: false };
 
// const initPoints = initBox?.objectPoints || initBox?.boxPoints;
// const currPoints = currentBox?.objectPoints || currentBox?.boxPoints;
// if (!initPoints?.[pivotIndex] || !initPoints?.[activeIndex] || !currPoints?.[activeIndex]) {
// return { inverseX: false, inverseY: false };
// }
 
// const pivotX = initPoints[pivotIndex][0];
// const pivotY = initPoints[pivotIndex][1];
// const initActiveX = initPoints[activeIndex][0];
// const initActiveY = initPoints[activeIndex][1];
// const currActiveX = currPoints[activeIndex][0];
// const currActiveY = currPoints[activeIndex][1];
 
// const initDx = initActiveX - pivotX;
// const initDy = initActiveY - pivotY;
// const currDx = currActiveX - pivotX;
// const currDy = currActiveY - pivotY;
 
// const inverseX = initDx !== 0 && currDx !== 0 && (initDx > 0) !== (currDx > 0);
// const inverseY = initDy !== 0 && currDy !== 0 && (initDy > 0) !== (currDy > 0);
 
// return { inverseX, inverseY };
// }
 
// const EditorCanvasResize = React.memo((props) => {
// const {
// playerInstance, canvasRef, overlayRef, fetcherRef, magicLinesRef, resizeSubscribers,
// } = props;
 
// const [zoom, zoomRef] = useStoreCurrentValue(selectPlayerZoom);
// const [isPlaying, isPlayingRef] = useStoreCurrentValue(selectPlayerIsPlaying);
// const [, isTextEditorActiveRef] = useStoreCurrentValue(selectShowTextEditor);
// const [, magicLinesTypeRef] = useStoreCurrentValue(selectMagicLinesType);
// const [, selectionBoxRef] = useStoreCurrentValue(selectCanvasContourSelectionBox);
// const [, selectedObjectsIDsRef] = useStoreCurrentValue(selectSelectedObjectIDs);
// const [, firstSelectedObjTypeRef] = useStoreCurrentValue(selectFirstSelectedObjType);
// const [, pickerObjectIdRef] = useStoreCurrentValue(selectPickerObjectID);
 
// const dispatch = useDispatch();
 
// const scaleMatrix = useMemo(() => getScaleMatrix(zoom), [zoom]);
 
// const scaleMatrixRef = useCurrentValue(scaleMatrix);
 
// const fetcherDataRef = useRef(null);
// const totalResizedObjectsRef = useRef(null);
// const overlayBoundingBoxRef = useRef(null);
// const pointRef = useRef(null);
// const initSelectionBoxSizeRef = useRef(null);
// const initSelectedObjectsSizeRef = useRef(null);
// const initSelectedObjectsRef = useRef(null);
// const selectedObjectsRef = useRef(null);
// const allGroupChildsIdsRef = useRef([]);
// const magicPointsRef = useRef([]);
// const initBoxesRef = useRef([]);
// const draggableDetachers = useRef([]);
// const keepAspectRatioRef = useRef(false);
// const wereObjectsResizedRef = useRef(false);
// const isResizingBlockedRef = useRef({ state: false, cause: '' });
// const precalculatedUpdatedObjectsRef = useRef({});
// const reflectionRef = useRef({ isReflectX: false, isReflectY: false });
// // Per-object curve points for multi-selection resize (keyed by object.id)
// const updatedCurvePointsRef = useRef({});
 
// const throttledHandleDrawMagicLines = useThrottle((selectionBox) => {
// requestAnimationFrame(() => {
// const objectMagicPoints = getObjectMagicPoints(selectionBox);
 
// if (magicLinesRef.current) {
// magicLinesRef.current.drawMagicLines(objectMagicPoints, magicPointsRef.current, zoomRef.current);
// }
// });
// }, 20, { leading: true });
 
// const handleDotClicked = useCallback((e) => {
// if (!canvasRef.current || !fetcherRef.current || isPlayingRef.current) return;
 
// const dot = e.detail?.dot;
 
// if (!dot) return;
 
// if (dot.classList.contains('selection-box-line-dot')) return;
 
// if (selectedObjectsIDsRef.current.length === 1 && (
// OBJECTS_WITH_CROP.includes(firstSelectedObjTypeRef.current) || firstSelectedObjTypeRef.current === 'table'
// )) {
// if (dot.classList.contains('selection-box-side-dot')) return;
// }
 
// pointRef.current = `${dot.getAttribute('x-param') || ''}${dot.getAttribute('y-param') || ''}`;
 
// fetcherDataRef.current = fetcherRef.current.getData();
 
// const { allObjects } = fetcherDataRef.current;
 
// let ids = selectedObjectsIDsRef.current;
// let selectedObjects = ids.map((id) => allObjects.find((o) => o.id === id));
 
// if (ids.length === 1 && selectedObjects[0].type !== 'group') {
// // replace child with its group parent object
// const groupId = getObjectGroupId(allObjects, ids[0]);
 
// if (groupId) {
// ids = [groupId];
// selectedObjects = ids.map((id) => allObjects.find((o) => o.id === id));
// }
// }
 
// const selectedGroups = selectedObjects.filter((obj) => obj.type === 'group');
// const allGroupChilds = flatten(selectedGroups.map((go) => allObjects.filter((obj) => go.objects.includes(obj.id))));
// const allGroupChildsIds = allGroupChilds.map((o) => o.id);
// const totalObjectsIds = [...selectedObjects.map((o) => o.id), ...allGroupChildsIds];
 
// allGroupChildsIdsRef.current = allGroupChildsIds;
// totalResizedObjectsRef.current = fetcherRef.current.getSpecificDomElementsWithBoxes(canvasRef, totalObjectsIds);
// selectedObjectsRef.current = ids
// .map((id) => totalResizedObjectsRef.current.find((o) => o.object.id === id))
// .filter(Boolean);
// }, []);
 
// const handleObjectsMove = useCallback((
// params, data, object, textLayer, objData, sharedSelectionBox, initSharedBox, resizePoint,
// ) => {
// if (object.type === 'text') {
// if (textLayer) {
// if (data?.style?.font_size) textLayer.style.fontSize = `${data.style.font_size}px`;
 
// if (['x1', 'x2'].includes(pointRef.current)) textLayer.style.whiteSpace = 'normal';
// }
// }
 
// let updatedCurvePoints = null;
// let updatedReflection = null;
 
// if (object.type === 'line' && object.style?.points && initSelectedObjectsRef?.current) {
// const point = resizePoint ?? pointRef.current;
// const currentSharedBox = selectionBoxRef.current;
// // inverseX / inverseY: true when dragged corner passed pivot (works for rotated group box)
// // eslint-disable-next-line no-unused-vars -- reserved for line shift logic
// const { inverseX, inverseY } = getResizeInversion(
// initSharedBox ?? initBoxesRef.current?.[0],
// currentSharedBox,
// point,
// );
// // TODO: на основе этих полей нужно будет задать reflect_x, reflect_y
// // но важно учесть что их у объекта может изначально не быть
// // если их нету то задаются reflect_x: inverseX, reflect_y: inverseY
// // если они уже есть, то инвертируются текущие (если был reflect_x: true и inverseX: true, то reflect_x: false etc.)
// console.log('inverseX, inverseY', inverseX, inverseY)
 
// updatedReflection = { reflect_x: inverseX, reflect_y: inverseY };
 
// const initObj = object;
 
// const k = data.width / initObj.width;
 
// const lineInfo = getLineInfo(initObj);
 
// const v = {
// x: initObj.style.points[0][0] - lineInfo.center.x,
// y: initObj.style.points[0][1] - lineInfo.center.y,
// };
// const l = Math.hypot(v.x, v.y);
// const dir = { x: v.x / l, y: v.y / l };
// const newL = l * k;
 
// const newPoint = { x: params.cx + dir.x * newL, y: params.cy + dir.y * newL };
 
// updatedCurvePoints = [[newPoint.x, newPoint.y]];
// }
 
// if (!OBJECTS_WITH_MOVE_CALLBACKS.includes(object.type)) return;
 
// const updatedObject = fixVideoDataCrop({ ...object, ...data });
 
// if (updatedCurvePoints) {
// updatedObject.x = params.left;
// updatedObject.y = params.top;
// updatedObject.style = { ...updatedObject.style, points: updatedCurvePoints };
 
// updatedCurvePointsRef.current[object.id] = {
// height: params.height,
// width: params.width,
// x: params.left,
// y: params.top,
// points: updatedCurvePoints,
// };
// }
// console.log('objData', objData)
// if (updatedReflection) {
// // if (object.reflect_x !== undefined) {
// // if (updatedReflection.reflect_x) updatedObject.reflect_x = true;
// // } else {
// // if (updatedReflection.reflect_x) updatedObject.reflect_x = !object.reflect_x; // eslint-disable-line
// // }
// // if (object.reflect_y !== undefined) {
// // if (updatedReflection.reflect_y) updatedObject.reflect_y = true;
// // } else {
// // if (updatedReflection.reflect_y) updatedObject.reflect_y = !object.reflect_y; // eslint-disable-line
// // }
 
// // if (updatedCurvePointsRef.current[object.id]) {
// // updatedCurvePointsRef.current[object.id].reflect_x = updatedObject.reflect_x;
// // updatedCurvePointsRef.current[object.id].reflect_y = updatedObject.reflect_y;
// // }
 
// // if (objData.dom) {
// // const transformLayer = objData.dom.querySelector('.__supa_player__slide-object-transform-layer');
 
// // if (transformLayer) {
// // transformLayer.style.transform = transformLayer.style.transform
// // .replace(/scaleX\([^)]*\)/, `scaleX(${updatedCurvePointsRef.current[object.id].reflect_x ? -1 : 1})`)
// // .replace(/scaleY\([^)]*\)/, `scaleY(${updatedCurvePointsRef.current[object.id].reflect_y ? -1 : 1})`);
// // }
// // }
// }
 
// console.log('updatedObject', updatedObject, 'object.type', object.type)
 
// playerInstance.updateObjectHTML(JSON.parse(s3Replace(JSON.stringify(updatedObject))));
// }, [playerInstance]);
 
// const handleUpdateObjects = useCallback((
// objData, params, e, resultUpdatedObjects, isGroupResizing, allObjectsTypeCheckResult,
// sharedSelectionBox, initSharedBox, resizePoint,
// ) => {
// const isSideDot = ['x1', 'x2', 'y1', 'y2'].includes(pointRef.current);
 
// const updateSelectionBox = (box) => {
// if (!box || (isTextEditorActiveRef.current && isSideDot)) return;
 
// const boxViewPoints = transformBoxPointsToView(box, scaleMatrixRef.current);
 
// dispatch(updateCanvasContour({
// selection: { points: boxViewPoints, lines: { points: boxViewPoints }, thinLines: null },
// hover: null,
// mergeData: true,
// }));
// };
 
// const resizeResult = getResizeObjectsUpdateResult(
// objData,
// params,
// e,
// resultUpdatedObjects,
// isGroupResizing,
// allObjectsTypeCheckResult,
// selectionBoxRef.current,
// fetcherDataRef.current.allObjects,
// pointRef.current,
// initSelectionBoxSizeRef.current,
// initSelectedObjectsSizeRef.current,
// initBoxesRef.current,
// selectedObjectsIDsRef.current,
// isTextEditorActiveRef.current,
// reflectionRef.current,
// precalculatedUpdatedObjectsRef.current,
// keepAspectRatioRef.current,
// isResizingBlockedRef.current,
// totalResizedObjectsRef.current,
// );
 
// if (!resizeResult) return false;
 
// const { result, textLayer, correctSelectionBox } = resizeResult;
 
// updateSelectionBox(correctSelectionBox);
 
// handleObjectsMove(
// params, result, objData.object, textLayer, objData, sharedSelectionBox, initSharedBox, resizePoint,
// );
 
// resizeSubscribers.current?.forEach((clbk) => clbk('move', result, updateSelectionBox, pointRef.current));
 
// return true;
// }, [handleObjectsMove]);
 
// const handleUpdateData = useCallback((updatedObjects, groupObjects) => {
// let objects = [];
// let updatedData = [];
 
// const { slides } = fetcherDataRef.current;
 
// forIn(updatedObjects, (value, path) => {
// const [a, b] = path.split('_');
 
// if (!slides[a].objects[b]) return;
 
// if (slides[a].objects[b].id === pickerObjectIdRef.current) {
// dispatch(setSlideOrObjectId({ initialObjectSize: null }));
// }
 
// objects.push(slides[a].objects[b]);
// updatedData.push(value);
// });
 
// dispatch(updateSlideObjectsThunk(objects, updatedData));
 
// objects = [];
// updatedData = [];
 
// // Correct group object size after childs has been updated
// // Use setTimeout in case we have curved text which takes time to render
// setTimeout(() => {
// Object.keys(groupObjects).forEach((key) => {
// const [a, b] = key.split('_');
 
// const audioObjects = slides[a].objects[b].objects
// .map((id) => slides[a].objects.find((o) => o.id === id))
// .filter(Boolean)
// .filter((obj) => obj.type === 'audio');
// const groupObjectParams = getGroupObjectParams([...groupObjects[key], ...audioObjects]);
 
// if (groupObjectParams?.data) {
// objects.push(slides[a].objects[b]);
// updatedData.push(groupObjectParams.data);
// }
 
// if (groupObjectParams?.childsData) {
// objects.push(...groupObjects[key]);
// updatedData.push(...groupObjectParams.childsData);
// }
// });
 
// dispatch(updateSlideObjectsThunk(objects, updatedData));
// });
// }, []);
 
// const handleResizeDone = useCallback((e) => {
// removeCursorTrackTooltip();
 
// // Store group object path and it's childs with updated data
// // Will be used to calculate correct group objects sizes with round values
// const groupObjects = {};
// const updatedObjects = {};
 
// if (wereObjectsResizedRef.current || e?.type === 'canvas:mobileScaleStart') {
// dispatch(switchObjectsResizingState(false));
// dispatch(switchCanvasHoverDisabledState(false));
 
// if (totalResizedObjectsRef.current && fetcherDataRef.current) {
// const { allObjects } = fetcherDataRef.current;
 
// totalResizedObjectsRef.current.forEach(({ dom: item, object }) => {
// const slideIndex = item.getAttribute('slide-index');
// const objectIndex = item.getAttribute('object-index');
 
// const { left, top, width, height } = getComputedStyle(item);
 
// const result = {};
 
// const selectionBoxPoints = selectionBoxRef.current?.lineBoxWithCurvePoints
// || selectionBoxRef.current?.boxPoints;
// const geomParams = getGeomParams(selectionBoxPoints);
 
// const isSideHorizontalDot = ['x1', 'x2'].includes(pointRef.current);
 
// const precalculatedResult = precalculatedUpdatedObjectsRef.current[`${slideIndex}_${objectIndex}`];
 
// if (object.type === 'text' && !isSideHorizontalDot) {
// if (precalculatedResult) Object.assign(result, precalculatedResult);
// }
 
// if (object.type === 'chart' && !isSideHorizontalDot) {
// const diffW = initSelectionBoxSizeRef.current.width / geomParams.width;
 
// const newLegendFontSize = object.style.legend.font_size / diffW;
// const newLabelsFontSize = object.style.labels.font_size / diffW;
// const newValuesFontSize = object.style.values.font_size / diffW;
// const newValuesDistance = (object.style.values.distance || 10) / diffW;
 
// result.style = {
// legend: { font_size: Math.min(Math.max(newLegendFontSize, 1), 100) },
// labels: { font_size: Math.min(Math.max(newLabelsFontSize, 1), 100) },
// values: {
// font_size: Math.min(Math.max(newValuesFontSize, 1), 100),
// ...['pie', 'doughnut'].includes(object.chart_type) && { distance: Math.min(Math.max(newValuesDistance, 1), 100) },
// },
// };
// }
 
// if (object.type === 'table' && !isSideHorizontalDot) {
// if (precalculatedResult) Object.assign(result, precalculatedResult);
// }
 
// const groupId = getObjectGroupId(allObjects, object.id);
 
// let groupKey = null;
 
// // group objects values will be rounded after resizing will be finished
// const keepDecimal = groupId || (object.type === 'group' && object.rotate);
 
// let x = keepDecimal ? parseFloat(left) : Math.round(parseFloat(left));
// let y = keepDecimal ? parseFloat(top) : Math.round(parseFloat(top));
 
// const widthRes = keepDecimal ? parseFloat(width) : Math.round(parseFloat(width));
// const heightRes = keepDecimal ? parseFloat(height) : Math.round(parseFloat(height));
 
// if (groupId) {
// const groupDom = item.closest('div[object-type="group"]');
// const groupSlideIndex = groupDom.getAttribute('slide-index');
// const groupObjectIndex = groupDom.getAttribute('object-index');
// const groupDomStyles = getComputedStyle(groupDom);
 
// groupKey = `${groupSlideIndex}_${groupObjectIndex}`;
 
// x += parseFloat(groupDomStyles.left);
// y += parseFloat(groupDomStyles.top);
// }
 
// result.x = x;
// result.y = y;
// result.width = widthRes;
// result.height = object.type === 'line' ? 1 : heightRes;
// result.width_auto = false;
// result.reflect_x = reflectionRef.current.isReflectX ? !object.reflect_x : object.reflect_x;
// result.reflect_y = reflectionRef.current.isReflectY ? !object.reflect_y : object.reflect_y;
 
// if (object.type === 'text') result.style = { ...(result.style ?? {}), word_break: true };
 
// if (object.type === 'line' && object.style?.points) {
// result.height = 1;
 
// const curveData = updatedCurvePointsRef.current[object.id];
 
// if (curveData) {
// // Use final curve geometry calculated during resize (correct for rotated groups).
// result.width = curveData.width;
// result.x = curveData.x;
// result.y = curveData.y;
// result.style = { points: curveData.points };
 
// if (curveData.reflect_x !== undefined) result.reflect_x = curveData.reflect_x;
// if (curveData.reflect_y !== undefined) result.reflect_y = curveData.reflect_y;
// } else if (groupId && initBoxesRef.current?.[0]) {
// // Fallback: line in group when we don't have curve data – compute from group scale.
// // Use group's own init box, not the overall selection box (which may include other selected objects).
// const resizedObjects = totalResizedObjectsRef.current;
// const groupIndex = resizedObjects?.findIndex((o) => o.object.id === groupId);
// const initGroupBox = groupIndex >= 0 ? initBoxesRef.current[groupIndex + 1] : null;
// const initGroup = initGroupBox?.boxPoints ? getGeomParams(initGroupBox.boxPoints) : null;
 
// if (!initGroup) {
// result.width = object.width;
// result.style = { points: object.style.points };
// } else {
// const groupDom = item.closest('div[object-type="group"]');
// const groupDomStyles = getComputedStyle(groupDom);
 
// const scaleX = parseFloat(groupDomStyles.width) / initGroup.width;
// const scaleY = parseFloat(groupDomStyles.height) / initGroup.height;
 
// const groupLeft = parseFloat(groupDomStyles.left);
// const groupTop = parseFloat(groupDomStyles.top);
 
// result.x = Math.round(groupLeft + (object.x - initGroup.left) * scaleX);
// result.y = Math.round(groupTop + (object.y - initGroup.top) * scaleY);
// result.width = Math.round(object.width * scaleX);
 
// const pt = object.style.points[0];
 
// result.style = {
// points: [[
// Math.round(groupLeft + (pt[0] - initGroup.left) * scaleX),
// Math.round(groupTop + (pt[1] - initGroup.top) * scaleY),
// ]],
// };
// }
// }
// }
 
// if (groupKey) {
// const updatedObject = { ...object, ...result };
 
// if (result.style) updatedObject.style = { ...object.style, ...result.style };
 
// groupObjects[groupKey] = groupObjects[groupKey]
// ? [...groupObjects[groupKey], updatedObject]
// : [updatedObject];
// }
 
// updatedObjects[`${slideIndex}_${objectIndex}`] = result;
 
// setTimeout(() => {
// resizeSubscribers.current?.forEach((clbk) => clbk('done', result, null, pointRef.current));
// });
// });
// }
// }
 
// if (wereObjectsResizedRef.current && fetcherDataRef.current) handleUpdateData(updatedObjects, groupObjects);
 
// totalResizedObjectsRef.current = null;
// wereObjectsResizedRef.current = false;
// fetcherDataRef.current = null;
// isResizingBlockedRef.current = { state: false, cause: '' };
// precalculatedUpdatedObjectsRef.current = {};
// reflectionRef.current = { isReflectX: false, isReflectY: false };
// initSelectedObjectsRef.current = null;
// updatedCurvePointsRef.current = {};
 
// magicLinesRef.current.clearMagicLines();
// }, [handleUpdateData]);
 
// const initResize = useCallback(() => {
// if (!canvasRef.current || !overlayRef.current) return;
 
// const detachListeners = draggableOnListeners(canvasRef.current, {
// cancelStopPropagation: true,
// start: () => {
// if (!selectionBoxRef.current) return;
// if (!totalResizedObjectsRef.current || !magicLinesRef.current || isPlayingRef.current) return;
// if (!totalResizedObjectsRef.current[0]) return;
 
// const resizedObjects = totalResizedObjectsRef.current;
// const firstObjType = firstSelectedObjTypeRef.current;
 
// resizeSubscribers.current?.forEach((clbk) => clbk('start'));
 
// const isSingleSelection = selectedObjectsIDsRef.current.length === 1;
// const isFirstObjText = firstObjType === 'text';
// const isFirstObjHasWidthAuto = resizedObjects[0].object.width_auto;
// const isSideHorizontalDot = ['x1', 'x2'].includes(pointRef.current);
// const isAnyHasFixedAspectRatio = resizedObjects.some((o) => FIXED_ASPECT_RATIO_OBJECTS.includes(o.object.type));
// const isAnyHasRotation = resizedObjects.some(({ box, object }) => !!(box.angle || object.rotate));
// const isOnlyShapes = resizedObjects.every((o) => OBJECT_SHAPE_TYPES.includes(o.object.type));
 
// initBoxesRef.current = [cloneDeep(selectionBoxRef.current), ...cloneDeep(resizedObjects.map((o) => o.box))];
 
// const initBoxPoints = initBoxesRef.current[0]?.lineBoxWithCurvePoints || initBoxesRef.current[0]?.boxPoints;
 
// initSelectionBoxSizeRef.current = getGeomParams(initBoxPoints);
// overlayBoundingBoxRef.current = overlayRef.current.getBoundingClientRect();
// magicPointsRef.current = magicLinesRef.current.getMagicPoints(canvasRef, fetcherDataRef.current.allObjects);
// keepAspectRatioRef.current = isAnyHasFixedAspectRatio || (!isSingleSelection && isAnyHasRotation);
 
// // Allow shapes to ignore aspect ratio
// if (isOnlyShapes) keepAspectRatioRef.current = false;
 
// // reset auto width for single text
// if (isSingleSelection && isFirstObjText && isFirstObjHasWidthAuto && isSideHorizontalDot) {
// resizedObjects[0].object.width = initSelectionBoxSizeRef.current.width;
// resizedObjects[0].object.width_auto = false;
 
// resizedObjects[0].dom.style.width = `${initSelectionBoxSizeRef.current.width}px`;
// }
 
// initSelectedObjectsSizeRef.current = resizedObjects.map((obj) => {
// const childSelectionBox = getSelectionBox(obj.dom, obj.object, null, null, true);
 
// return { id: obj.object.id, params: getGeomParams(childSelectionBox.boxPoints) };
// });
 
// initSelectedObjectsRef.current = resizedObjects.map((obj) => obj.object);
// },
// move: ({ dX }, e) => {
// if (!selectionBoxRef.current) return;
// if (!totalResizedObjectsRef.current || isPlayingRef.current) return;
// if (!totalResizedObjectsRef.current[0]) return;
 
// if (!wereObjectsResizedRef.current) {
// dispatch(switchObjectsResizingState(true));
// dispatch(switchCanvasHoverDisabledState(true));
// }
 
// const cursorPos = getCursorPosition(e, overlayBoundingBoxRef.current, zoomRef.current);
 
// if (e.shiftKey) keepAspectRatioRef.current = true;
 
// const resizedObjects = totalResizedObjectsRef.current;
// const groupChildsIds = allGroupChildsIdsRef.current;
// const selectedObjectsLength = selectedObjectsIDsRef.current.length;
 
// const currentBoxes = [
// selectionBoxRef.current,
// ...resizedObjects.map(({ box, object }) => ({ ...box, isChild: groupChildsIds.includes(object.id) })),
// ];
 
// const isSideDot = ['x1', 'x2', 'y1', 'y2'].includes(pointRef.current);
// const isSideXDot = ['x1', 'x2'].includes(pointRef.current);
// const settingsAngle = selectedObjectsLength === 1 && resizedObjects[0].object.rotate;
// const angle = selectedObjectsLength === 1 && Math.round(resizedObjects[0].box.angle * (180 / Math.PI));
// const isGroupResizingBySide = selectedObjectsLength === 1 && resizedObjects[0].object.type === 'group' && isSideXDot;
// const stopMagnet = !!(isGroupResizingBySide ? true : (angle || settingsAngle));
// const isTableResizing = resizedObjects.length > 1 && resizedObjects.filter(({ object }) => object.type === 'table').length > 0;
 
// if (isSideDot) keepAspectRatioRef.current = false;
// if (isTableResizing) keepAspectRatioRef.current = true;
 
// const params = calcResizeMagnetVector({
// currentBoxes,
// point: pointRef.current,
// initBoxes: initBoxesRef.current,
// cursorPos,
// keepAspectRatio: keepAspectRatioRef.current,
// magicPoints: magicPointsRef.current.magicPoints,
// angle,
// stopMagnet: stopMagnet || isResizingBlockedRef.current.state,
// isGroupResizingBySide,
// dir: dX,
// }, magicLinesTypeRef.current);
 
// const objectsToUpdate = [];
// const allObjectsTypeCheckResult = checkAreAllObjectsTextOrShapes(selectedObjectsRef.current);
 
// wereObjectsResizedRef.current = true;
 
// if (shouldBlockResizing(params, resizedObjects)) return;
 
// // params[0] is the shared selection box; params[1], params[2], ... are per-object
// const sharedSelectionBox = params[0];
// const initSharedBox = initBoxesRef.current?.[0];
// const resizePoint = pointRef.current;
// console.log('params', params, resizedObjects, initBoxesRef.current)
// resizedObjects.forEach((obj, i) => {
// handleUpdateObjects(
// obj,
// params[i + 1],
// e,
// objectsToUpdate,
// isGroupResizingBySide,
// allObjectsTypeCheckResult,
// sharedSelectionBox,
// initSharedBox,
// resizePoint,
// );
// });
 
// // Prevent from following manipulations like drawing magic lines, etc., if we exceeded some limitation during updating objects
// if (isResizingBlockedRef.current.state) return;
 
// const updatedSelectionBox = applyAdditionalTransformationAfterResize(
// isSideDot,
// isSideXDot,
// isGroupResizingBySide,
// allObjectsTypeCheckResult,
// selectedObjectsRef.current,
// reflectionRef.current,
// objectsToUpdate,
// resizedObjects,
// canvasRef.current,
// e,
// );
 
// if (updatedSelectionBox) {
// const boxViewPoints = transformBoxPointsToView(updatedSelectionBox, scaleMatrixRef.current);
 
// dispatch(updateCanvasContour({
// selection: { points: boxViewPoints, lines: { points: boxViewPoints }, thinLines: null },
// hover: null,
// mergeData: true,
// }));
// }
 
// if (['all', 'canvas'].includes(magicLinesTypeRef.current)) throttledHandleDrawMagicLines(selectionBoxRef.current);
// },
// done: handleResizeDone,
// });
 
// draggableDetachers.current.push(detachListeners);
// }, [handleResizeDone, handleUpdateObjects]);
 
// useEffect(handleResizeDone, [isPlaying, handleResizeDone]);
 
// useEffect(() => {
// initResize();
 
// return () => {
// draggableDetachers.current.forEach((detacher) => detacher());
 
// draggableDetachers.current = [];
// };
// }, [initResize]);
 
// useEffect(() => {
// document.addEventListener('canvas:selectionDotClicked', handleDotClicked);
 
// return () => {
// document.removeEventListener('canvas:selectionDotClicked', handleDotClicked);
// };
// }, [handleDotClicked]);
 
// useEffect(() => {
// if (isMobileOrTablet()) document.addEventListener('canvas:mobileScaleStart', handleResizeDone);
 
// return () => {
// document.removeEventListener('canvas:mobileScaleStart', handleResizeDone);
// };
// }, [handleResizeDone]);
 
// return null;
// });
 
// EditorCanvasResize.propTypes = {
// canvasRef: PropTypes.object,
// fetcherRef: PropTypes.object,
// overlayRef: PropTypes.object,
// magicLinesRef: PropTypes.object,
// resizeSubscribers: PropTypes.object,
// playerInstance: PropTypes.object.isRequired,
// };
 
// EditorCanvasResize.displayName = 'EditorCanvasResize';
// EditorCanvasResize.name = 'EditorCanvasResize';
 
// export default withEditor(EditorCanvasResize);
 
import React, { useCallback, useEffect, useMemo, useRef } from 'react';
import PropTypes from 'prop-types';
import { useDispatch } from 'react-redux';
import { cloneDeep, flatten, forIn } from 'lodash';
 
import withEditor from '../../../../HOCs/withEditor';
 
import {
selectCanvasContourSelectionBox,
selectFirstSelectedObjType,
selectMagicLinesType,
selectPickerObjectID,
selectPlayerIsPlaying,
selectPlayerZoom,
selectSelectedObjectIDs,
selectShowTextEditor,
} from '../../../../../store/selectors';
 
import { useCurrentValue, useStoreCurrentValue, useThrottle } from '../../../../hooks';
 
import {
applyAdditionalTransformationAfterResize,
calcResizeMagnetVector,
checkAreAllObjectsTextOrShapes,
draggableOnListeners,
fixVideoDataCrop,
getCursorPosition,
getGeomParams,
getGroupObjectParams,
getLineInfo,
getObjectGroupId,
getObjectMagicPoints,
getResizeObjectsUpdateResult,
getScaleMatrix,
getSelectionBox,
isMobileOrTablet,
removeCursorTrackTooltip,
s3Replace,
shouldBlockResizing,
transformBoxPointsToView,
} from '../../../../../utils';
 
import {
setSlideOrObjectId,
switchCanvasHoverDisabledState,
switchObjectsResizingState,
updateCanvasContour,
updateSlideObjectsThunk,
} from '../../../../../actions';
 
import {
FIXED_ASPECT_RATIO_OBJECTS,
OBJECT_SHAPE_TYPES,
OBJECTS_WITH_CROP,
OBJECTS_WITH_MOVE_CALLBACKS,
} from '../../../../../constants';
 
const PIVOT_INDEX_BY_POINT = {
x1y1: 2,
y1: 3,
x2y1: 3,
x2: 0,
x2y2: 0,
y2: 1,
x1y2: 1,
x1: 2,
};
const ACTIVE_INDEX_BY_POINT = {
x1y1: 0,
y1: 1,
x2y1: 1,
x2: 2,
x2y2: 2,
y2: 3,
x1y2: 3,
x1: 0,
};
 
/**
* Detects resize inversion (dragged corner passed the pivot) in world coordinates.
* Works for rotated boxes (e.g. group resize).
* @returns {{ inverseX: boolean, inverseY: boolean }}
*/
function getResizeInversion(initBox, currentBox, point) {
const pivotIndex = PIVOT_INDEX_BY_POINT[point];
const activeIndex = ACTIVE_INDEX_BY_POINT[point];
if (pivotIndex === undefined || activeIndex === undefined)
return { inverseX: false, inverseY: false };
 
const initPoints = initBox?.objectPoints || initBox?.boxPoints;
const currPoints = currentBox?.objectPoints || currentBox?.boxPoints;
if (!initPoints?.[pivotIndex] || !initPoints?.[activeIndex] || !currPoints?.[activeIndex]) {
return { inverseX: false, inverseY: false };
}
 
const pivotX = initPoints[pivotIndex][0];
const pivotY = initPoints[pivotIndex][1];
const initActiveX = initPoints[activeIndex][0];
const initActiveY = initPoints[activeIndex][1];
const currActiveX = currPoints[activeIndex][0];
const currActiveY = currPoints[activeIndex][1];
 
const initDx = initActiveX - pivotX;
const initDy = initActiveY - pivotY;
const currDx = currActiveX - pivotX;
const currDy = currActiveY - pivotY;
 
const inverseX = initDx !== 0 && currDx !== 0 && initDx > 0 !== currDx > 0;
const inverseY = initDy !== 0 && currDy !== 0 && initDy > 0 !== currDy > 0;
 
return { inverseX, inverseY };
}
 
const EditorCanvasResize = React.memo(props => {
const {
playerInstance,
canvasRef,
overlayRef,
fetcherRef,
magicLinesRef,
resizeSubscribers,
} = props;
 
const [zoom, zoomRef] = useStoreCurrentValue(selectPlayerZoom);
const [isPlaying, isPlayingRef] = useStoreCurrentValue(selectPlayerIsPlaying);
const [, isTextEditorActiveRef] = useStoreCurrentValue(selectShowTextEditor);
const [, magicLinesTypeRef] = useStoreCurrentValue(selectMagicLinesType);
const [, selectionBoxRef] = useStoreCurrentValue(selectCanvasContourSelectionBox);
const [, selectedObjectsIDsRef] = useStoreCurrentValue(selectSelectedObjectIDs);
const [, firstSelectedObjTypeRef] = useStoreCurrentValue(selectFirstSelectedObjType);
const [, pickerObjectIdRef] = useStoreCurrentValue(selectPickerObjectID);
 
const dispatch = useDispatch();
 
const scaleMatrix = useMemo(() => getScaleMatrix(zoom), [zoom]);
 
const scaleMatrixRef = useCurrentValue(scaleMatrix);
 
const fetcherDataRef = useRef(null);
const totalResizedObjectsRef = useRef(null);
const overlayBoundingBoxRef = useRef(null);
const pointRef = useRef(null);
const initSelectionBoxSizeRef = useRef(null);
const initSelectedObjectsSizeRef = useRef(null);
const initSelectedObjectsRef = useRef(null);
const selectedObjectsRef = useRef(null);
const allGroupChildsIdsRef = useRef([]);
const magicPointsRef = useRef([]);
const initBoxesRef = useRef([]);
const draggableDetachers = useRef([]);
const keepAspectRatioRef = useRef(false);
const wereObjectsResizedRef = useRef(false);
const isResizingBlockedRef = useRef({ state: false, cause: '' });
const precalculatedUpdatedObjectsRef = useRef({});
const reflectionRef = useRef({ isReflectX: false, isReflectY: false });
// Per-object curve points for multi-selection resize (keyed by object.id)
const updatedCurvePointsRef = useRef({});
 
const throttledHandleDrawMagicLines = useThrottle(
selectionBox => {
requestAnimationFrame(() => {
const objectMagicPoints = getObjectMagicPoints(selectionBox);
 
if (magicLinesRef.current) {
magicLinesRef.current.drawMagicLines(
objectMagicPoints,
magicPointsRef.current,
zoomRef.current
);
}
});
},
20,
{ leading: true }
);
 
const handleDotClicked = useCallback(e => {
if (!canvasRef.current || !fetcherRef.current || isPlayingRef.current) return;
 
const dot = e.detail?.dot;
 
if (!dot) return;
 
if (dot.classList.contains('selection-box-line-dot')) return;
 
if (
selectedObjectsIDsRef.current.length === 1 &&
(OBJECTS_WITH_CROP.includes(firstSelectedObjTypeRef.current) ||
firstSelectedObjTypeRef.current === 'table')
) {
if (dot.classList.contains('selection-box-side-dot')) return;
}
 
pointRef.current = `${dot.getAttribute('x-param') || ''}${dot.getAttribute('y-param') || ''}`;
 
fetcherDataRef.current = fetcherRef.current.getData();
 
const { allObjects } = fetcherDataRef.current;
 
let ids = selectedObjectsIDsRef.current;
let selectedObjects = ids.map(id => allObjects.find(o => o.id === id));
 
if (ids.length === 1 && selectedObjects[0].type !== 'group') {
// replace child with its group parent object
const groupId = getObjectGroupId(allObjects, ids[0]);
 
if (groupId) {
ids = [groupId];
selectedObjects = ids.map(id => allObjects.find(o => o.id === id));
}
}
 
const selectedGroups = selectedObjects.filter(obj => obj.type === 'group');
const allGroupChilds = flatten(
selectedGroups.map(go => allObjects.filter(obj => go.objects.includes(obj.id)))
);
const allGroupChildsIds = allGroupChilds.map(o => o.id);
const totalObjectsIds = [...selectedObjects.map(o => o.id), ...allGroupChildsIds];
 
allGroupChildsIdsRef.current = allGroupChildsIds;
totalResizedObjectsRef.current = fetcherRef.current.getSpecificDomElementsWithBoxes(
canvasRef,
totalObjectsIds
);
selectedObjectsRef.current = ids
.map(id => totalResizedObjectsRef.current.find(o => o.object.id === id))
.filter(Boolean);
}, []);
 
const handleObjectsMove = useCallback(
(params, data, object, textLayer, objData, initSharedBox, resizePoint) => {
if (object.type === 'text') {
if (textLayer) {
if (data?.style?.font_size) textLayer.style.fontSize = `${data.style.font_size}px`;
 
if (['x1', 'x2'].includes(pointRef.current)) textLayer.style.whiteSpace = 'normal';
}
}
 
let updatedCurvePoints = null;
let updatedReflection = null;
 
if (object.type === 'line' && object.style?.points && initSelectedObjectsRef?.current) {
const point = resizePoint ?? pointRef.current;
const currentSharedBox = selectionBoxRef.current;
 
// inverseX / inverseY: true when dragged corner passed pivot (works for rotated group box)
const { inverseX, inverseY } = getResizeInversion(
initSharedBox ?? initBoxesRef.current?.[0],
currentSharedBox,
point
);
 
updatedReflection = { reflect_x: inverseX, reflect_y: inverseY };
 
const initObj = object;
 
const k = data.width / initObj.width;
 
const lineInfo = getLineInfo(initObj);
 
const v = {
x: initObj.style.points[0][0] - lineInfo.center.x,
y: initObj.style.points[0][1] - lineInfo.center.y,
};
const l = Math.hypot(v.x, v.y);
const dir = { x: v.x / l, y: v.y / l };
const newL = l * k;
 
const newPoint = { x: params.cx + dir.x * newL, y: params.cy + dir.y * newL };
 
updatedCurvePoints = [[newPoint.x, newPoint.y]];
}
 
if (!OBJECTS_WITH_MOVE_CALLBACKS.includes(object.type)) return;
 
const updatedObject = fixVideoDataCrop({ ...object, ...data });
 
if (updatedCurvePoints) {
updatedObject.x = params.left;
updatedObject.y = params.top;
updatedObject.style = { ...updatedObject.style, points: updatedCurvePoints };
 
updatedCurvePointsRef.current[object.id] = {
height: params.height,
width: params.width,
x: params.left,
y: params.top,
points: updatedCurvePoints,
};
}
 
if (updatedReflection) {
if (object.reflect_x === undefined) {
if (updatedReflection.reflect_x) updatedObject.reflect_x = true;
} else {
if (updatedReflection.reflect_x) updatedObject.reflect_x = !object.reflect_x; // eslint-disable-line
}
if (object.reflect_y === undefined) {
if (updatedReflection.reflect_y) updatedObject.reflect_y = true;
} else {
if (updatedReflection.reflect_y) updatedObject.reflect_y = !object.reflect_y; // eslint-disable-line
}
 
if (updatedCurvePointsRef.current[object.id]) {
updatedCurvePointsRef.current[object.id].reflect_x = updatedObject.reflect_x;
updatedCurvePointsRef.current[object.id].reflect_y = updatedObject.reflect_y;
}
 
if (objData.dom) {
const transformLayer = objData.dom.querySelector(
'.__supa_player__slide-object-transform-layer'
);
 
if (transformLayer) {
transformLayer.style.transform = transformLayer.style.transform
.replace(
/scaleX\([^)]*\)/,
`scaleX(${updatedCurvePointsRef.current[object.id].reflect_x ? -1 : 1})`
)
.replace(
/scaleY\([^)]*\)/,
`scaleY(${updatedCurvePointsRef.current[object.id].reflect_y ? -1 : 1})`
);
}
}
}
 
playerInstance.updateObjectHTML(JSON.parse(s3Replace(JSON.stringify(updatedObject))));
},
[playerInstance]
);
 
const handleUpdateObjects = useCallback(
(
objData,
params,
e,
resultUpdatedObjects,
isGroupResizing,
allObjectsTypeCheckResult,
initSharedBox,
resizePoint
) => {
const isSideDot = ['x1', 'x2', 'y1', 'y2'].includes(pointRef.current);
 
const updateSelectionBox = box => {
if (!box || (isTextEditorActiveRef.current && isSideDot)) return;
 
const boxViewPoints = transformBoxPointsToView(box, scaleMatrixRef.current);
 
dispatch(
updateCanvasContour({
selection: { points: boxViewPoints, lines: { points: boxViewPoints }, thinLines: null },
hover: null,
mergeData: true,
})
);
};
 
const resizeResult = getResizeObjectsUpdateResult(
objData,
params,
e,
resultUpdatedObjects,
isGroupResizing,
allObjectsTypeCheckResult,
selectionBoxRef.current,
fetcherDataRef.current.allObjects,
pointRef.current,
initSelectionBoxSizeRef.current,
initSelectedObjectsSizeRef.current,
initBoxesRef.current,
selectedObjectsIDsRef.current,
isTextEditorActiveRef.current,
reflectionRef.current,
precalculatedUpdatedObjectsRef.current,
keepAspectRatioRef.current,
isResizingBlockedRef.current,
totalResizedObjectsRef.current
);
 
if (!resizeResult) return false;
 
const { result, textLayer, correctSelectionBox } = resizeResult;
 
updateSelectionBox(correctSelectionBox);
 
handleObjectsMove(
params,
result,
objData.object,
textLayer,
objData,
initSharedBox,
resizePoint
);
 
resizeSubscribers.current?.forEach(clbk =>
clbk('move', result, updateSelectionBox, pointRef.current)
);
 
return true;
},
[handleObjectsMove]
);
 
const handleUpdateData = useCallback((updatedObjects, groupObjects) => {
let objects = [];
let updatedData = [];
 
const { slides } = fetcherDataRef.current;
 
forIn(updatedObjects, (value, path) => {
const [a, b] = path.split('_');
 
if (!slides[a].objects[b]) return;
 
if (slides[a].objects[b].id === pickerObjectIdRef.current) {
dispatch(setSlideOrObjectId({ initialObjectSize: null }));
}
 
objects.push(slides[a].objects[b]);
updatedData.push(value);
});
 
dispatch(updateSlideObjectsThunk(objects, updatedData));
 
objects = [];
updatedData = [];
 
// Correct group object size after childs has been updated
// Use setTimeout in case we have curved text which takes time to render
setTimeout(() => {
Object.keys(groupObjects).forEach(key => {
const [a, b] = key.split('_');
 
const audioObjects = slides[a].objects[b].objects
.map(id => slides[a].objects.find(o => o.id === id))
.filter(Boolean)
.filter(obj => obj.type === 'audio');
const groupObjectParams = getGroupObjectParams([...groupObjects[key], ...audioObjects]);
 
if (groupObjectParams?.data) {
objects.push(slides[a].objects[b]);
updatedData.push(groupObjectParams.data);
}
 
if (groupObjectParams?.childsData) {
objects.push(...groupObjects[key]);
updatedData.push(...groupObjectParams.childsData);
}
});
 
dispatch(updateSlideObjectsThunk(objects, updatedData));
});
}, []);
 
const handleResizeDone = useCallback(
e => {
removeCursorTrackTooltip();
 
// Store group object path and it's childs with updated data
// Will be used to calculate correct group objects sizes with round values
const groupObjects = {};
const updatedObjects = {};
 
if (wereObjectsResizedRef.current || e?.type === 'canvas:mobileScaleStart') {
dispatch(switchObjectsResizingState(false));
dispatch(switchCanvasHoverDisabledState(false));
 
if (totalResizedObjectsRef.current && fetcherDataRef.current) {
const { allObjects } = fetcherDataRef.current;
 
totalResizedObjectsRef.current.forEach(({ dom: item, object }) => {
const slideIndex = item.getAttribute('slide-index');
const objectIndex = item.getAttribute('object-index');
 
const { left, top, width, height } = getComputedStyle(item);
 
const result = {};
 
const selectionBoxPoints =
selectionBoxRef.current?.lineBoxWithCurvePoints || selectionBoxRef.current?.boxPoints;
const geomParams = getGeomParams(selectionBoxPoints);
 
const isSideHorizontalDot = ['x1', 'x2'].includes(pointRef.current);
 
const precalculatedResult =
precalculatedUpdatedObjectsRef.current[`${slideIndex}_${objectIndex}`];
 
if (object.type === 'text' && !isSideHorizontalDot) {
if (precalculatedResult) Object.assign(result, precalculatedResult);
}
 
if (object.type === 'chart' && !isSideHorizontalDot) {
const diffW = initSelectionBoxSizeRef.current.width / geomParams.width;
 
const newLegendFontSize = object.style.legend.font_size / diffW;
const newLabelsFontSize = object.style.labels.font_size / diffW;
const newValuesFontSize = object.style.values.font_size / diffW;
const newValuesDistance = (object.style.values.distance || 10) / diffW;
 
result.style = {
legend: { font_size: Math.min(Math.max(newLegendFontSize, 1), 100) },
labels: { font_size: Math.min(Math.max(newLabelsFontSize, 1), 100) },
values: {
font_size: Math.min(Math.max(newValuesFontSize, 1), 100),
...(['pie', 'doughnut'].includes(object.chart_type) && {
distance: Math.min(Math.max(newValuesDistance, 1), 100),
}),
},
};
}
 
if (object.type === 'table' && !isSideHorizontalDot) {
if (precalculatedResult) Object.assign(result, precalculatedResult);
}
 
const groupId = getObjectGroupId(allObjects, object.id);
 
let groupKey = null;
 
// group objects values will be rounded after resizing will be finished
const keepDecimal = groupId || (object.type === 'group' && object.rotate);
 
let x = keepDecimal ? parseFloat(left) : Math.round(parseFloat(left));
let y = keepDecimal ? parseFloat(top) : Math.round(parseFloat(top));
 
const widthRes = keepDecimal ? parseFloat(width) : Math.round(parseFloat(width));
const heightRes = keepDecimal ? parseFloat(height) : Math.round(parseFloat(height));
 
if (groupId) {
const groupDom = item.closest('div[object-type="group"]');
const groupSlideIndex = groupDom.getAttribute('slide-index');
const groupObjectIndex = groupDom.getAttribute('object-index');
const groupDomStyles = getComputedStyle(groupDom);
 
groupKey = `${groupSlideIndex}_${groupObjectIndex}`;
 
x += parseFloat(groupDomStyles.left);
y += parseFloat(groupDomStyles.top);
}
 
result.x = x;
result.y = y;
result.width = widthRes;
result.height = object.type === 'line' ? 1 : heightRes;
result.width_auto = false;
result.reflect_x = reflectionRef.current.isReflectX
? !object.reflect_x
: object.reflect_x;
result.reflect_y = reflectionRef.current.isReflectY
? !object.reflect_y
: object.reflect_y;
 
if (object.type === 'text')
result.style = { ...(result.style ?? {}), word_break: true };
 
if (object.type === 'line' && object.style?.points) {
result.height = 1;
 
const curveData = updatedCurvePointsRef.current[object.id];
 
if (curveData) {
// Use final curve geometry calculated during resize (correct for rotated groups).
result.width = curveData.width;
result.x = curveData.x;
result.y = curveData.y;
result.style = { points: curveData.points };
 
if (curveData.reflect_x !== undefined) result.reflect_x = curveData.reflect_x;
if (curveData.reflect_y !== undefined) result.reflect_y = curveData.reflect_y;
} else if (groupId && initBoxesRef.current?.[0]) {
// Fallback: line in group when we don't have curve data – compute from group scale.
// Use group's own init box, not the overall selection box (which may include other selected objects).
const resizedObjects = totalResizedObjectsRef.current;
const groupIndex = resizedObjects?.findIndex(o => o.object.id === groupId);
const initGroupBox = groupIndex >= 0 ? initBoxesRef.current[groupIndex + 1] : null;
const initGroup = initGroupBox?.boxPoints
? getGeomParams(initGroupBox.boxPoints)
: null;
 
if (!initGroup) {
result.width = object.width;
result.style = { points: object.style.points };
} else {
const groupDom = item.closest('div[object-type="group"]');
const groupDomStyles = getComputedStyle(groupDom);
 
const scaleX = parseFloat(groupDomStyles.width) / initGroup.width;
const scaleY = parseFloat(groupDomStyles.height) / initGroup.height;
 
const groupLeft = parseFloat(groupDomStyles.left);
const groupTop = parseFloat(groupDomStyles.top);
 
result.x = Math.round(groupLeft + (object.x - initGroup.left) * scaleX);
result.y = Math.round(groupTop + (object.y - initGroup.top) * scaleY);
result.width = Math.round(object.width * scaleX);
 
const pt = object.style.points[0];
 
result.style = {
points: [
[
Math.round(groupLeft + (pt[0] - initGroup.left) * scaleX),
Math.round(groupTop + (pt[1] - initGroup.top) * scaleY),
],
],
};
}
}
}
 
if (groupKey) {
const updatedObject = { ...object, ...result };
 
if (result.style) updatedObject.style = { ...object.style, ...result.style };
 
groupObjects[groupKey] = groupObjects[groupKey]
? [...groupObjects[groupKey], updatedObject]
: [updatedObject];
}
 
updatedObjects[`${slideIndex}_${objectIndex}`] = result;
 
setTimeout(() => {
resizeSubscribers.current?.forEach(clbk =>
clbk('done', result, null, pointRef.current)
);
});
});
}
}
 
if (wereObjectsResizedRef.current && fetcherDataRef.current)
handleUpdateData(updatedObjects, groupObjects);
 
totalResizedObjectsRef.current = null;
wereObjectsResizedRef.current = false;
fetcherDataRef.current = null;
isResizingBlockedRef.current = { state: false, cause: '' };
precalculatedUpdatedObjectsRef.current = {};
reflectionRef.current = { isReflectX: false, isReflectY: false };
initSelectedObjectsRef.current = null;
updatedCurvePointsRef.current = {};
 
magicLinesRef.current.clearMagicLines();
},
[handleUpdateData]
);
 
const initResize = useCallback(
() => {
if (!canvasRef.current || !overlayRef.current) return;
 
const detachListeners = draggableOnListeners(canvasRef.current, {
cancelStopPropagation: true,
start: () => {
if (!selectionBoxRef.current) return;
if (!totalResizedObjectsRef.current || !magicLinesRef.current || isPlayingRef.current)
return;
if (!totalResizedObjectsRef.current[0]) return;
 
const resizedObjects = totalResizedObjectsRef.current;
const firstObjType = firstSelectedObjTypeRef.current;
 
resizeSubscribers.current?.forEach(clbk => clbk('start'));
 
const isSingleSelection = selectedObjectsIDsRef.current.length === 1;
const isFirstObjText = firstObjType === 'text';
const isFirstObjHasWidthAuto = resizedObjects[0].object.width_auto;
const isSideHorizontalDot = ['x1', 'x2'].includes(pointRef.current);
const isAnyHasFixedAspectRatio = resizedObjects.some(o =>
FIXED_ASPECT_RATIO_OBJECTS.includes(o.object.type)
);
const isAnyHasRotation = resizedObjects.some(
({ box, object }) => !!(box.angle || object.rotate)
);
const isOnlyShapes = resizedObjects.every(o =>
OBJECT_SHAPE_TYPES.includes(o.object.type)
);
 
initBoxesRef.current = [
cloneDeep(selectionBoxRef.current),
...cloneDeep(resizedObjects.map(o => o.box)),
];
 
const initBoxPoints =
initBoxesRef.current[0]?.lineBoxWithCurvePoints || initBoxesRef.current[0]?.boxPoints;
 
initSelectionBoxSizeRef.current = getGeomParams(initBoxPoints);
overlayBoundingBoxRef.current = overlayRef.current.getBoundingClientRect();
magicPointsRef.current = magicLinesRef.current.getMagicPoints(
canvasRef,
fetcherDataRef.current.allObjects
);
keepAspectRatioRef.current =
isAnyHasFixedAspectRatio || (!isSingleSelection && isAnyHasRotation);
 
// Allow shapes to ignore aspect ratio
if (isOnlyShapes) keepAspectRatioRef.current = false;
 
// reset auto width for single text
if (
isSingleSelection &&
isFirstObjText &&
isFirstObjHasWidthAuto &&
isSideHorizontalDot
) {
resizedObjects[0].object.width = initSelectionBoxSizeRef.current.width;
resizedObjects[0].object.width_auto = false;
 
resizedObjects[0].dom.style.width = `${initSelectionBoxSizeRef.current.width}px`;
}
 
initSelectedObjectsSizeRef.current = resizedObjects.map(obj => {
const childSelectionBox = getSelectionBox(obj.dom, obj.object, null, null, true);
 
return { id: obj.object.id, params: getGeomParams(childSelectionBox.boxPoints) };
});
 
initSelectedObjectsRef.current = resizedObjects.map(obj => obj.object);
},
move: ({ dX }, e) => {
if (!selectionBoxRef.current) return;
if (!totalResizedObjectsRef.current || isPlayingRef.current) return;
if (!totalResizedObjectsRef.current[0]) return;
 
if (!wereObjectsResizedRef.current) {
dispatch(switchObjectsResizingState(true));
dispatch(switchCanvasHoverDisabledState(true));
}
 
const cursorPos = getCursorPosition(e, overlayBoundingBoxRef.current, zoomRef.current);
 
if (e.shiftKey) keepAspectRatioRef.current = true;
 
const resizedObjects = totalResizedObjectsRef.current;
const groupChildsIds = allGroupChildsIdsRef.current;
const selectedObjectsLength = selectedObjectsIDsRef.current.length;
 
const currentBoxes = [
selectionBoxRef.current,
...resizedObjects.map(({ box, object }) => ({
...box,
isChild: groupChildsIds.includes(object.id),
})),
];
 
const isSideDot = ['x1', 'x2', 'y1', 'y2'].includes(pointRef.current);
const isSideXDot = ['x1', 'x2'].includes(pointRef.current);
const settingsAngle = selectedObjectsLength === 1 && resizedObjects[0].object.rotate;
const angle =
selectedObjectsLength === 1 &&
Math.round(resizedObjects[0].box.angle * (180 / Math.PI));
const isGroupResizingBySide =
selectedObjectsLength === 1 && resizedObjects[0].object.type === 'group' && isSideXDot;
const stopMagnet = !!(isGroupResizingBySide ? true : angle || settingsAngle);
const isTableResizing =
resizedObjects.length > 1 &&
resizedObjects.filter(({ object }) => object.type === 'table').length > 0;
 
if (isSideDot) keepAspectRatioRef.current = false;
if (isTableResizing) keepAspectRatioRef.current = true;
 
const params = calcResizeMagnetVector(
{
currentBoxes,
point: pointRef.current,
initBoxes: initBoxesRef.current,
cursorPos,
keepAspectRatio: keepAspectRatioRef.current,
magicPoints: magicPointsRef.current.magicPoints,
angle,
stopMagnet: stopMagnet || isResizingBlockedRef.current.state,
isGroupResizingBySide,
dir: dX,
},
magicLinesTypeRef.current
);
 
const objectsToUpdate = [];
const allObjectsTypeCheckResult = checkAreAllObjectsTextOrShapes(
selectedObjectsRef.current
);
 
wereObjectsResizedRef.current = true;
 
if (shouldBlockResizing(params, resizedObjects)) return;
 
// params[0] is the shared selection box; params[1], params[2], ... are per-object
const initSharedBox = initBoxesRef.current?.[0];
const resizePoint = pointRef.current;
 
resizedObjects.forEach((obj, i) => {
handleUpdateObjects(
obj,
params[i + 1],
e,
objectsToUpdate,
isGroupResizingBySide,
allObjectsTypeCheckResult,
initSharedBox,
resizePoint
);
});
 
// Prevent from following manipulations like drawing magic lines, etc., if we exceeded some limitation during updating objects
if (isResizingBlockedRef.current.state) return;
 
const updatedSelectionBox = applyAdditionalTransformationAfterResize(
isSideDot,
isSideXDot,
isGroupResizingBySide,
allObjectsTypeCheckResult,
selectedObjectsRef.current,
reflectionRef.current,
objectsToUpdate,
resizedObjects,
canvasRef.current,
e
);
 
if (updatedSelectionBox) {
const boxViewPoints = transformBoxPointsToView(
updatedSelectionBox,
scaleMatrixRef.current
);
 
dispatch(
updateCanvasContour({
selection: {
points: boxViewPoints,
lines: { points: boxViewPoints },
thinLines: null,
},
hover: null,
mergeData: true,
})
);
}
 
if (['all', 'canvas'].includes(magicLinesTypeRef.current))
throttledHandleDrawMagicLines(selectionBoxRef.current);
},
done: handleResizeDone,
});
 
draggableDetachers.current.push(detachListeners);
},
[handleResizeDone, handleUpdateObjects]
);
 
useEffect(handleResizeDone, [isPlaying, handleResizeDone]);
 
useEffect(
() => {
initResize();
 
return () => {
draggableDetachers.current.forEach(detacher => detacher());
 
draggableDetachers.current = [];
};
},
[initResize]
);
 
useEffect(
() => {
document.addEventListener('canvas:selectionDotClicked', handleDotClicked);
 
return () => {
document.removeEventListener('canvas:selectionDotClicked', handleDotClicked);
};
},
[handleDotClicked]
);
 
useEffect(
() => {
if (isMobileOrTablet())
document.addEventListener('canvas:mobileScaleStart', handleResizeDone);
 
return () => {
document.removeEventListener('canvas:mobileScaleStart', handleResizeDone);
};
},
[handleResizeDone]
);
 
return null;
});
 
EditorCanvasResize.propTypes = {
canvasRef: PropTypes.object,
fetcherRef: PropTypes.object,
overlayRef: PropTypes.object,
magicLinesRef: PropTypes.object,
resizeSubscribers: PropTypes.object,
playerInstance: PropTypes.object.isRequired,
};
 
EditorCanvasResize.displayName = 'EditorCanvasResize';
EditorCanvasResize.name = 'EditorCanvasResize';
 
export default withEditor(EditorCanvasResize);
 
// import React, { useCallback, useEffect, useMemo, useRef } from 'react';
// import PropTypes from 'prop-types';
// import { useDispatch } from 'react-redux';
// import { cloneDeep, flatten, forIn } from 'lodash';
 
// import withEditor from '../../../../HOCs/withEditor';
 
// import {
// selectCanvasContourSelectionBox,
// selectFirstSelectedObjType,
// selectMagicLinesType,
// selectPickerObjectID,
// selectPlayerIsPlaying,
// selectPlayerZoom,
// selectSelectedObjectIDs,
// selectShowTextEditor,
// } from '../../../../../store/selectors';
 
// import { useCurrentValue, useStoreCurrentValue, useThrottle } from '../../../../hooks';
 
// import {
// applyAdditionalTransformationAfterResize,
// calcResizeMagnetVector,
// checkAreAllObjectsTextOrShapes,
// draggableOnListeners,
// fixVideoDataCrop,
// getCursorPosition,
// getGeomParams,
// getGroupObjectParams,
// getLineInfo,
// getObjectGroupId,
// getObjectMagicPoints,
// getResizeObjectsUpdateResult,
// getScaleMatrix,
// getSelectionBox,
// isMobileOrTablet,
// removeCursorTrackTooltip,
// s3Replace,
// shouldBlockResizing,
// transformBoxPointsToView,
// } from '../../../../../utils';
 
// import {
// setSlideOrObjectId,
// switchCanvasHoverDisabledState,
// switchObjectsResizingState,
// updateCanvasContour,
// updateSlideObjectsThunk,
// } from '../../../../../actions';
 
// import {
// FIXED_ASPECT_RATIO_OBJECTS,
// OBJECT_SHAPE_TYPES,
// OBJECTS_WITH_CROP,
// OBJECTS_WITH_MOVE_CALLBACKS,
// } from '../../../../../constants';
 
// const EditorCanvasResize = React.memo((props) => {
// const {
// playerInstance, canvasRef, overlayRef, fetcherRef, magicLinesRef, resizeSubscribers,
// } = props;
 
// const [zoom, zoomRef] = useStoreCurrentValue(selectPlayerZoom);
// const [isPlaying, isPlayingRef] = useStoreCurrentValue(selectPlayerIsPlaying);
// const [, isTextEditorActiveRef] = useStoreCurrentValue(selectShowTextEditor);
// const [, magicLinesTypeRef] = useStoreCurrentValue(selectMagicLinesType);
// const [, selectionBoxRef] = useStoreCurrentValue(selectCanvasContourSelectionBox);
// const [, selectedObjectsIDsRef] = useStoreCurrentValue(selectSelectedObjectIDs);
// const [, firstSelectedObjTypeRef] = useStoreCurrentValue(selectFirstSelectedObjType);
// const [, pickerObjectIdRef] = useStoreCurrentValue(selectPickerObjectID);
 
// const dispatch = useDispatch();
 
// const scaleMatrix = useMemo(() => getScaleMatrix(zoom), [zoom]);
 
// const scaleMatrixRef = useCurrentValue(scaleMatrix);
 
// const fetcherDataRef = useRef(null);
// const totalResizedObjectsRef = useRef(null);
// const overlayBoundingBoxRef = useRef(null);
// const pointRef = useRef(null);
// const initSelectionBoxSizeRef = useRef(null);
// const initSelectedObjectsSizeRef = useRef(null);
// const initSelectedObjectsRef = useRef(null);
// const selectedObjectsRef = useRef(null);
// const allGroupChildsIdsRef = useRef([]);
// const magicPointsRef = useRef([]);
// const initBoxesRef = useRef([]);
// const draggableDetachers = useRef([]);
// const keepAspectRatioRef = useRef(false);
// const wereObjectsResizedRef = useRef(false);
// const isResizingBlockedRef = useRef({ state: false, cause: '' });
// const precalculatedUpdatedObjectsRef = useRef({});
// const reflectionRef = useRef({ isReflectX: false, isReflectY: false });
// // Per-object curve points for multi-selection resize (keyed by object.id)
// const updatedCurvePointsRef = useRef({});
 
// const throttledHandleDrawMagicLines = useThrottle((selectionBox) => {
// requestAnimationFrame(() => {
// const objectMagicPoints = getObjectMagicPoints(selectionBox);
 
// if (magicLinesRef.current) {
// magicLinesRef.current.drawMagicLines(objectMagicPoints, magicPointsRef.current, zoomRef.current);
// }
// });
// }, 20, { leading: true });
 
// const handleDotClicked = useCallback((e) => {
// if (!canvasRef.current || !fetcherRef.current || isPlayingRef.current) return;
 
// const dot = e.detail?.dot;
 
// if (!dot) return;
 
// if (dot.classList.contains('selection-box-line-dot')) return;
 
// if (selectedObjectsIDsRef.current.length === 1 && (
// OBJECTS_WITH_CROP.includes(firstSelectedObjTypeRef.current) || firstSelectedObjTypeRef.current === 'table'
// )) {
// if (dot.classList.contains('selection-box-side-dot')) return;
// }
 
// pointRef.current = `${dot.getAttribute('x-param') || ''}${dot.getAttribute('y-param') || ''}`;
 
// fetcherDataRef.current = fetcherRef.current.getData();
 
// const { allObjects } = fetcherDataRef.current;
 
// let ids = selectedObjectsIDsRef.current;
// let selectedObjects = ids.map((id) => allObjects.find((o) => o.id === id));
 
// if (ids.length === 1 && selectedObjects[0].type !== 'group') {
// // replace child with its group parent object
// const groupId = getObjectGroupId(allObjects, ids[0]);
 
// if (groupId) {
// ids = [groupId];
// selectedObjects = ids.map((id) => allObjects.find((o) => o.id === id));
// }
// }
 
// const selectedGroups = selectedObjects.filter((obj) => obj.type === 'group');
// const allGroupChilds = flatten(selectedGroups.map((go) => allObjects.filter((obj) => go.objects.includes(obj.id))));
// const allGroupChildsIds = allGroupChilds.map((o) => o.id);
// const totalObjectsIds = [...selectedObjects.map((o) => o.id), ...allGroupChildsIds];
 
// allGroupChildsIdsRef.current = allGroupChildsIds;
// totalResizedObjectsRef.current = fetcherRef.current.getSpecificDomElementsWithBoxes(canvasRef, totalObjectsIds);
// selectedObjectsRef.current = ids
// .map((id) => totalResizedObjectsRef.current.find((o) => o.object.id === id))
// .filter(Boolean);
// }, []);
 
// const handleObjectsMove = useCallback((params, data, object, textLayer) => {
// if (object.type === 'text') {
// if (textLayer) {
// if (data?.style?.font_size) textLayer.style.fontSize = `${data.style.font_size}px`;
 
// if (['x1', 'x2'].includes(pointRef.current)) textLayer.style.whiteSpace = 'normal';
// }
// }
 
// let updatedCurvePoints = null;
 
// if (object.type === 'line' && object.style?.points && initSelectedObjectsRef?.current) {
// const initObj = object;
 
// const k = data.width / initObj.width;
 
// const lineInfo = getLineInfo(initObj);
 
// const v = {
// x: initObj.style.points[0][0] - lineInfo.center.x,
// y: initObj.style.points[0][1] - lineInfo.center.y,
// };
// const l = Math.hypot(v.x, v.y);
// const dir = { x: v.x / l, y: v.y / l };
// const newL = l * k;
 
// const newPoint = { x: params.cx + dir.x * newL, y: params.cy + dir.y * newL };
 
// updatedCurvePoints = [[newPoint.x, newPoint.y]];
// }
 
// if (!OBJECTS_WITH_MOVE_CALLBACKS.includes(object.type)) return;
 
// const updatedObject = fixVideoDataCrop({ ...object, ...data });
 
// if (updatedCurvePoints) {
// updatedObject.x = params.left;
// updatedObject.y = params.top;
// updatedObject.style = { ...updatedObject.style, points: updatedCurvePoints };
 
// updatedCurvePointsRef.current[object.id] = {
// height: params.height,
// width: params.width,
// x: params.left,
// y: params.top,
// points: updatedCurvePoints,
// };
// }
 
// playerInstance.updateObjectHTML(JSON.parse(s3Replace(JSON.stringify(updatedObject))));
// }, [playerInstance]);
 
// const handleUpdateObjects = useCallback((
// objData, params, e, resultUpdatedObjects, isGroupResizing, allObjectsTypeCheckResult,
// ) => {
// const isSideDot = ['x1', 'x2', 'y1', 'y2'].includes(pointRef.current);
 
// const updateSelectionBox = (box) => {
// if (!box || (isTextEditorActiveRef.current && isSideDot)) return;
 
// const boxViewPoints = transformBoxPointsToView(box, scaleMatrixRef.current);
 
// dispatch(updateCanvasContour({
// selection: { points: boxViewPoints, lines: { points: boxViewPoints }, thinLines: null },
// hover: null,
// mergeData: true,
// }));
// };
 
// const resizeResult = getResizeObjectsUpdateResult(
// objData,
// params,
// e,
// resultUpdatedObjects,
// isGroupResizing,
// allObjectsTypeCheckResult,
// selectionBoxRef.current,
// fetcherDataRef.current.allObjects,
// pointRef.current,
// initSelectionBoxSizeRef.current,
// initSelectedObjectsSizeRef.current,
// initBoxesRef.current,
// selectedObjectsIDsRef.current,
// isTextEditorActiveRef.current,
// reflectionRef.current,
// precalculatedUpdatedObjectsRef.current,
// keepAspectRatioRef.current,
// isResizingBlockedRef.current,
// totalResizedObjectsRef.current,
// );
 
// if (!resizeResult) return false;
 
// const { result, textLayer, correctSelectionBox } = resizeResult;
 
// updateSelectionBox(correctSelectionBox);
 
// handleObjectsMove(params, result, objData.object, textLayer);
 
// resizeSubscribers.current?.forEach((clbk) => clbk('move', result, updateSelectionBox, pointRef.current));
 
// return true;
// }, [handleObjectsMove]);
 
// const handleUpdateData = useCallback((updatedObjects, groupObjects) => {
// let objects = [];
// let updatedData = [];
 
// const { slides } = fetcherDataRef.current;
 
// forIn(updatedObjects, (value, path) => {
// const [a, b] = path.split('_');
 
// if (!slides[a].objects[b]) return;
 
// if (slides[a].objects[b].id === pickerObjectIdRef.current) {
// dispatch(setSlideOrObjectId({ initialObjectSize: null }));
// }
 
// objects.push(slides[a].objects[b]);
// updatedData.push(value);
// });
 
// dispatch(updateSlideObjectsThunk(objects, updatedData));
 
// objects = [];
// updatedData = [];
 
// // Correct group object size after childs has been updated
// // Use setTimeout in case we have curved text which takes time to render
// setTimeout(() => {
// Object.keys(groupObjects).forEach((key) => {
// const [a, b] = key.split('_');
 
// const audioObjects = slides[a].objects[b].objects
// .map((id) => slides[a].objects.find((o) => o.id === id))
// .filter(Boolean)
// .filter((obj) => obj.type === 'audio');
// const groupObjectParams = getGroupObjectParams([...groupObjects[key], ...audioObjects]);
 
// if (groupObjectParams?.data) {
// objects.push(slides[a].objects[b]);
// updatedData.push(groupObjectParams.data);
// }
 
// if (groupObjectParams?.childsData) {
// objects.push(...groupObjects[key]);
// updatedData.push(...groupObjectParams.childsData);
// }
// });
 
// dispatch(updateSlideObjectsThunk(objects, updatedData));
// });
// }, []);
 
// const handleResizeDone = useCallback((e) => {
// removeCursorTrackTooltip();
 
// // Store group object path and it's childs with updated data
// // Will be used to calculate correct group objects sizes with round values
// const groupObjects = {};
// const updatedObjects = {};
 
// if (wereObjectsResizedRef.current || e?.type === 'canvas:mobileScaleStart') {
// dispatch(switchObjectsResizingState(false));
// dispatch(switchCanvasHoverDisabledState(false));
 
// if (totalResizedObjectsRef.current && fetcherDataRef.current) {
// const { allObjects } = fetcherDataRef.current;
 
// totalResizedObjectsRef.current.forEach(({ dom: item, object }) => {
// const slideIndex = item.getAttribute('slide-index');
// const objectIndex = item.getAttribute('object-index');
 
// const { left, top, width, height } = getComputedStyle(item);
 
// const result = {};
 
// const selectionBoxPoints = selectionBoxRef.current?.lineBoxWithCurvePoints
// || selectionBoxRef.current?.boxPoints;
// const geomParams = getGeomParams(selectionBoxPoints);
 
// const isSideHorizontalDot = ['x1', 'x2'].includes(pointRef.current);
 
// const precalculatedResult = precalculatedUpdatedObjectsRef.current[`${slideIndex}_${objectIndex}`];
 
// if (object.type === 'text' && !isSideHorizontalDot) {
// if (precalculatedResult) Object.assign(result, precalculatedResult);
// }
 
// if (object.type === 'chart' && !isSideHorizontalDot) {
// const diffW = initSelectionBoxSizeRef.current.width / geomParams.width;
 
// const newLegendFontSize = object.style.legend.font_size / diffW;
// const newLabelsFontSize = object.style.labels.font_size / diffW;
// const newValuesFontSize = object.style.values.font_size / diffW;
// const newValuesDistance = (object.style.values.distance || 10) / diffW;
 
// result.style = {
// legend: { font_size: Math.min(Math.max(newLegendFontSize, 1), 100) },
// labels: { font_size: Math.min(Math.max(newLabelsFontSize, 1), 100) },
// values: {
// font_size: Math.min(Math.max(newValuesFontSize, 1), 100),
// ...['pie', 'doughnut'].includes(object.chart_type) && { distance: Math.min(Math.max(newValuesDistance, 1), 100) },
// },
// };
// }
 
// if (object.type === 'table' && !isSideHorizontalDot) {
// if (precalculatedResult) Object.assign(result, precalculatedResult);
// }
 
// const groupId = getObjectGroupId(allObjects, object.id);
 
// let groupKey = null;
 
// // group objects values will be rounded after resizing will be finished
// const keepDecimal = groupId || (object.type === 'group' && object.rotate);
 
// let x = keepDecimal ? parseFloat(left) : Math.round(parseFloat(left));
// let y = keepDecimal ? parseFloat(top) : Math.round(parseFloat(top));
 
// const widthRes = keepDecimal ? parseFloat(width) : Math.round(parseFloat(width));
// const heightRes = keepDecimal ? parseFloat(height) : Math.round(parseFloat(height));
 
// if (groupId) {
// const groupDom = item.closest('div[object-type="group"]');
// const groupSlideIndex = groupDom.getAttribute('slide-index');
// const groupObjectIndex = groupDom.getAttribute('object-index');
// const groupDomStyles = getComputedStyle(groupDom);
 
// groupKey = `${groupSlideIndex}_${groupObjectIndex}`;
 
// x += parseFloat(groupDomStyles.left);
// y += parseFloat(groupDomStyles.top);
// }
 
// result.x = x;
// result.y = y;
// result.width = widthRes;
// result.height = object.type === 'line' ? 1 : heightRes;
// result.width_auto = false;
// result.reflect_x = reflectionRef.current.isReflectX ? !object.reflect_x : object.reflect_x;
// result.reflect_y = reflectionRef.current.isReflectY ? !object.reflect_y : object.reflect_y;
// console.log('reflectionRef', reflectionRef.current)
 
// if (object.type === 'text') result.style = { ...(result.style ?? {}), word_break: true };
 
// if (object.type === 'line' && object.style?.points) {
// result.height = 1;
 
// const curveData = updatedCurvePointsRef.current[object.id];
 
// if (curveData) {
// // Use final curve geometry calculated during resize (correct for rotated groups).
// result.width = curveData.width;
// result.x = curveData.x;
// result.y = curveData.y;
// result.style = { points: curveData.points };
// } else if (groupId && initBoxesRef.current?.[0]) {
// // Fallback: line in group when we don't have curve data – compute from group scale.
// // Use group's own init box, not the overall selection box (which may include other selected objects).
// const resizedObjects = totalResizedObjectsRef.current;
// const groupIndex = resizedObjects?.findIndex((o) => o.object.id === groupId);
// const initGroupBox = groupIndex >= 0 ? initBoxesRef.current[groupIndex + 1] : null;
// const initGroup = initGroupBox?.boxPoints ? getGeomParams(initGroupBox.boxPoints) : null;
 
// if (!initGroup) {
// result.width = object.width;
// result.style = { points: object.style.points };
// } else {
// const groupDom = item.closest('div[object-type="group"]');
// const groupDomStyles = getComputedStyle(groupDom);
 
// const scaleX = parseFloat(groupDomStyles.width) / initGroup.width;
// const scaleY = parseFloat(groupDomStyles.height) / initGroup.height;
 
// const groupLeft = parseFloat(groupDomStyles.left);
// const groupTop = parseFloat(groupDomStyles.top);
 
// result.x = Math.round(groupLeft + (object.x - initGroup.left) * scaleX);
// result.y = Math.round(groupTop + (object.y - initGroup.top) * scaleY);
// result.width = Math.round(object.width * scaleX);
 
// const pt = object.style.points[0];
 
// result.style = {
// points: [[
// Math.round(groupLeft + (pt[0] - initGroup.left) * scaleX),
// Math.round(groupTop + (pt[1] - initGroup.top) * scaleY),
// ]],
// };
// }
// }
// }
 
// if (groupKey) {
// const updatedObject = { ...object, ...result };
 
// if (result.style) updatedObject.style = { ...object.style, ...result.style };
 
// groupObjects[groupKey] = groupObjects[groupKey]
// ? [...groupObjects[groupKey], updatedObject]
// : [updatedObject];
// }
 
// updatedObjects[`${slideIndex}_${objectIndex}`] = result;
 
// setTimeout(() => {
// resizeSubscribers.current?.forEach((clbk) => clbk('done', result, null, pointRef.current));
// });
// });
// }
// }
 
// if (wereObjectsResizedRef.current && fetcherDataRef.current) handleUpdateData(updatedObjects, groupObjects);
 
// totalResizedObjectsRef.current = null;
// wereObjectsResizedRef.current = false;
// fetcherDataRef.current = null;
// isResizingBlockedRef.current = { state: false, cause: '' };
// precalculatedUpdatedObjectsRef.current = {};
// reflectionRef.current = { isReflectX: false, isReflectY: false };
// initSelectedObjectsRef.current = null;
// updatedCurvePointsRef.current = {};
 
// magicLinesRef.current.clearMagicLines();
// }, [handleUpdateData]);
 
// const initResize = useCallback(() => {
// if (!canvasRef.current || !overlayRef.current) return;
 
// const detachListeners = draggableOnListeners(canvasRef.current, {
// cancelStopPropagation: true,
// start: () => {
// if (!selectionBoxRef.current) return;
// if (!totalResizedObjectsRef.current || !magicLinesRef.current || isPlayingRef.current) return;
// if (!totalResizedObjectsRef.current[0]) return;
 
// const resizedObjects = totalResizedObjectsRef.current;
// const firstObjType = firstSelectedObjTypeRef.current;
 
// resizeSubscribers.current?.forEach((clbk) => clbk('start'));
 
// const isSingleSelection = selectedObjectsIDsRef.current.length === 1;
// const isFirstObjText = firstObjType === 'text';
// const isFirstObjHasWidthAuto = resizedObjects[0].object.width_auto;
// const isSideHorizontalDot = ['x1', 'x2'].includes(pointRef.current);
// const isAnyHasFixedAspectRatio = resizedObjects.some((o) => FIXED_ASPECT_RATIO_OBJECTS.includes(o.object.type));
// const isAnyHasRotation = resizedObjects.some(({ box, object }) => !!(box.angle || object.rotate));
// const isOnlyShapes = resizedObjects.every((o) => OBJECT_SHAPE_TYPES.includes(o.object.type));
 
// initBoxesRef.current = [cloneDeep(selectionBoxRef.current), ...cloneDeep(resizedObjects.map((o) => o.box))];
 
// const initBoxPoints = initBoxesRef.current[0]?.lineBoxWithCurvePoints || initBoxesRef.current[0]?.boxPoints;
 
// initSelectionBoxSizeRef.current = getGeomParams(initBoxPoints);
// overlayBoundingBoxRef.current = overlayRef.current.getBoundingClientRect();
// magicPointsRef.current = magicLinesRef.current.getMagicPoints(canvasRef, fetcherDataRef.current.allObjects);
// keepAspectRatioRef.current = isAnyHasFixedAspectRatio || (!isSingleSelection && isAnyHasRotation);
 
// // Allow shapes to ignore aspect ratio
// if (isOnlyShapes) keepAspectRatioRef.current = false;
 
// // reset auto width for single text
// if (isSingleSelection && isFirstObjText && isFirstObjHasWidthAuto && isSideHorizontalDot) {
// resizedObjects[0].object.width = initSelectionBoxSizeRef.current.width;
// resizedObjects[0].object.width_auto = false;
 
// resizedObjects[0].dom.style.width = `${initSelectionBoxSizeRef.current.width}px`;
// }
 
// initSelectedObjectsSizeRef.current = resizedObjects.map((obj) => {
// const childSelectionBox = getSelectionBox(obj.dom, obj.object, null, null, true);
 
// return { id: obj.object.id, params: getGeomParams(childSelectionBox.boxPoints) };
// });
 
// initSelectedObjectsRef.current = resizedObjects.map((obj) => obj.object);
// },
// move: ({ dX }, e) => {
// if (!selectionBoxRef.current) return;
// if (!totalResizedObjectsRef.current || isPlayingRef.current) return;
// if (!totalResizedObjectsRef.current[0]) return;
 
// if (!wereObjectsResizedRef.current) {
// dispatch(switchObjectsResizingState(true));
// dispatch(switchCanvasHoverDisabledState(true));
// }
 
// const cursorPos = getCursorPosition(e, overlayBoundingBoxRef.current, zoomRef.current);
 
// if (e.shiftKey) keepAspectRatioRef.current = true;
 
// const resizedObjects = totalResizedObjectsRef.current;
// const groupChildsIds = allGroupChildsIdsRef.current;
// const selectedObjectsLength = selectedObjectsIDsRef.current.length;
 
// const currentBoxes = [
// selectionBoxRef.current,
// ...resizedObjects.map(({ box, object }) => ({ ...box, isChild: groupChildsIds.includes(object.id) })),
// ];
 
// const isSideDot = ['x1', 'x2', 'y1', 'y2'].includes(pointRef.current);
// const isSideXDot = ['x1', 'x2'].includes(pointRef.current);
// const settingsAngle = selectedObjectsLength === 1 && resizedObjects[0].object.rotate;
// const angle = selectedObjectsLength === 1 && Math.round(resizedObjects[0].box.angle * (180 / Math.PI));
// const isGroupResizingBySide = selectedObjectsLength === 1 && resizedObjects[0].object.type === 'group' && isSideXDot;
// const stopMagnet = !!(isGroupResizingBySide ? true : (angle || settingsAngle));
// const isTableResizing = resizedObjects.length > 1 && resizedObjects.filter(({ object }) => object.type === 'table').length > 0;
 
// if (isSideDot) keepAspectRatioRef.current = false;
// if (isTableResizing) keepAspectRatioRef.current = true;
 
// const params = calcResizeMagnetVector({
// currentBoxes,
// point: pointRef.current,
// initBoxes: initBoxesRef.current,
// cursorPos,
// keepAspectRatio: keepAspectRatioRef.current,
// magicPoints: magicPointsRef.current.magicPoints,
// angle,
// stopMagnet: stopMagnet || isResizingBlockedRef.current.state,
// isGroupResizingBySide,
// dir: dX,
// }, magicLinesTypeRef.current);
 
// const objectsToUpdate = [];
// const allObjectsTypeCheckResult = checkAreAllObjectsTextOrShapes(selectedObjectsRef.current);
 
// wereObjectsResizedRef.current = true;
 
// if (shouldBlockResizing(params, resizedObjects)) return;
 
// resizedObjects.forEach((obj, i) => {
// handleUpdateObjects(
// obj,
// params[i + 1],
// e,
// objectsToUpdate,
// isGroupResizingBySide,
// allObjectsTypeCheckResult,
// );
// });
 
// // Prevent from following manipulations like drawing magic lines, etc., if we exceeded some limitation during updating objects
// if (isResizingBlockedRef.current.state) return;
 
// const updatedSelectionBox = applyAdditionalTransformationAfterResize(
// isSideDot,
// isSideXDot,
// isGroupResizingBySide,
// allObjectsTypeCheckResult,
// selectedObjectsRef.current,
// reflectionRef.current,
// objectsToUpdate,
// resizedObjects,
// canvasRef.current,
// e,
// );
 
// if (updatedSelectionBox) {
// const boxViewPoints = transformBoxPointsToView(updatedSelectionBox, scaleMatrixRef.current);
 
// dispatch(updateCanvasContour({
// selection: { points: boxViewPoints, lines: { points: boxViewPoints }, thinLines: null },
// hover: null,
// mergeData: true,
// }));
// }
 
// if (['all', 'canvas'].includes(magicLinesTypeRef.current)) throttledHandleDrawMagicLines(selectionBoxRef.current);
// },
// done: handleResizeDone,
// });
 
// draggableDetachers.current.push(detachListeners);
// }, [handleResizeDone, handleUpdateObjects]);
 
// useEffect(handleResizeDone, [isPlaying, handleResizeDone]);
 
// useEffect(() => {
// initResize();
 
// return () => {
// draggableDetachers.current.forEach((detacher) => detacher());
 
// draggableDetachers.current = [];
// };
// }, [initResize]);
 
// useEffect(() => {
// document.addEventListener('canvas:selectionDotClicked', handleDotClicked);
 
// return () => {
// document.removeEventListener('canvas:selectionDotClicked', handleDotClicked);
// };
// }, [handleDotClicked]);
 
// useEffect(() => {
// if (isMobileOrTablet()) document.addEventListener('canvas:mobileScaleStart', handleResizeDone);
 
// return () => {
// document.removeEventListener('canvas:mobileScaleStart', handleResizeDone);
// };
// }, [handleResizeDone]);
 
// return null;
// });
 
// EditorCanvasResize.propTypes = {
// canvasRef: PropTypes.object,
// fetcherRef: PropTypes.object,
// overlayRef: PropTypes.object,
// magicLinesRef: PropTypes.object,
// resizeSubscribers: PropTypes.object,
// playerInstance: PropTypes.object.isRequired,
// };
 
// EditorCanvasResize.displayName = 'EditorCanvasResize';
// EditorCanvasResize.name = 'EditorCanvasResize';
 
// export default withEditor(EditorCanvasResize);
 
// import React, { useCallback, useEffect, useMemo, useRef } from 'react';
// import PropTypes from 'prop-types';
// import { useDispatch } from 'react-redux';
// import { cloneDeep, flatten, forIn } from 'lodash';
 
// import withEditor from '../../../../HOCs/withEditor';
 
// import {
// selectCanvasContourSelectionBox,
// selectFirstSelectedObjType,
// selectMagicLinesType,
// selectPickerObjectID,
// selectPlayerIsPlaying,
// selectPlayerZoom,
// selectSelectedObjectIDs,
// selectShowTextEditor,
// } from '../../../../../store/selectors';
 
// import { useCurrentValue, useStoreCurrentValue, useThrottle } from '../../../../hooks';
 
// import {
// applyAdditionalTransformationAfterResize,
// calcResizeMagnetVector,
// checkAreAllObjectsTextOrShapes,
// draggableOnListeners,
// fixVideoDataCrop,
// getCursorPosition,
// getGeomParams,
// getGroupObjectParams,
// getLineInfo,
// getObjectGroupId,
// getObjectMagicPoints,
// getResizeObjectsUpdateResult,
// getScaleMatrix,
// getSelectionBox,
// isMobileOrTablet,
// removeCursorTrackTooltip,
// s3Replace,
// shouldBlockResizing,
// transformBoxPointsToView,
// } from '../../../../../utils';
 
// import {
// setSlideOrObjectId,
// switchCanvasHoverDisabledState,
// switchObjectsResizingState,
// updateCanvasContour,
// updateSlideObjectsThunk,
// } from '../../../../../actions';
 
// import {
// FIXED_ASPECT_RATIO_OBJECTS,
// OBJECT_SHAPE_TYPES,
// OBJECTS_WITH_CROP,
// OBJECTS_WITH_MOVE_CALLBACKS,
// } from '../../../../../constants';
 
// const EditorCanvasResize = React.memo((props) => {
// const {
// playerInstance, canvasRef, overlayRef, fetcherRef, magicLinesRef, resizeSubscribers,
// } = props;
 
// const [zoom, zoomRef] = useStoreCurrentValue(selectPlayerZoom);
// const [isPlaying, isPlayingRef] = useStoreCurrentValue(selectPlayerIsPlaying);
// const [, isTextEditorActiveRef] = useStoreCurrentValue(selectShowTextEditor);
// const [, magicLinesTypeRef] = useStoreCurrentValue(selectMagicLinesType);
// const [, selectionBoxRef] = useStoreCurrentValue(selectCanvasContourSelectionBox);
// const [, selectedObjectsIDsRef] = useStoreCurrentValue(selectSelectedObjectIDs);
// const [, firstSelectedObjTypeRef] = useStoreCurrentValue(selectFirstSelectedObjType);
// const [, pickerObjectIdRef] = useStoreCurrentValue(selectPickerObjectID);
 
// const dispatch = useDispatch();
 
// const scaleMatrix = useMemo(() => getScaleMatrix(zoom), [zoom]);
 
// const scaleMatrixRef = useCurrentValue(scaleMatrix);
 
// const fetcherDataRef = useRef(null);
// const totalResizedObjectsRef = useRef(null);
// const overlayBoundingBoxRef = useRef(null);
// const pointRef = useRef(null);
// const initSelectionBoxSizeRef = useRef(null);
// const initSelectedObjectsSizeRef = useRef(null);
// const initSelectedObjectsRef = useRef(null);
// const selectedObjectsRef = useRef(null);
// const allGroupChildsIdsRef = useRef([]);
// const magicPointsRef = useRef([]);
// const initBoxesRef = useRef([]);
// const draggableDetachers = useRef([]);
// const keepAspectRatioRef = useRef(false);
// const wereObjectsResizedRef = useRef(false);
// const isResizingBlockedRef = useRef({ state: false, cause: '' });
// const precalculatedUpdatedObjectsRef = useRef({});
// const reflectionRef = useRef({ isReflectX: false, isReflectY: false });
// // Per-object curve points for multi-selection resize (keyed by object.id)
// const updatedCurvePointsRef = useRef({});
 
// const throttledHandleDrawMagicLines = useThrottle((selectionBox) => {
// requestAnimationFrame(() => {
// const objectMagicPoints = getObjectMagicPoints(selectionBox);
 
// if (magicLinesRef.current) {
// magicLinesRef.current.drawMagicLines(objectMagicPoints, magicPointsRef.current, zoomRef.current);
// }
// });
// }, 20, { leading: true });
 
// const handleDotClicked = useCallback((e) => {
// if (!canvasRef.current || !fetcherRef.current || isPlayingRef.current) return;
 
// const dot = e.detail?.dot;
 
// if (!dot) return;
 
// if (dot.classList.contains('selection-box-line-dot')) return;
 
// if (selectedObjectsIDsRef.current.length === 1 && (
// OBJECTS_WITH_CROP.includes(firstSelectedObjTypeRef.current) || firstSelectedObjTypeRef.current === 'table'
// )) {
// if (dot.classList.contains('selection-box-side-dot')) return;
// }
 
// pointRef.current = `${dot.getAttribute('x-param') || ''}${dot.getAttribute('y-param') || ''}`;
 
// fetcherDataRef.current = fetcherRef.current.getData();
 
// const { allObjects } = fetcherDataRef.current;
 
// let ids = selectedObjectsIDsRef.current;
// let selectedObjects = ids.map((id) => allObjects.find((o) => o.id === id));
 
// if (ids.length === 1 && selectedObjects[0].type !== 'group') {
// // replace child with its group parent object
// const groupId = getObjectGroupId(allObjects, ids[0]);
 
// if (groupId) {
// ids = [groupId];
// selectedObjects = ids.map((id) => allObjects.find((o) => o.id === id));
// }
// }
 
// const selectedGroups = selectedObjects.filter((obj) => obj.type === 'group');
// const allGroupChilds = flatten(selectedGroups.map((go) => allObjects.filter((obj) => go.objects.includes(obj.id))));
// const allGroupChildsIds = allGroupChilds.map((o) => o.id);
// const totalObjectsIds = [...selectedObjects.map((o) => o.id), ...allGroupChildsIds];
 
// allGroupChildsIdsRef.current = allGroupChildsIds;
// totalResizedObjectsRef.current = fetcherRef.current.getSpecificDomElementsWithBoxes(canvasRef, totalObjectsIds);
// selectedObjectsRef.current = ids
// .map((id) => totalResizedObjectsRef.current.find((o) => o.object.id === id))
// .filter(Boolean);
// }, []);
 
// const handleObjectsMove = useCallback((params, data, object, textLayer, objData, sharedSelectionBox) => {
// if (object.type === 'text') {
// if (textLayer) {
// if (data?.style?.font_size) textLayer.style.fontSize = `${data.style.font_size}px`;
 
// if (['x1', 'x2'].includes(pointRef.current)) textLayer.style.whiteSpace = 'normal';
// }
// }
 
// let finalLeft = null;
// let finalTop = null;
// let updatedCurvePoints = null;
 
// if (object.type === 'line' && object.style?.points && initSelectedObjectsRef?.current) {
// const initObj = object;
 
// const k = data.width / initObj.width;
 
// const lineInfo = getLineInfo(initObj);
 
// const v = {
// x: initObj.style.points[0][0] - lineInfo.center.x,
// y: initObj.style.points[0][1] - lineInfo.center.y,
// };
// const l = Math.hypot(v.x, v.y);
// // const dir = l > 1e-10 ? { x: v.x / l, y: v.y / l } : { x: 1, y: 0 };
// const dir = { x: v.x / l, y: v.y / l };
// const newL = l * k;
 
// const newPoint = { x: params.cx + dir.x * newL, y: params.cy + dir.y * newL };
 
// finalLeft = params.left;
// finalTop = params.top;
// updatedCurvePoints = [[newPoint.x, newPoint.y]];
 
// // When resizing multi-selection, line+curve must stay inside the shared selection box.
// // Use shared selection box bounds when provided (multi-selection); otherwise line's own box.
// const box = sharedSelectionBox || params;
// const boxLeft = box.left;
// const boxTop = box.top;
// const boxRight = box.left + box.width;
// const boxBottom = box.top + box.height;
 
// const lineParamsForBox = {
// x: params.left,
// y: params.top,
// width: params.width,
// height: 1,
// rotate: object.rotate ?? 0,
// };
// const segmentInfo = getLineInfo(lineParamsForBox);
// const minX = Math.min(segmentInfo.start.x, segmentInfo.end.x, newPoint.x);
// const maxX = Math.max(segmentInfo.start.x, segmentInfo.end.x, newPoint.x);
// const minY = Math.min(segmentInfo.start.y, segmentInfo.end.y, newPoint.y);
// const maxY = Math.max(segmentInfo.start.y, segmentInfo.end.y, newPoint.y);
 
// let shiftX = 0;
// if (minX < boxLeft) shiftX = boxLeft - minX;
// else if (maxX > boxRight) shiftX = boxRight - maxX;
 
// let shiftY = 0;
// if (minY < boxTop) shiftY = boxTop - minY;
// else if (maxY > boxBottom) shiftY = boxBottom - maxY;
 
// if (shiftX !== 0 || shiftY !== 0) {
// finalLeft = params.left + shiftX;
// finalTop = params.top + shiftY;
// updatedCurvePoints = [[newPoint.x + shiftX, newPoint.y + shiftY]];
 
// data.x = finalLeft;
// data.y = finalTop;
// if (data.style) data.style = { ...data.style, points: updatedCurvePoints };
 
// if (objData?.dom) {
// objData.dom.style.left = `${finalLeft}px`;
// objData.dom.style.top = `${finalTop}px`;
// }
// }
// }
 
// if (!OBJECTS_WITH_MOVE_CALLBACKS.includes(object.type)) return;
 
// const updatedObject = fixVideoDataCrop({ ...object, ...data });
 
// if (updatedCurvePoints) {
// updatedObject.x = finalLeft ?? params.left;
// updatedObject.y = finalTop ?? params.top;
// updatedObject.style = { ...updatedObject.style, points: updatedCurvePoints };
 
// updatedCurvePointsRef.current[object.id] = {
// height: params.height,
// width: params.width,
// x: finalLeft ?? params.left,
// y: finalTop ?? params.top,
// points: updatedCurvePoints,
// };
// }
 
// playerInstance.updateObjectHTML(JSON.parse(s3Replace(JSON.stringify(updatedObject))));
// }, [playerInstance]);
 
// const handleUpdateObjects = useCallback((
// objData, params, e, resultUpdatedObjects, isGroupResizing, allObjectsTypeCheckResult, sharedSelectionBox,
// ) => {
// const isSideDot = ['x1', 'x2', 'y1', 'y2'].includes(pointRef.current);
 
// const updateSelectionBox = (box) => {
// if (!box || (isTextEditorActiveRef.current && isSideDot)) return;
 
// const boxViewPoints = transformBoxPointsToView(box, scaleMatrixRef.current);
 
// dispatch(updateCanvasContour({
// selection: { points: boxViewPoints, lines: { points: boxViewPoints }, thinLines: null },
// hover: null,
// mergeData: true,
// }));
// };
 
// const resizeResult = getResizeObjectsUpdateResult(
// objData,
// params,
// e,
// resultUpdatedObjects,
// isGroupResizing,
// allObjectsTypeCheckResult,
// selectionBoxRef.current,
// fetcherDataRef.current.allObjects,
// pointRef.current,
// initSelectionBoxSizeRef.current,
// initSelectedObjectsSizeRef.current,
// initBoxesRef.current,
// selectedObjectsIDsRef.current,
// isTextEditorActiveRef.current,
// reflectionRef.current,
// precalculatedUpdatedObjectsRef.current,
// keepAspectRatioRef.current,
// isResizingBlockedRef.current,
// totalResizedObjectsRef.current,
// );
 
// if (!resizeResult) return false;
 
// const { result, textLayer, correctSelectionBox } = resizeResult;
 
// updateSelectionBox(correctSelectionBox);
 
// handleObjectsMove(params, result, objData.object, textLayer, objData, sharedSelectionBox);
 
// resizeSubscribers.current?.forEach((clbk) => clbk('move', result, updateSelectionBox, pointRef.current));
 
// return true;
// }, [handleObjectsMove]);
 
// const handleUpdateData = useCallback((updatedObjects, groupObjects) => {
// let objects = [];
// let updatedData = [];
 
// const { slides } = fetcherDataRef.current;
 
// forIn(updatedObjects, (value, path) => {
// const [a, b] = path.split('_');
 
// if (!slides[a].objects[b]) return;
 
// if (slides[a].objects[b].id === pickerObjectIdRef.current) {
// dispatch(setSlideOrObjectId({ initialObjectSize: null }));
// }
 
// objects.push(slides[a].objects[b]);
// updatedData.push(value);
// });
 
// dispatch(updateSlideObjectsThunk(objects, updatedData));
 
// objects = [];
// updatedData = [];
 
// // Correct group object size after childs has been updated
// // Use setTimeout in case we have curved text which takes time to render
// setTimeout(() => {
// Object.keys(groupObjects).forEach((key) => {
// const [a, b] = key.split('_');
 
// const audioObjects = slides[a].objects[b].objects
// .map((id) => slides[a].objects.find((o) => o.id === id))
// .filter(Boolean)
// .filter((obj) => obj.type === 'audio');
// const groupObjectParams = getGroupObjectParams([...groupObjects[key], ...audioObjects]);
 
// if (groupObjectParams?.data) {
// objects.push(slides[a].objects[b]);
// updatedData.push(groupObjectParams.data);
// }
 
// if (groupObjectParams?.childsData) {
// objects.push(...groupObjects[key]);
// updatedData.push(...groupObjectParams.childsData);
// }
// });
 
// dispatch(updateSlideObjectsThunk(objects, updatedData));
// });
// }, []);
 
// const handleResizeDone = useCallback((e) => {
// removeCursorTrackTooltip();
 
// // Store group object path and it's childs with updated data
// // Will be used to calculate correct group objects sizes with round values
// const groupObjects = {};
// const updatedObjects = {};
 
// if (wereObjectsResizedRef.current || e?.type === 'canvas:mobileScaleStart') {
// dispatch(switchObjectsResizingState(false));
// dispatch(switchCanvasHoverDisabledState(false));
 
// if (totalResizedObjectsRef.current && fetcherDataRef.current) {
// const { allObjects } = fetcherDataRef.current;
 
// totalResizedObjectsRef.current.forEach(({ dom: item, object }) => {
// const slideIndex = item.getAttribute('slide-index');
// const objectIndex = item.getAttribute('object-index');
 
// const { left, top, width, height } = getComputedStyle(item);
 
// const result = {};
 
// const selectionBoxPoints = selectionBoxRef.current?.lineBoxWithCurvePoints
// || selectionBoxRef.current?.boxPoints;
// const geomParams = getGeomParams(selectionBoxPoints);
 
// const isSideHorizontalDot = ['x1', 'x2'].includes(pointRef.current);
 
// const precalculatedResult = precalculatedUpdatedObjectsRef.current[`${slideIndex}_${objectIndex}`];
 
// if (object.type === 'text' && !isSideHorizontalDot) {
// if (precalculatedResult) Object.assign(result, precalculatedResult);
// }
 
// if (object.type === 'chart' && !isSideHorizontalDot) {
// const diffW = initSelectionBoxSizeRef.current.width / geomParams.width;
 
// const newLegendFontSize = object.style.legend.font_size / diffW;
// const newLabelsFontSize = object.style.labels.font_size / diffW;
// const newValuesFontSize = object.style.values.font_size / diffW;
// const newValuesDistance = (object.style.values.distance || 10) / diffW;
 
// result.style = {
// legend: { font_size: Math.min(Math.max(newLegendFontSize, 1), 100) },
// labels: { font_size: Math.min(Math.max(newLabelsFontSize, 1), 100) },
// values: {
// font_size: Math.min(Math.max(newValuesFontSize, 1), 100),
// ...['pie', 'doughnut'].includes(object.chart_type) && { distance: Math.min(Math.max(newValuesDistance, 1), 100) },
// },
// };
// }
 
// if (object.type === 'table' && !isSideHorizontalDot) {
// if (precalculatedResult) Object.assign(result, precalculatedResult);
// }
 
// const groupId = getObjectGroupId(allObjects, object.id);
 
// let groupKey = null;
 
// // group objects values will be rounded after resizing will be finished
// const keepDecimal = groupId || (object.type === 'group' && object.rotate);
 
// let x = keepDecimal ? parseFloat(left) : Math.round(parseFloat(left));
// let y = keepDecimal ? parseFloat(top) : Math.round(parseFloat(top));
 
// const widthRes = keepDecimal ? parseFloat(width) : Math.round(parseFloat(width));
// const heightRes = keepDecimal ? parseFloat(height) : Math.round(parseFloat(height));
 
// if (groupId) {
// const groupDom = item.closest('div[object-type="group"]');
// const groupSlideIndex = groupDom.getAttribute('slide-index');
// const groupObjectIndex = groupDom.getAttribute('object-index');
// const groupDomStyles = getComputedStyle(groupDom);
 
// groupKey = `${groupSlideIndex}_${groupObjectIndex}`;
 
// x += parseFloat(groupDomStyles.left);
// y += parseFloat(groupDomStyles.top);
// }
 
// result.x = x;
// result.y = y;
// result.width = widthRes;
// result.height = object.type === 'line' ? 1 : heightRes;
// result.width_auto = false;
// result.reflect_x = reflectionRef.current.isReflectX ? !object.reflect_x : object.reflect_x;
// result.reflect_y = reflectionRef.current.isReflectY ? !object.reflect_y : object.reflect_y;
 
// if (object.type === 'text') result.style = { ...(result.style ?? {}), word_break: true };
 
// if (object.type === 'line' && object.style?.points) {
// result.height = 1;
 
// const curveData = updatedCurvePointsRef.current[object.id];
 
// if (curveData) {
// // Use final curve geometry calculated during resize (correct for rotated groups).
// result.width = curveData.width;
// result.x = curveData.x;
// result.y = curveData.y;
// result.style = { points: curveData.points };
// } else if (groupId && initBoxesRef.current?.[0]) {
// // Fallback: line in group when we don't have curve data – compute from group scale.
// // Use group's own init box, not the overall selection box (which may include other selected objects).
// const resizedObjects = totalResizedObjectsRef.current;
// const groupIndex = resizedObjects?.findIndex((o) => o.object.id === groupId);
// const initGroupBox = groupIndex >= 0 ? initBoxesRef.current[groupIndex + 1] : null;
// const initGroup = initGroupBox?.boxPoints ? getGeomParams(initGroupBox.boxPoints) : null;
 
// if (!initGroup) {
// result.width = object.width;
// result.style = { points: object.style.points };
// } else {
// const groupDom = item.closest('div[object-type="group"]');
// const groupDomStyles = getComputedStyle(groupDom);
 
// const scaleX = parseFloat(groupDomStyles.width) / initGroup.width;
// const scaleY = parseFloat(groupDomStyles.height) / initGroup.height;
 
// const groupLeft = parseFloat(groupDomStyles.left);
// const groupTop = parseFloat(groupDomStyles.top);
 
// result.x = Math.round(groupLeft + (object.x - initGroup.left) * scaleX);
// result.y = Math.round(groupTop + (object.y - initGroup.top) * scaleY);
// result.width = Math.round(object.width * scaleX);
 
// const pt = object.style.points[0];
 
// result.style = {
// points: [[
// Math.round(groupLeft + (pt[0] - initGroup.left) * scaleX),
// Math.round(groupTop + (pt[1] - initGroup.top) * scaleY),
// ]],
// };
// }
// }
// }
 
// if (groupKey) {
// const updatedObject = { ...object, ...result };
 
// if (result.style) updatedObject.style = { ...object.style, ...result.style };
 
// groupObjects[groupKey] = groupObjects[groupKey]
// ? [...groupObjects[groupKey], updatedObject]
// : [updatedObject];
// }
 
// updatedObjects[`${slideIndex}_${objectIndex}`] = result;
 
// setTimeout(() => {
// resizeSubscribers.current?.forEach((clbk) => clbk('done', result, null, pointRef.current));
// });
// });
// }
// }
 
// if (wereObjectsResizedRef.current && fetcherDataRef.current) handleUpdateData(updatedObjects, groupObjects);
 
// totalResizedObjectsRef.current = null;
// wereObjectsResizedRef.current = false;
// fetcherDataRef.current = null;
// isResizingBlockedRef.current = { state: false, cause: '' };
// precalculatedUpdatedObjectsRef.current = {};
// reflectionRef.current = { isReflectX: false, isReflectY: false };
// initSelectedObjectsRef.current = null;
// updatedCurvePointsRef.current = {};
 
// magicLinesRef.current.clearMagicLines();
// }, [handleUpdateData]);
 
// const initResize = useCallback(() => {
// if (!canvasRef.current || !overlayRef.current) return;
 
// const detachListeners = draggableOnListeners(canvasRef.current, {
// cancelStopPropagation: true,
// start: () => {
// if (!selectionBoxRef.current) return;
// if (!totalResizedObjectsRef.current || !magicLinesRef.current || isPlayingRef.current) return;
// if (!totalResizedObjectsRef.current[0]) return;
 
// const resizedObjects = totalResizedObjectsRef.current;
// const firstObjType = firstSelectedObjTypeRef.current;
 
// resizeSubscribers.current?.forEach((clbk) => clbk('start'));
 
// const isSingleSelection = selectedObjectsIDsRef.current.length === 1;
// const isFirstObjText = firstObjType === 'text';
// const isFirstObjHasWidthAuto = resizedObjects[0].object.width_auto;
// const isSideHorizontalDot = ['x1', 'x2'].includes(pointRef.current);
// const isAnyHasFixedAspectRatio = resizedObjects.some((o) => FIXED_ASPECT_RATIO_OBJECTS.includes(o.object.type));
// const isAnyHasRotation = resizedObjects.some(({ box, object }) => !!(box.angle || object.rotate));
// const isOnlyShapes = resizedObjects.every((o) => OBJECT_SHAPE_TYPES.includes(o.object.type));
 
// initBoxesRef.current = [cloneDeep(selectionBoxRef.current), ...cloneDeep(resizedObjects.map((o) => o.box))];
 
// const initBoxPoints = initBoxesRef.current[0]?.lineBoxWithCurvePoints || initBoxesRef.current[0]?.boxPoints;
 
// initSelectionBoxSizeRef.current = getGeomParams(initBoxPoints);
// overlayBoundingBoxRef.current = overlayRef.current.getBoundingClientRect();
// magicPointsRef.current = magicLinesRef.current.getMagicPoints(canvasRef, fetcherDataRef.current.allObjects);
// keepAspectRatioRef.current = isAnyHasFixedAspectRatio || (!isSingleSelection && isAnyHasRotation);
 
// // Allow shapes to ignore aspect ratio
// if (isOnlyShapes) keepAspectRatioRef.current = false;
 
// // reset auto width for single text
// if (isSingleSelection && isFirstObjText && isFirstObjHasWidthAuto && isSideHorizontalDot) {
// resizedObjects[0].object.width = initSelectionBoxSizeRef.current.width;
// resizedObjects[0].object.width_auto = false;
 
// resizedObjects[0].dom.style.width = `${initSelectionBoxSizeRef.current.width}px`;
// }
 
// initSelectedObjectsSizeRef.current = resizedObjects.map((obj) => {
// const childSelectionBox = getSelectionBox(obj.dom, obj.object, null, null, true);
 
// return { id: obj.object.id, params: getGeomParams(childSelectionBox.boxPoints) };
// });
 
// initSelectedObjectsRef.current = resizedObjects.map((obj) => obj.object);
// },
// move: ({ dX }, e) => {
// if (!selectionBoxRef.current) return;
// if (!totalResizedObjectsRef.current || isPlayingRef.current) return;
// if (!totalResizedObjectsRef.current[0]) return;
 
// if (!wereObjectsResizedRef.current) {
// dispatch(switchObjectsResizingState(true));
// dispatch(switchCanvasHoverDisabledState(true));
// }
 
// const cursorPos = getCursorPosition(e, overlayBoundingBoxRef.current, zoomRef.current);
 
// if (e.shiftKey) keepAspectRatioRef.current = true;
 
// const resizedObjects = totalResizedObjectsRef.current;
// const groupChildsIds = allGroupChildsIdsRef.current;
// const selectedObjectsLength = selectedObjectsIDsRef.current.length;
 
// const currentBoxes = [
// selectionBoxRef.current,
// ...resizedObjects.map(({ box, object }) => ({ ...box, isChild: groupChildsIds.includes(object.id) })),
// ];
 
// const isSideDot = ['x1', 'x2', 'y1', 'y2'].includes(pointRef.current);
// const isSideXDot = ['x1', 'x2'].includes(pointRef.current);
// const settingsAngle = selectedObjectsLength === 1 && resizedObjects[0].object.rotate;
// const angle = selectedObjectsLength === 1 && Math.round(resizedObjects[0].box.angle * (180 / Math.PI));
// const isGroupResizingBySide = selectedObjectsLength === 1 && resizedObjects[0].object.type === 'group' && isSideXDot;
// const stopMagnet = !!(isGroupResizingBySide ? true : (angle || settingsAngle));
// const isTableResizing = resizedObjects.length > 1 && resizedObjects.filter(({ object }) => object.type === 'table').length > 0;
 
// if (isSideDot) keepAspectRatioRef.current = false;
// if (isTableResizing) keepAspectRatioRef.current = true;
 
// const params = calcResizeMagnetVector({
// currentBoxes,
// point: pointRef.current,
// initBoxes: initBoxesRef.current,
// cursorPos,
// keepAspectRatio: keepAspectRatioRef.current,
// magicPoints: magicPointsRef.current.magicPoints,
// angle,
// stopMagnet: stopMagnet || isResizingBlockedRef.current.state,
// isGroupResizingBySide,
// dir: dX,
// }, magicLinesTypeRef.current);
 
// const objectsToUpdate = [];
// const allObjectsTypeCheckResult = checkAreAllObjectsTextOrShapes(selectedObjectsRef.current);
 
// wereObjectsResizedRef.current = true;
 
// if (shouldBlockResizing(params, resizedObjects)) return;
 
// // params[0] is the shared selection box; params[1], params[2], ... are per-object
// const sharedSelectionBox = params[0];
// resizedObjects.forEach((obj, i) => {
// handleUpdateObjects(
// obj,
// params[i + 1],
// e,
// objectsToUpdate,
// isGroupResizingBySide,
// allObjectsTypeCheckResult,
// sharedSelectionBox,
// );
// });
 
// // Prevent from following manipulations like drawing magic lines, etc., if we exceeded some limitation during updating objects
// if (isResizingBlockedRef.current.state) return;
 
// const updatedSelectionBox = applyAdditionalTransformationAfterResize(
// isSideDot,
// isSideXDot,
// isGroupResizingBySide,
// allObjectsTypeCheckResult,
// selectedObjectsRef.current,
// reflectionRef.current,
// objectsToUpdate,
// resizedObjects,
// canvasRef.current,
// e,
// );
 
// if (updatedSelectionBox) {
// const boxViewPoints = transformBoxPointsToView(updatedSelectionBox, scaleMatrixRef.current);
 
// dispatch(updateCanvasContour({
// selection: { points: boxViewPoints, lines: { points: boxViewPoints }, thinLines: null },
// hover: null,
// mergeData: true,
// }));
// }
 
// if (['all', 'canvas'].includes(magicLinesTypeRef.current)) throttledHandleDrawMagicLines(selectionBoxRef.current);
// },
// done: handleResizeDone,
// });
 
// draggableDetachers.current.push(detachListeners);
// }, [handleResizeDone, handleUpdateObjects]);
 
// useEffect(handleResizeDone, [isPlaying, handleResizeDone]);
 
// useEffect(() => {
// initResize();
 
// return () => {
// draggableDetachers.current.forEach((detacher) => detacher());
 
// draggableDetachers.current = [];
// };
// }, [initResize]);
 
// useEffect(() => {
// document.addEventListener('canvas:selectionDotClicked', handleDotClicked);
 
// return () => {
// document.removeEventListener('canvas:selectionDotClicked', handleDotClicked);
// };
// }, [handleDotClicked]);
 
// useEffect(() => {
// if (isMobileOrTablet()) document.addEventListener('canvas:mobileScaleStart', handleResizeDone);
 
// return () => {
// document.removeEventListener('canvas:mobileScaleStart', handleResizeDone);
// };
// }, [handleResizeDone]);
 
// return null;
// });
 
// EditorCanvasResize.propTypes = {
// canvasRef: PropTypes.object,
// fetcherRef: PropTypes.object,
// overlayRef: PropTypes.object,
// magicLinesRef: PropTypes.object,
// resizeSubscribers: PropTypes.object,
// playerInstance: PropTypes.object.isRequired,
// };
 
// EditorCanvasResize.displayName = 'EditorCanvasResize';
// EditorCanvasResize.name = 'EditorCanvasResize';
 
// export default withEditor(EditorCanvasResize);