"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.TimelineSequenceItem = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = __importStar(require("react"));
const remotion_1 = require("remotion");
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 interactivity_enabled_1 = require("../../helpers/interactivity-enabled");
const studio_runtime_config_1 = require("../../helpers/studio-runtime-config");
const timeline_layout_1 = require("../../helpers/timeline-layout");
const use_keybinding_1 = require("../../helpers/use-keybinding");
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 ExpandedTracksProvider_1 = require("../ExpandedTracksProvider");
const layout_1 = require("../layout");
const NotificationCenter_1 = require("../Notifications/NotificationCenter");
const use_select_asset_1 = require("../use-select-asset");
const disable_sequence_interactivity_1 = require("./disable-sequence-interactivity");
const duplicate_selected_timeline_item_1 = require("./duplicate-selected-timeline-item");
const get_sequence_context_menu_items_1 = require("./get-sequence-context-menu-items");
const save_sequence_prop_1 = require("./save-sequence-prop");
const timeline_asset_link_1 = require("./timeline-asset-link");
const TimelineExpandArrowButton_1 = require("./TimelineExpandArrowButton");
const TimelineExpandedSection_1 = require("./TimelineExpandedSection");
const TimelineLayerEye_1 = require("./TimelineLayerEye");
const TimelineMediaInfo_1 = require("./TimelineMediaInfo");
const TimelineRowChrome_1 = require("./TimelineRowChrome");
const TimelineSelection_1 = require("./TimelineSelection");
const TimelineSequenceName_1 = require("./TimelineSequenceName");
const use_open_sequence_in_editor_1 = require("./use-open-sequence-in-editor");
const use_rename_sequence_1 = require("./use-rename-sequence");
const use_sequence_freeze_frame_menu_item_1 = require("./use-sequence-freeze-frame-menu-item");
const use_timeline_expanded_tree_1 = require("./use-timeline-expanded-tree");
const labelContainerStyle = {
    alignItems: 'center',
    alignSelf: 'stretch',
    display: 'flex',
    flexDirection: 'row',
    minWidth: 0,
};
const effectDropHighlight = {
    backgroundColor: colors_1.TIMELINE_DROP_BLUE_ALPHA_16,
    outline: colors_1.BORDER_TIMELINE_DROP_BLUE,
    outlineOffset: -1,
};
const SEQUENCE_REORDER_MIME_TYPE = 'application/remotion-sequence-reorder';
let currentSequenceDrag = null;
const TimelineSequenceExpandArrow = ({ disabled, isExpanded, nodePathInfo, onToggleExpand, sequence }) => {
    const { filteredTree } = (0, use_timeline_expanded_tree_1.useTimelineExpandedTree)({
        sequence,
        nodePathInfo,
        includeTextContent: false,
    });
    if (filteredTree.length === 0) {
        return jsx_runtime_1.jsx(TimelineExpandArrowButton_1.TimelineExpandArrowSpacer, {});
    }
    return (jsx_runtime_1.jsx(TimelineExpandArrowButton_1.TimelineExpandArrowButton, { isExpanded: isExpanded, onClick: onToggleExpand, label: "track properties", disabled: disabled }));
};
const sequenceReorderWrapper = {
    position: 'relative',
};
const sequenceReorderLineBase = {
    backgroundColor: colors_1.TIMELINE_BLUE,
    height: 2,
    left: 0,
    pointerEvents: 'none',
    position: 'absolute',
    right: 0,
    zIndex: 1,
};
const sequenceReorderRejectionStyle = {
    backgroundColor: colors_1.BLACK_ALPHA_85,
    border: colors_1.BORDER_WHITE_ALPHA_20,
    borderRadius: 4,
    color: colors_1.WHITE,
    fontSize: 11,
    lineHeight: 1.2,
    maxWidth: 260,
    padding: '3px 6px',
    pointerEvents: 'none',
    position: 'absolute',
    right: 6,
    top: 2,
    zIndex: 2,
};
const hasSequenceReorderDragType = (dataTransfer) => {
    return Array.from(dataTransfer.types).includes(SEQUENCE_REORDER_MIME_TYPE);
};
const isSequenceReorderDrag = (dataTransfer) => {
    return (currentSequenceDrag !== null || hasSequenceReorderDragType(dataTransfer));
};
const getSequenceReorderDragData = (dataTransfer) => {
    if (currentSequenceDrag) {
        return currentSequenceDrag;
    }
    const value = dataTransfer.getData(SEQUENCE_REORDER_MIME_TYPE);
    if (!value) {
        return null;
    }
    try {
        const parsed = JSON.parse(value);
        if (typeof parsed.nodePathKey === 'string' &&
            typeof parsed.trackIndex === 'number' &&
            (typeof parsed.parentId === 'string' || parsed.parentId === null) &&
            typeof parsed.fileName === 'string' &&
            parsed.nodePath &&
            Array.isArray(parsed.nodePath.nodePath)) {
            return parsed;
        }
    }
    catch (_a) {
        return null;
    }
    return null;
};
const getDestinationIndex = ({ fromIndex, insertionIndex, }) => {
    return insertionIndex > fromIndex ? insertionIndex - 1 : insertionIndex;
};
const TimelineSequenceItem = ({ nestedDepth, sequence, nodePathInfo, keyframeDisplayOffset, sequenceFrameOffset, trackIndex, }) => {
    var _a, _b, _c;
    var _d, _e, _f;
    const nodePath = (_d = nodePathInfo === null || nodePathInfo === void 0 ? void 0 : nodePathInfo.sequenceSubscriptionKey) !== null && _d !== void 0 ? _d : null;
    const { previewServerState } = (0, react_1.useContext)(client_id_1.StudioServerConnectionCtx);
    const previewConnected = previewServerState.type === 'connected';
    const previewInteractive = previewConnected && interactivity_enabled_1.studioInteractivityEnabled;
    const { getIsExpanded } = (0, react_1.useContext)(ExpandedTracksProvider_1.ExpandedTracksGetterContext);
    const { toggleTrack } = (0, react_1.useContext)(ExpandedTracksProvider_1.ExpandedTracksSetterContext);
    const { setPropStatuses } = (0, react_1.useContext)(remotion_1.Internals.VisualModeSettersContext);
    const { setSelectedModal } = (0, react_1.useContext)(modals_1.ModalsContext);
    const { isHighestContext } = (0, use_keybinding_1.useKeybinding)();
    const selectAsset = (0, use_select_asset_1.useSelectAsset)();
    const { onSelect, selectable, selected, selectionItem } = (0, TimelineSelection_1.useTimelineRowSelection)(nodePathInfo);
    const { selectedItems } = (0, TimelineSelection_1.useTimelineSelection)();
    const containsSelection = (0, TimelineSelection_1.useTimelineRowContainsSelection)(nodePathInfo);
    const [effectDropHovered, setEffectDropHovered] = (0, react_1.useState)(false);
    const [isRenaming, setIsRenaming] = (0, react_1.useState)(false);
    const [sequenceDropIndicator, setSequenceDropIndicator] = (0, react_1.useState)(null);
    const [sequenceDropRejection, setSequenceDropRejection] = (0, react_1.useState)(null);
    const timelinePosition = remotion_1.Internals.Timeline.useTimelinePosition();
    const { canOpenInEditor, openInEditor, originalLocation } = (0, use_open_sequence_in_editor_1.useOpenSequenceInEditor)(sequence);
    const fileLocation = (0, react_1.useMemo)(() => (0, format_file_location_1.formatFileLocation)({
        location: originalLocation,
        root: window.remotion_cwd,
    }), [originalLocation]);
    const validatedLocation = (0, react_1.useMemo)(() => {
        var _a;
        if (!originalLocation ||
            !originalLocation.source ||
            !originalLocation.line) {
            return null;
        }
        return {
            source: originalLocation.source,
            line: originalLocation.line,
            column: (_a = originalLocation.column) !== null && _a !== void 0 ? _a : 0,
        };
    }, [originalLocation]);
    const { canRename: canRenameThisSequence, displayName, fallbackDisplayName, propStatusesForOverride, saveName, } = (0, use_rename_sequence_1.useRenameSequence)({
        clientId: previewInteractive && previewServerState.type === 'connected'
            ? previewServerState.clientId
            : null,
        nodePathInfo,
        sequence,
        validatedLocation,
    });
    const canDeleteFromSource = Boolean(nodePath && (validatedLocation === null || validatedLocation === void 0 ? void 0 : validatedLocation.source));
    const nodePathKey = (0, react_1.useMemo)(() => nodePath ? remotion_1.Internals.makeSequencePropsSubscriptionKey(nodePath) : null, [nodePath]);
    const parentId = (_e = sequence.parent) !== null && _e !== void 0 ? _e : null;
    const canReorderSequence = previewInteractive &&
        Boolean(nodePath && nodePathKey && (validatedLocation === null || validatedLocation === void 0 ? void 0 : validatedLocation.source)) &&
        (nodePathInfo === null || nodePathInfo === void 0 ? void 0 : nodePathInfo.numberOfSequencesWithThisNodePath) === 1;
    const canHandleSequenceDrag = previewInteractive;
    const confirm = (0, ConfirmationDialog_1.useConfirmationDialog)();
    const deleteDisabled = (0, react_1.useMemo)(() => !previewInteractive || !sequence.controls || !canDeleteFromSource, [previewInteractive, sequence.controls, canDeleteFromSource]);
    const duplicateDisabled = deleteDisabled;
    const disableInteractivityDisabled = !previewInteractive ||
        !sequence.showInTimeline ||
        !nodePath ||
        !(validatedLocation === null || validatedLocation === void 0 ? void 0 : validatedLocation.source);
    const onDuplicateSequenceFromSource = (0, react_1.useCallback)(() => {
        if (duplicateDisabled || !(validatedLocation === null || validatedLocation === void 0 ? void 0 : validatedLocation.source) || !nodePathInfo) {
            return;
        }
        (0, duplicate_selected_timeline_item_1.duplicateSequencesFromSource)([nodePathInfo], confirm).catch(() => undefined);
    }, [confirm, duplicateDisabled, nodePathInfo, validatedLocation === null || validatedLocation === void 0 ? void 0 : validatedLocation.source]);
    const onDeleteSequenceFromSource = (0, react_1.useCallback)(async () => {
        if (deleteDisabled || !(validatedLocation === null || validatedLocation === void 0 ? void 0 : validatedLocation.source) || !nodePath) {
            return;
        }
        if (nodePathInfo && nodePathInfo.numberOfSequencesWithThisNodePath > 1) {
            const shouldDelete = await confirm({
                title: 'Delete sequence?',
                message: 'This sequence is programmatically duplicated ' +
                    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: validatedLocation.source,
                        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);
        }
    }, [
        confirm,
        deleteDisabled,
        nodePath,
        validatedLocation === null || validatedLocation === void 0 ? void 0 : validatedLocation.source,
        nodePathInfo,
    ]);
    const onDisableSequenceInteractivity = (0, react_1.useCallback)(() => {
        if (disableInteractivityDisabled ||
            !nodePath ||
            !(validatedLocation === null || validatedLocation === void 0 ? void 0 : validatedLocation.source) ||
            previewServerState.type !== 'connected') {
            return;
        }
        (0, disable_sequence_interactivity_1.disableSequenceInteractivity)({
            fileName: validatedLocation.source,
            nodePath,
            setPropStatuses,
            clientId: previewServerState.clientId,
        });
    }, [
        disableInteractivityDisabled,
        nodePath,
        previewServerState,
        setPropStatuses,
        validatedLocation === null || validatedLocation === void 0 ? void 0 : validatedLocation.source,
    ]);
    const getSequenceDropTarget = (0, react_1.useCallback)((e) => {
        const dragData = getSequenceReorderDragData(e.dataTransfer);
        if (!dragData) {
            return null;
        }
        if (!nodePath || !nodePathKey || !(validatedLocation === null || validatedLocation === void 0 ? void 0 : validatedLocation.source)) {
            return {
                type: 'invalid',
                reason: 'This sequence cannot be reordered from source.',
            };
        }
        if (dragData.nodePathKey === nodePathKey) {
            return {
                type: 'invalid',
                reason: 'Drop onto another sequence to reorder.',
            };
        }
        if ((nodePathInfo === null || nodePathInfo === void 0 ? void 0 : nodePathInfo.numberOfSequencesWithThisNodePath) !== 1) {
            return {
                type: 'invalid',
                reason: 'Programmatically duplicated sequences cannot be reordered.',
            };
        }
        if (dragData.parentId !== parentId ||
            dragData.fileName !== validatedLocation.source) {
            return {
                type: 'invalid',
                reason: 'Sequences can only be reordered with direct JSX siblings.',
            };
        }
        const rect = e.currentTarget.getBoundingClientRect();
        const before = e.clientY < rect.top + rect.height / 2;
        const insertionIndex = before ? trackIndex : trackIndex + 1;
        const toIndex = getDestinationIndex({
            fromIndex: dragData.trackIndex,
            insertionIndex,
        });
        if (toIndex === dragData.trackIndex) {
            return {
                type: 'invalid',
                reason: 'This sequence is already in that position.',
            };
        }
        return {
            type: 'valid',
            dragData,
            position: before ? 'before' : 'after',
        };
    }, [
        nodePath,
        nodePathInfo === null || nodePathInfo === void 0 ? void 0 : nodePathInfo.numberOfSequencesWithThisNodePath,
        nodePathKey,
        parentId,
        trackIndex,
        validatedLocation === null || validatedLocation === void 0 ? void 0 : validatedLocation.source,
    ]);
    const onSequenceDragStart = (0, react_1.useCallback)((e) => {
        if (!canReorderSequence ||
            !nodePath ||
            !nodePathKey ||
            !(validatedLocation === null || validatedLocation === void 0 ? void 0 : validatedLocation.source)) {
            e.preventDefault();
            return;
        }
        const dragData = {
            nodePath,
            nodePathKey,
            trackIndex,
            parentId,
            fileName: validatedLocation.source,
        };
        currentSequenceDrag = dragData;
        e.dataTransfer.effectAllowed = 'move';
        e.dataTransfer.setData(SEQUENCE_REORDER_MIME_TYPE, JSON.stringify(dragData));
        e.stopPropagation();
    }, [
        canReorderSequence,
        nodePath,
        nodePathKey,
        parentId,
        trackIndex,
        validatedLocation === null || validatedLocation === void 0 ? void 0 : validatedLocation.source,
    ]);
    const onSequenceDragEnd = (0, react_1.useCallback)(() => {
        currentSequenceDrag = null;
        setSequenceDropIndicator(null);
        setSequenceDropRejection(null);
    }, []);
    const onSequenceDragOver = (0, react_1.useCallback)((e) => {
        if (!hasSequenceReorderDragType(e.dataTransfer)) {
            return;
        }
        const dropTarget = getSequenceDropTarget(e);
        if (!dropTarget) {
            setSequenceDropIndicator(null);
            setSequenceDropRejection(null);
            return;
        }
        if (dropTarget.type === 'invalid') {
            setSequenceDropIndicator(null);
            setSequenceDropRejection(dropTarget.reason);
            e.dataTransfer.dropEffect = 'none';
            return;
        }
        e.preventDefault();
        e.stopPropagation();
        e.dataTransfer.dropEffect = 'move';
        setSequenceDropIndicator(dropTarget.position);
        setSequenceDropRejection(null);
    }, [getSequenceDropTarget]);
    const onSequenceDragLeave = (0, react_1.useCallback)((e) => {
        if (e.currentTarget.contains(e.relatedTarget)) {
            return;
        }
        setSequenceDropIndicator(null);
        setSequenceDropRejection(null);
    }, []);
    const onSequenceDrop = (0, react_1.useCallback)(async (e) => {
        if (!canReorderSequence ||
            previewServerState.type !== 'connected' ||
            !nodePath ||
            !(validatedLocation === null || validatedLocation === void 0 ? void 0 : validatedLocation.source)) {
            return;
        }
        const dropTarget = getSequenceDropTarget(e);
        if (!dropTarget || dropTarget.type === 'invalid') {
            setSequenceDropIndicator(null);
            setSequenceDropRejection((dropTarget === null || dropTarget === void 0 ? void 0 : dropTarget.type) === 'invalid' ? dropTarget.reason : null);
            return;
        }
        e.preventDefault();
        e.stopPropagation();
        setSequenceDropIndicator(null);
        setSequenceDropRejection(null);
        currentSequenceDrag = null;
        try {
            const result = await (0, call_api_1.callApi)('/api/reorder-sequence', {
                fileName: validatedLocation.source,
                sourceNodePath: dropTarget.dragData.nodePath,
                targetNodePath: nodePath,
                position: dropTarget.position,
                clientId: previewServerState.clientId,
            });
            if (result.success) {
                (0, NotificationCenter_1.showNotification)('Reordered sequence', 2000);
            }
            else {
                (0, NotificationCenter_1.showNotification)(result.reason, 4000);
            }
        }
        catch (err) {
            (0, NotificationCenter_1.showNotification)(err.message, 4000);
        }
    }, [
        canReorderSequence,
        getSequenceDropTarget,
        nodePath,
        previewServerState,
        validatedLocation === null || validatedLocation === void 0 ? void 0 : validatedLocation.source,
    ]);
    const mediaSrc = sequence.type === 'audio' ||
        sequence.type === 'video' ||
        sequence.type === 'image'
        ? sequence.src
        : null;
    const assetLinkInfo = (0, react_1.useMemo)(() => (mediaSrc ? (0, timeline_asset_link_1.getTimelineAssetLinkInfo)(mediaSrc) : null), [mediaSrc]);
    const isExpanded = previewConnected && nodePathInfo !== null && getIsExpanded(nodePathInfo);
    const onToggleExpand = (0, react_1.useCallback)(() => {
        if (nodePathInfo === null) {
            return;
        }
        toggleTrack(nodePathInfo);
    }, [nodePathInfo, toggleTrack]);
    const codeHiddenStatus = propStatusesForOverride === null || propStatusesForOverride === void 0 ? void 0 : propStatusesForOverride.hidden;
    const isItemHidden = (0, react_1.useMemo)(() => {
        var _a;
        const propStatus = codeHiddenStatus && codeHiddenStatus.status === 'static'
            ? codeHiddenStatus.codeValue
            : undefined;
        const runtimeValue = (_a = sequence.controls) === null || _a === void 0 ? void 0 : _a.currentRuntimeValueDotNotation.hidden;
        const effective = (propStatus !== null && propStatus !== void 0 ? propStatus : runtimeValue);
        return effective !== null && effective !== void 0 ? effective : false;
    }, [codeHiddenStatus, (_a = sequence.controls) === null || _a === void 0 ? void 0 : _a.currentRuntimeValueDotNotation]);
    const onToggleVisibility = (0, react_1.useCallback)((type) => {
        if (!sequence.controls ||
            !nodePath ||
            !validatedLocation ||
            !propStatusesForOverride ||
            !codeHiddenStatus ||
            codeHiddenStatus.status !== 'static' ||
            previewServerState.type !== 'connected') {
            return;
        }
        const newValue = type !== 'enable';
        const { schema } = sequence.controls;
        const fieldSchema = schema.hidden;
        const defaultValue = fieldSchema && fieldSchema.type === 'boolean'
            ? JSON.stringify(fieldSchema.default)
            : null;
        (0, save_sequence_prop_1.saveSequenceProps)({
            changes: [
                {
                    fileName: validatedLocation.source,
                    nodePath,
                    fieldKey: 'hidden',
                    value: newValue,
                    defaultValue,
                    schema,
                },
            ],
            setPropStatuses,
            clientId: previewServerState.clientId,
            undoLabel: newValue ? 'Hide sequence' : 'Show sequence',
            redoLabel: newValue ? 'Hide sequence again' : 'Show sequence again',
        });
    }, [
        codeHiddenStatus,
        propStatusesForOverride,
        nodePath,
        previewServerState,
        sequence.controls,
        setPropStatuses,
        validatedLocation,
    ]);
    const outerHeight = (0, react_1.useMemo)(() => (0, timeline_layout_1.getTimelineLayerHeight)(sequence.type) + timeline_layout_1.TIMELINE_ITEM_BORDER_BOTTOM, [sequence.type]);
    const inner = (0, react_1.useMemo)(() => {
        return {
            height: timeline_layout_1.TIMELINE_LIST_ITEM_ROW_HEIGHT,
            color: colors_1.WHITE,
            fontFamily: 'Arial, Helvetica, sans-serif',
            wordBreak: 'break-all',
            textAlign: 'left',
            flexShrink: 0,
        };
    }, []);
    const rowStyle = (0, react_1.useMemo)(() => {
        return effectDropHovered
            ? {
                ...inner,
                ...effectDropHighlight,
            }
            : inner;
    }, [effectDropHovered, inner]);
    const hasExpandableContent = interactivity_enabled_1.studioInteractivityEnabled &&
        (Boolean(sequence.controls) || sequence.effects.length > 0);
    const canToggleVisibility = previewInteractive &&
        Boolean(sequence.controls) &&
        nodePath !== null &&
        validatedLocation !== null &&
        codeHiddenStatus !== undefined &&
        codeHiddenStatus !== null &&
        codeHiddenStatus.status === 'static';
    const onShowInEditorDoubleClick = (0, react_1.useCallback)((e) => {
        if (!canOpenInEditor) {
            return;
        }
        if ((0, TimelineSelection_1.isTimelineSelectionModifierEvent)(e)) {
            e.stopPropagation();
            return;
        }
        e.stopPropagation();
        openInEditor();
    }, [canOpenInEditor, openInEditor]);
    const canRenameSelectedSequence = canRenameThisSequence &&
        selected &&
        selectedItems.length === 1 &&
        ((_b = selectedItems[0]) === null || _b === void 0 ? void 0 : _b.type) === 'sequence';
    const onCancelRenaming = (0, react_1.useCallback)(() => {
        setIsRenaming(false);
    }, []);
    const onSaveName = (0, react_1.useCallback)(async (name) => {
        setIsRenaming(false);
        await saveName(name);
    }, [saveName]);
    react_1.default.useEffect(() => {
        if (!canRenameSelectedSequence || !(0, studio_runtime_config_1.getStudioKeyboardShortcutsEnabled)()) {
            setIsRenaming(false);
            return;
        }
        const onKeyDown = (e) => {
            if (!isHighestContext) {
                return;
            }
            const commandKey = window.navigator.platform.startsWith('Mac')
                ? e.metaKey
                : e.ctrlKey;
            if (commandKey || e.key.toLowerCase() !== 'enter') {
                return;
            }
            if (document.activeElement instanceof HTMLInputElement ||
                document.activeElement instanceof HTMLTextAreaElement) {
                return;
            }
            e.preventDefault();
            e.stopImmediatePropagation();
            setIsRenaming(true);
        };
        window.addEventListener('keydown', onKeyDown, true);
        return () => {
            window.removeEventListener('keydown', onKeyDown, true);
        };
    }, [canRenameSelectedSequence, isHighestContext]);
    const onRenameSequence = (0, react_1.useCallback)(() => {
        if (!canRenameThisSequence) {
            return;
        }
        setIsRenaming(true);
    }, [canRenameThisSequence]);
    const freezeFrameMenuItem = (0, use_sequence_freeze_frame_menu_item_1.useSequenceFreezeFrameMenuItem)({
        clientId: previewInteractive && previewServerState.type === 'connected'
            ? previewServerState.clientId
            : null,
        nodePath,
        propStatusesForOverride,
        sequence,
        sequenceFrameOffset,
        setPropStatuses,
        timelinePosition,
        validatedSource: (_f = validatedLocation === null || validatedLocation === void 0 ? void 0 : validatedLocation.source) !== null && _f !== void 0 ? _f : null,
    });
    const canAddEffect = (nodePathInfo === null || nodePathInfo === void 0 ? void 0 : nodePathInfo.supportsEffects) === true &&
        previewInteractive &&
        Boolean(validatedLocation === null || validatedLocation === void 0 ? void 0 : validatedLocation.source);
    const onAddEffect = (0, react_1.useCallback)(() => {
        if (!canAddEffect ||
            previewServerState.type !== 'connected' ||
            !nodePath ||
            !(validatedLocation === null || validatedLocation === void 0 ? void 0 : validatedLocation.source)) {
            return;
        }
        setSelectedModal({
            type: 'add-effect',
            clientId: previewServerState.clientId,
            fileName: validatedLocation.source,
            nodePath,
        });
    }, [
        canAddEffect,
        nodePath,
        previewServerState,
        setSelectedModal,
        validatedLocation === null || validatedLocation === void 0 ? void 0 : validatedLocation.source,
    ]);
    const contextMenuValues = (0, react_1.useMemo)(() => {
        if (!previewConnected) {
            return [];
        }
        return (0, get_sequence_context_menu_items_1.getSequenceContextMenuItems)({
            assetLinkInfo,
            canOpenInEditor,
            deleteDisabled,
            disableInteractivityDisabled,
            duplicateDisabled,
            fileLocation,
            includeSourceEditItems: interactivity_enabled_1.studioInteractivityEnabled,
            onDeleteSequenceFromSource,
            onDisableSequenceInteractivity,
            onDuplicateSequenceFromSource,
            openInEditor,
            originalLocation,
            selectAsset,
            sequence,
            sourceActions: interactivity_enabled_1.studioInteractivityEnabled
                ? [
                    ...((nodePathInfo === null || nodePathInfo === void 0 ? void 0 : nodePathInfo.supportsEffects)
                        ? [
                            {
                                type: 'item',
                                id: 'add-effect',
                                keyHint: null,
                                label: 'Add effect...',
                                leftItem: null,
                                disabled: !canAddEffect,
                                onClick: onAddEffect,
                                quickSwitcherLabel: null,
                                subMenu: null,
                                value: 'add-effect',
                            },
                            {
                                type: 'divider',
                                id: 'add-effect-divider',
                            },
                        ]
                        : []),
                    {
                        type: 'item',
                        id: 'rename-sequence',
                        keyHint: null,
                        label: 'Rename...',
                        leftItem: null,
                        disabled: !canRenameThisSequence,
                        onClick: () => {
                            onRenameSequence();
                        },
                        quickSwitcherLabel: null,
                        subMenu: null,
                        value: 'rename-sequence',
                    },
                    ...(freezeFrameMenuItem ? [freezeFrameMenuItem] : []),
                ]
                : [],
        });
    }, [
        assetLinkInfo,
        canAddEffect,
        canOpenInEditor,
        canRenameThisSequence,
        deleteDisabled,
        disableInteractivityDisabled,
        duplicateDisabled,
        fileLocation,
        freezeFrameMenuItem,
        nodePathInfo === null || nodePathInfo === void 0 ? void 0 : nodePathInfo.supportsEffects,
        onAddEffect,
        onDeleteSequenceFromSource,
        onDisableSequenceInteractivity,
        onDuplicateSequenceFromSource,
        onRenameSequence,
        openInEditor,
        originalLocation,
        previewConnected,
        selectAsset,
        sequence,
    ]);
    const canDropEffect = previewInteractive &&
        nodePath !== null &&
        validatedLocation !== null &&
        ((_c = sequence.controls) === null || _c === void 0 ? void 0 : _c.supportsEffects) === true;
    const sequenceReorderLineStyle = (0, react_1.useMemo)(() => {
        if (!sequenceDropIndicator) {
            return null;
        }
        return {
            ...sequenceReorderLineBase,
            ...(sequenceDropIndicator === 'before' ? { top: -1 } : { bottom: -1 }),
        };
    }, [sequenceDropIndicator]);
    const onEffectDragOver = (0, react_1.useCallback)((e) => {
        if (!canDropEffect ||
            isSequenceReorderDrag(e.dataTransfer) ||
            !(0, effect_drag_and_drop_1.hasEffectDragType)(e.dataTransfer)) {
            return;
        }
        e.preventDefault();
        e.dataTransfer.dropEffect = 'copy';
        setEffectDropHovered(true);
    }, [canDropEffect]);
    const onEffectDragLeave = (0, react_1.useCallback)((e) => {
        if (e.currentTarget.contains(e.relatedTarget)) {
            return;
        }
        setEffectDropHovered(false);
    }, []);
    const onEffectDrop = (0, react_1.useCallback)(async (e) => {
        if (!canDropEffect ||
            previewServerState.type !== 'connected' ||
            nodePath === null ||
            validatedLocation === null ||
            isSequenceReorderDrag(e.dataTransfer) ||
            !(0, effect_drag_and_drop_1.hasEffectDragType)(e.dataTransfer)) {
            return;
        }
        const dragData = (0, effect_drag_and_drop_1.getEffectDragData)(e.dataTransfer);
        if (!dragData) {
            if ((0, effect_drag_and_drop_1.hasExplicitEffectDragType)(e.dataTransfer)) {
                e.preventDefault();
                e.stopPropagation();
                setEffectDropHovered(false);
                (0, NotificationCenter_1.showNotification)('Could not read effect drag data', 3000);
            }
            return;
        }
        e.preventDefault();
        e.stopPropagation();
        setEffectDropHovered(false);
        await (0, effect_drag_and_drop_1.addEffectFromDragData)({
            dragData,
            fileName: validatedLocation.source,
            nodePath,
            clientId: previewServerState.clientId,
        });
    }, [canDropEffect, nodePath, previewServerState, validatedLocation]);
    const trackRow = (jsx_runtime_1.jsx(TimelineRowChrome_1.TimelineRowChrome, { depth: nestedDepth, eye: canToggleVisibility ? (jsx_runtime_1.jsx(TimelineLayerEye_1.TimelineLayerEye, { type: sequence.type === 'audio' ? 'speaker' : 'eye', hidden: isItemHidden, onInvoked: onToggleVisibility })) : (jsx_runtime_1.jsx(TimelineLayerEye_1.TimelineLayerEyeSpacer, {})), arrow: hasExpandableContent && nodePathInfo !== null ? (jsx_runtime_1.jsx(TimelineSequenceExpandArrow, { disabled: !previewInteractive, isExpanded: isExpanded, nodePathInfo: nodePathInfo, onToggleExpand: onToggleExpand, sequence: sequence })) : (jsx_runtime_1.jsx(TimelineExpandArrowButton_1.TimelineExpandArrowSpacer, {})), style: rowStyle, selected: selected, selectable: selectable, selectionItem: selectionItem, onSelect: onSelect, showSelectedBackground: true, containsSelection: containsSelection, outerHeight: outerHeight, onDragLeave: canDropEffect ? onEffectDragLeave : undefined, onDragOver: canDropEffect ? onEffectDragOver : undefined, onDrop: canDropEffect ? onEffectDrop : undefined, onDoubleClick: canOpenInEditor ? onShowInEditorDoubleClick : undefined, children: jsx_runtime_1.jsxs("div", { style: labelContainerStyle, children: [
                jsx_runtime_1.jsx(TimelineSequenceName_1.TimelineSequenceName, { displayName: displayName, fallbackDisplayName: fallbackDisplayName, selected: selected, containsSelection: containsSelection, editing: isRenaming, onCancelEditing: onCancelRenaming, onSaveName: onSaveName }), mediaSrc ? (jsx_runtime_1.jsxs(jsx_runtime_1.Fragment, { children: [
                        jsx_runtime_1.jsx(layout_1.Spacing, { x: 0.5 }),
                        " ",
                        jsx_runtime_1.jsx(TimelineMediaInfo_1.TimelineMediaInfo, { src: mediaSrc })
                    ] })) : null] }) }));
    const draggableTrackRow = canHandleSequenceDrag ? (jsx_runtime_1.jsxs("div", { draggable: canReorderSequence, onDragStart: onSequenceDragStart, onDragEnd: onSequenceDragEnd, onDragOver: onSequenceDragOver, onDragLeave: onSequenceDragLeave, onDrop: onSequenceDrop, style: sequenceReorderWrapper, children: [sequenceReorderLineStyle ? (jsx_runtime_1.jsx("div", { style: sequenceReorderLineStyle })) : null, sequenceDropRejection ? (jsx_runtime_1.jsx("div", { style: sequenceReorderRejectionStyle, children: sequenceDropRejection })) : null, trackRow] })) : (trackRow);
    return (jsx_runtime_1.jsxs(jsx_runtime_1.Fragment, { children: [previewConnected ? (jsx_runtime_1.jsx(ContextMenu_1.ContextMenu, { values: contextMenuValues, onOpen: selectable ? onSelect : null, children: draggableTrackRow })) : (draggableTrackRow), previewConnected &&
                interactivity_enabled_1.studioInteractivityEnabled &&
                isExpanded &&
                hasExpandableContent &&
                nodePathInfo &&
                validatedLocation ? (jsx_runtime_1.jsx(TimelineExpandedSection_1.TimelineExpandedSection, { sequence: sequence, validatedLocation: validatedLocation, nodePathInfo: nodePathInfo, nestedDepth: nestedDepth, keyframeDisplayOffset: keyframeDisplayOffset })) : null] }));
};
exports.TimelineSequenceItem = TimelineSequenceItem;
