// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import React, { useCallback, useImperativeHandle, useRef } from 'react';
import clsx from 'clsx';
import { useContainerQuery } from '@cloudscape-design/component-toolkit';
import { useMergeRefs, warnOnce } from '@cloudscape-design/component-toolkit/internal';
import { getAnalyticsMetadataAttribute, } from '@cloudscape-design/component-toolkit/internal/analytics-metadata';
import InternalContainer from '../container/internal';
import { useFunnelSubStep } from '../internal/analytics/hooks/use-funnel';
import { getAnalyticsMetadataProps, getBaseProps } from '../internal/base-component';
import { getVisualContextClassname } from '../internal/components/visual-context';
import { CollectionLabelContext } from '../internal/context/collection-label-context';
import { LinkDefaultVariantContext } from '../internal/context/link-default-variant-context';
import { TableComponentsContextProvider, } from '../internal/context/table-component-context';
import { fireNonCancelableEvent } from '../internal/events';
import { useMobile } from '../internal/hooks/use-mobile';
import useMouseDownTarget from '../internal/hooks/use-mouse-down-target';
import { usePerformanceMarks } from '../internal/hooks/use-performance-marks';
import { usePrevious } from '../internal/hooks/use-previous';
import { useScrollSync } from '../internal/hooks/use-scroll-sync';
import { useTableInteractionMetrics } from '../internal/hooks/use-table-interaction-metrics';
import { useVisualRefresh } from '../internal/hooks/use-visual-mode';
import { isDevelopment } from '../internal/is-development';
import InternalLiveRegion from '../live-region/internal';
import { TableBodyCell } from './body-cell';
import { TableColGroup } from './column-groups/col-group';
import { useColumnGroups } from './column-groups/use-column-groups';
import { checkColumnWidths } from './column-widths-utils';
import { useExpandableTableProps } from './expandable-rows/expandable-rows-utils';
import { NoDataCell } from './no-data-cell';
import { getLoaderContent } from './progressive-loading/items-loader';
import { TableLoaderCell } from './progressive-loading/loader-cell';
import { useProgressiveLoadingProps } from './progressive-loading/progressive-loading-utils';
import { ResizeTracker } from './resizer';
import { focusMarkers, useSelection, useSelectionFocusMove } from './selection';
import { TableBodySelectionCell } from './selection/selection-cell';
import { useGroupSelection } from './selection/use-group-selection';
import { useStickyColumns } from './sticky-columns';
import StickyHeader from './sticky-header';
import { StickyScrollbar } from './sticky-scrollbar';
import { getTableRoleProps, getTableRowRoleProps, getTableWrapperRoleProps, GridNavigationProvider, } from './table-role';
import Thead from './thead';
import ToolsHeader from './tools-header';
import { useCellEditing } from './use-cell-editing';
import { ColumnWidthsProvider, DEFAULT_COLUMN_WIDTH } from './use-column-widths';
import { usePreventStickyClickScroll } from './use-prevent-sticky-click-scroll';
import { useRowEvents } from './use-row-events';
import useTableFocusNavigation from './use-table-focus-navigation';
import { checkSortingState, getColumnKey, getItemKey, getVisibleColumnDefinitions, toContainerVariant } from './utils';
import buttonStyles from '../button/styles.css.js';
import headerStyles from '../header/styles.css.js';
import styles from './styles.css.js';
const GRID_NAVIGATION_PAGE_SIZE = 10;
const SELECTION_COLUMN_WIDTH = 54;
const selectionColumnId = Symbol('selection-column-id');
export const InternalTableAsSubstep = React.forwardRef((props, ref) => {
    const { funnelSubStepProps } = useFunnelSubStep();
    const tableProps = {
        ...props,
        __funnelSubStepProps: funnelSubStepProps,
    };
    return React.createElement(InternalTable, { ...tableProps, ref: ref });
});
const InternalTable = React.forwardRef(({ header, footer, empty, filter, pagination, preferences, items, columnDefinitions, groupDefinitions, trackBy, loading, loadingText, selectionType: externalSelectionType, selectedItems, isItemDisabled, ariaLabels, onSelectionChange, onSortingChange, sortingColumn, sortingDescending, sortingDisabled, visibleColumns, stickyHeader, stickyHeaderVerticalOffset, onRowClick, onRowContextMenu, wrapLines, stripedRows, contentDensity, submitEdit, onEditCancel, resizableColumns, onColumnWidthsChange, variant, __internalRootRef, totalItemsCount, firstIndex, renderAriaLive, stickyColumns, columnDisplay, enableKeyboardNavigation, expandableRows: externalExpandableRows, getLoadingStatus, renderLoaderPending, renderLoaderLoading, renderLoaderError, renderLoaderEmpty, renderLoaderCounter, cellVerticalAlign, __funnelSubStepProps, ...rest }, ref) => {
    var _a, _b, _c, _d, _e;
    // Keyboard navigation defaults to `true` for tables with expandable rows.
    if (externalExpandableRows && enableKeyboardNavigation === undefined) {
        enableKeyboardNavigation = true;
    }
    const baseProps = getBaseProps(rest);
    const prevStickyHeader = usePrevious(stickyHeader);
    if (prevStickyHeader !== undefined && !!stickyHeader !== !!prevStickyHeader) {
        warnOnce('Table', `\`stickyHeader\` has changed from "${prevStickyHeader}" to "${stickyHeader}". It is not recommended to change the value of this property during the component lifecycle. Please set it to either "true" or "false" unconditionally.`);
    }
    const isMobile = useMobile();
    const expandableRows = useExpandableTableProps({
        items,
        expandableRows: externalExpandableRows,
        trackBy,
        ariaLabels,
    });
    const { allItems, isExpandable } = expandableRows;
    const { allRows } = useProgressiveLoadingProps({ getLoadingStatus, expandableRows });
    const selectionType = expandableRows.hasGroupSelection ? 'group' : externalSelectionType;
    const [containerWidth, wrapperMeasureRef] = useContainerQuery(rect => rect.borderBoxWidth);
    const wrapperMeasureRefObject = useRef(null);
    const wrapperMeasureMergedRef = useMergeRefs(wrapperMeasureRef, wrapperMeasureRefObject);
    const [tableWidth, tableMeasureRef] = useContainerQuery(rect => rect.borderBoxWidth);
    const tableRefObject = useRef(null);
    const secondaryWrapperRef = React.useRef(null);
    const theadRef = useRef(null);
    const stickyHeaderRef = React.useRef(null);
    const scrollbarRef = React.useRef(null);
    const { cancelEdit, ...cellEditing } = useCellEditing({ onCancel: onEditCancel, onSubmit: submitEdit });
    const paginationRef = useRef({});
    const filterRef = useRef({});
    const preferencesRef = useRef({});
    const headerRef = useRef({});
    /* istanbul ignore next: performance marks do not work in JSDOM */
    const getHeaderText = () => {
        var _a, _b, _c, _d;
        return (_c = (_b = (_a = toolsHeaderPerformanceMarkRef.current) === null || _a === void 0 ? void 0 : _a.querySelector(`.${headerStyles['heading-text']}`)) === null || _b === void 0 ? void 0 : _b.innerText) !== null && _c !== void 0 ? _c : (_d = toolsHeaderPerformanceMarkRef.current) === null || _d === void 0 ? void 0 : _d.innerText;
    };
    const getPatternIdentifier = () => {
        var _a;
        const hasActions = !!((_a = toolsHeaderPerformanceMarkRef.current) === null || _a === void 0 ? void 0 : _a.querySelector(`.${headerStyles.actions} .${buttonStyles.button}`));
        if (hasActions) {
            return 'table-with-actions';
        }
        return '';
    };
    const performanceMarkAttributes = usePerformanceMarks('table', () => !loading, tableRefObject, () => ({
        loading: loading !== null && loading !== void 0 ? loading : false,
        header: getHeaderText(),
    }), [loading]);
    const analyticsMetadata = getAnalyticsMetadataProps(rest);
    const interactionMetadata = () => {
        const filterData = filterRef.current;
        const paginationData = paginationRef.current;
        return JSON.stringify({
            filterData,
            paginationData,
            sortingColumn: sortingColumn === null || sortingColumn === void 0 ? void 0 : sortingColumn.sortingField,
            sortingOrder: sortingColumn ? (sortingDescending ? 'Descending' : 'Ascending') : undefined,
        });
    };
    const getComponentConfiguration = () => {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
        const headerData = headerRef.current;
        const filterData = filterRef.current;
        const paginationData = paginationRef.current;
        const preferencesData = preferencesRef.current;
        return {
            variant,
            flowType: (_a = rest.analyticsMetadata) === null || _a === void 0 ? void 0 : _a.flowType,
            resourceType: (_b = rest.analyticsMetadata) === null || _b === void 0 ? void 0 : _b.resourceType,
            instanceIdentifier: analyticsMetadata === null || analyticsMetadata === void 0 ? void 0 : analyticsMetadata.instanceIdentifier,
            taskName: (_c = analyticsMetadata === null || analyticsMetadata === void 0 ? void 0 : analyticsMetadata.instanceIdentifier) !== null && _c !== void 0 ? _c : getHeaderText(),
            uxTaskName: getHeaderText(),
            patternIdentifier: getPatternIdentifier(),
            sortedBy: {
                columnId: sortingColumn === null || sortingColumn === void 0 ? void 0 : sortingColumn.sortingField,
                sortingOrder: sortingColumn ? (sortingDescending ? 'desc' : 'asc') : undefined,
            },
            filtered: (_d = filterData === null || filterData === void 0 ? void 0 : filterData.filtered) !== null && _d !== void 0 ? _d : null,
            filteredBy: (_e = filterData === null || filterData === void 0 ? void 0 : filterData.filteredBy) !== null && _e !== void 0 ? _e : [],
            filteredCount: (_f = filterData === null || filterData === void 0 ? void 0 : filterData.filterCount) !== null && _f !== void 0 ? _f : null,
            totalNumberOfResources: (_g = headerData === null || headerData === void 0 ? void 0 : headerData.totalCount) !== null && _g !== void 0 ? _g : null,
            tablePreferences: {
                visibleColumns: (_h = preferencesData === null || preferencesData === void 0 ? void 0 : preferencesData.visibleColumns) !== null && _h !== void 0 ? _h : [],
                resourcesPerPage: (_j = preferencesData === null || preferencesData === void 0 ? void 0 : preferencesData.pageSize) !== null && _j !== void 0 ? _j : null,
            },
            pagination: {
                currentPageIndex: (_k = paginationData === null || paginationData === void 0 ? void 0 : paginationData.currentPageIndex) !== null && _k !== void 0 ? _k : 0,
                totalNumberOfPages: (paginationData === null || paginationData === void 0 ? void 0 : paginationData.openEnd) ? null : ((_l = paginationData === null || paginationData === void 0 ? void 0 : paginationData.totalPageCount) !== null && _l !== void 0 ? _l : null),
                openEnd: Boolean(paginationData === null || paginationData === void 0 ? void 0 : paginationData.openEnd),
            },
            resourcesSelected: (selectedItems === null || selectedItems === void 0 ? void 0 : selectedItems.length) > 0,
        };
    };
    const { setLastUserAction, tableInteractionAttributes } = useTableInteractionMetrics({
        elementRef: tableRefObject,
        loading,
        items,
        instanceIdentifier: analyticsMetadata === null || analyticsMetadata === void 0 ? void 0 : analyticsMetadata.instanceIdentifier,
        itemCount: items.length,
        getComponentIdentifier: getHeaderText,
        getComponentConfiguration,
        interactionMetadata,
    });
    useImperativeHandle(ref, () => {
        var _a;
        return ({
            scrollToTop: ((_a = stickyHeaderRef.current) === null || _a === void 0 ? void 0 : _a.scrollToTop) || (() => undefined),
            cancelEdit,
        });
    }, [cancelEdit]);
    const wrapperRefObject = useRef(null);
    const handleScroll = useScrollSync([wrapperRefObject, scrollbarRef, secondaryWrapperRef]);
    const { moveFocusDown, moveFocusUp, moveFocus } = useSelectionFocusMove(selectionType, allItems.length);
    const { onRowClickHandler, onRowContextMenuHandler } = useRowEvents({ onRowClick, onRowContextMenu });
    const visibleColumnDefinitions = getVisibleColumnDefinitions({
        columnDefinitions,
        columnDisplay,
        visibleColumns,
    });
    const visibleColumnIds = visibleColumnDefinitions.map((col, idx) => getColumnKey(col, idx).toString());
    const { groupColumnMap, ...columnGroupsLayout } = useColumnGroups(columnDefinitions, visibleColumnIds, groupDefinitions, columnDisplay);
    const selectionProps = {
        items: allItems,
        rootItems: items,
        trackBy,
        selectedItems,
        totalItemsCount,
        selectionType,
        isItemDisabled,
        onSelectionChange,
        ariaLabels: {
            ...ariaLabels,
            // `selectionGroupLabel` should not be part of the selection control, it is already part of the selection column header.
            selectionGroupLabel: undefined,
        },
        loading,
        expandableRows,
        getLoadingStatus,
        setLastUserAction,
    };
    const normalSelection = useSelection(selectionProps);
    const groupSelection = useGroupSelection(selectionProps);
    const selection = selectionType === 'group' ? groupSelection : normalSelection;
    const isRowSelected = (row) => {
        if (row.type === 'data') {
            return selection.isItemSelected(row.item);
        }
        if (selectionType !== 'group') {
            return false;
        }
        // Group loader is selected when its parent is selected.
        return !row.item ? expandableRows.groupSelection.inverted : selection.isItemSelected(row.item);
    };
    if (isDevelopment) {
        if (resizableColumns) {
            checkColumnWidths(columnDefinitions);
        }
        if (sortingColumn === null || sortingColumn === void 0 ? void 0 : sortingColumn.sortingComparator) {
            checkSortingState(columnDefinitions, sortingColumn.sortingComparator);
        }
    }
    const isVisualRefresh = useVisualRefresh();
    const computedVariant = isVisualRefresh
        ? variant
        : ['embedded', 'full-page'].indexOf(variant) > -1
            ? 'container'
            : variant;
    const hasHeader = !!(header || filter || pagination || preferences);
    const hasSelection = !!selectionType;
    const hasFooterPagination = isMobile && variant === 'full-page' && !!pagination;
    const hasFooter = !!footer || hasFooterPagination;
    const headerIdRef = useRef(undefined);
    const isLabelledByHeader = !(ariaLabels === null || ariaLabels === void 0 ? void 0 : ariaLabels.tableLabel) && !!header;
    const ariaLabelledby = isLabelledByHeader && headerIdRef.current ? headerIdRef.current : undefined;
    const setHeaderRef = useCallback((id) => {
        headerIdRef.current = id;
    }, []);
    const visibleColumnWidthsWithSelection = [];
    const visibleColumnIdsWithSelection = [];
    if (hasSelection) {
        visibleColumnWidthsWithSelection.push({ id: selectionColumnId, width: SELECTION_COLUMN_WIDTH });
        visibleColumnIdsWithSelection.push(selectionColumnId);
    }
    for (let columnIndex = 0; columnIndex < visibleColumnDefinitions.length; columnIndex++) {
        const columnId = getColumnKey(visibleColumnDefinitions[columnIndex], columnIndex);
        visibleColumnWidthsWithSelection.push({ ...visibleColumnDefinitions[columnIndex], id: columnId });
        visibleColumnIdsWithSelection.push(columnId);
    }
    const stickyState = useStickyColumns({
        visibleColumns: visibleColumnIdsWithSelection,
        stickyColumnsFirst: ((_a = stickyColumns === null || stickyColumns === void 0 ? void 0 : stickyColumns.first) !== null && _a !== void 0 ? _a : 0) + ((stickyColumns === null || stickyColumns === void 0 ? void 0 : stickyColumns.first) && hasSelection ? 1 : 0),
        stickyColumnsLast: (stickyColumns === null || stickyColumns === void 0 ? void 0 : stickyColumns.last) || 0,
    });
    const hasStickyColumns = !!(((_b = stickyColumns === null || stickyColumns === void 0 ? void 0 : stickyColumns.first) !== null && _b !== void 0 ? _b : 0) + ((_c = stickyColumns === null || stickyColumns === void 0 ? void 0 : stickyColumns.last) !== null && _c !== void 0 ? _c : 0) > 0);
    const hasEditableCells = !!columnDefinitions.find(col => col.editConfig);
    let tableRole = 'table';
    if (isExpandable) {
        tableRole = 'treegrid';
    }
    else if (enableKeyboardNavigation) {
        tableRole = 'grid';
    }
    else if (hasEditableCells) {
        tableRole = 'grid-default';
    }
    const theadProps = {
        selectionType,
        getSelectAllProps: selection.getSelectAllProps,
        columnDefinitions: visibleColumnDefinitions,
        groupDefinitions,
        columnGroupsLayout,
        variant: computedVariant,
        tableVariant: computedVariant,
        wrapLines,
        resizableColumns,
        sortingColumn,
        sortingDisabled,
        sortingDescending,
        onSortingChange,
        onFocusMove: moveFocus,
        onResizeFinish(newWidth) {
            const widthsDetail = columnDefinitions.map((column, index) => newWidth.get(getColumnKey(column, index)) || column.width || DEFAULT_COLUMN_WIDTH);
            const widthsChanged = widthsDetail.some((width, index) => columnDefinitions[index].width !== width);
            if (widthsChanged) {
                fireNonCancelableEvent(onColumnWidthsChange, { widths: widthsDetail });
            }
        },
        singleSelectionHeaderAriaLabel: ariaLabels === null || ariaLabels === void 0 ? void 0 : ariaLabels.selectionGroupLabel,
        resizerRoleDescription: ariaLabels === null || ariaLabels === void 0 ? void 0 : ariaLabels.resizerRoleDescription,
        resizerTooltipText: ariaLabels === null || ariaLabels === void 0 ? void 0 : ariaLabels.resizerTooltipText,
        stripedRows,
        stickyState,
        stickyColumnsFirst: (_d = stickyColumns === null || stickyColumns === void 0 ? void 0 : stickyColumns.first) !== null && _d !== void 0 ? _d : 0,
        stickyColumnsLast: (_e = stickyColumns === null || stickyColumns === void 0 ? void 0 : stickyColumns.last) !== null && _e !== void 0 ? _e : 0,
        selectionColumnId,
        tableRole,
        isExpandable,
        setLastUserAction,
    };
    usePreventStickyClickScroll(wrapperRefObject);
    const wrapperRef = useMergeRefs(wrapperRefObject, stickyState.refs.wrapper);
    const tableRef = useMergeRefs(tableMeasureRef, tableRefObject, stickyState.refs.table);
    const wrapperProps = getTableWrapperRoleProps({
        tableRole,
        isScrollable: !!(tableWidth && containerWidth && tableWidth > containerWidth),
        ariaLabel: ariaLabels === null || ariaLabels === void 0 ? void 0 : ariaLabels.tableLabel,
        ariaLabelledby,
    });
    const getMouseDownTarget = useMouseDownTarget();
    useTableFocusNavigation({
        enableKeyboardNavigation,
        selectionType,
        tableRoot: tableRefObject,
        columnDefinitions: visibleColumnDefinitions,
        numRows: allRows === null || allRows === void 0 ? void 0 : allRows.length,
    });
    const toolsHeaderPerformanceMarkRef = useRef(null);
    // If is mobile, we take into consideration the AppLayout's mobile bar and we subtract the tools wrapper height so only the table header is sticky
    const [toolsHeaderHeight, toolsHeaderWrapperMeasureRef] = useContainerQuery(rect => rect.borderBoxHeight);
    const toolsHeaderWrapper = useMergeRefs(toolsHeaderPerformanceMarkRef, toolsHeaderWrapperMeasureRef);
    const colIndexOffset = selectionType ? 1 : 0;
    const totalColumnsCount = visibleColumnDefinitions.length + colIndexOffset;
    const headerRowCount = (columnGroupsLayout === null || columnGroupsLayout === void 0 ? void 0 : columnGroupsLayout.rows.length) || 1;
    return (React.createElement(LinkDefaultVariantContext.Provider, { value: { defaultVariant: 'primary' } },
        React.createElement(TableComponentsContextProvider, { value: { paginationRef, filterRef, preferencesRef, headerRef } },
            React.createElement(ColumnWidthsProvider, { visibleColumns: visibleColumnWidthsWithSelection, resizableColumns: resizableColumns, containerRef: wrapperMeasureRefObject, groupColumnMap: groupColumnMap },
                React.createElement(InternalContainer, { ...baseProps, ...tableInteractionAttributes, __internalRootRef: __internalRootRef, className: clsx(baseProps.className, styles.root), __funnelSubStepProps: __funnelSubStepProps, __fullPage: variant === 'full-page', header: React.createElement(React.Fragment, null,
                        hasHeader && (React.createElement("div", null,
                            React.createElement("div", { ref: toolsHeaderWrapper, className: clsx(styles['header-controls'], styles[`variant-${computedVariant}`]) },
                                React.createElement(CollectionLabelContext.Provider, { value: { assignId: setHeaderRef } },
                                    React.createElement(ToolsHeader, { header: header, filter: filter, pagination: pagination, preferences: preferences, setLastUserAction: setLastUserAction }))))),
                        stickyHeader && (React.createElement(StickyHeader, { ref: stickyHeaderRef, variant: computedVariant, theadProps: theadProps, wrapperRef: wrapperRefObject, theadRef: theadRef, secondaryWrapperRef: secondaryWrapperRef, tableRef: tableRefObject, onScroll: handleScroll, tableHasHeader: hasHeader, contentDensity: contentDensity, tableRole: tableRole, hasGroupedColumns: !!columnGroupsLayout && columnGroupsLayout.rows.length > 1, columnDefinitions: visibleColumnDefinitions, hasSelection: hasSelection }))), disableHeaderPaddings: true, disableContentPaddings: true, disableFooterPaddings: true, variant: toContainerVariant(computedVariant), __disableFooterDivider: true, __disableStickyMobile: false, footer: hasFooter ? (React.createElement("div", { className: clsx(styles['footer-wrapper'], styles[`variant-${computedVariant}`]) },
                        React.createElement("div", { className: clsx(styles.footer, hasFooterPagination && styles['footer-with-pagination']) },
                            footer && React.createElement("span", null, footer),
                            hasFooterPagination && React.createElement("div", { className: styles['footer-pagination'] }, pagination)))) : null, __stickyHeader: stickyHeader, __mobileStickyOffset: toolsHeaderHeight !== null && toolsHeaderHeight !== void 0 ? toolsHeaderHeight : 0, __stickyOffset: stickyHeaderVerticalOffset, ...focusMarkers.root },
                    React.createElement("div", { ref: wrapperRef, className: clsx(styles.wrapper, styles[`variant-${computedVariant}`], {
                            [styles['has-footer']]: hasFooter,
                            [styles['has-header']]: hasHeader,
                        }), style: stickyState.style.wrapper, onScroll: handleScroll, ...wrapperProps },
                        React.createElement("div", { className: styles['wrapper-content-measure'], ref: wrapperMeasureMergedRef }),
                        !!renderAriaLive && !!firstIndex && !loading && (React.createElement(InternalLiveRegion, { hidden: true, tagName: "span" },
                            React.createElement("span", null, renderAriaLive({
                                firstIndex,
                                lastIndex: firstIndex + items.length - 1,
                                visibleItemsCount: allItems.length,
                                totalItemsCount,
                            })))),
                        React.createElement(GridNavigationProvider, { keyboardNavigation: !!enableKeyboardNavigation, pageSize: GRID_NAVIGATION_PAGE_SIZE, getTable: () => tableRefObject.current },
                            React.createElement("table", { ...performanceMarkAttributes, ref: tableRef, className: clsx(styles.table, resizableColumns && styles['table-layout-fixed'], columnGroupsLayout && columnGroupsLayout.rows.length > 1 && styles['has-grouped-header'], contentDensity === 'compact' && getVisualContextClassname('compact-table')), ...getTableRoleProps({
                                    tableRole,
                                    totalItemsCount,
                                    totalColumnsCount: totalColumnsCount,
                                    headerRowCount,
                                    ariaLabel: ariaLabels === null || ariaLabels === void 0 ? void 0 : ariaLabels.tableLabel,
                                    ariaLabelledby,
                                }) },
                                resizableColumns && columnGroupsLayout && columnGroupsLayout.rows.length > 1 && (React.createElement(TableColGroup, { visibleColumnDefinitions: visibleColumnDefinitions, hasSelection: hasSelection })),
                                React.createElement(Thead, { ref: theadRef, hidden: stickyHeader, onFocusedComponentChange: focusId => { var _a; return (_a = stickyHeaderRef.current) === null || _a === void 0 ? void 0 : _a.setFocus(focusId); }, ...theadProps }),
                                React.createElement("tbody", null, loading || allItems.length === 0 ? (React.createElement("tr", null,
                                    React.createElement(NoDataCell, { totalColumnsCount: totalColumnsCount, hasFooter: hasFooter, loading: loading, loadingText: loadingText, empty: empty, tableRef: tableRefObject, containerRef: wrapperMeasureRefObject }))) : (allRows.map((row, rowIndex) => {
                                    const isFirstRow = rowIndex === 0;
                                    const isLastRow = rowIndex === allRows.length - 1;
                                    const rowExpandableProps = row.type === 'data' ? expandableRows.getExpandableItemProps(row.item) : undefined;
                                    const rowRoleProps = getTableRowRoleProps({
                                        tableRole,
                                        firstIndex,
                                        rowIndex,
                                        headerRowCount,
                                        level: row.type === 'loader' ? row.level : undefined,
                                        ...rowExpandableProps,
                                    });
                                    const getTableItemKey = (item) => getItemKey(trackBy, item, rowIndex);
                                    const sharedCellProps = {
                                        isFirstRow,
                                        isLastRow,
                                        isSelected: hasSelection && isRowSelected(row),
                                        isPrevSelected: hasSelection && !isFirstRow && isRowSelected(allRows[rowIndex - 1]),
                                        isNextSelected: hasSelection && !isLastRow && isRowSelected(allRows[rowIndex + 1]),
                                        isEvenRow: rowIndex % 2 === 0,
                                        stripedRows,
                                        hasSelection,
                                        hasFooter,
                                        stickyState,
                                        tableRole,
                                    };
                                    if (row.type === 'data') {
                                        const rowId = `${getTableItemKey(row.item)}`;
                                        return (React.createElement("tr", { key: rowId, className: clsx(styles.row, sharedCellProps.isSelected && styles['row-selected']), onFocus: ({ currentTarget }) => {
                                                var _a;
                                                // When an element inside table row receives focus we want to adjust the scroll.
                                                // However, that behavior is unwanted when the focus is received as result of a click
                                                // as it causes the click to never reach the target element.
                                                if (!currentTarget.contains(getMouseDownTarget())) {
                                                    (_a = stickyHeaderRef.current) === null || _a === void 0 ? void 0 : _a.scrollToRow(currentTarget);
                                                }
                                            }, ...focusMarkers.item, onClick: onRowClickHandler && onRowClickHandler.bind(null, rowIndex, row.item), onContextMenu: onRowContextMenuHandler && onRowContextMenuHandler.bind(null, rowIndex, row.item), ...rowRoleProps },
                                            selection.getItemSelectionProps && (React.createElement(TableBodySelectionCell, { ...sharedCellProps, columnId: selectionColumnId, selectionControlProps: {
                                                    ...selection.getItemSelectionProps(row.item),
                                                    onFocusDown: moveFocusDown,
                                                    onFocusUp: moveFocusUp,
                                                    rowIndex,
                                                    itemKey: rowId,
                                                }, verticalAlign: cellVerticalAlign, tableVariant: computedVariant })),
                                            visibleColumnDefinitions.map((column, colIndex) => {
                                                var _a, _b, _c;
                                                const colId = `${getColumnKey(column, colIndex)}`;
                                                const cellId = { row: rowId, col: colId };
                                                const isEditing = cellEditing.checkEditing(cellId);
                                                const successfulEdit = cellEditing.checkLastSuccessfulEdit(cellId);
                                                const isEditable = !!column.editConfig && !cellEditing.isLoading;
                                                const cellExpandableProps = isExpandable && colIndex === 0 ? rowExpandableProps : undefined;
                                                const counter = (_a = column.counter) === null || _a === void 0 ? void 0 : _a.call(column, {
                                                    item: row.item,
                                                    itemsCount: rowExpandableProps === null || rowExpandableProps === void 0 ? void 0 : rowExpandableProps.itemsCount,
                                                    selectedItemsCount: rowExpandableProps === null || rowExpandableProps === void 0 ? void 0 : rowExpandableProps.selectedItemsCount,
                                                });
                                                const analyticsMetadata = {
                                                    component: {
                                                        innerContext: {
                                                            position: `${rowIndex + 1},${colIndex + 1}`,
                                                            columnId: column.id ? `${column.id}` : '',
                                                            columnLabel: {
                                                                selector: `table thead tr th:nth-child(${colIndex + (selectionType ? 2 : 1)})`,
                                                                root: 'component',
                                                            },
                                                            item: rowId,
                                                        },
                                                    },
                                                };
                                                return (React.createElement(TableBodyCell, { key: colId, ...sharedCellProps, resizableStyle: {
                                                        width: column.width,
                                                        minWidth: column.minWidth,
                                                        maxWidth: column.maxWidth,
                                                    }, ariaLabels: ariaLabels, column: column, item: row.item, wrapLines: wrapLines, isEditable: isEditable, isEditing: isEditing, isRowHeader: column.isRowHeader, successfulEdit: successfulEdit, resizableColumns: resizableColumns, onEditStart: () => cellEditing.startEdit(cellId), onEditEnd: editCancelled => cellEditing.completeEdit(cellId, editCancelled), submitEdit: cellEditing.submitEdit, columnId: (_b = column.id) !== null && _b !== void 0 ? _b : colIndex, colIndex: colIndex + colIndexOffset, verticalAlign: (_c = column.verticalAlign) !== null && _c !== void 0 ? _c : cellVerticalAlign, tableVariant: computedVariant, counter: counter, ...cellExpandableProps, ...getAnalyticsMetadataAttribute(analyticsMetadata) }));
                                            })));
                                    }
                                    const loaderSelectionProps = selection.getLoaderSelectionProps && selection.getLoaderSelectionProps(row.item);
                                    const rowSelection = selectionType === 'group' ? loaderSelectionProps : undefined;
                                    const loaderContent = getLoaderContent({
                                        item: row.item,
                                        loadingStatus: row.status,
                                        renderLoaderPending,
                                        renderLoaderLoading,
                                        renderLoaderError,
                                        renderLoaderEmpty,
                                    });
                                    const loaderCounter = renderLoaderCounter === null || renderLoaderCounter === void 0 ? void 0 : renderLoaderCounter({
                                        item: row.item,
                                        loadingStatus: row.status,
                                        selected: !!(rowSelection === null || rowSelection === void 0 ? void 0 : rowSelection.checked),
                                    });
                                    return (loaderContent && (React.createElement("tr", { key: (row.item ? getTableItemKey(row.item) : 'root-' + rowIndex) + '-' + row.from, className: styles.row, ...rowRoleProps },
                                        selectionType ? (React.createElement(TableBodySelectionCell, { ...sharedCellProps, columnId: selectionColumnId, verticalAlign: cellVerticalAlign, tableVariant: computedVariant, selectionControlProps: selectionType === 'group' ? loaderSelectionProps : undefined, isSelected: selectionType === 'group' && !!(loaderSelectionProps === null || loaderSelectionProps === void 0 ? void 0 : loaderSelectionProps.checked) })) : null,
                                        visibleColumnDefinitions.map((column, colIndex) => {
                                            var _a;
                                            return (React.createElement(TableLoaderCell, { key: getColumnKey(column, colIndex), ...sharedCellProps, wrapLines: false, columnId: (_a = column.id) !== null && _a !== void 0 ? _a : colIndex, colIndex: colIndex + colIndexOffset, isSelected: selectionType === 'group' && !!(loaderSelectionProps === null || loaderSelectionProps === void 0 ? void 0 : loaderSelectionProps.checked), isRowHeader: colIndex === 0, level: row.level, item: row.item, trackBy: trackBy, counter: loaderCounter }, loaderContent));
                                        }))));
                                }))))),
                        resizableColumns && React.createElement(ResizeTracker, null)),
                    React.createElement(StickyScrollbar, { ref: scrollbarRef, wrapperRef: wrapperRefObject, tableRef: tableRefObject, onScroll: handleScroll, hasStickyColumns: hasStickyColumns }))))));
});
export default InternalTable;
//# sourceMappingURL=internal.js.map