import React, { useCallback, useEffect, useMemo, useRef } from 'react';
import PropTypes from 'prop-types';
import { cloneDeep, forIn, round } from 'lodash';
import { useDispatch } from 'react-redux';
 
import withEditor from '../../../../HOCs/withEditor';
 
import {
selectCanvasContourSelectionBox,
selectFirstSelectedObjType,
selectMagicLinesType,
selectPlayerIsPlaying,
selectPlayerZoom,
selectSelectedObjectIDs,
} from '../../../../../store/selectors';
 
import { useCurrentValue, useStoreCurrentValue, useThrottle } from '../../../../hooks';
 
import {
calcManipulateMagnetVector,
draggableOnListeners,
getAnimationTransformationValues,
getBoxPoints,
getCursorPosition,
getLineInfo,
getMiddlePoints,
getRotationMatrix,
getScaleMatrix,
getSlideObjectParams,
invertPointBeyondLine,
invertViewPointToObjectPoint,
isMobileOrTablet,
isPointOnPerpendicularFromCenter,
listToMatrix,
multiplyMatrix,
mxv,
removeCursorTrackTooltip,
rotatePoint,
rotateSelectionBox,
setCursorTrackTooltip,
transformBoxPointsToView,
transformLineCurvePointsToView,
vectorAddition,
vectorSubtraction,
} from '../../../../../utils';
 
import { getSelectionBox } from '../../../../../utils/editor/canvas/selection-box';
 
import { switchCanvasHoverDisabledState, switchObjectsResizingState, updateCanvasContour, updateSlideObjectsThunk } from '../../../../../actions';
 
import { SUPA_PLAYER_CLASS_PREFIX } from '../../../../../constants';
 
/**
* Preserves curve point in line's local coords: t (0-1 along line) and d (perpendicular offset).
* Rotation is handled via new line direction.
*/
function curvePointInLineCoords(
curvePoint, initStart, initEnd, newStart, newEnd,
) {
const oldDx = initEnd.x - initStart.x;
const oldDy = initEnd.y - initStart.y;
const oldLenSq = oldDx * oldDx + oldDy * oldDy;
 
const newDx = newEnd.x - newStart.x;
const newDy = newEnd.y - newStart.y;
const newLen = Math.hypot(newDx, newDy) || 1;
 
if (oldLenSq < 1e-12) {
return { x: curvePoint.x, y: curvePoint.y };
}
 
const t = ((curvePoint.x - initStart.x) * oldDx + (curvePoint.y - initStart.y) * oldDy) / oldLenSq;
 
const onLineX = initStart.x + t * oldDx;
const onLineY = initStart.y + t * oldDy;
const oldPerpX = -oldDy / Math.sqrt(oldLenSq);
const oldPerpY = oldDx / Math.sqrt(oldLenSq);
const d = (curvePoint.x - onLineX) * oldPerpX + (curvePoint.y - onLineY) * oldPerpY;
 
const newOnLineX = newStart.x + t * newDx;
const newOnLineY = newStart.y + t * newDy;
const newPerpLen = newLen || 1;
const newPerpX = -newDy / newPerpLen;
const newPerpY = newDx / newPerpLen;
 
return {
x: newOnLineX + d * newPerpX,
y: newOnLineY + d * newPerpY,
};
}
 
/**
* Projects point onto the infinite line passing through [start, end].
*/
function projectPointOnLine(point, start, end) {
const abx = end.x - start.x;
const aby = end.y - start.y;
const apx = point.x - start.x;
const apy = point.y - start.y;
 
const abLenSq = abx * abx + aby * aby;
 
if (abLenSq < 1e-12) return { x: start.x, y: start.y };
 
const t = (apx * abx + apy * aby) / abLenSq;
 
return {
x: start.x + abx * t,
y: start.y + aby * t,
};
}
 
/**
* Projects point onto the perpendicular line through center in direction of normal.
*/
function projectPointOnPerpendicular(point, center, normal) {
const s = (point.x - center.x) * normal.x + (point.y - center.y) * normal.y;
 
return {
x: center.x + s * normal.x,
y: center.y + s * normal.y,
};
}
 
/**
* Applies animation transformations to a point (from object coordinates to view coordinates with animation)
* @param {[number, number]} point - Point in object coordinates [x, y]
* @param {Element} dom - DOM element of the object
* @param {Object} obj - Slide object
* @returns {[number, number]} - Transformed point [x, y]
*/
function applyAnimationTransformations(point, dom, obj) {
const transformation = getAnimationTransformationValues(dom);
 
if (!transformation) return [point[0], point[1]];
 
const params = getSlideObjectParams(dom, obj);
const { width, height, left, top, rotate } = params;
const angle = rotate * (Math.PI / 180);
const rotMatrix = getRotationMatrix(angle);
const cx = left + width / 2;
const cy = top + height / 2;
 
const originEntrance = transformation.transformOriginEntrance;
const originOngoing = transformation.transformOriginOngoing;
const ongoingOffsets = [(width * originOngoing[0]) / 100, (height * originOngoing[1]) / 100];
const entranceOffsets = [(width * originEntrance[0]) / 100, (height * originEntrance[1]) / 100];
const vectorToTransformOrigin = vectorAddition([left, top], ongoingOffsets);
const newVectorToTransformOrigin = vectorAddition([left, top], entranceOffsets);
 
// Apply object rotation
let transformedPoint = vectorAddition(point, [-cx, -cy]);
 
transformedPoint = mxv(rotMatrix, transformedPoint);
transformedPoint = vectorAddition(transformedPoint, [cx, cy]);
 
// Apply ongoing animation transform
transformedPoint = vectorSubtraction(transformedPoint, vectorToTransformOrigin);
 
const matrixOngoing = listToMatrix(transformation.tmOngoing, 4);
const vectorOngoing = listToMatrix([...transformedPoint, 0, 1], 1);
const resultOngoing = multiplyMatrix(matrixOngoing, vectorOngoing);
 
transformedPoint = [resultOngoing[0], resultOngoing[1]];
transformedPoint = vectorAddition(transformedPoint, vectorToTransformOrigin);
 
// Apply entrance animation transform
transformedPoint = vectorSubtraction(transformedPoint, newVectorToTransformOrigin);
 
const matrixEntrance = listToMatrix(transformation.tmEntrance, 4);
const vectorEntrance = listToMatrix([...transformedPoint, 0, 1], 1);
const resultEntrance = multiplyMatrix(matrixEntrance, vectorEntrance);
 
transformedPoint = [resultEntrance[0], resultEntrance[1]];
transformedPoint = vectorAddition(transformedPoint, newVectorToTransformOrigin);
 
return transformedPoint;
}
 
// eslint-disable-next-line
const ARROW_SHIFT_ANGLES = [-180, -165, -150, -135, -120, -105, -90, -75, -60, -45, -30, -15, 0, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180];
const ARROW_MAGNET_ANGLES = [-180, -90, -0, 90, 180];
 
const EditorCanvasLine = React.memo((props) => {
const { canvasRef, overlayRef, fetcherRef, magicLinesRef, playerInstance } = props;
 
const [zoom, zoomRef] = useStoreCurrentValue(selectPlayerZoom);
const [, magicLinesTypeRef] = useStoreCurrentValue(selectMagicLinesType);
const [, selectionBoxRef] = useStoreCurrentValue(selectCanvasContourSelectionBox);
const [, selectedObjectsIDsRef] = useStoreCurrentValue(selectSelectedObjectIDs);
const [, firstSelectedObjTypeRef] = useStoreCurrentValue(selectFirstSelectedObjType);
const [, isPlayingRef] = useStoreCurrentValue(selectPlayerIsPlaying);
 
const dispatch = useDispatch();
 
const scaleMatrix = useMemo(() => getScaleMatrix(zoom), [zoom]);
 
const scaleMatrixRef = useCurrentValue(scaleMatrix);
 
const fetcherDataRef = useRef(null);
const elementRef = useRef(null);
const overlayBoundingBoxRef = useRef(null);
const pointRef = useRef(null);
const selectionBoxAngleRef = useRef(null);
const resultArrowAngleRef = useRef(null);
const updateResultRef = useRef(null);
const magicPointsRef = useRef([]);
const initBoxesRef = useRef([]);
const draggableDetachers = useRef([]);
const wereObjectsResizedRef = useRef(false);
const resultCurvedBoxRef = useRef(null);
const curvePointElemRef = useRef(null);
 
const throttledHandleDrawMagicLines = useThrottle((selectionBox) => {
requestAnimationFrame(() => {
const [p1, p2] = getMiddlePoints(selectionBox.boxPoints);
 
const objectMagicPoints = {
x: [Math.round(p1[0]), Math.round(p2[0])],
y: [Math.round(p1[1]), Math.round(p2[1])],
};
 
if (magicLinesRef.current) {
magicLinesRef.current.drawMagicLines(objectMagicPoints, magicPointsRef.current, zoomRef.current);
}
});
}, 20, { leading: true });
 
const throttledHandleDrawCurveLineMagicLines = useThrottle((
{
angle, curvePointPos, center, curvePointOnLine, curvePointOnLinePerpendicular, lineWidth,
},
) => {
requestAnimationFrame(() => {
if (magicLinesRef.current) {
magicLinesRef.current.drawCurveLineMagicPoints(
{
angle, curvePointPos, center, curvePointOnLine, curvePointOnLinePerpendicular, lineWidth,
},
zoomRef.current,
);
}
});
}, 20, { leading: true });
 
const handleDotClicked = useCallback((e) => {
if (!canvasRef.current || !fetcherRef.current || isPlayingRef.current) return;
 
const dot = e.detail?.dot;
 
if (!dot || !dot.classList.contains('selection-box-line-dot')) return;
if (selectedObjectsIDsRef.current.length !== 1 || firstSelectedObjTypeRef.current !== 'line') return;
 
const ids = selectedObjectsIDsRef.current;
 
pointRef.current = `${dot.getAttribute('x-param') || ''}${dot.getAttribute('y-param') || ''}`;
 
fetcherDataRef.current = fetcherRef.current.getData();
 
[elementRef.current] = fetcherRef.current.getSpecificDomElementsWithBoxes(canvasRef, ids);
 
if (!elementRef.current) return;
 
elementRef.current.transformLayer = elementRef.current.dom.querySelector(`.${SUPA_PLAYER_CLASS_PREFIX}slide-object-transform-layer`);
}, []);
 
const handleUpdateObject = useCallback((dom, object, params, e, isCurvedDot = false, rotate, box) => {
if (isCurvedDot && object?.style?.points?.length > 0 && params.cursorPos) {
const newCurvedPos = {
x: params.cursorPos[0],
y: params.cursorPos[1],
};
 
updateResultRef.current = {
style: { points: [[newCurvedPos.x, newCurvedPos.y]] },
};
 
const updatedObject = { ...object, style: { ...object.style, ...updateResultRef.current.style } };
 
playerInstance.updateObjectHTML(updatedObject);
 
return;
}
 
if (!params.width || !params.height) return;
if (!Math.round(params.width) || !Math.round(params.height)) return;
 
forIn(params, (value, prop) => {
dom.style[prop] = `${value}px`;
});
 
const { left, top, width } = getComputedStyle(dom);
 
updateResultRef.current = {
x: Math.round(parseFloat(left)),
y: Math.round(parseFloat(top)),
width: Math.round(parseFloat(width)),
};
 
setCursorTrackTooltip(e, `W:${updateResultRef.current.width}`);
 
let newMidPoints = null;
 
if (object?.style?.points?.length > 0 && box) {
const initBox = initBoxesRef.current[0];
 
const curvePoint = { x: object.style.points[0][0], y: object.style.points[0][1] };
const initStart = { x: initBox.objectPoints[0][0], y: initBox.objectPoints[0][1] };
const initEnd = { x: initBox.objectPoints[1][0], y: initBox.objectPoints[1][1] };
const newStart = { x: box.objectPoints[0][0], y: box.objectPoints[0][1] };
const newEnd = { x: box.objectPoints[1][0], y: box.objectPoints[1][1] };
 
const newRes = curvePointInLineCoords(curvePoint, initStart, initEnd, newStart, newEnd);
 
resultCurvedBoxRef.current = [newRes.x, newRes.y];
 
newMidPoints = [newRes.x, newRes.y];
}
 
const updatedObject = {
...object,
...updateResultRef.current,
rotate,
...newMidPoints && { style: { ...object.style, points: [newMidPoints] } },
};
 
playerInstance.updateObjectHTML(updatedObject);
}, [playerInstance]);
 
const handleUpdateData = useCallback(() => {
const finalResult = {
...updateResultRef.current,
...wereObjectsResizedRef.current ? { rotate: resultArrowAngleRef.current } : {},
...resultCurvedBoxRef.current
? { style: { ...elementRef.current.object.style, points: [resultCurvedBoxRef.current] } } : {},
};
 
dispatch(updateSlideObjectsThunk([elementRef.current.object], finalResult));
}, []);
 
const handleResizeDone = useCallback((e) => {
removeCursorTrackTooltip();
 
if ((wereObjectsResizedRef.current && elementRef.current) || e?.type === 'canvas:mobileScaleStart') {
dispatch(switchObjectsResizingState(false));
dispatch(switchCanvasHoverDisabledState(false));
}
 
if (wereObjectsResizedRef.current) handleUpdateData();
 
if (curvePointElemRef.current) {
curvePointElemRef.current.style.display = 'block';
}
 
elementRef.current = null;
wereObjectsResizedRef.current = false;
fetcherDataRef.current = null;
resultArrowAngleRef.current = null;
updateResultRef.current = null;
resultCurvedBoxRef.current = null;
curvePointElemRef.current = null;
 
magicLinesRef.current.clearMagicLines();
}, [handleUpdateData]);
 
const initResize = useCallback(() => {
if (!canvasRef.current || !overlayRef.current) return;
 
const detachListeners = draggableOnListeners(canvasRef.current, {
cancelStopPropagation: true,
start: () => {
if (!elementRef.current || !magicLinesRef.current || isPlayingRef.current) return;
 
const objRotateValue = elementRef.current.object.rotate || 0;
 
if (!pointRef.current.includes('cx')) {
selectionBoxAngleRef.current = (elementRef.current.box.angle * (180 / Math.PI)) || objRotateValue;
 
curvePointElemRef.current = document.querySelector('.selection-box-line-dot_cx1');
 
if (curvePointElemRef.current) {
curvePointElemRef.current.style.display = 'none';
}
}
 
initBoxesRef.current = [cloneDeep(selectionBoxRef.current), cloneDeep(elementRef.current.box)];
overlayBoundingBoxRef.current = overlayRef.current.getBoundingClientRect();
magicPointsRef.current = magicLinesRef.current.getMagicPoints(canvasRef, fetcherDataRef.current.allObjects);
},
move: (_coords, e) => {
if (!elementRef.current || isPlayingRef.current) return;
 
if (!wereObjectsResizedRef.current) {
dispatch(switchObjectsResizingState(true));
dispatch(switchCanvasHoverDisabledState(true));
}
 
const { dom, box, transformLayer, object } = elementRef.current;
 
const cursorPos = getCursorPosition(e, overlayBoundingBoxRef.current, zoomRef.current);
 
// move curve point
if (pointRef.current.includes('cx')) {
const rotate = parseFloat(round(object.rotate, 3).toFixed(3));
 
resultArrowAngleRef.current = rotate;
 
const keepAspectRatio = e.shiftKey || false;
 
const { start, end, direction, normal, center } = getLineInfo(object);
 
const baseCenter = [center.x, center.y]; // line center
 
// Order: 1) rotate cursorPos by -object.rotate → 2) apply inverse animation matrix → 3) invert across the line.
const rotatedCursorPos = rotatePoint(
[cursorPos[0], cursorPos[1]],
-(object.rotate * (Math.PI / 180)),
baseCenter,
);
 
const objectSpaceCurvePoint = invertViewPointToObjectPoint(
rotatedCursorPos,
dom,
object,
);
 
let invertedCursorPos = invertPointBeyondLine(
objectSpaceCurvePoint,
start,
end,
direction,
normal,
object.reflect_x,
object.reflect_y,
);
 
const lineProj = projectPointOnLine(invertedCursorPos, start, end);
const perpProj = projectPointOnPerpendicular(invertedCursorPos, center, normal);
const centerPoint = { x: center.x, y: center.y };
const distToLine = (invertedCursorPos.x - lineProj.x) ** 2 + (invertedCursorPos.y - lineProj.y) ** 2;
const distToPerp = (invertedCursorPos.x - perpProj.x) ** 2 + (invertedCursorPos.y - perpProj.y) ** 2;
const distToCenter = (invertedCursorPos.x - centerPoint.x) ** 2 + (invertedCursorPos.y - centerPoint.y) ** 2;
 
if (keepAspectRatio) {
invertedCursorPos = distToLine <= distToPerp ? lineProj : perpProj;
} else {
// Snap to center, guide line or perpendicular when cursor is within threshold
const SNAP_THRESHOLD_PX = 6;
const snapThresholdObj = SNAP_THRESHOLD_PX / (zoomRef.current || 1);
const SNAP_THRESHOLD_SQ = snapThresholdObj * snapThresholdObj;
if (distToCenter <= SNAP_THRESHOLD_SQ
&& distToCenter <= distToLine
&& distToCenter <= distToPerp) {
invertedCursorPos = centerPoint;
} else if (distToLine <= SNAP_THRESHOLD_SQ && distToLine <= distToPerp) {
invertedCursorPos = lineProj;
} else if (distToPerp <= SNAP_THRESHOLD_SQ) {
invertedCursorPos = perpProj;
}
}
 
const curvePointOnLine = (invertedCursorPos.x - lineProj.x) ** 2
+ (invertedCursorPos.y - lineProj.y) ** 2 <= 1 ** 2;
 
const curvePointOnLinePerpendicular = isPointOnPerpendicularFromCenter(
invertedCursorPos,
center,
normal,
1,
);
 
// Apply animation transformations to points for correct magic lines positioning
const transformedCenter = applyAnimationTransformations(
[center.x, center.y],
dom,
object,
);
 
const transformedCurvePointPos = applyAnimationTransformations(
[invertedCursorPos.x, invertedCursorPos.y],
dom,
object,
);
 
throttledHandleDrawCurveLineMagicLines({
lineWidth: object.width,
curvePointPos: transformedCurvePointPos,
angle: selectionBoxRef.current.angle,
center: { x: transformedCenter[0], y: transformedCenter[1] },
curvePointOnLine,
curvePointOnLinePerpendicular,
});
 
handleUpdateObject(dom, object, {
cursorPos: [invertedCursorPos.x, invertedCursorPos.y],
}, e, true);
 
const boxViewPoints = transformBoxPointsToView(selectionBoxRef.current, scaleMatrixRef.current);
 
// Use getSelectionBox with current curve position so lineCurvePoints are in the same space as contour (with or without animation)
const objectWithNewCurve = {
...object,
style: { ...object.style, points: [[invertedCursorPos.x, invertedCursorPos.y]] },
};
 
const curveBox = getSelectionBox(dom, objectWithNewCurve);
 
if (curveBox?.lineCurvePoints) {
selectionBoxRef.current.lineCurvePoints = curveBox.lineCurvePoints;
} else {
selectionBoxRef.current.lineCurvePoints = getBoxPoints(invertedCursorPos.x, invertedCursorPos.y, 1, 1);
}
 
const viewLineCurvePoints = transformLineCurvePointsToView(selectionBoxRef.current, scaleMatrixRef.current);
 
dispatch(updateCanvasContour({
selection: {
points: boxViewPoints,
lines: { points: boxViewPoints, viewLineCurvePoints },
thinLines: null,
},
hover: null,
mergeData: true,
}));
 
wereObjectsResizedRef.current = true;
 
return;
}
 
// move start or end point of the line
const keepAspectRatio = e.shiftKey || false;
const currentBoxes = [selectionBoxRef.current, box];
const realAngle = wereObjectsResizedRef.current ? selectionBoxRef.current.angle * (180 / Math.PI) : 0;
 
let params = calcManipulateMagnetVector({
currentBoxes,
point: pointRef.current,
initBoxes: initBoxesRef.current,
cursorPos,
keepAspectRatio,
magicPoints: magicPointsRef.current.magicPoints,
angle: selectionBoxAngleRef.current,
realAngle: selectionBoxAngleRef.current + realAngle,
stopMagnet: Math.abs((selectionBoxAngleRef.current + realAngle) % 90) !== 0,
objectAngle: object.rotate,
}, magicLinesTypeRef.current);
 
const scaleX = object.reflect_x ? -1 : 1;
const scaleY = object.reflect_y ? -1 : 1;
 
let { arrowAngle } = params;
 
if (typeof arrowAngle === 'number') {
const animationAngle = box.animationAngle * (180 / Math.PI);
let rotate = object.rotate ? object.rotate + arrowAngle : arrowAngle;
 
if (rotate > 180) rotate -= 360;
if (rotate < -180) rotate += 360;
 
const withNoAnimAngle = rotate + animationAngle;
 
if (keepAspectRatio) {
const closest = ARROW_SHIFT_ANGLES.sort((a, b) => (
Math.abs(withNoAnimAngle - a) - Math.abs(withNoAnimAngle - b)
))[0];
 
arrowAngle += (closest - withNoAnimAngle);
rotate = closest - animationAngle;
} else {
const closest = ARROW_MAGNET_ANGLES.sort((a, b) => (
Math.abs(withNoAnimAngle - a) - Math.abs(withNoAnimAngle - b)
))[0];
const angleDiff = closest - withNoAnimAngle;
 
if (Math.abs(angleDiff) <= 1.5) {
arrowAngle += (closest - withNoAnimAngle);
rotate = closest - animationAngle;
}
}
 
rotate = parseFloat(round(rotate, 3).toFixed(3));
 
rotateSelectionBox(selectionBoxRef.current, arrowAngle, selectionBoxRef.current, params.pivot);
 
params = rotateSelectionBox(box, arrowAngle, box, params.pivot);
 
handleUpdateObject(dom, object, params, e, false, rotate, selectionBoxRef.current);
 
const boxViewPoints = transformBoxPointsToView(selectionBoxRef.current, scaleMatrixRef.current);
 
dispatch(updateCanvasContour({
selection: { points: boxViewPoints, lines: { points: boxViewPoints }, thinLines: null },
hover: null,
mergeData: true,
}));
 
transformLayer.style.transform = `rotate(${rotate}deg) scaleX(${scaleX}) scaleY(${scaleY})`;
 
resultArrowAngleRef.current = rotate;
}
 
if (['all', 'canvas'].includes(magicLinesTypeRef.current)) throttledHandleDrawMagicLines(selectionBoxRef.current);
 
wereObjectsResizedRef.current = true;
},
done: handleResizeDone,
});
 
draggableDetachers.current.push(detachListeners);
}, [handleUpdateObject, 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;
});
 
EditorCanvasLine.propTypes = {
canvasRef: PropTypes.object,
fetcherRef: PropTypes.object,
overlayRef: PropTypes.object,
magicLinesRef: PropTypes.object,
playerInstance: PropTypes.object.isRequired,
};
 
EditorCanvasLine.displayName = 'EditorCanvasLine';
EditorCanvasLine.name = 'EditorCanvasLine';
 
export default withEditor(EditorCanvasLine);