"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.SelectedOutlineElement = exports.SelectedOutlineTransformOriginHandle = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = __importStar(require("react"));
const remotion_1 = require("remotion");
const no_react_1 = require("remotion/no-react");
const client_id_1 = require("../helpers/client-id");
const colors_1 = require("../helpers/colors");
const format_file_location_1 = require("../helpers/format-file-location");
const get_connected_compositions_1 = require("../helpers/get-connected-compositions");
const get_sequence_double_click_action_1 = require("../helpers/get-sequence-double-click-action");
const open_in_editor_1 = require("../helpers/open-in-editor");
const editor_snapping_1 = require("../state/editor-snapping");
const modals_1 = require("../state/modals");
const call_api_1 = require("./call-api");
const ConfirmationDialog_1 = require("./ConfirmationDialog");
const ContextMenu_1 = require("./ContextMenu");
const effect_drag_and_drop_1 = require("./effect-drag-and-drop");
const ForceSpecificCursor_1 = require("./ForceSpecificCursor");
const InitialCompositionLoader_1 = require("./InitialCompositionLoader");
const NotificationCenter_1 = require("./Notifications/NotificationCenter");
const selected_outline_drag_1 = require("./selected-outline-drag");
const selected_outline_measurement_1 = require("./selected-outline-measurement");
const selected_outline_snap_1 = require("./selected-outline-snap");
const selected_outline_types_1 = require("./selected-outline-types");
const selected_outline_uv_1 = require("./selected-outline-uv");
const call_add_keyframe_1 = require("./Timeline/call-add-keyframe");
const disable_sequence_interactivity_1 = require("./Timeline/disable-sequence-interactivity");
const duplicate_selected_timeline_item_1 = require("./Timeline/duplicate-selected-timeline-item");
const focus_inspector_field_1 = require("./Timeline/focus-inspector-field");
const get_sequence_context_menu_items_1 = require("./Timeline/get-sequence-context-menu-items");
const save_sequence_prop_1 = require("./Timeline/save-sequence-prop");
const timeline_asset_link_1 = require("./Timeline/timeline-asset-link");
const timeline_translate_utils_1 = require("./Timeline/timeline-translate-utils");
const get_stack_1 = require("./Timeline/TimelineStack/get-stack");
const transform_origin_utils_1 = require("./Timeline/transform-origin-utils");
const use_select_asset_1 = require("./use-select-asset");
const emptyContextMenuValues = [];
const SelectedOutlineTransformOriginHandle = ({ outline, onDraggingChange, target }) => {
    var _a;
    const { setDragOverrides, clearDragOverrides, setPropStatuses } = (0, react_1.useContext)(remotion_1.Internals.VisualModeSettersContext);
    const { editorSnapping } = (0, react_1.useContext)(editor_snapping_1.EditorSnappingContext);
    const transformOriginDrag = (_a = target === null || target === void 0 ? void 0 : target.transformOriginDrag) !== null && _a !== void 0 ? _a : null;
    const parsed = (0, react_1.useMemo)(() => transformOriginDrag === null
        ? null
        : (0, transform_origin_utils_1.parseTransformOrigin)(transformOriginDrag.originValue), [transformOriginDrag]);
    const uv = (0, react_1.useMemo)(() => {
        if (parsed === null || outline.dimensions === null) {
            return null;
        }
        return (0, transform_origin_utils_1.parsedTransformOriginToUv)({
            parsed,
            width: outline.dimensions.width,
            height: outline.dimensions.height,
        });
    }, [outline.dimensions, parsed]);
    const position = (0, react_1.useMemo)(() => (uv === null ? null : (0, selected_outline_uv_1.getUvHandlePosition)(outline.points, uv)), [outline.points, uv]);
    const onPointerDown = react_1.default.useCallback((event) => {
        if (event.button !== 0 ||
            transformOriginDrag === null ||
            parsed === null ||
            uv === null ||
            outline.dimensions === null) {
            return;
        }
        event.preventDefault();
        event.stopPropagation();
        const svg = event.currentTarget.ownerSVGElement;
        if (svg === null) {
            return;
        }
        const rotation = (0, selected_outline_drag_1.parseCssRotationToRadians)(transformOriginDrag.rotateValue);
        if (rotation === null) {
            return;
        }
        const { dimensions } = outline;
        if (dimensions === null) {
            return;
        }
        const [scaleX, scaleY] = no_react_1.NoReactInternals.parseScaleValue(transformOriginDrag.scaleValue);
        const startTranslate = (0, timeline_translate_utils_1.parseTranslate)(transformOriginDrag.translateValue);
        const svgRect = svg.getBoundingClientRect();
        const defaultOrigin = transformOriginDrag.originDefault !== undefined
            ? JSON.stringify(transformOriginDrag.originDefault)
            : null;
        const defaultTranslate = transformOriginDrag.translateDefault !== undefined
            ? JSON.stringify(transformOriginDrag.translateDefault)
            : null;
        let last = null;
        let currentPointerX = event.clientX;
        let currentPointerY = event.clientY;
        let axisLocked = event.shiftKey;
        onDraggingChange(true);
        (0, ForceSpecificCursor_1.forceSpecificCursor)('crosshair');
        const updateFromPointerPosition = () => {
            const point = {
                x: currentPointerX - svgRect.left,
                y: currentPointerY - svgRect.top,
            };
            const rawUv = (0, selected_outline_uv_1.getUvCoordinateForPoint)(outline.points, point);
            const lockedAxis = (0, selected_outline_drag_1.getSelectedOutlineTransformOriginLockedAxis)({
                axisLocked,
                dimensions,
                startUv: uv,
                uv: rawUv,
            });
            const axisLockedUv = (0, selected_outline_drag_1.applySelectedOutlineTransformOriginAxisLock)({
                lockedAxis,
                startUv: uv,
                uv: rawUv,
            });
            const snapPoint = lockedAxis === null
                ? point
                : (0, selected_outline_uv_1.getUvHandlePosition)(outline.points, axisLockedUv);
            const snappedUv = editorSnapping
                ? (0, selected_outline_drag_1.snapSelectedOutlineTransformOriginUv)({
                    point: snapPoint,
                    points: outline.points,
                    uv: axisLockedUv,
                })
                : axisLockedUv;
            const nextUv = (0, selected_outline_drag_1.applySelectedOutlineTransformOriginAxisLock)({
                lockedAxis,
                startUv: uv,
                uv: snappedUv,
            });
            const deltaOrigin = [
                (nextUv[0] - uv[0]) * dimensions.width,
                (nextUv[1] - uv[1]) * dimensions.height,
            ];
            const [nextTranslateX, nextTranslateY] = (0, selected_outline_drag_1.compensateTranslateForTransformOrigin)({
                startTranslate,
                deltaOrigin,
                rotate: rotation,
                scale: [scaleX, scaleY],
            });
            const origin = (0, transform_origin_utils_1.serializeTransformOrigin)({
                uv: nextUv,
                z: parsed.z,
            });
            const translate = (0, timeline_translate_utils_1.serializeTranslate)(nextTranslateX, nextTranslateY);
            last = { uv: nextUv, origin, translate };
            setDragOverrides(transformOriginDrag.nodePath, selected_outline_types_1.transformOriginFieldKey, transformOriginDrag.originPropStatus.status === 'keyframed'
                ? remotion_1.Internals.makeKeyframedDragOverride({
                    status: transformOriginDrag.originPropStatus,
                    frame: transformOriginDrag.sourceFrame,
                    value: origin,
                })
                : remotion_1.Internals.makeStaticDragOverride(origin));
            setDragOverrides(transformOriginDrag.nodePath, selected_outline_types_1.translateFieldKey, transformOriginDrag.translatePropStatus.status === 'keyframed'
                ? remotion_1.Internals.makeKeyframedDragOverride({
                    status: transformOriginDrag.translatePropStatus,
                    frame: transformOriginDrag.sourceFrame,
                    value: translate,
                })
                : remotion_1.Internals.makeStaticDragOverride(translate));
        };
        updateFromPointerPosition();
        const onPointerMove = (moveEvent) => {
            moveEvent.preventDefault();
            currentPointerX = moveEvent.clientX;
            currentPointerY = moveEvent.clientY;
            axisLocked = moveEvent.shiftKey;
            updateFromPointerPosition();
        };
        const onKeyChange = (keyEvent) => {
            if (keyEvent.key !== 'Shift') {
                return;
            }
            const nextAxisLocked = keyEvent.type === 'keydown';
            if (nextAxisLocked === axisLocked) {
                return;
            }
            axisLocked = nextAxisLocked;
            updateFromPointerPosition();
        };
        const onPointerUp = () => {
            window.removeEventListener('pointermove', onPointerMove);
            window.removeEventListener('pointerup', onPointerUp);
            window.removeEventListener('pointercancel', onPointerUp);
            window.removeEventListener('keydown', onKeyChange);
            window.removeEventListener('keyup', onKeyChange);
            (0, ForceSpecificCursor_1.stopForcingSpecificCursor)();
            onDraggingChange(false);
            if (last === null || (0, selected_outline_drag_1.uvsEqual)(last.uv, uv)) {
                clearDragOverrides(transformOriginDrag.nodePath);
                return;
            }
            const originChanged = last.origin !== transformOriginDrag.originValue;
            const translateChanged = last.translate !== transformOriginDrag.translateValue;
            if (!originChanged && !translateChanged) {
                clearDragOverrides(transformOriginDrag.nodePath);
                return;
            }
            const shouldSaveAsKeyframes = transformOriginDrag.originPropStatus.status === 'keyframed' ||
                transformOriginDrag.translatePropStatus.status === 'keyframed';
            const promise = shouldSaveAsKeyframes
                ? (0, call_add_keyframe_1.callAddKeyframes)({
                    sequenceKeyframes: [
                        originChanged
                            ? {
                                fileName: transformOriginDrag.nodePath.absolutePath,
                                nodePath: transformOriginDrag.nodePath,
                                fieldKey: selected_outline_types_1.transformOriginFieldKey,
                                sourceFrame: transformOriginDrag.sourceFrame,
                                value: last.origin,
                                schema: transformOriginDrag.schema,
                            }
                            : null,
                        translateChanged
                            ? {
                                fileName: transformOriginDrag.nodePath.absolutePath,
                                nodePath: transformOriginDrag.nodePath,
                                fieldKey: selected_outline_types_1.translateFieldKey,
                                sourceFrame: transformOriginDrag.sourceFrame,
                                value: last.translate,
                                schema: transformOriginDrag.schema,
                            }
                            : null,
                    ].filter(no_react_1.NoReactInternals.truthy),
                    effectKeyframes: [],
                    setPropStatuses,
                    clientId: transformOriginDrag.clientId,
                })
                : (0, save_sequence_prop_1.saveSequenceProps)({
                    changes: [
                        originChanged
                            ? {
                                fileName: transformOriginDrag.nodePath.absolutePath,
                                nodePath: transformOriginDrag.nodePath,
                                fieldKey: selected_outline_types_1.transformOriginFieldKey,
                                value: last.origin,
                                defaultValue: defaultOrigin,
                                schema: transformOriginDrag.schema,
                            }
                            : null,
                        translateChanged
                            ? {
                                fileName: transformOriginDrag.nodePath.absolutePath,
                                nodePath: transformOriginDrag.nodePath,
                                fieldKey: selected_outline_types_1.translateFieldKey,
                                value: last.translate,
                                defaultValue: defaultTranslate,
                                schema: transformOriginDrag.schema,
                            }
                            : null,
                    ].filter(no_react_1.NoReactInternals.truthy),
                    setPropStatuses,
                    clientId: transformOriginDrag.clientId,
                    undoLabel: 'Move transform origin',
                    redoLabel: 'Move transform origin back',
                });
            promise
                .catch((err) => {
                (0, NotificationCenter_1.showNotification)(`Could not save transform origin: ${err instanceof Error ? err.message : String(err)}`, 4000);
            })
                .finally(() => {
                clearDragOverrides(transformOriginDrag.nodePath);
            });
        };
        window.addEventListener('pointermove', onPointerMove);
        window.addEventListener('pointerup', onPointerUp);
        window.addEventListener('pointercancel', onPointerUp);
        window.addEventListener('keydown', onKeyChange);
        window.addEventListener('keyup', onKeyChange);
    }, [
        clearDragOverrides,
        editorSnapping,
        onDraggingChange,
        outline,
        parsed,
        setDragOverrides,
        setPropStatuses,
        transformOriginDrag,
        uv,
    ]);
    if (transformOriginDrag === null ||
        parsed === null ||
        uv === null ||
        position === null) {
        return null;
    }
    return (jsx_runtime_1.jsxs("g", { pointerEvents: "all", cursor: "crosshair", onPointerDown: onPointerDown, "aria-hidden": "true", style: {
            filter: colors_1.SELECTED_OUTLINE_DROP_SHADOW,
        }, children: [
            jsx_runtime_1.jsx("circle", { cx: position.x, cy: position.y, r: 4, stroke: colors_1.BLUE, fill: "none", strokeWidth: 2, vectorEffect: "non-scaling-stroke" }), jsx_runtime_1.jsx("line", { x1: position.x - 8, y1: position.y, x2: position.x + 8, y2: position.y, stroke: colors_1.BLUE, strokeWidth: 2, vectorEffect: "non-scaling-stroke" }), jsx_runtime_1.jsx("line", { x1: position.x, y1: position.y - 8, x2: position.x, y2: position.y + 8, stroke: colors_1.BLUE, strokeWidth: 2, vectorEffect: "non-scaling-stroke" })
        ] }));
};
exports.SelectedOutlineTransformOriginHandle = SelectedOutlineTransformOriginHandle;
const SelectedOutlinePolygon = ({ allDragTargets, allDragOutlines, contextMenuValues, dragging, hovered, onContextMenuOpen, outline, onDraggingChange, onHoverChange, onSnapPointsChange, onSelect, onDoubleClickTarget, scale, snapTargets, target, }) => {
    var _a, _b, _c, _d;
    const { getDragOverrides } = (0, react_1.useContext)(remotion_1.Internals.VisualModeDragOverridesContext);
    const { setPropStatuses, setDragOverrides, clearDragOverrides } = (0, react_1.useContext)(remotion_1.Internals.VisualModeSettersContext);
    const { editorSnapping } = (0, react_1.useContext)(editor_snapping_1.EditorSnappingContext);
    const timelinePosition = remotion_1.Internals.Timeline.useTimelinePosition();
    const timelinePositionRef = (0, react_1.useRef)(timelinePosition);
    timelinePositionRef.current = timelinePosition;
    const polygonRef = (0, react_1.useRef)(null);
    const points = (0, react_1.useMemo)(() => outline.points.map(selected_outline_measurement_1.pointToString).join(' '), [outline.points]);
    const drag = (_a = target === null || target === void 0 ? void 0 : target.drag) !== null && _a !== void 0 ? _a : null;
    const selected = (_b = target === null || target === void 0 ? void 0 : target.selected) !== null && _b !== void 0 ? _b : false;
    const containsSelection = (_c = target === null || target === void 0 ? void 0 : target.containsSelection) !== null && _c !== void 0 ? _c : false;
    const effectDrop = (_d = target === null || target === void 0 ? void 0 : target.effectDrop) !== null && _d !== void 0 ? _d : null;
    const [effectDropHovered, setEffectDropHovered] = (0, react_1.useState)(false);
    const visible = containsSelection || hovered;
    const onPointerDown = react_1.default.useCallback((event) => {
        if (event.button !== 0 || target === undefined) {
            return;
        }
        event.preventDefault();
        event.stopPropagation();
        const interaction = (0, selected_outline_measurement_1.getOutlineSelectionInteraction)(event);
        const shouldUpdateSelection = !selected || interaction.shiftKey || interaction.toggleKey;
        if (shouldUpdateSelection) {
            onSelect(target.selection, interaction);
        }
        if (drag === null || interaction.shiftKey || interaction.toggleKey) {
            return;
        }
        if ((0, focus_inspector_field_1.commitPendingInspectorFields)()) {
            return;
        }
        const startPointerX = event.clientX;
        const startPointerY = event.clientY;
        const dragStates = (0, selected_outline_drag_1.getSelectedOutlineDragStates)({
            dragTargets: selected ? allDragTargets : [drag],
            getDragOverrides,
            timelinePosition: timelinePositionRef.current,
        });
        let lastValues = new Map();
        let currentPointerX = startPointerX;
        let currentPointerY = startPointerY;
        let axisLocked = false;
        let dragStarted = false;
        let snappingDisabled = event.metaKey || event.ctrlKey;
        const updateDragOverrides = () => {
            const screenDeltaX = currentPointerX - startPointerX;
            const screenDeltaY = currentPointerY - startPointerY;
            if (!dragStarted) {
                if (!(0, selected_outline_drag_1.isSelectedOutlineDragPastThreshold)({
                    deltaX: screenDeltaX,
                    deltaY: screenDeltaY,
                })) {
                    return;
                }
                dragStarted = true;
                onDraggingChange(true);
                (0, ForceSpecificCursor_1.forceSpecificCursor)('default');
            }
            const axisLockedDirection = axisLocked
                ? Math.abs(screenDeltaX) >= Math.abs(screenDeltaY)
                    ? 'horizontal'
                    : 'vertical'
                : null;
            const dragDelta = (0, selected_outline_drag_1.applySelectedOutlineDragAxisLock)({
                deltaX: screenDeltaX / scale,
                deltaY: screenDeltaY / scale,
                axisLocked,
            });
            let { deltaX, deltaY } = dragDelta;
            if (editorSnapping && !snappingDisabled) {
                const snapResult = (0, selected_outline_snap_1.findSelectedOutlineSnap)({
                    allowX: axisLockedDirection !== 'vertical',
                    allowY: axisLockedDirection !== 'horizontal',
                    deltaX,
                    deltaY,
                    outlines: selected ? allDragOutlines : [outline],
                    scale,
                    targets: snapTargets,
                });
                if (snapResult.snapOffsetX !== null) {
                    deltaX += snapResult.snapOffsetX;
                }
                if (snapResult.snapOffsetY !== null) {
                    deltaY += snapResult.snapOffsetY;
                }
                onSnapPointsChange(snapResult.activeSnapPoints);
            }
            else {
                onSnapPointsChange([]);
            }
            lastValues = (0, selected_outline_drag_1.getSelectedOutlineDragValues)({
                dragStates,
                deltaX,
                deltaY,
            });
            for (const dragState of dragStates) {
                const value = lastValues.get(dragState.key);
                if (value === undefined) {
                    throw new Error('Expected drag value to be available');
                }
                if (dragState.target.propStatus.status === 'keyframed') {
                    setDragOverrides(dragState.target.nodePath, selected_outline_types_1.translateFieldKey, remotion_1.Internals.makeKeyframedDragOverride({
                        status: dragState.target.propStatus,
                        frame: dragState.sourceFrame,
                        value,
                    }));
                }
                else {
                    setDragOverrides(dragState.target.nodePath, selected_outline_types_1.translateFieldKey, remotion_1.Internals.makeStaticDragOverride(value));
                }
            }
        };
        const onPointerMove = (moveEvent) => {
            moveEvent.preventDefault();
            currentPointerX = moveEvent.clientX;
            currentPointerY = moveEvent.clientY;
            axisLocked = moveEvent.shiftKey;
            snappingDisabled = moveEvent.metaKey || moveEvent.ctrlKey;
            updateDragOverrides();
        };
        const onKeyChange = (keyEvent) => {
            if (keyEvent.key !== 'Shift') {
                return;
            }
            const nextAxisLocked = keyEvent.type === 'keydown';
            if (nextAxisLocked === axisLocked) {
                return;
            }
            axisLocked = nextAxisLocked;
            updateDragOverrides();
        };
        const onPointerUp = () => {
            window.removeEventListener('pointermove', onPointerMove);
            window.removeEventListener('pointerup', onPointerUp);
            window.removeEventListener('pointercancel', onPointerUp);
            window.removeEventListener('keydown', onKeyChange);
            window.removeEventListener('keyup', onKeyChange);
            if (dragStarted) {
                (0, ForceSpecificCursor_1.stopForcingSpecificCursor)();
                onDraggingChange(false);
            }
            const changes = (0, selected_outline_drag_1.getSelectedOutlineDragChanges)({
                dragStates,
                lastValues,
            });
            if (changes.length === 0) {
                (0, selected_outline_drag_1.clearSelectedOutlineDragOverrides)({ clearDragOverrides, dragStates });
                return;
            }
            const staticChanges = changes.filter((change) => change.type === 'static');
            const keyframedChanges = changes.filter((change) => change.type === 'keyframed');
            Promise.all([
                staticChanges.length > 0
                    ? (0, save_sequence_prop_1.saveSequenceProps)({
                        changes: staticChanges,
                        setPropStatuses,
                        clientId: drag.clientId,
                        undoLabel: changes.length > 1
                            ? 'Move selected sequences'
                            : 'Move sequence',
                        redoLabel: changes.length > 1
                            ? 'Move selected sequences back'
                            : 'Move sequence back',
                    })
                    : Promise.resolve(),
                ...keyframedChanges.map((change) => (0, call_add_keyframe_1.callAddSequenceKeyframe)({
                    fileName: change.fileName,
                    nodePath: change.nodePath,
                    fieldKey: change.fieldKey,
                    sourceFrame: change.sourceFrame,
                    value: change.value,
                    schema: change.schema,
                    setPropStatuses,
                    clientId: change.clientId,
                })),
            ])
                .catch((err) => {
                (0, NotificationCenter_1.showNotification)(`Could not save sequence props: ${err instanceof Error ? err.message : String(err)}`, 4000);
            })
                .finally(() => {
                (0, selected_outline_drag_1.clearSelectedOutlineDragOverrides)({ clearDragOverrides, dragStates });
            });
        };
        window.addEventListener('pointermove', onPointerMove);
        window.addEventListener('pointerup', onPointerUp);
        window.addEventListener('pointercancel', onPointerUp);
        window.addEventListener('keydown', onKeyChange);
        window.addEventListener('keyup', onKeyChange);
    }, [
        allDragTargets,
        allDragOutlines,
        clearDragOverrides,
        drag,
        editorSnapping,
        getDragOverrides,
        onDraggingChange,
        onSelect,
        onSnapPointsChange,
        outline,
        scale,
        selected,
        setPropStatuses,
        setDragOverrides,
        snapTargets,
        target,
    ]);
    const onDoubleClick = react_1.default.useCallback((event) => {
        if (target === undefined) {
            return;
        }
        if (!onDoubleClickTarget(target, event.button)) {
            return;
        }
        event.preventDefault();
        event.stopPropagation();
    }, [onDoubleClickTarget, target]);
    const onEffectDragOver = react_1.default.useCallback((event) => {
        if (effectDrop === null || !(0, effect_drag_and_drop_1.hasEffectDragType)(event.dataTransfer)) {
            return;
        }
        event.preventDefault();
        event.stopPropagation();
        event.dataTransfer.dropEffect = 'copy';
        setEffectDropHovered(true);
    }, [effectDrop]);
    const onEffectDragLeave = react_1.default.useCallback((event) => {
        if (event.currentTarget.contains(event.relatedTarget)) {
            return;
        }
        setEffectDropHovered(false);
    }, []);
    const onEffectDrop = react_1.default.useCallback(async (event) => {
        if (effectDrop === null || !(0, effect_drag_and_drop_1.hasEffectDragType)(event.dataTransfer)) {
            return;
        }
        const dragData = (0, effect_drag_and_drop_1.getEffectDragData)(event.dataTransfer);
        if (!dragData) {
            if ((0, effect_drag_and_drop_1.hasExplicitEffectDragType)(event.dataTransfer)) {
                event.preventDefault();
                event.stopPropagation();
                setEffectDropHovered(false);
                (0, NotificationCenter_1.showNotification)('Could not read effect drag data', 3000);
            }
            return;
        }
        event.preventDefault();
        event.stopPropagation();
        setEffectDropHovered(false);
        await (0, effect_drag_and_drop_1.addEffectFromDragData)({
            dragData,
            fileName: effectDrop.fileName,
            nodePath: effectDrop.nodePath,
            clientId: effectDrop.clientId,
        });
    }, [effectDrop]);
    return (jsx_runtime_1.jsxs(jsx_runtime_1.Fragment, { children: [
            jsx_runtime_1.jsx("polygon", { ref: polygonRef, points: points, fill: effectDropHovered ? colors_1.TIMELINE_DROP_BLUE_ALPHA_12 : colors_1.TRANSPARENT, stroke: colors_1.BLUE, strokeOpacity: visible || effectDropHovered ? 1 : 0, strokeWidth: 2, vectorEffect: "non-scaling-stroke", pointerEvents: target === undefined ? undefined : 'all', onPointerEnter: () => {
                    if (!dragging) {
                        onHoverChange(outline.key);
                    }
                }, onPointerLeave: () => {
                    if (!dragging) {
                        onHoverChange(null);
                    }
                }, onPointerDown: onPointerDown, onDoubleClick: onDoubleClick, onDragOver: effectDrop === null ? undefined : onEffectDragOver, onDragLeave: effectDrop === null ? undefined : onEffectDragLeave, onDrop: effectDrop === null ? undefined : onEffectDrop }), jsx_runtime_1.jsx(ContextMenu_1.ContextMenuForTarget, { triggerRef: polygonRef, values: [...contextMenuValues], onOpen: onContextMenuOpen })
        ] }));
};
const SelectedOutlineScaleEdgeLine = ({ allScaleDragTargets, contextMenuValues, dragging, edge, outline, onDraggingChange, onContextMenuOpen, onHoverChange, onSelect, target, }) => {
    var _a, _b;
    const { getDragOverrides } = (0, react_1.useContext)(remotion_1.Internals.VisualModeDragOverridesContext);
    const { setPropStatuses, setDragOverrides, clearDragOverrides } = (0, react_1.useContext)(remotion_1.Internals.VisualModeSettersContext);
    const timelinePosition = remotion_1.Internals.Timeline.useTimelinePosition();
    const timelinePositionRef = (0, react_1.useRef)(timelinePosition);
    timelinePositionRef.current = timelinePosition;
    const scaleDrag = (_a = target === null || target === void 0 ? void 0 : target.scaleDrag) !== null && _a !== void 0 ? _a : null;
    const selected = (_b = target === null || target === void 0 ? void 0 : target.selected) !== null && _b !== void 0 ? _b : false;
    const lineRef = (0, react_1.useRef)(null);
    const edgeInfo = (0, react_1.useMemo)(() => (0, selected_outline_drag_1.getSelectedOutlineScaleEdgeInfo)(outline.points, edge), [edge, outline.points]);
    const onPointerDown = react_1.default.useCallback((event) => {
        if (event.button !== 0 || scaleDrag === null || edgeInfo === null) {
            return;
        }
        event.preventDefault();
        event.stopPropagation();
        const interaction = (0, selected_outline_measurement_1.getOutlineSelectionInteraction)(event);
        const shouldUpdateSelection = !selected || interaction.shiftKey || interaction.toggleKey;
        if (shouldUpdateSelection && target !== undefined) {
            onSelect(target.selection, interaction);
        }
        if (interaction.shiftKey || interaction.toggleKey) {
            return;
        }
        if ((0, focus_inspector_field_1.commitPendingInspectorFields)()) {
            return;
        }
        const startPointer = { x: event.clientX, y: event.clientY };
        const dragStates = (0, selected_outline_drag_1.getSelectedOutlineScaleDragStates)({
            dragTargets: selected ? allScaleDragTargets : [scaleDrag],
            getDragOverrides,
            timelinePosition: timelinePositionRef.current,
        });
        let lastValues = new Map();
        let dragStarted = false;
        const onPointerMove = (moveEvent) => {
            moveEvent.preventDefault();
            const delta = {
                x: moveEvent.clientX - startPointer.x,
                y: moveEvent.clientY - startPointer.y,
            };
            if (!dragStarted) {
                if (!(0, selected_outline_drag_1.isSelectedOutlineDragPastThreshold)({
                    deltaX: delta.x,
                    deltaY: delta.y,
                })) {
                    return;
                }
                dragStarted = true;
                onDraggingChange(true);
                (0, ForceSpecificCursor_1.forceSpecificCursor)(edgeInfo.cursor);
            }
            const projectedDelta = (0, selected_outline_measurement_1.dot)(delta, edgeInfo.normal);
            const scaleFactor = Math.max(0.001, 1 + projectedDelta / edgeInfo.extent);
            lastValues = (0, selected_outline_drag_1.getSelectedOutlineScaleDragValues)({
                dragStates,
                axis: edgeInfo.axis,
                scaleFactor,
            });
            for (const dragState of dragStates) {
                const value = lastValues.get(dragState.key);
                if (value === undefined) {
                    throw new Error('Expected scale drag value to be available');
                }
                if (dragState.target.propStatus.status === 'keyframed') {
                    setDragOverrides(dragState.target.nodePath, selected_outline_types_1.scaleFieldKey, remotion_1.Internals.makeKeyframedDragOverride({
                        status: dragState.target.propStatus,
                        frame: dragState.sourceFrame,
                        value,
                    }));
                }
                else {
                    setDragOverrides(dragState.target.nodePath, selected_outline_types_1.scaleFieldKey, remotion_1.Internals.makeStaticDragOverride(value));
                }
            }
        };
        const onPointerUp = () => {
            window.removeEventListener('pointermove', onPointerMove);
            window.removeEventListener('pointerup', onPointerUp);
            window.removeEventListener('pointercancel', onPointerUp);
            if (dragStarted) {
                (0, ForceSpecificCursor_1.stopForcingSpecificCursor)();
                onDraggingChange(false);
            }
            const changes = (0, selected_outline_drag_1.getSelectedOutlineScaleDragChanges)({
                dragStates,
                lastValues,
            });
            if (changes.length === 0) {
                (0, selected_outline_drag_1.clearSelectedOutlineScaleDragOverrides)({
                    clearDragOverrides,
                    dragStates,
                });
                return;
            }
            const staticChanges = changes.filter((change) => change.type === 'static');
            const keyframedChanges = changes.filter((change) => change.type === 'keyframed');
            Promise.all([
                staticChanges.length > 0
                    ? (0, save_sequence_prop_1.saveSequenceProps)({
                        changes: staticChanges,
                        setPropStatuses,
                        clientId: scaleDrag.clientId,
                        undoLabel: changes.length > 1
                            ? 'Scale selected sequences'
                            : 'Scale sequence',
                        redoLabel: changes.length > 1
                            ? 'Scale selected sequences back'
                            : 'Scale sequence back',
                    })
                    : Promise.resolve(),
                ...keyframedChanges.map((change) => (0, call_add_keyframe_1.callAddSequenceKeyframe)({
                    fileName: change.fileName,
                    nodePath: change.nodePath,
                    fieldKey: change.fieldKey,
                    sourceFrame: change.sourceFrame,
                    value: change.value,
                    schema: change.schema,
                    setPropStatuses,
                    clientId: change.clientId,
                })),
            ])
                .catch((err) => {
                (0, NotificationCenter_1.showNotification)(`Could not save sequence props: ${err instanceof Error ? err.message : String(err)}`, 4000);
            })
                .finally(() => {
                (0, selected_outline_drag_1.clearSelectedOutlineScaleDragOverrides)({
                    clearDragOverrides,
                    dragStates,
                });
            });
        };
        window.addEventListener('pointermove', onPointerMove);
        window.addEventListener('pointerup', onPointerUp);
        window.addEventListener('pointercancel', onPointerUp);
    }, [
        allScaleDragTargets,
        clearDragOverrides,
        edgeInfo,
        getDragOverrides,
        onDraggingChange,
        onSelect,
        scaleDrag,
        selected,
        setPropStatuses,
        setDragOverrides,
        target,
    ]);
    if (scaleDrag === null || edgeInfo === null) {
        return null;
    }
    return (jsx_runtime_1.jsxs(jsx_runtime_1.Fragment, { children: [
            jsx_runtime_1.jsx("line", { ref: lineRef, x1: edgeInfo.start.x, y1: edgeInfo.start.y, x2: edgeInfo.end.x, y2: edgeInfo.end.y, stroke: colors_1.TRANSPARENT, strokeWidth: 12, vectorEffect: "non-scaling-stroke", pointerEvents: "stroke", cursor: edgeInfo.cursor, onPointerEnter: () => {
                    if (!dragging) {
                        onHoverChange(outline.key);
                    }
                }, onPointerLeave: () => {
                    if (!dragging) {
                        onHoverChange(null);
                    }
                }, onPointerDown: onPointerDown }), jsx_runtime_1.jsx(ContextMenu_1.ContextMenuForTarget, { triggerRef: lineRef, values: [...contextMenuValues], onOpen: onContextMenuOpen })
        ] }));
};
const svgPointToClientPoint = (point, rect) => {
    return {
        x: point.x + rect.left,
        y: point.y + rect.top,
    };
};
const SelectedOutlineRotationCornerHandle = ({ allRotationDragTargets, contextMenuValues, corner, dragging, outline, onDraggingChange, onContextMenuOpen, onHoverChange, onSelect, target, }) => {
    var _a, _b;
    const { getDragOverrides } = (0, react_1.useContext)(remotion_1.Internals.VisualModeDragOverridesContext);
    const { setPropStatuses, setDragOverrides, clearDragOverrides } = (0, react_1.useContext)(remotion_1.Internals.VisualModeSettersContext);
    const { editorSnapping } = (0, react_1.useContext)(editor_snapping_1.EditorSnappingContext);
    const timelinePosition = remotion_1.Internals.Timeline.useTimelinePosition();
    const timelinePositionRef = (0, react_1.useRef)(timelinePosition);
    timelinePositionRef.current = timelinePosition;
    const rotationDrag = (_a = target === null || target === void 0 ? void 0 : target.rotationDrag) !== null && _a !== void 0 ? _a : null;
    const selected = (_b = target === null || target === void 0 ? void 0 : target.selected) !== null && _b !== void 0 ? _b : false;
    const circleRef = (0, react_1.useRef)(null);
    const cornerInfo = (0, react_1.useMemo)(() => (0, selected_outline_measurement_1.getSelectedOutlineRotationCornerInfo)(outline.points, corner), [corner, outline.points]);
    const onPointerDown = react_1.default.useCallback((event) => {
        if (event.button !== 0 || rotationDrag === null) {
            return;
        }
        event.preventDefault();
        event.stopPropagation();
        const svg = event.currentTarget.ownerSVGElement;
        if (svg === null) {
            return;
        }
        const interaction = (0, selected_outline_measurement_1.getOutlineSelectionInteraction)(event);
        const shouldUpdateSelection = !selected || interaction.toggleKey;
        if (shouldUpdateSelection && target !== undefined) {
            onSelect(target.selection, {
                shiftKey: false,
                toggleKey: interaction.toggleKey,
            });
        }
        if (interaction.toggleKey) {
            return;
        }
        if ((0, focus_inspector_field_1.commitPendingInspectorFields)()) {
            return;
        }
        const startPointer = { x: event.clientX, y: event.clientY };
        const svgRect = svg.getBoundingClientRect();
        const center = svgPointToClientPoint((0, selected_outline_measurement_1.getSelectedOutlineRotationPivot)({
            dimensions: outline.dimensions,
            points: outline.points,
            transformOriginValue: rotationDrag.transformOriginValue,
        }), svgRect);
        const dragStates = (0, selected_outline_drag_1.getSelectedOutlineRotationDragStates)({
            dragTargets: selected ? allRotationDragTargets : [rotationDrag],
            getDragOverrides,
            timelinePosition: timelinePositionRef.current,
        });
        let previousAngle = (0, selected_outline_measurement_1.getAngleDegrees)(center, {
            x: event.clientX,
            y: event.clientY,
        });
        let accumulatedDelta = 0;
        let rotationLocked = event.shiftKey;
        let lastValues = new Map();
        let dragStarted = false;
        const updateRotationDragOverrides = () => {
            const rotationDeltaDegrees = rotationLocked && editorSnapping
                ? (0, selected_outline_drag_1.snapSelectedOutlineRotationDeltaDegrees)({
                    dragStates,
                    rotationDeltaDegrees: accumulatedDelta,
                })
                : accumulatedDelta;
            lastValues = (0, selected_outline_drag_1.getSelectedOutlineRotationDragValues)({
                dragStates,
                rotationDeltaDegrees,
            });
            (0, ForceSpecificCursor_1.forceSpecificCursor)((0, selected_outline_measurement_1.getRotationCursor)(cornerInfo.cursorDegrees + rotationDeltaDegrees));
            for (const dragState of dragStates) {
                const value = lastValues.get(dragState.key);
                if (value === undefined) {
                    throw new Error('Expected rotation drag value to be available');
                }
                if (dragState.target.propStatus.status === 'keyframed') {
                    setDragOverrides(dragState.target.nodePath, selected_outline_types_1.rotateFieldKey, remotion_1.Internals.makeKeyframedDragOverride({
                        status: dragState.target.propStatus,
                        frame: dragState.sourceFrame,
                        value,
                    }));
                }
                else {
                    setDragOverrides(dragState.target.nodePath, selected_outline_types_1.rotateFieldKey, remotion_1.Internals.makeStaticDragOverride(value));
                }
            }
        };
        const onPointerMove = (moveEvent) => {
            moveEvent.preventDefault();
            const screenDeltaX = moveEvent.clientX - startPointer.x;
            const screenDeltaY = moveEvent.clientY - startPointer.y;
            if (!dragStarted) {
                if (!(0, selected_outline_drag_1.isSelectedOutlineDragPastThreshold)({
                    deltaX: screenDeltaX,
                    deltaY: screenDeltaY,
                })) {
                    return;
                }
                dragStarted = true;
                onDraggingChange(true);
            }
            const nextAngle = (0, selected_outline_measurement_1.getAngleDegrees)(center, {
                x: moveEvent.clientX,
                y: moveEvent.clientY,
            });
            accumulatedDelta += (0, selected_outline_measurement_1.getSelectedOutlineRotationDeltaDegrees)({
                from: previousAngle,
                to: nextAngle,
            });
            previousAngle = nextAngle;
            rotationLocked = moveEvent.shiftKey;
            updateRotationDragOverrides();
        };
        const onKeyChange = (keyEvent) => {
            if (keyEvent.key !== 'Shift') {
                return;
            }
            const nextRotationLocked = keyEvent.type === 'keydown';
            if (nextRotationLocked === rotationLocked) {
                return;
            }
            rotationLocked = nextRotationLocked;
            if (dragStarted) {
                updateRotationDragOverrides();
            }
        };
        const onPointerUp = () => {
            window.removeEventListener('pointermove', onPointerMove);
            window.removeEventListener('pointerup', onPointerUp);
            window.removeEventListener('pointercancel', onPointerUp);
            window.removeEventListener('keydown', onKeyChange);
            window.removeEventListener('keyup', onKeyChange);
            if (dragStarted) {
                (0, ForceSpecificCursor_1.stopForcingSpecificCursor)();
                onDraggingChange(false);
            }
            const changes = (0, selected_outline_drag_1.getSelectedOutlineRotationDragChanges)({
                dragStates,
                lastValues,
            });
            if (changes.length === 0) {
                (0, selected_outline_drag_1.clearSelectedOutlineRotationDragOverrides)({
                    clearDragOverrides,
                    dragStates,
                });
                return;
            }
            const staticChanges = changes.filter((change) => change.type === 'static');
            const keyframedChanges = changes.filter((change) => change.type === 'keyframed');
            Promise.all([
                staticChanges.length > 0
                    ? (0, save_sequence_prop_1.saveSequenceProps)({
                        changes: staticChanges,
                        setPropStatuses,
                        clientId: rotationDrag.clientId,
                        undoLabel: changes.length > 1
                            ? 'Rotate selected sequences'
                            : 'Rotate sequence',
                        redoLabel: changes.length > 1
                            ? 'Rotate selected sequences back'
                            : 'Rotate sequence back',
                    })
                    : Promise.resolve(),
                ...keyframedChanges.map((change) => (0, call_add_keyframe_1.callAddSequenceKeyframe)({
                    fileName: change.fileName,
                    nodePath: change.nodePath,
                    fieldKey: change.fieldKey,
                    sourceFrame: change.sourceFrame,
                    value: change.value,
                    schema: change.schema,
                    setPropStatuses,
                    clientId: change.clientId,
                })),
            ])
                .catch((err) => {
                (0, NotificationCenter_1.showNotification)(`Could not save sequence props: ${err instanceof Error ? err.message : String(err)}`, 4000);
            })
                .finally(() => {
                (0, selected_outline_drag_1.clearSelectedOutlineRotationDragOverrides)({
                    clearDragOverrides,
                    dragStates,
                });
            });
        };
        window.addEventListener('pointermove', onPointerMove);
        window.addEventListener('pointerup', onPointerUp);
        window.addEventListener('pointercancel', onPointerUp);
        window.addEventListener('keydown', onKeyChange);
        window.addEventListener('keyup', onKeyChange);
    }, [
        allRotationDragTargets,
        clearDragOverrides,
        cornerInfo,
        editorSnapping,
        getDragOverrides,
        onDraggingChange,
        outline.dimensions,
        outline.points,
        onSelect,
        rotationDrag,
        selected,
        setPropStatuses,
        setDragOverrides,
        target,
    ]);
    if (rotationDrag === null) {
        return null;
    }
    return (jsx_runtime_1.jsxs(jsx_runtime_1.Fragment, { children: [
            jsx_runtime_1.jsx("circle", { ref: circleRef, cx: cornerInfo.point.x, cy: cornerInfo.point.y, r: 12, fill: colors_1.TRANSPARENT, stroke: colors_1.TRANSPARENT, vectorEffect: "non-scaling-stroke", pointerEvents: "all", cursor: cornerInfo.cursor, onPointerEnter: () => {
                    if (!dragging) {
                        onHoverChange(outline.key);
                    }
                }, onPointerLeave: () => {
                    if (!dragging) {
                        onHoverChange(null);
                    }
                }, onPointerDown: onPointerDown }), jsx_runtime_1.jsx(ContextMenu_1.ContextMenuForTarget, { triggerRef: circleRef, values: [...contextMenuValues], onOpen: onContextMenuOpen })
        ] }));
};
const SelectedOutlineElement = ({ allDragTargets, allDragOutlines, allRotationDragTargets, allScaleDragTargets, dragging, hovered, outline, onDraggingChange, onHoverChange, onSnapPointsChange, onSelect, scale, snapTargets, target, }) => {
    const { previewServerState } = (0, react_1.useContext)(client_id_1.StudioServerConnectionCtx);
    const { setPropStatuses } = (0, react_1.useContext)(remotion_1.Internals.VisualModeSettersContext);
    const updateResolvedStackTrace = (0, react_1.useContext)(remotion_1.Internals.SequenceStackTracesUpdateContext);
    const confirm = (0, ConfirmationDialog_1.useConfirmationDialog)();
    const selectAsset = (0, use_select_asset_1.useSelectAsset)();
    const selectComposition = (0, InitialCompositionLoader_1.useSelectComposition)();
    const { compositions } = (0, react_1.useContext)(remotion_1.Internals.CompositionManager);
    const { setSelectedModal } = (0, react_1.useContext)(modals_1.ModalsContext);
    const resolveOriginalLocation = react_1.default.useCallback(async (resolveTarget) => {
        const stack = resolveTarget.sequence.getStack();
        if (!stack) {
            return null;
        }
        let originalLocation = null;
        try {
            originalLocation = await (0, get_stack_1.getOriginalLocationFromStack)(stack, 'sequence');
        }
        catch (err) {
            (0, NotificationCenter_1.showNotification)(err.message, 2000);
        }
        updateResolvedStackTrace(stack, originalLocation);
        return originalLocation;
    }, [updateResolvedStackTrace]);
    const onDoubleClickTarget = react_1.default.useCallback((doubleClickTarget, button) => {
        const connectedCompositions = (0, get_connected_compositions_1.getConnectedCompositions)({
            compositions,
            singleChildComponent: doubleClickTarget.sequence.singleChildComponent,
        });
        const action = (0, get_sequence_double_click_action_1.getSequenceDoubleClickAction)({
            button,
            canOpenInEditor: previewServerState.type === 'connected' &&
                Boolean(window.remotion_editorName),
            numberOfConnectedCompositions: connectedCompositions.length,
        });
        if (action === null) {
            return false;
        }
        if (action === 'open-connected-composition') {
            selectComposition(connectedCompositions[0], true);
            return true;
        }
        const openTargetInEditor = async () => {
            const originalLocation = await resolveOriginalLocation(doubleClickTarget);
            if (originalLocation === null) {
                return;
            }
            await (0, open_in_editor_1.openOriginalPositionInEditor)(originalLocation);
        };
        openTargetInEditor().catch((err) => {
            (0, NotificationCenter_1.showNotification)(err.message, 2000);
        });
        return true;
    }, [
        compositions,
        previewServerState.type,
        resolveOriginalLocation,
        selectComposition,
    ]);
    const onContextMenuOpen = react_1.default.useCallback(async () => {
        if (target === undefined || previewServerState.type !== 'connected') {
            return false;
        }
        if (!target.selected) {
            onSelect(target.selection, { shiftKey: false, toggleKey: false });
        }
        const originalLocation = await resolveOriginalLocation(target);
        const fileLocation = (0, format_file_location_1.formatFileLocation)({
            location: originalLocation,
            root: window.remotion_cwd,
        });
        const nodePath = target.nodePathInfo.sequenceSubscriptionKey;
        const mediaSrc = target.sequence.type === 'audio' ||
            target.sequence.type === 'video' ||
            target.sequence.type === 'image'
            ? target.sequence.src
            : null;
        const assetLinkInfo = mediaSrc ? (0, timeline_asset_link_1.getTimelineAssetLinkInfo)(mediaSrc) : null;
        const canOpenInEditor = Boolean(window.remotion_editorName && originalLocation);
        const disableInteractivityDisabled = !target.sequence.showInTimeline;
        const sourceEditDisabled = !target.sequence.controls || !nodePath.absolutePath;
        const canAddEffect = target.nodePathInfo.supportsEffects &&
            !sourceEditDisabled &&
            previewServerState.type === 'connected';
        return (0, get_sequence_context_menu_items_1.getSequenceContextMenuItems)({
            assetLinkInfo,
            canOpenInEditor,
            deleteDisabled: sourceEditDisabled,
            disableInteractivityDisabled,
            duplicateDisabled: sourceEditDisabled,
            fileLocation,
            includeSourceEditItems: true,
            onDeleteSequenceFromSource: async () => {
                if (sourceEditDisabled || previewServerState.type !== 'connected') {
                    return;
                }
                if (target.nodePathInfo.numberOfSequencesWithThisNodePath > 1) {
                    const shouldDelete = await confirm({
                        title: 'Delete sequence?',
                        message: 'This sequence is programmatically duplicated ' +
                            target.nodePathInfo.numberOfSequencesWithThisNodePath +
                            ' times in the code. Deleting removes all instances. Continue?',
                        confirmLabel: 'Delete',
                    });
                    if (!shouldDelete) {
                        return;
                    }
                }
                try {
                    const result = await (0, call_api_1.callApi)('/api/delete-jsx-node', {
                        nodes: [
                            {
                                fileName: nodePath.absolutePath,
                                nodePath: nodePath.nodePath,
                            },
                        ],
                    });
                    if (result.success) {
                        (0, NotificationCenter_1.showNotification)('Removed sequence from source file', 2000);
                    }
                    else {
                        (0, NotificationCenter_1.showNotification)(result.reason, 4000);
                    }
                }
                catch (err) {
                    (0, NotificationCenter_1.showNotification)(err.message, 4000);
                }
            },
            onDisableSequenceInteractivity: () => {
                if (disableInteractivityDisabled ||
                    previewServerState.type !== 'connected') {
                    return;
                }
                (0, disable_sequence_interactivity_1.disableSequenceInteractivity)({
                    fileName: nodePath.absolutePath,
                    nodePath,
                    setPropStatuses,
                    clientId: previewServerState.clientId,
                });
            },
            onDuplicateSequenceFromSource: () => {
                if (sourceEditDisabled) {
                    return;
                }
                (0, duplicate_selected_timeline_item_1.duplicateSequencesFromSource)([target.nodePathInfo], confirm).catch(() => undefined);
            },
            openInEditor: () => {
                if (!originalLocation) {
                    return;
                }
                (0, open_in_editor_1.openOriginalPositionInEditor)(originalLocation).catch((err) => {
                    (0, NotificationCenter_1.showNotification)(err.message, 2000);
                });
            },
            originalLocation,
            selectAsset,
            sequence: target.sequence,
            sourceActions: [
                ...(target.nodePathInfo.supportsEffects
                    ? [
                        {
                            type: 'item',
                            id: 'add-effect',
                            keyHint: null,
                            label: 'Add effect...',
                            leftItem: null,
                            disabled: !canAddEffect,
                            onClick: () => {
                                if (!canAddEffect ||
                                    previewServerState.type !== 'connected') {
                                    return;
                                }
                                setSelectedModal({
                                    type: 'add-effect',
                                    clientId: previewServerState.clientId,
                                    fileName: nodePath.absolutePath,
                                    nodePath,
                                });
                            },
                            quickSwitcherLabel: null,
                            subMenu: null,
                            value: 'add-effect',
                        },
                        {
                            type: 'divider',
                            id: 'add-effect-divider',
                        },
                    ]
                    : []),
            ],
        });
    }, [
        confirm,
        onSelect,
        previewServerState,
        resolveOriginalLocation,
        selectAsset,
        setSelectedModal,
        setPropStatuses,
        target,
    ]);
    return (jsx_runtime_1.jsxs(jsx_runtime_1.Fragment, { children: [
            jsx_runtime_1.jsx(SelectedOutlinePolygon, { allDragTargets: allDragTargets, allDragOutlines: allDragOutlines, contextMenuValues: emptyContextMenuValues, dragging: dragging, hovered: hovered, outline: outline, onContextMenuOpen: onContextMenuOpen, onDraggingChange: onDraggingChange, onHoverChange: onHoverChange, onSnapPointsChange: onSnapPointsChange, onSelect: onSelect, onDoubleClickTarget: onDoubleClickTarget, scale: scale, snapTargets: snapTargets, target: target }), (target === null || target === void 0 ? void 0 : target.containsSelection) || hovered
                ? ['top', 'right', 'bottom', 'left'].map((edge) => (jsx_runtime_1.jsx(SelectedOutlineScaleEdgeLine, { allScaleDragTargets: allScaleDragTargets, contextMenuValues: emptyContextMenuValues, dragging: dragging, edge: edge, outline: outline, onContextMenuOpen: onContextMenuOpen, onDraggingChange: onDraggingChange, onHoverChange: onHoverChange, onSelect: onSelect, target: target }, edge)))
                : null, (target === null || target === void 0 ? void 0 : target.containsSelection) || hovered
                ? ['top-left', 'top-right', 'bottom-right', 'bottom-left'].map((corner) => (jsx_runtime_1.jsx(SelectedOutlineRotationCornerHandle, { allRotationDragTargets: allRotationDragTargets, contextMenuValues: emptyContextMenuValues, corner: corner, dragging: dragging, outline: outline, onContextMenuOpen: onContextMenuOpen, onDraggingChange: onDraggingChange, onHoverChange: onHoverChange, onSelect: onSelect, target: target }, corner)))
                : null] }));
};
exports.SelectedOutlineElement = SelectedOutlineElement;
