"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;
    };
})();
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ACTION_CELL_WIDTH = exports.DataTableTr = void 0;
const react_1 = __importStar(require("react"));
const aksel_icons_1 = require("@navikt/aksel-icons");
const button_1 = require("../../../button");
const DataGridRoot_context_1 = require("../../../data-grid/root/DataGridRoot.context");
const CheckboxInput_1 = require("../../../form/checkbox/checkbox-input/CheckboxInput");
const RadioInput_1 = require("../../../form/radio/radio-input/RadioInput");
const skeleton_1 = require("../../../skeleton");
const typography_1 = require("../../../typography");
const utils_external_1 = require("../../../utils-external");
const helpers_1 = require("../../../utils/helpers");
const consoleWarning_1 = require("../../../utils/helpers/consoleWarning");
const DataTableBaseCell_1 = require("../base-cell/DataTableBaseCell");
const DataTableColumnHeader_1 = require("../column-header/DataTableColumnHeader");
const useTableDetailsPanel_1 = require("../hooks/useTableDetailsPanel");
const DataTableRoot_context_1 = require("../root/DataTableRoot.context");
const DataTableTd_1 = require("../td/DataTableTd");
const ACTION_CELL_WIDTH = 50;
exports.ACTION_CELL_WIDTH = ACTION_CELL_WIDTH;
const ACTION_CELL_CSS_WIDTH = `${ACTION_CELL_WIDTH}px`;
const DataTableTr = (0, react_1.forwardRef)((_a, forwardedRef) => {
    var _b;
    var { className, children, selected: selectedProp = false, rowId, onClick } = _a, rest = __rest(_a, ["className", "children", "selected", "rowId", "onClick"]);
    const { layout, selectionState, onRowAction, tableItems } = (0, DataTableRoot_context_1.useDataTableContext)();
    const { location } = (0, DataTableRoot_context_1.useDataTableLocation)();
    const renderFillerCell = layout === "fixed" && children;
    const selected = (_b = selectionState.selection.isRowSelected(rowId !== null && rowId !== void 0 ? rowId : "")) !== null && _b !== void 0 ? _b : selectedProp;
    const handleClick = location === "tbody" &&
        rowId !== undefined &&
        ((selectionState.selectionTrigger === "row" &&
            selectionState.selection.mode !== "none") ||
            onRowAction)
        ? (event) => {
            var _a, _b, _c;
            if (rowId === undefined ||
                isInteractiveTarget(event.target) ||
                ((_a = event.target) === null || _a === void 0 ? void 0 : _a.closest("[data-prevent-row-click]"))) {
                return;
            }
            if (onRowAction) {
                const rowData = (_b = tableItems.itemDetails.get(rowId)) === null || _b === void 0 ? void 0 : _b.rowData;
                if (rowData) {
                    onRowAction({
                        row: rowData,
                        id: rowId,
                        event,
                    });
                }
                else {
                    (0, consoleWarning_1.consoleWarning)(`DataGrid.Table: Unable to find row data for rowId ${rowId} when calling onRowAction.`);
                }
            }
            if (event.defaultPrevented) {
                return;
            }
            const selection = window.getSelection();
            if (selection && selection.toString().length > 0) {
                return;
            }
            if (selectionState.selectionTrigger === "row" &&
                selectionState.selection.mode !== "none") {
                const rowData = (_c = tableItems.itemDetails.get(rowId)) === null || _c === void 0 ? void 0 : _c.rowData;
                if (!rowData) {
                    (0, consoleWarning_1.consoleWarning)(`DataGrid.Table: No row data found for rowId ${rowId}. This may cause issues with selection if enableRowSelection is used.`);
                }
                selectionState.selection.toggleSelection(rowId, rowData);
            }
        }
        : undefined;
    return (react_1.default.createElement("tr", Object.assign({}, rest, { 
        // Avoid setting onClick if not needed, since this causes NVDA to announce the row as clickable.
        onClick: (onClick || handleClick) && (0, helpers_1.composeEventHandlers)(onClick, handleClick), ref: forwardedRef, className: (0, helpers_1.cl)("aksel-data-table__tr", className), "data-selected": selected }),
        react_1.default.createElement(RowExpansionCell, { rowId: rowId }),
        react_1.default.createElement(RowSelectionCell, { rowId: rowId }),
        children,
        renderFillerCell && (react_1.default.createElement("td", { "aria-hidden": true, className: "aksel-data-table__cell aksel-data-table__filler-cell", "data-block-keyboard-nav": true }))));
});
exports.DataTableTr = DataTableTr;
function RowExpansionCell({ rowId }) {
    const { isLoading } = (0, DataGridRoot_context_1.useDataGridContext)();
    const { tableId, loading, stickyStart } = (0, DataTableRoot_context_1.useDataTableContext)();
    const stickyExpansion = stickyStart.expansion;
    const expansionHeaderId = (0, utils_external_1.useId)();
    const { location } = (0, DataTableRoot_context_1.useDataTableLocation)();
    const { isExpanded, isDetailsPanelExpandable, toggleExpansion, enableDetailsPanel, isAllExpanded, toggleAll, showExpandAll, } = (0, useTableDetailsPanel_1.useDataTableDetailsPanel)();
    if (!enableDetailsPanel) {
        return null;
    }
    if (isLoading && (loading === null || loading === void 0 ? void 0 : loading.variant) === "skeleton") {
        if (location === "thead") {
            return (react_1.default.createElement(DataTableColumnHeader_1.DataTableColumnHeader, { id: expansionHeaderId, width: { value: ACTION_CELL_CSS_WIDTH }, cellType: "action", "data-block-keyboard-nav": true, label: "", isSticky: stickyExpansion && "start", style: stickyExpansion ? { left: 0 } : undefined }));
        }
        return (react_1.default.createElement(DataTableBaseCell_1.DataTableBaseCell, { as: "td", isSticky: stickyExpansion && "start", style: stickyExpansion ? { left: 0 } : undefined },
            react_1.default.createElement(skeleton_1.Skeleton, { variant: "text" })));
    }
    if (location === "thead" && !showExpandAll) {
        return (react_1.default.createElement(DataTableColumnHeader_1.DataTableColumnHeader, { id: expansionHeaderId, width: { value: ACTION_CELL_CSS_WIDTH }, cellType: "action", "data-block-keyboard-nav": true, label: "", isSticky: stickyExpansion && "start", style: stickyExpansion ? { left: 0 } : undefined }));
    }
    if (location === "thead") {
        return (react_1.default.createElement(DataTableColumnHeader_1.DataTableColumnHeader, { id: expansionHeaderId, align: "center", width: { value: ACTION_CELL_CSS_WIDTH }, cellType: "action", label: "", isSticky: stickyExpansion && "start", style: stickyExpansion ? { left: 0 } : undefined },
            react_1.default.createElement(button_1.Button, { variant: "tertiary", "data-color": "neutral", size: "xsmall", onClick: toggleAll, "aria-expanded": isAllExpanded, "aria-label": isAllExpanded ? "Skjul alle rader" : "Vis alle rader", icon: isAllExpanded ? (react_1.default.createElement(aksel_icons_1.ChevronDownUpIcon, { "aria-hidden": true })) : (react_1.default.createElement(aksel_icons_1.ChevronUpDownIcon, { "aria-hidden": true })) })));
    }
    if (!rowId) {
        return null;
    }
    const isRowExpanded = isExpanded(rowId);
    const canExpandRow = isDetailsPanelExpandable(rowId);
    const expansionId = (0, useTableDetailsPanel_1.getDataTableDetailsPanelId)(tableId, rowId);
    if (!canExpandRow) {
        return (react_1.default.createElement(DataTableTd_1.DataTableTd, { cellType: "action", preventRowClick: true, isSticky: stickyExpansion && "start", style: stickyExpansion ? { left: 0 } : undefined }));
    }
    return (react_1.default.createElement(DataTableTd_1.DataTableTd, { cellType: "action", preventRowClick: true, isSticky: stickyExpansion && "start", style: stickyExpansion ? { left: 0 } : undefined },
        react_1.default.createElement(button_1.Button, { variant: "tertiary", "data-color": "neutral", size: "xsmall", onClick: (e) => {
                e.stopPropagation();
                toggleExpansion(rowId);
            }, "aria-expanded": isRowExpanded, "aria-controls": expansionId, "aria-label": isRowExpanded ? "Skjul detaljer" : "Vis detaljer", icon: isRowExpanded ? react_1.default.createElement(aksel_icons_1.MinusIcon, { "aria-hidden": true }) : react_1.default.createElement(aksel_icons_1.PlusIcon, { "aria-hidden": true }) })));
}
/**
 * TODO: How do these cells handle multiple thead rows, or col/row-spans?
 * TODO: a11y for labels
 */
function RowSelectionCell({ rowId }) {
    var _a, _b;
    const { isLoading } = (0, DataGridRoot_context_1.useDataGridContext)();
    const { selectionState, stickyStart, loading } = (0, DataTableRoot_context_1.useDataTableContext)();
    const stickySelection = stickyStart.selection;
    const stickySelectionOffset = stickyStart.selectionOffset;
    const { location } = (0, DataTableRoot_context_1.useDataTableLocation)();
    const { tableItems } = (0, DataTableRoot_context_1.useDataTableContext)();
    const inputId = (0, utils_external_1.useId)();
    const selectionHeaderId = (0, utils_external_1.useId)();
    const { selection, renderSelection } = selectionState;
    if (selection.mode === "none" || !renderSelection) {
        return null;
    }
    if (isLoading && (loading === null || loading === void 0 ? void 0 : loading.variant) === "skeleton") {
        if (location === "thead") {
            return (react_1.default.createElement(DataTableColumnHeader_1.DataTableColumnHeader, { id: selectionHeaderId, width: { value: ACTION_CELL_CSS_WIDTH }, cellType: "action", label: "", "data-block-keyboard-nav": true, isSticky: stickySelection && "start", style: stickySelection ? { left: stickySelectionOffset } : undefined }));
        }
        return (react_1.default.createElement(DataTableBaseCell_1.DataTableBaseCell, { as: "td", isSticky: stickySelection && "start", style: stickySelection ? { left: stickySelectionOffset } : undefined },
            react_1.default.createElement(skeleton_1.Skeleton, { variant: "text" })));
    }
    /* TODO: A11y support */
    if (selection.mode === "multiple" && location === "thead") {
        const theadCheckboxProps = selection.getTheadCheckboxProps();
        let labelText = "Velg alle synlige rader";
        if (theadCheckboxProps.checked) {
            labelText = "Fjern alle synlige valgte rader";
        }
        return (react_1.default.createElement(DataTableColumnHeader_1.DataTableColumnHeader, { id: selectionHeaderId, align: "center", width: { value: ACTION_CELL_CSS_WIDTH }, cellType: "action", label: "", isSticky: stickySelection && "start", style: stickySelection ? { left: stickySelectionOffset } : undefined },
            react_1.default.createElement(typography_1.Label, { htmlFor: inputId, visuallyHidden: true }, labelText),
            react_1.default.createElement(CheckboxInput_1.CheckboxInput, Object.assign({}, theadCheckboxProps, { id: inputId, compact: true }))));
    }
    if (selection.mode === "single" && location === "thead") {
        return (react_1.default.createElement(DataTableColumnHeader_1.DataTableColumnHeader, { id: selectionHeaderId, width: { value: ACTION_CELL_CSS_WIDTH }, cellType: "action", label: "", "data-block-keyboard-nav": true, isSticky: stickySelection && "start", style: stickySelection ? { left: stickySelectionOffset } : undefined }));
    }
    if (rowId == null) {
        return null;
    }
    if (selection.mode === "multiple" && location === "tbody") {
        return (react_1.default.createElement(DataTableTd_1.DataTableTd, { cellType: "action", isSticky: stickySelection && "start", style: stickySelection ? { left: stickySelectionOffset } : undefined },
            react_1.default.createElement(CheckboxInput_1.CheckboxInput, Object.assign({}, selection.getRowCheckboxProps(rowId, (_a = tableItems.itemDetails.get(rowId)) === null || _a === void 0 ? void 0 : _a.rowData), { compact: true }))));
    }
    if (selection.mode === "single" && location === "tbody") {
        return (react_1.default.createElement(DataTableTd_1.DataTableTd, { cellType: "action", isSticky: stickySelection && "start", style: stickySelection ? { left: stickySelectionOffset } : undefined },
            react_1.default.createElement(RadioInput_1.RadioInput, Object.assign({}, selection.getRowRadioProps(rowId, (_b = tableItems.itemDetails.get(rowId)) === null || _b === void 0 ? void 0 : _b.rowData)))));
    }
    return null;
}
/* Utils */
function isInteractiveTarget(target) {
    return !!(target === null || target === void 0 ? void 0 : target.closest("a, button, input, select, textarea"));
}
//# sourceMappingURL=DataTableTr.js.map