@umodeapporg/ui 0.24.2 → 0.24.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/UI/DataTable/DataTable.js +10 -1
- package/dist/components/UI/DataTable/DataTable.js.map +1 -1
- package/dist/components/UI/DataTable/grid/GridProvider.d.ts +2 -0
- package/dist/components/UI/DataTable/grid/GridProvider.js +22 -1
- package/dist/components/UI/DataTable/grid/GridProvider.js.map +1 -1
- package/dist/components/UI/DataTable/grid/gridStore.d.ts +5 -0
- package/dist/components/UI/DataTable/grid/gridStore.js +13 -0
- package/dist/components/UI/DataTable/grid/gridStore.js.map +1 -1
- package/package.json +1 -1
|
@@ -589,7 +589,16 @@ const DataTable = ({
|
|
|
589
589
|
);
|
|
590
590
|
const editableContent = config.editing?.clickToEdit ? /* @__PURE__ */ jsx(DataTableCellEditingProvider, { children: content }) : content;
|
|
591
591
|
if (!gridStore) return editableContent;
|
|
592
|
-
return /* @__PURE__ */ jsx(
|
|
592
|
+
return /* @__PURE__ */ jsx(
|
|
593
|
+
GridProvider,
|
|
594
|
+
{
|
|
595
|
+
store: gridStore,
|
|
596
|
+
gridAreaRef: listScrollRef,
|
|
597
|
+
canEditCell,
|
|
598
|
+
onFillCommit: handleFillCommit,
|
|
599
|
+
children: editableContent
|
|
600
|
+
}
|
|
601
|
+
);
|
|
593
602
|
};
|
|
594
603
|
export {
|
|
595
604
|
DataTable as default
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DataTable.js","sources":["../../../../src/components/UI/DataTable/DataTable.tsx"],"sourcesContent":["import { Fragment, JSX, KeyboardEvent, ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport classNames from 'classnames';\nimport { useTranslation } from 'react-i18next';\n\nimport ControlledButton from '@/components/Form/ControlledButton';\nimport { ActiveFiltersBar, buildEmptyFilterValues, emptyValueForKind } from '@/components/Search/filters';\nimport LoadingSpinner from '@/components/UI/LoadingSpinner';\nimport { MaterialSymbol } from '@/components/UI/MaterialSymbol';\nimport { useBreakpoint } from '@/hooks/useBreakpoint';\n\nimport GridProvider from './grid/GridProvider';\nimport { type IGridCellCoord } from './grid/gridTypes';\nimport { useGridFillApply } from './grid/useGridFillApply';\nimport { useGridEditMode, useGridInstance, useGridMatrixSync } from './grid/useGridInstance';\nimport { useGridKeyboard } from './grid/useGridKeyboard';\nimport DataTableAutoCard from './DataTableAutoCard';\nimport DataTableBody from './DataTableBody';\nimport DataTableBulkEditButton from './DataTableBulkEditButton';\nimport DataTableBulkEditDialog from './DataTableBulkEditDialog';\nimport { isBadgeColumnType } from './dataTableClasses';\nimport DataTableColumnToggle from './DataTableColumnToggle';\nimport { type IDataTableDetailColumnsState } from './DataTableDetailTable';\nimport DataTableEditModeButton from './DataTableEditModeButton';\nimport DataTableHead from './DataTableHead';\nimport DataTablePaginationBar, { DATA_TABLE_MIN_PAGE_SIZE } from './DataTablePagination';\nimport {\n DataTableCardsSkeletonState,\n DataTableEmptyState,\n DataTableErrorState,\n DataTableSkeletonState,\n} from './DataTableStates';\nimport DataTableToolbar from './DataTableToolbar';\nimport {\n DATA_TABLE_REMOVE_COLUMN_ID,\n type IDataTableColumnConfig,\n type IDataTableConfig,\n type IDataTableRow,\n type IDataTableSortState,\n type IDataTableSpreadsheetConfig,\n isDataTableDetailTableExpansion,\n type TDataTableFilterValues,\n type TDataTableViewMode,\n} from './types';\nimport DataTableCellEditingProvider from './useCellEditingState';\nimport { useColumnOrder, useDetailColumnOrder } from './useColumnOrder';\nimport { useColumnSizing } from './useColumnSizing';\nimport { useColumnVisibility, useDetailColumnVisibility } from './useColumnVisibility';\nimport {\n type IDataTableClientPaginationState,\n type IDataTablePagination,\n useDataTableInstance,\n} from './useDataTableInstance';\nimport { useDataTableUndoHistory } from './useDataTableUndoHistory';\n\ninterface IDataTableProps<T extends IDataTableRow, C extends IDataTableRow = IDataTableRow> {\n config: IDataTableConfig<T, C>;\n rows: Array<T>;\n loading?: boolean;\n error?: boolean;\n /** Cause behind `error`, so the empty state can name a denial instead of a system failure. */\n errorCause?: unknown;\n onRetry?: () => void;\n emptyMessage?: string;\n searchLabel?: string;\n onSearch?: (value: string) => void;\n initialSearch?: string;\n onSearchTermChange?: (value: string) => void;\n searchDisabled?: boolean;\n searchDebounceTime?: number;\n searchMinLength?: number;\n /** Renders the search input in the toolbar's start (left) group instead of the end. */\n searchAtStart?: boolean;\n sort?: IDataTableSortState | null;\n onSortChange?: (sort: IDataTableSortState | null) => void;\n pagination?: IDataTablePagination;\n /** Client mode: seeds page/pageSize (1-based page), e.g. from the URL. */\n initialClientPagination?: IDataTableClientPaginationState;\n /** Client mode: reports page/pageSize changes and keeps the page across in-place row updates. */\n onClientPaginationChange?: (pagination: IDataTableClientPaginationState) => void;\n toolbarSlot?: JSX.Element;\n /**\n * Extra controls rendered in the footer's left group, right after the table's\n * own buttons (columns, edit mode, bulk edit). For an action that belongs to\n * the list itself rather than to the page header, so it sits beside the\n * controls it relates to instead of competing with the page actions. The\n * footer row renders for this slot alone when the table has no other control.\n */\n footerActionsSlot?: ReactNode;\n /**\n * Applied filter values. Passing them (together with `config.filters`) makes\n * the table render the always-visible active-filter chips above the toolbar,\n * so the user never has to hover the button to see what is filtering.\n */\n filterValues?: TDataTableFilterValues;\n onFilterValuesChange?: (values: TDataTableFilterValues) => void;\n /** Rendered at the start (left) of the toolbar, before tabs and view toggle. */\n toolbarStartSlot?: JSX.Element;\n /**\n * Full-width band rendered as the first row of the list body, spanning every\n * column (below the header, above the data rows). Opt-in: omit for a normal\n * table. When set, the empty state is skipped so the band stays visible even\n * with zero data rows (e.g. an inline \"create the first record\" editor).\n */\n bodyTopRow?: ReactNode;\n /** Client mode: reports the filtered (post-search) row count on every change. */\n onFilteredCountChange?: (count: number) => void;\n /**\n * Controlled view mode. When provided, the host owns the state (e.g. to persist\n * it) and must update it via `onViewModeChange`; omit for internal state.\n */\n viewMode?: TDataTableViewMode;\n /**\n * Fired on every view-toggle click, including re-selecting the active mode\n * (hosts use it e.g. to reopen the grouping dialog).\n */\n onViewModeChange?: (mode: TDataTableViewMode) => void;\n /**\n * Where the \"Columns\" toggle renders: `header` (default, inside the table\n * header), `toolbar` (next to the view toggle) or `footer` (bottom-left,\n * on the same row as the pagination).\n */\n columnTogglePlacement?: 'header' | 'toolbar' | 'footer';\n /**\n * Enables infinite scroll in the Cards view: the table observes a bottom\n * sentinel and calls `loadMore` while `hasMore`. Pass `source.cardsInfinite`\n * from `useDataTableSource`. The Lista view keeps its pagination bar.\n */\n cardsInfiniteScroll?: {\n hasMore: boolean;\n loadingMore: boolean;\n loadMore: () => void;\n };\n /**\n * Hides the built-in segmented view toggle. Use when the host renders its own\n * Cards/Lista switcher (e.g. a page-level `ControlledTabs`) and drives `viewMode`\n * itself. Other consumers keep the default toggle.\n */\n hideViewToggle?: boolean;\n /**\n * Layout mode. `page` (default): the table owns a bounded, vertically-scrolling\n * region (`flex-1 min-h-0`) for full-page lists. `fit`: the table sizes to its\n * content and scrolls only horizontally — for embedding inside a dialog / card /\n * editor grid where the host container owns vertical scroll. In `fit` mode the\n * empty state is compact (no full illustration) so surrounding controls such as\n * the add-row button stay visible.\n */\n layout?: 'page' | 'fit';\n /** Reduces cell vertical padding for more visible rows per viewport. */\n dense?: boolean;\n /** Roomier cell padding and type scale, for tables that need to read bigger. */\n spacious?: boolean;\n /**\n * Per-cell persistence state (`statuses` from `useDataTableCommitQueue`), painted\n * on the cells so the user sees what is saving and what failed.\n */\n commitStatuses?: ReadonlyMap<string, string>;\n}\n\nconst DataTable = <T extends IDataTableRow, C extends IDataTableRow = IDataTableRow>({\n config: configProp,\n rows,\n loading = false,\n error = false,\n errorCause,\n onRetry,\n emptyMessage,\n searchLabel,\n onSearch,\n initialSearch = '',\n onSearchTermChange,\n searchDisabled = false,\n searchDebounceTime = 400,\n searchMinLength = 1,\n searchAtStart = false,\n sort,\n onSortChange,\n pagination,\n initialClientPagination,\n onClientPaginationChange,\n toolbarSlot,\n footerActionsSlot,\n filterValues,\n onFilterValuesChange,\n toolbarStartSlot,\n bodyTopRow,\n onFilteredCountChange,\n viewMode: controlledViewMode,\n onViewModeChange,\n columnTogglePlacement = 'header',\n cardsInfiniteScroll,\n hideViewToggle = false,\n layout = 'page',\n dense: denseProp = false,\n spacious = false,\n commitStatuses,\n}: IDataTableProps<T, C>) => {\n const { t } = useTranslation('ui');\n\n const isFit = layout === 'fit';\n const dense = !spacious && (isFit || denseProp);\n const editingRows = configProp.editing?.rows;\n const showAddRow = !!editingRows?.canAdd && !!editingRows.onAddRow;\n\n const hostFillCells = configProp.spreadsheet ? configProp.spreadsheet.fill?.onFillCells : undefined;\n const isUndoEnabled = !!configProp.editing?.onCellChange && configProp.editing.undo !== false;\n const { recordedOnCellChange, recordedOnFillCells, handleUndoShortcut } = useDataTableUndoHistory<T>({\n enabled: isUndoEnabled,\n rows,\n columns: configProp.columns,\n onCellChange: configProp.editing?.onCellChange,\n onFillCells: hostFillCells,\n });\n\n const configWithUndo = useMemo<IDataTableConfig<T, C>>(() => {\n if (!isUndoEnabled || !configProp.editing) return configProp;\n\n const spreadsheetConfig = configProp.spreadsheet;\n return {\n ...configProp,\n editing: { ...configProp.editing, onCellChange: recordedOnCellChange },\n spreadsheet:\n spreadsheetConfig && spreadsheetConfig.fill?.onFillCells\n ? { ...spreadsheetConfig, fill: { ...spreadsheetConfig.fill, onFillCells: recordedOnFillCells } }\n : spreadsheetConfig,\n };\n }, [configProp, isUndoEnabled, recordedOnCellChange, recordedOnFillCells]);\n\n // When `editing.rows.onRemoveRow` is set, append a synthetic trailing actions\n // column carrying a per-row delete control. It is a real `actions` column, so\n // it flows through the existing sizing / sticky-right / flex-exclusion / order\n // paths unchanged (see useColumnOrder: actions columns are pinned to the end).\n const config = useMemo<IDataTableConfig<T, C>>(() => {\n if (!editingRows?.onRemoveRow) return configWithUndo;\n\n const removeColumn: IDataTableColumnConfig<T> = {\n id: DATA_TABLE_REMOVE_COLUMN_ID,\n header: '',\n type: 'actions',\n hideable: false,\n resizable: false,\n actions: [\n {\n key: 'remove',\n label: t('dataTable.removeRow'),\n icon: 'delete',\n danger: true,\n hidden: (row) => (editingRows.canRemove ? !editingRows.canRemove(row) : false),\n onClick: (row) => editingRows.onRemoveRow?.(row),\n },\n ],\n };\n\n return { ...configWithUndo, columns: [...configWithUndo.columns, removeColumn] };\n }, [configWithUndo, editingRows, t]);\n\n const { columnVisibility, onColumnVisibilityChange } = useColumnVisibility(config);\n const { columnOrder, onColumnOrderChange, resetColumnOrder } = useColumnOrder(config);\n const { columnSizing, onColumnSizingChange, resetColumnSizing } = useColumnSizing(config);\n\n // Every table restores the persisted column order back to the config default\n // on mount (equivalent to firing \"Restaurar ordem padrão\" from the columns\n // menu), so a stale/incompatible persisted order never sticks. Does not touch\n // column widths or visibility, and does not affect the Cards view.\n useEffect(() => {\n resetColumnOrder();\n }, []);\n\n const detailExpansionColumns =\n config.expansion && isDataTableDetailTableExpansion(config.expansion) && Array.isArray(config.expansion.columns)\n ? config.expansion.columns\n : null;\n const { detailColumnVisibility, toggleDetailColumn } = useDetailColumnVisibility(\n config.entityKey,\n detailExpansionColumns,\n );\n const { detailColumnOrder, onDetailColumnOrderChange, resetDetailColumnOrder } = useDetailColumnOrder(\n config.entityKey,\n detailExpansionColumns,\n );\n\n const detailColumnsState: IDataTableDetailColumnsState | undefined = detailExpansionColumns\n ? {\n visibility: detailColumnVisibility,\n toggleVisibility: toggleDetailColumn,\n order: detailColumnOrder,\n onOrderChange: onDetailColumnOrderChange,\n resetOrder: resetDetailColumnOrder,\n }\n : undefined;\n\n const { isMobile } = useBreakpoint();\n\n const hasCardView = !!config.renderCard;\n const hasGroupedView = !!config.renderGroupedBody;\n const hasKanbanView = !!config.renderKanbanBody;\n // Fixed behaviour: card-capable tables always open on Cards (first), Lista second.\n // The toggle switches within the session and resets to Cards on remount, unless\n // the host controls the mode via the `viewMode` prop (e.g. persisted preference).\n const [internalViewMode, setInternalViewMode] = useState<TDataTableViewMode>('cards');\n const viewMode = controlledViewMode ?? internalViewMode;\n\n const [isBulkEditOpen, setIsBulkEditOpen] = useState(false);\n\n const handleViewModeChange = (mode: TDataTableViewMode) => {\n if (controlledViewMode === undefined) setInternalViewMode(mode);\n onViewModeChange?.(mode);\n };\n\n const {\n table,\n isClientMode,\n columnContentWidths,\n registerRow,\n beginRowsExit,\n visibleRows,\n activeTab,\n tabs,\n handleTabChange,\n handleSearchInput,\n handleHeaderSortClick,\n resolveSortDirection,\n clientPaginationProps,\n showUpdatingBar,\n contentOpacityStyle,\n dataTableOpacityTransitionClass,\n showSkeleton,\n hasRows,\n clientSearchDebounceMs,\n } = useDataTableInstance({\n config,\n rows,\n loading,\n sort,\n onSortChange,\n onSearch,\n initialSearch,\n onSearchTermChange,\n pagination,\n initialClientPagination,\n onClientPaginationChange,\n columnVisibility,\n onColumnVisibilityChange,\n columnOrder,\n onColumnOrderChange,\n columnSizing,\n onColumnSizingChange,\n onFilteredCountChange,\n });\n\n const columnConfigById = useMemo(\n () => new Map(config.columns.map((columnConfig) => [columnConfig.id, columnConfig])),\n [config.columns],\n );\n\n // Under `table-fixed` one column absorbs leftover horizontal space. The last\n // visible non-actions, non-badge, non-first column is the flex column.\n const visibleLeafColumns = table.getVisibleLeafColumns();\n const flexColumnId = useMemo(() => {\n if (config.flexColumnId && visibleLeafColumns.some((leafColumn) => leafColumn.id === config.flexColumnId)) {\n return config.flexColumnId;\n }\n\n const candidates = visibleLeafColumns.filter((leafColumn, index) => {\n if (index === 0) return false;\n const type = columnConfigById.get(leafColumn.id)?.type;\n return type !== 'actions' && !isBadgeColumnType(type);\n });\n return candidates[candidates.length - 1]?.id ?? null;\n }, [visibleLeafColumns, columnConfigById, config.flexColumnId]);\n\n // `table-fixed` sizes columns from the table width, so the table must be at\n // least the sum of ALL column widths (including the absorber's seed) for their\n // widths to be honored; below that the browser shrinks them proportionally.\n // `min-w-full` still lets the table stretch to fill the container, and the\n // auto-width absorber soaks the surplus (never shrinking below its own seed,\n // because its seed is part of this total).\n const totalTableWidth = useMemo(\n () => visibleLeafColumns.reduce((sum, leafColumn) => sum + leafColumn.getSize(), 0),\n [visibleLeafColumns, columnSizing],\n );\n\n // ----- Spreadsheet layer -----\n // Toda tabela com coluna editável ganha a camada de planilha sem configuração, ativa\n // desde a montagem. Numa tabela com `onRowClick` a célula editável é dona do próprio\n // clique (abre o editor) e o resto da linha continua abrindo o registro.\n const spreadsheet = useMemo<IDataTableSpreadsheetConfig<T> | undefined>(() => {\n if (config.spreadsheet === false) return undefined;\n return config.spreadsheet ?? { selection: 'range', fill: {} };\n }, [config.spreadsheet]);\n\n const hasEditableColumns = useMemo(\n () => !!config.editing?.onCellChange && config.columns.some((columnConfig) => !!columnConfig.editable),\n [config.editing, config.columns],\n );\n\n const editModeBehavior = spreadsheet?.mode ?? 'always';\n const gridEnabled = !!spreadsheet && (hasEditableColumns || !!config.spreadsheet);\n\n const gridStore = useGridInstance({\n spreadsheet,\n enabled: gridEnabled,\n startsInEditMode: editModeBehavior === 'always',\n });\n\n const isEditMode = useGridEditMode(gridStore);\n const showEditModeToggle = gridEnabled && editModeBehavior === 'toggle';\n\n // Below the tablet edge a real table is unreadable: even the narrowest column\n // set overflows and the user reads it through a horizontal scrollbar. Cards are\n // the readable shape there, so the narrow viewport takes over the choice.\n // Excluded: `fit` layouts without a bespoke card (their cell geometry IS the\n // feature) and a table whose reason to exist is editing. Merely being able to edit\n // is not enough: a table that opens a record on row click is a reading surface\n // first, unless the user turned its edit toggle on. A `fit` table that ships\n // `renderCard` opted into a narrow shape, so it takes over as well.\n const isEditingSurface = isEditMode && (editModeBehavior === 'toggle' || !config.onRowClick);\n const forceCardsOnMobile = isMobile && (!isFit || hasCardView) && !isEditingSurface;\n\n const isGroupedView = hasGroupedView && viewMode === 'grouped';\n const isKanbanView = hasKanbanView && viewMode === 'kanban';\n // Grouped and kanban both hand the whole body to the host, so everything the\n // table draws around a real row list is off in either of them.\n const isDelegatedView = isGroupedView || isKanbanView;\n const isCardsView = hasCardView && (viewMode === 'cards' || (forceCardsOnMobile && !isDelegatedView));\n const useAutoCards = forceCardsOnMobile && !hasCardView && !isDelegatedView;\n\n useEffect(() => {\n if (!gridStore || !commitStatuses) return;\n gridStore.getState().setCellStatuses(commitStatuses);\n }, [gridStore, commitStatuses]);\n\n const navigableColumnIds = useMemo(\n () =>\n visibleLeafColumns\n .filter((leafColumn) => columnConfigById.get(leafColumn.id)?.type !== 'actions')\n .map((leafColumn) => leafColumn.id),\n [visibleLeafColumns, columnConfigById],\n );\n const gridRowIds = useMemo(() => visibleRows.map((row) => row.id), [visibleRows]);\n\n useGridMatrixSync(gridStore, gridRowIds, navigableColumnIds);\n\n // Read through a ref so the callback stays stable while the rows change on\n // every edit: an unstable handler would re-bind the grid keyboard each render.\n const visibleRowsRef = useRef(visibleRows);\n visibleRowsRef.current = visibleRows;\n\n const canEditCell = useCallback(\n ({ rowId, columnId }: IGridCellCoord) => {\n if (!config.editing?.onCellChange) return false;\n\n const editable = columnConfigById.get(columnId)?.editable;\n if (!editable) return false;\n\n const row = visibleRowsRef.current.find((candidate) => candidate.id === rowId);\n if (!row) return false;\n\n return !(editable.disabled?.(row.original) ?? false);\n },\n [config.editing, columnConfigById],\n );\n\n const acceptsTypedValue = useCallback(\n ({ columnId }: IGridCellCoord) => {\n const editable = columnConfigById.get(columnId)?.editable;\n if (!editable || editable.renderEditor) return false;\n\n return editable.type === 'text' || editable.type === 'number';\n },\n [columnConfigById],\n );\n\n const handleGridKeyDown = useGridKeyboard({\n store: gridStore,\n canEditCell: hasEditableColumns ? canEditCell : undefined,\n acceptsTypedValue,\n onSave: spreadsheet?.onSave,\n });\n\n const handleFillCommit = useGridFillApply<T>({\n visibleRows,\n columnConfigById,\n spreadsheet,\n onCellChange: config.editing?.onCellChange,\n });\n\n // After an undo in the spreadsheet grid the restored cell becomes the active one, so\n // the user sees which cell changed, even when it sits on another row of the page.\n const handleTableKeyDown = useCallback(\n (event: KeyboardEvent<HTMLDivElement>) => {\n const restoredCell = handleUndoShortcut(event);\n if (!restoredCell || !gridStore || !gridStore.getState().isEditMode) return;\n\n const restoredGridRow = visibleRowsRef.current.find((candidate) => candidate.original.id === restoredCell.row.id);\n if (!restoredGridRow) return;\n gridStore.getState().setActiveCell({ rowId: restoredGridRow.id, columnId: restoredCell.columnId });\n },\n [handleUndoShortcut, gridStore],\n );\n\n const handleEditModeToggle = useCallback(() => {\n const store = gridStore;\n if (!store) return;\n store.getState().setEditMode(!store.getState().isEditMode);\n }, [gridStore]);\n\n const cardsScrollRef = useRef<HTMLDivElement | null>(null);\n const cardsSentinelRef = useRef<HTMLDivElement | null>(null);\n const cardsLoadMore = cardsInfiniteScroll?.loadMore;\n const cardsHasMore = cardsInfiniteScroll?.hasMore ?? false;\n\n // Cards infinite scroll: load the next page when the bottom sentinel enters the\n // cards scroll container. `loadMore` is stable and self-guards while a page is\n // in flight; re-running on row count keeps the observer bound after each append.\n useEffect(() => {\n if (!isCardsView || !cardsHasMore || !cardsLoadMore) return;\n\n const root = cardsScrollRef.current;\n const sentinel = cardsSentinelRef.current;\n if (!root || !sentinel) return;\n\n const observer = new IntersectionObserver(\n (entries) => {\n if (entries.some((entry) => entry.isIntersecting)) cardsLoadMore();\n },\n { root, rootMargin: '300px' },\n );\n observer.observe(sentinel);\n\n return () => observer.disconnect();\n }, [isCardsView, cardsHasMore, cardsLoadMore, visibleRows.length]);\n\n const listScrollRef = useRef<HTMLDivElement | null>(null);\n const [detailSlotWidth, setDetailSlotWidth] = useState<number | undefined>(undefined);\n const [parentHasHorizontalOverflow, setParentHasHorizontalOverflow] = useState(false);\n\n // Track the list scrollport: its clientWidth sizes the detail panel to the\n // visible area (detailTable expansion), and its horizontal overflow toggles the\n // frozen actions-column shadow (shown only while columns scroll under it, so\n // there is no always-on divider line otherwise). Observing the inner table too\n // keeps both in sync when columns are toggled or the layout reflows. The\n // branch-state deps re-bind when the scroller remounts (view/skeleton/error/\n // empty transitions swap the rendered subtree).\n useEffect(() => {\n const scroller = listScrollRef.current;\n if (!scroller) return undefined;\n\n const measure = () => {\n setDetailSlotWidth(scroller.clientWidth || undefined);\n setParentHasHorizontalOverflow(scroller.scrollWidth > scroller.clientWidth + 1);\n };\n measure();\n\n const observer = new ResizeObserver(measure);\n observer.observe(scroller);\n const parentTable = scroller.querySelector('table');\n if (parentTable) observer.observe(parentTable);\n\n return () => observer.disconnect();\n }, [isCardsView, isDelegatedView, showSkeleton, error, hasRows]);\n\n const renderBody = () => {\n // Grouped view delegates the whole body to the host (it owns fetching,\n // accordions, loading and empty states for each group).\n if (isGroupedView && config.renderGroupedBody) return config.renderGroupedBody();\n if (isKanbanView && config.renderKanbanBody) return config.renderKanbanBody();\n\n if (showSkeleton)\n return isCardsView ? (\n <DataTableCardsSkeletonState cardClassName={config.cardSkeletonClassName} />\n ) : (\n <DataTableSkeletonState rows={config.skeletonRows} />\n );\n\n if (error) return <DataTableErrorState onRetry={onRetry} errorCause={errorCause} />;\n\n // A `bodyTopRow` (e.g. an inline create editor) must stay visible even with\n // zero data rows, so it takes precedence over the empty state.\n if (!hasRows && !bodyTopRow) {\n if (isFit) {\n // Embedded/editor context: skip the full illustration so surrounding\n // controls (e.g. the add-row button) stay visible in a compact dialog.\n return emptyMessage ? (\n <div className=\"py-6 text-center text-sm text-foreground-faint\">{emptyMessage}</div>\n ) : null;\n }\n return <DataTableEmptyState emptyMessage={emptyMessage} />;\n }\n\n if (isCardsView && config.renderCard) {\n // Cards render from the SAME visible rows the table uses (already searched,\n // filtered, sorted and paginated), so both views share one source. No grid:\n // flex-wrap keeps the layout responsive per the project's no-CSS-grid rule.\n return (\n <div ref={cardsScrollRef} className=\"relative min-h-0 flex-1 overflow-y-auto @container\">\n {showUpdatingBar && (\n <div className=\"absolute inset-x-0 top-0 z-10 h-0.5 animate-pulse bg-brand-hover\" aria-hidden />\n )}\n {/* Cards têm largura fixa, então uma faixa estreita demais para duas colunas\n deixa a sobra toda de um lado. Abaixo disso eles se centram; a partir de\n duas colunas o alinhamento à esquerda volta a ser o que lê melhor. */}\n <div\n className={classNames(\n 'flex flex-wrap justify-center gap-4 @md:justify-start',\n dataTableOpacityTransitionClass,\n config.cardGridClassName,\n )}\n style={contentOpacityStyle}\n >\n {visibleRows\n .filter((row) => row.depth === 0)\n .map((row) => (\n <Fragment key={row.id}>{config.renderCard?.(row.original)}</Fragment>\n ))}\n </div>\n\n {cardsInfiniteScroll?.loadingMore && (\n <div className=\"flex justify-center py-4\">\n <LoadingSpinner size={6} />\n </div>\n )}\n\n {cardsHasMore && <div ref={cardsSentinelRef} className=\"h-px w-full\" aria-hidden />}\n </div>\n );\n }\n\n // Narrow viewport with no bespoke card renderer: stack each row into a card\n // derived from the same columns, so the list stays readable without the host\n // authoring a second renderer.\n if (useAutoCards) {\n return (\n <div className=\"flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto\">\n {visibleRows\n .filter((row) => row.depth === 0)\n .map((row) => (\n <DataTableAutoCard key={row.id} row={row} columnConfigById={columnConfigById} />\n ))}\n </div>\n );\n }\n\n // The table scrolls inside this bounded region (flex-1 + min-h-0). The sticky\n // header pins to the top of the data area; the region also scrolls horizontally\n // so columns keep a minimum readable width instead of being crushed. The first\n // column and the actions column are frozen (sticky left/right) so navigation\n // anchors stay visible while the middle columns scroll past.\n return (\n <div\n ref={listScrollRef}\n onKeyDown={gridStore ? handleGridKeyDown : undefined}\n className={classNames(\n 'relative [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-border-emphasis hover:[&::-webkit-scrollbar-thumb]:bg-foreground-faint [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar]:h-2.5 [&::-webkit-scrollbar]:w-2.5',\n // The rows scroll inside this bounded region (flex-1 + min-h-0), so the\n // host provides the height (a full page, or a bounded flex parent like a\n // fixed-size dialog) and the add-row/footer below stay pinned outside it.\n 'min-h-0 flex-1 overflow-auto',\n )}\n >\n {showUpdatingBar && (\n <div className=\"absolute inset-x-0 top-0 z-10 h-0.5 animate-pulse bg-brand-hover\" aria-hidden />\n )}\n <table\n role={gridStore ? 'grid' : undefined}\n aria-multiselectable={gridStore && spreadsheet?.selection === 'range' ? true : undefined}\n className={classNames(\n // `table-fixed`: column widths come exclusively from the colgroup so\n // user resizes are honored exactly (under `table-auto` the browser\n // ignores explicit col widths and sizes by content). The slack\n // absorber (auto-width col) still soaks any leftover space.\n 'min-w-full table-fixed border-separate border-spacing-0 rounded-md border-y border-border-subtle',\n dataTableOpacityTransitionClass,\n )}\n style={{ ...contentOpacityStyle, width: totalTableWidth || undefined }}\n >\n <DataTableHead\n table={table}\n columns={config.columns}\n columnConfigById={columnConfigById}\n columnContentWidths={columnContentWidths}\n columnOrder={columnOrder}\n onColumnOrderChange={onColumnOrderChange}\n resetColumnOrder={resetColumnOrder}\n resetColumnSizing={resetColumnSizing}\n onHeaderSortClick={handleHeaderSortClick}\n resolveSortDirection={resolveSortDirection}\n hideColumnToggle={columnTogglePlacement !== 'header'}\n flexColumnId={flexColumnId}\n showActionsShadow={parentHasHorizontalOverflow}\n dense={dense}\n spacious={spacious}\n />\n\n <DataTableBody\n config={config}\n visibleRows={visibleRows}\n columnConfigById={columnConfigById}\n columnContentWidths={columnContentWidths}\n registerRow={registerRow}\n onCollapseStart={beginRowsExit}\n detailColumnsState={detailColumnsState}\n detailSlotWidth={detailSlotWidth}\n showActionsShadow={parentHasHorizontalOverflow}\n dense={dense}\n spacious={spacious}\n fillEnabled={!!spreadsheet?.fill}\n editMode={isEditMode}\n canEditCell={canEditCell}\n bodyTopRow={bodyTopRow}\n bodyTopRowColSpan={table.getVisibleLeafColumns().length}\n />\n </table>\n </div>\n );\n };\n\n // Cards normally page themselves through infinite scroll, so the pager is\n // hidden. When the narrow viewport takes the choice over, the host is still in\n // list mode and its `cardsInfiniteScroll` is not wired: without the pager the\n // user would be stranded on the first page.\n const isMobileCardsTakeover = isCardsView && viewMode !== 'cards' && !cardsInfiniteScroll;\n\n const showPagination =\n (!isCardsView || isMobileCardsTakeover) &&\n !isDelegatedView &&\n !!clientPaginationProps &&\n !showSkeleton &&\n !error &&\n hasRows &&\n clientPaginationProps.numberOfPages > 0 &&\n !(clientPaginationProps.numberOfPages === 1 && clientPaginationProps.pageSize <= DATA_TABLE_MIN_PAGE_SIZE);\n\n // The toolbar only skeletons on the very first load: a refetch (tab switch,\n // filter, search) keeps the real controls mounted, so the search term and the\n // focus survive and the row never changes height.\n const [hasLoadedOnce, setHasLoadedOnce] = useState(!loading);\n\n useEffect(() => {\n if (!loading) setHasLoadedOnce(true);\n }, [loading]);\n\n const showSearch = (!!onSearch || isClientMode) && config.searchable !== false;\n const showToolbar =\n (tabs?.length ?? 0) > 0 ||\n hasCardView ||\n showSearch ||\n !!toolbarSlot ||\n !!toolbarStartSlot ||\n columnTogglePlacement === 'toolbar';\n\n const columnToggleSlot =\n columnTogglePlacement === 'toolbar' ? (\n <DataTableColumnToggle\n table={table}\n columns={config.columns}\n columnOrder={columnOrder}\n onColumnOrderChange={onColumnOrderChange}\n resetColumnOrder={resetColumnOrder}\n resetColumnSizing={resetColumnSizing}\n variant=\"toolbar\"\n />\n ) : undefined;\n\n // O rodapé é o lugar dos controles da própria tabela (colunas e modo de edição),\n // ao lado da paginação. Ambos só existem sobre uma lista real.\n const showTableControls = !isCardsView && !isDelegatedView && !showSkeleton && !error && hasRows;\n const showFooterColumnToggle = columnTogglePlacement === 'footer' && showTableControls;\n const showFooterEditToggle = showEditModeToggle && showTableControls;\n\n // A edição em massa não depende do modo de exibição: em cards ela é a única\n // forma de editar, já que não existe célula para clicar.\n const showBulkEdit =\n hasEditableColumns && !!spreadsheet?.fill?.onFillCells && !isDelegatedView && !showSkeleton && !error && hasRows;\n\n const showFooterControls = showFooterColumnToggle || showFooterEditToggle || showBulkEdit || !!footerActionsSlot;\n const bulkEditRows = useMemo(\n () => visibleRows.filter((row) => row.depth === 0).map((row) => row.original),\n [visibleRows],\n );\n\n const activeFiltersBar =\n config.filters && filterValues && onFilterValuesChange ? (\n <ActiveFiltersBar\n fields={config.filters.fields ?? []}\n values={filterValues}\n onRemove={(key) =>\n onFilterValuesChange({\n ...filterValues,\n [key]: emptyValueForKind((config.filters?.fields ?? []).find((field) => field.key === key)?.kind ?? 'text'),\n })\n }\n onClearAll={() => onFilterValuesChange(buildEmptyFilterValues(config.filters?.fields ?? []))}\n />\n ) : null;\n\n const content = (\n <div\n className=\"flex min-h-0 w-full flex-1 flex-col gap-4\"\n onKeyDown={isUndoEnabled ? handleTableKeyDown : undefined}\n >\n {activeFiltersBar}\n {showToolbar && (\n <DataTableToolbar\n tabs={tabs}\n activeTab={activeTab}\n onTabChange={handleTabChange}\n showViewToggle={hasCardView && !hideViewToggle && !forceCardsOnMobile}\n showGroupedView={hasGroupedView}\n showKanbanView={hasKanbanView}\n viewMode={viewMode}\n onViewModeChange={handleViewModeChange}\n showSearch={showSearch}\n searchLabel={searchLabel}\n initialSearch={initialSearch}\n searchDisabled={searchDisabled}\n searchDebounceTime={isClientMode ? clientSearchDebounceMs : searchDebounceTime}\n searchMinLength={searchMinLength}\n searchAtStart={searchAtStart}\n onSearchInput={handleSearchInput}\n toolbarSlot={toolbarSlot}\n toolbarStartSlot={toolbarStartSlot}\n columnToggleSlot={columnToggleSlot}\n showSkeleton={loading && !hasLoadedOnce}\n />\n )}\n\n <div key={viewMode} className=\"flex min-h-0 flex-1 animate-fade-in flex-col\">\n {renderBody()}\n </div>\n\n {showAddRow && (\n // Sibling of the scrolling rows region, so it stays pinned below the grid\n // (outside its scroll) — the rows scroll, this control does not move.\n <div className=\"flex\">\n <ControlledButton\n variant=\"outlined\"\n className=\"flex items-center gap-1.5\"\n onClick={() => editingRows?.onAddRow?.()}\n >\n <MaterialSymbol icon=\"add\" size={16} />\n {t('dataTable.addRow')}\n </ControlledButton>\n </div>\n )}\n\n {(showFooterControls || showPagination) && (\n <div className=\"flex items-center justify-between gap-4\">\n {showFooterControls && (\n <div className=\"flex flex-wrap items-center gap-2 pb-3\">\n {showFooterColumnToggle && (\n <DataTableColumnToggle\n table={table}\n columns={config.columns}\n columnOrder={columnOrder}\n onColumnOrderChange={onColumnOrderChange}\n resetColumnOrder={resetColumnOrder}\n resetColumnSizing={resetColumnSizing}\n variant=\"toolbar\"\n />\n )}\n {showFooterEditToggle && <DataTableEditModeButton active={isEditMode} onToggle={handleEditModeToggle} />}\n {showBulkEdit && <DataTableBulkEditButton onClick={() => setIsBulkEditOpen(true)} />}\n {footerActionsSlot}\n </div>\n )}\n\n {showPagination && (\n <div className=\"flex-1\">\n <DataTablePaginationBar\n pageSize={clientPaginationProps.pageSize}\n numberOfPages={clientPaginationProps.numberOfPages}\n currentPage={clientPaginationProps.currentPage}\n setCurrentPage={clientPaginationProps.setCurrentPage}\n onPageSizeChange={clientPaginationProps.onPageSizeChange}\n totalItems={clientPaginationProps.totalItems}\n />\n </div>\n )}\n </div>\n )}\n\n {showBulkEdit && (\n <DataTableBulkEditDialog\n open={isBulkEditOpen}\n onClose={() => setIsBulkEditOpen(false)}\n columns={config.columns}\n rows={bulkEditRows}\n getRowLabel={config.getRowLabel}\n onApply={(changes) => spreadsheet?.fill?.onFillCells?.(changes)}\n />\n )}\n </div>\n );\n\n // Os providers ficam por fora do conteúdo já montado: abrir ou fechar uma célula re-renderiza\n // apenas as células editáveis, não a tabela inteira.\n const editableContent = config.editing?.clickToEdit ? (\n <DataTableCellEditingProvider>{content}</DataTableCellEditingProvider>\n ) : (\n content\n );\n\n if (!gridStore) return editableContent;\n\n return (\n <GridProvider store={gridStore} canEditCell={canEditCell} onFillCommit={handleFillCommit}>\n {editableContent}\n </GridProvider>\n );\n};\n\nexport default DataTable;\n"],"names":["DataTablePaginationBar"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8JA,MAAM,YAAY,CAAmE;AAAA,EACnF,QAAQ;AAAA,EACR;AAAA,EACA,UAAU;AAAA,EACV,QAAQ;AAAA,EACR;AAAA,EACA;AAAA,EACA;AAA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,gBACA,SAAQ;AAAA,cAAA;AAAA,YAAA;AAAA,YAGX,wBAAwB,oBAAC,yBAAA,EAAwB,QAAQ,YAAY,UAAU,sBAAsB;AAAA,YACrG,gBAAgB,oBAAC,yBAAA,EAAwB,SAAS,MAAM,kBAAkB,IAAI,GAAG;AAAA,YACjF;AAAA,UAAA,GACH;AAAA,UAGD,kBACC,oBAAC,OAAA,EAAI,WAAU,UACb,UAAA;AAAA,YAACA;AAAAA,YAAA;AAAA,cACC,UAAU,sBAAsB;AAAA,cAChC,eAAe,sBAAsB;AAAA,cACrC,aAAa,sBAAsB;AAAA,cACnC,gBAAgB,sBAAsB;AAAA,cACtC,kBAAkB,sBAAsB;AAAA,cACxC,YAAY,sBAAsB;AAAA,YAAA;AAAA,UAAA,EACpC,CACF;AAAA,QAAA,GAEJ;AAAA,QAGD,gBACC;AAAA,UAAC;AAAA,UAAA;AAAA,YACC,MAAM;AAAA,YACN,SAAS,MAAM,kBAAkB,KAAK;AAAA,YACtC,SAAS,OAAO;AAAA,YAChB,MAAM;AAAA,YACN,aAAa,OAAO;AAAA,YACpB,SAAS,CAAC,YAAY,aAAa,MAAM,cAAc,OAAO;AAAA,UAAA;AAAA,QAAA;AAAA,MAChE;AAAA,IAAA;AAAA,EAAA;AAON,QAAM,kBAAkB,OAAO,SAAS,cACtC,oBAAC,8BAAA,EAA8B,mBAAQ,IAEvC;AAGF,MAAI,CAAC,UAAW,QAAO;AAEvB,6BACG,cAAA,EAAa,OAAO,WAAW,aAA0B,cAAc,kBACrE,UAAA,iBACH;AAEJ;"}
|
|
1
|
+
{"version":3,"file":"DataTable.js","sources":["../../../../src/components/UI/DataTable/DataTable.tsx"],"sourcesContent":["import { Fragment, JSX, KeyboardEvent, ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport classNames from 'classnames';\nimport { useTranslation } from 'react-i18next';\n\nimport ControlledButton from '@/components/Form/ControlledButton';\nimport { ActiveFiltersBar, buildEmptyFilterValues, emptyValueForKind } from '@/components/Search/filters';\nimport LoadingSpinner from '@/components/UI/LoadingSpinner';\nimport { MaterialSymbol } from '@/components/UI/MaterialSymbol';\nimport { useBreakpoint } from '@/hooks/useBreakpoint';\n\nimport GridProvider from './grid/GridProvider';\nimport { type IGridCellCoord } from './grid/gridTypes';\nimport { useGridFillApply } from './grid/useGridFillApply';\nimport { useGridEditMode, useGridInstance, useGridMatrixSync } from './grid/useGridInstance';\nimport { useGridKeyboard } from './grid/useGridKeyboard';\nimport DataTableAutoCard from './DataTableAutoCard';\nimport DataTableBody from './DataTableBody';\nimport DataTableBulkEditButton from './DataTableBulkEditButton';\nimport DataTableBulkEditDialog from './DataTableBulkEditDialog';\nimport { isBadgeColumnType } from './dataTableClasses';\nimport DataTableColumnToggle from './DataTableColumnToggle';\nimport { type IDataTableDetailColumnsState } from './DataTableDetailTable';\nimport DataTableEditModeButton from './DataTableEditModeButton';\nimport DataTableHead from './DataTableHead';\nimport DataTablePaginationBar, { DATA_TABLE_MIN_PAGE_SIZE } from './DataTablePagination';\nimport {\n DataTableCardsSkeletonState,\n DataTableEmptyState,\n DataTableErrorState,\n DataTableSkeletonState,\n} from './DataTableStates';\nimport DataTableToolbar from './DataTableToolbar';\nimport {\n DATA_TABLE_REMOVE_COLUMN_ID,\n type IDataTableColumnConfig,\n type IDataTableConfig,\n type IDataTableRow,\n type IDataTableSortState,\n type IDataTableSpreadsheetConfig,\n isDataTableDetailTableExpansion,\n type TDataTableFilterValues,\n type TDataTableViewMode,\n} from './types';\nimport DataTableCellEditingProvider from './useCellEditingState';\nimport { useColumnOrder, useDetailColumnOrder } from './useColumnOrder';\nimport { useColumnSizing } from './useColumnSizing';\nimport { useColumnVisibility, useDetailColumnVisibility } from './useColumnVisibility';\nimport {\n type IDataTableClientPaginationState,\n type IDataTablePagination,\n useDataTableInstance,\n} from './useDataTableInstance';\nimport { useDataTableUndoHistory } from './useDataTableUndoHistory';\n\ninterface IDataTableProps<T extends IDataTableRow, C extends IDataTableRow = IDataTableRow> {\n config: IDataTableConfig<T, C>;\n rows: Array<T>;\n loading?: boolean;\n error?: boolean;\n /** Cause behind `error`, so the empty state can name a denial instead of a system failure. */\n errorCause?: unknown;\n onRetry?: () => void;\n emptyMessage?: string;\n searchLabel?: string;\n onSearch?: (value: string) => void;\n initialSearch?: string;\n onSearchTermChange?: (value: string) => void;\n searchDisabled?: boolean;\n searchDebounceTime?: number;\n searchMinLength?: number;\n /** Renders the search input in the toolbar's start (left) group instead of the end. */\n searchAtStart?: boolean;\n sort?: IDataTableSortState | null;\n onSortChange?: (sort: IDataTableSortState | null) => void;\n pagination?: IDataTablePagination;\n /** Client mode: seeds page/pageSize (1-based page), e.g. from the URL. */\n initialClientPagination?: IDataTableClientPaginationState;\n /** Client mode: reports page/pageSize changes and keeps the page across in-place row updates. */\n onClientPaginationChange?: (pagination: IDataTableClientPaginationState) => void;\n toolbarSlot?: JSX.Element;\n /**\n * Extra controls rendered in the footer's left group, right after the table's\n * own buttons (columns, edit mode, bulk edit). For an action that belongs to\n * the list itself rather than to the page header, so it sits beside the\n * controls it relates to instead of competing with the page actions. The\n * footer row renders for this slot alone when the table has no other control.\n */\n footerActionsSlot?: ReactNode;\n /**\n * Applied filter values. Passing them (together with `config.filters`) makes\n * the table render the always-visible active-filter chips above the toolbar,\n * so the user never has to hover the button to see what is filtering.\n */\n filterValues?: TDataTableFilterValues;\n onFilterValuesChange?: (values: TDataTableFilterValues) => void;\n /** Rendered at the start (left) of the toolbar, before tabs and view toggle. */\n toolbarStartSlot?: JSX.Element;\n /**\n * Full-width band rendered as the first row of the list body, spanning every\n * column (below the header, above the data rows). Opt-in: omit for a normal\n * table. When set, the empty state is skipped so the band stays visible even\n * with zero data rows (e.g. an inline \"create the first record\" editor).\n */\n bodyTopRow?: ReactNode;\n /** Client mode: reports the filtered (post-search) row count on every change. */\n onFilteredCountChange?: (count: number) => void;\n /**\n * Controlled view mode. When provided, the host owns the state (e.g. to persist\n * it) and must update it via `onViewModeChange`; omit for internal state.\n */\n viewMode?: TDataTableViewMode;\n /**\n * Fired on every view-toggle click, including re-selecting the active mode\n * (hosts use it e.g. to reopen the grouping dialog).\n */\n onViewModeChange?: (mode: TDataTableViewMode) => void;\n /**\n * Where the \"Columns\" toggle renders: `header` (default, inside the table\n * header), `toolbar` (next to the view toggle) or `footer` (bottom-left,\n * on the same row as the pagination).\n */\n columnTogglePlacement?: 'header' | 'toolbar' | 'footer';\n /**\n * Enables infinite scroll in the Cards view: the table observes a bottom\n * sentinel and calls `loadMore` while `hasMore`. Pass `source.cardsInfinite`\n * from `useDataTableSource`. The Lista view keeps its pagination bar.\n */\n cardsInfiniteScroll?: {\n hasMore: boolean;\n loadingMore: boolean;\n loadMore: () => void;\n };\n /**\n * Hides the built-in segmented view toggle. Use when the host renders its own\n * Cards/Lista switcher (e.g. a page-level `ControlledTabs`) and drives `viewMode`\n * itself. Other consumers keep the default toggle.\n */\n hideViewToggle?: boolean;\n /**\n * Layout mode. `page` (default): the table owns a bounded, vertically-scrolling\n * region (`flex-1 min-h-0`) for full-page lists. `fit`: the table sizes to its\n * content and scrolls only horizontally — for embedding inside a dialog / card /\n * editor grid where the host container owns vertical scroll. In `fit` mode the\n * empty state is compact (no full illustration) so surrounding controls such as\n * the add-row button stay visible.\n */\n layout?: 'page' | 'fit';\n /** Reduces cell vertical padding for more visible rows per viewport. */\n dense?: boolean;\n /** Roomier cell padding and type scale, for tables that need to read bigger. */\n spacious?: boolean;\n /**\n * Per-cell persistence state (`statuses` from `useDataTableCommitQueue`), painted\n * on the cells so the user sees what is saving and what failed.\n */\n commitStatuses?: ReadonlyMap<string, string>;\n}\n\nconst DataTable = <T extends IDataTableRow, C extends IDataTableRow = IDataTableRow>({\n config: configProp,\n rows,\n loading = false,\n error = false,\n errorCause,\n onRetry,\n emptyMessage,\n searchLabel,\n onSearch,\n initialSearch = '',\n onSearchTermChange,\n searchDisabled = false,\n searchDebounceTime = 400,\n searchMinLength = 1,\n searchAtStart = false,\n sort,\n onSortChange,\n pagination,\n initialClientPagination,\n onClientPaginationChange,\n toolbarSlot,\n footerActionsSlot,\n filterValues,\n onFilterValuesChange,\n toolbarStartSlot,\n bodyTopRow,\n onFilteredCountChange,\n viewMode: controlledViewMode,\n onViewModeChange,\n columnTogglePlacement = 'header',\n cardsInfiniteScroll,\n hideViewToggle = false,\n layout = 'page',\n dense: denseProp = false,\n spacious = false,\n commitStatuses,\n}: IDataTableProps<T, C>) => {\n const { t } = useTranslation('ui');\n\n const isFit = layout === 'fit';\n const dense = !spacious && (isFit || denseProp);\n const editingRows = configProp.editing?.rows;\n const showAddRow = !!editingRows?.canAdd && !!editingRows.onAddRow;\n\n const hostFillCells = configProp.spreadsheet ? configProp.spreadsheet.fill?.onFillCells : undefined;\n const isUndoEnabled = !!configProp.editing?.onCellChange && configProp.editing.undo !== false;\n const { recordedOnCellChange, recordedOnFillCells, handleUndoShortcut } = useDataTableUndoHistory<T>({\n enabled: isUndoEnabled,\n rows,\n columns: configProp.columns,\n onCellChange: configProp.editing?.onCellChange,\n onFillCells: hostFillCells,\n });\n\n const configWithUndo = useMemo<IDataTableConfig<T, C>>(() => {\n if (!isUndoEnabled || !configProp.editing) return configProp;\n\n const spreadsheetConfig = configProp.spreadsheet;\n return {\n ...configProp,\n editing: { ...configProp.editing, onCellChange: recordedOnCellChange },\n spreadsheet:\n spreadsheetConfig && spreadsheetConfig.fill?.onFillCells\n ? { ...spreadsheetConfig, fill: { ...spreadsheetConfig.fill, onFillCells: recordedOnFillCells } }\n : spreadsheetConfig,\n };\n }, [configProp, isUndoEnabled, recordedOnCellChange, recordedOnFillCells]);\n\n // When `editing.rows.onRemoveRow` is set, append a synthetic trailing actions\n // column carrying a per-row delete control. It is a real `actions` column, so\n // it flows through the existing sizing / sticky-right / flex-exclusion / order\n // paths unchanged (see useColumnOrder: actions columns are pinned to the end).\n const config = useMemo<IDataTableConfig<T, C>>(() => {\n if (!editingRows?.onRemoveRow) return configWithUndo;\n\n const removeColumn: IDataTableColumnConfig<T> = {\n id: DATA_TABLE_REMOVE_COLUMN_ID,\n header: '',\n type: 'actions',\n hideable: false,\n resizable: false,\n actions: [\n {\n key: 'remove',\n label: t('dataTable.removeRow'),\n icon: 'delete',\n danger: true,\n hidden: (row) => (editingRows.canRemove ? !editingRows.canRemove(row) : false),\n onClick: (row) => editingRows.onRemoveRow?.(row),\n },\n ],\n };\n\n return { ...configWithUndo, columns: [...configWithUndo.columns, removeColumn] };\n }, [configWithUndo, editingRows, t]);\n\n const { columnVisibility, onColumnVisibilityChange } = useColumnVisibility(config);\n const { columnOrder, onColumnOrderChange, resetColumnOrder } = useColumnOrder(config);\n const { columnSizing, onColumnSizingChange, resetColumnSizing } = useColumnSizing(config);\n\n // Every table restores the persisted column order back to the config default\n // on mount (equivalent to firing \"Restaurar ordem padrão\" from the columns\n // menu), so a stale/incompatible persisted order never sticks. Does not touch\n // column widths or visibility, and does not affect the Cards view.\n useEffect(() => {\n resetColumnOrder();\n }, []);\n\n const detailExpansionColumns =\n config.expansion && isDataTableDetailTableExpansion(config.expansion) && Array.isArray(config.expansion.columns)\n ? config.expansion.columns\n : null;\n const { detailColumnVisibility, toggleDetailColumn } = useDetailColumnVisibility(\n config.entityKey,\n detailExpansionColumns,\n );\n const { detailColumnOrder, onDetailColumnOrderChange, resetDetailColumnOrder } = useDetailColumnOrder(\n config.entityKey,\n detailExpansionColumns,\n );\n\n const detailColumnsState: IDataTableDetailColumnsState | undefined = detailExpansionColumns\n ? {\n visibility: detailColumnVisibility,\n toggleVisibility: toggleDetailColumn,\n order: detailColumnOrder,\n onOrderChange: onDetailColumnOrderChange,\n resetOrder: resetDetailColumnOrder,\n }\n : undefined;\n\n const { isMobile } = useBreakpoint();\n\n const hasCardView = !!config.renderCard;\n const hasGroupedView = !!config.renderGroupedBody;\n const hasKanbanView = !!config.renderKanbanBody;\n // Fixed behaviour: card-capable tables always open on Cards (first), Lista second.\n // The toggle switches within the session and resets to Cards on remount, unless\n // the host controls the mode via the `viewMode` prop (e.g. persisted preference).\n const [internalViewMode, setInternalViewMode] = useState<TDataTableViewMode>('cards');\n const viewMode = controlledViewMode ?? internalViewMode;\n\n const [isBulkEditOpen, setIsBulkEditOpen] = useState(false);\n\n const handleViewModeChange = (mode: TDataTableViewMode) => {\n if (controlledViewMode === undefined) setInternalViewMode(mode);\n onViewModeChange?.(mode);\n };\n\n const {\n table,\n isClientMode,\n columnContentWidths,\n registerRow,\n beginRowsExit,\n visibleRows,\n activeTab,\n tabs,\n handleTabChange,\n handleSearchInput,\n handleHeaderSortClick,\n resolveSortDirection,\n clientPaginationProps,\n showUpdatingBar,\n contentOpacityStyle,\n dataTableOpacityTransitionClass,\n showSkeleton,\n hasRows,\n clientSearchDebounceMs,\n } = useDataTableInstance({\n config,\n rows,\n loading,\n sort,\n onSortChange,\n onSearch,\n initialSearch,\n onSearchTermChange,\n pagination,\n initialClientPagination,\n onClientPaginationChange,\n columnVisibility,\n onColumnVisibilityChange,\n columnOrder,\n onColumnOrderChange,\n columnSizing,\n onColumnSizingChange,\n onFilteredCountChange,\n });\n\n const columnConfigById = useMemo(\n () => new Map(config.columns.map((columnConfig) => [columnConfig.id, columnConfig])),\n [config.columns],\n );\n\n // Under `table-fixed` one column absorbs leftover horizontal space. The last\n // visible non-actions, non-badge, non-first column is the flex column.\n const visibleLeafColumns = table.getVisibleLeafColumns();\n const flexColumnId = useMemo(() => {\n if (config.flexColumnId && visibleLeafColumns.some((leafColumn) => leafColumn.id === config.flexColumnId)) {\n return config.flexColumnId;\n }\n\n const candidates = visibleLeafColumns.filter((leafColumn, index) => {\n if (index === 0) return false;\n const type = columnConfigById.get(leafColumn.id)?.type;\n return type !== 'actions' && !isBadgeColumnType(type);\n });\n return candidates[candidates.length - 1]?.id ?? null;\n }, [visibleLeafColumns, columnConfigById, config.flexColumnId]);\n\n // `table-fixed` sizes columns from the table width, so the table must be at\n // least the sum of ALL column widths (including the absorber's seed) for their\n // widths to be honored; below that the browser shrinks them proportionally.\n // `min-w-full` still lets the table stretch to fill the container, and the\n // auto-width absorber soaks the surplus (never shrinking below its own seed,\n // because its seed is part of this total).\n const totalTableWidth = useMemo(\n () => visibleLeafColumns.reduce((sum, leafColumn) => sum + leafColumn.getSize(), 0),\n [visibleLeafColumns, columnSizing],\n );\n\n // ----- Spreadsheet layer -----\n // Toda tabela com coluna editável ganha a camada de planilha sem configuração, ativa\n // desde a montagem. Numa tabela com `onRowClick` a célula editável é dona do próprio\n // clique (abre o editor) e o resto da linha continua abrindo o registro.\n const spreadsheet = useMemo<IDataTableSpreadsheetConfig<T> | undefined>(() => {\n if (config.spreadsheet === false) return undefined;\n return config.spreadsheet ?? { selection: 'range', fill: {} };\n }, [config.spreadsheet]);\n\n const hasEditableColumns = useMemo(\n () => !!config.editing?.onCellChange && config.columns.some((columnConfig) => !!columnConfig.editable),\n [config.editing, config.columns],\n );\n\n const editModeBehavior = spreadsheet?.mode ?? 'always';\n const gridEnabled = !!spreadsheet && (hasEditableColumns || !!config.spreadsheet);\n\n const gridStore = useGridInstance({\n spreadsheet,\n enabled: gridEnabled,\n startsInEditMode: editModeBehavior === 'always',\n });\n\n const isEditMode = useGridEditMode(gridStore);\n const showEditModeToggle = gridEnabled && editModeBehavior === 'toggle';\n\n // Below the tablet edge a real table is unreadable: even the narrowest column\n // set overflows and the user reads it through a horizontal scrollbar. Cards are\n // the readable shape there, so the narrow viewport takes over the choice.\n // Excluded: `fit` layouts without a bespoke card (their cell geometry IS the\n // feature) and a table whose reason to exist is editing. Merely being able to edit\n // is not enough: a table that opens a record on row click is a reading surface\n // first, unless the user turned its edit toggle on. A `fit` table that ships\n // `renderCard` opted into a narrow shape, so it takes over as well.\n const isEditingSurface = isEditMode && (editModeBehavior === 'toggle' || !config.onRowClick);\n const forceCardsOnMobile = isMobile && (!isFit || hasCardView) && !isEditingSurface;\n\n const isGroupedView = hasGroupedView && viewMode === 'grouped';\n const isKanbanView = hasKanbanView && viewMode === 'kanban';\n // Grouped and kanban both hand the whole body to the host, so everything the\n // table draws around a real row list is off in either of them.\n const isDelegatedView = isGroupedView || isKanbanView;\n const isCardsView = hasCardView && (viewMode === 'cards' || (forceCardsOnMobile && !isDelegatedView));\n const useAutoCards = forceCardsOnMobile && !hasCardView && !isDelegatedView;\n\n useEffect(() => {\n if (!gridStore || !commitStatuses) return;\n gridStore.getState().setCellStatuses(commitStatuses);\n }, [gridStore, commitStatuses]);\n\n const navigableColumnIds = useMemo(\n () =>\n visibleLeafColumns\n .filter((leafColumn) => columnConfigById.get(leafColumn.id)?.type !== 'actions')\n .map((leafColumn) => leafColumn.id),\n [visibleLeafColumns, columnConfigById],\n );\n const gridRowIds = useMemo(() => visibleRows.map((row) => row.id), [visibleRows]);\n\n useGridMatrixSync(gridStore, gridRowIds, navigableColumnIds);\n\n // Read through a ref so the callback stays stable while the rows change on\n // every edit: an unstable handler would re-bind the grid keyboard each render.\n const visibleRowsRef = useRef(visibleRows);\n visibleRowsRef.current = visibleRows;\n\n const canEditCell = useCallback(\n ({ rowId, columnId }: IGridCellCoord) => {\n if (!config.editing?.onCellChange) return false;\n\n const editable = columnConfigById.get(columnId)?.editable;\n if (!editable) return false;\n\n const row = visibleRowsRef.current.find((candidate) => candidate.id === rowId);\n if (!row) return false;\n\n return !(editable.disabled?.(row.original) ?? false);\n },\n [config.editing, columnConfigById],\n );\n\n const acceptsTypedValue = useCallback(\n ({ columnId }: IGridCellCoord) => {\n const editable = columnConfigById.get(columnId)?.editable;\n if (!editable || editable.renderEditor) return false;\n\n return editable.type === 'text' || editable.type === 'number';\n },\n [columnConfigById],\n );\n\n const handleGridKeyDown = useGridKeyboard({\n store: gridStore,\n canEditCell: hasEditableColumns ? canEditCell : undefined,\n acceptsTypedValue,\n onSave: spreadsheet?.onSave,\n });\n\n const handleFillCommit = useGridFillApply<T>({\n visibleRows,\n columnConfigById,\n spreadsheet,\n onCellChange: config.editing?.onCellChange,\n });\n\n // After an undo in the spreadsheet grid the restored cell becomes the active one, so\n // the user sees which cell changed, even when it sits on another row of the page.\n const handleTableKeyDown = useCallback(\n (event: KeyboardEvent<HTMLDivElement>) => {\n const restoredCell = handleUndoShortcut(event);\n if (!restoredCell || !gridStore || !gridStore.getState().isEditMode) return;\n\n const restoredGridRow = visibleRowsRef.current.find((candidate) => candidate.original.id === restoredCell.row.id);\n if (!restoredGridRow) return;\n gridStore.getState().setActiveCell({ rowId: restoredGridRow.id, columnId: restoredCell.columnId });\n },\n [handleUndoShortcut, gridStore],\n );\n\n const handleEditModeToggle = useCallback(() => {\n const store = gridStore;\n if (!store) return;\n store.getState().setEditMode(!store.getState().isEditMode);\n }, [gridStore]);\n\n const cardsScrollRef = useRef<HTMLDivElement | null>(null);\n const cardsSentinelRef = useRef<HTMLDivElement | null>(null);\n const cardsLoadMore = cardsInfiniteScroll?.loadMore;\n const cardsHasMore = cardsInfiniteScroll?.hasMore ?? false;\n\n // Cards infinite scroll: load the next page when the bottom sentinel enters the\n // cards scroll container. `loadMore` is stable and self-guards while a page is\n // in flight; re-running on row count keeps the observer bound after each append.\n useEffect(() => {\n if (!isCardsView || !cardsHasMore || !cardsLoadMore) return;\n\n const root = cardsScrollRef.current;\n const sentinel = cardsSentinelRef.current;\n if (!root || !sentinel) return;\n\n const observer = new IntersectionObserver(\n (entries) => {\n if (entries.some((entry) => entry.isIntersecting)) cardsLoadMore();\n },\n { root, rootMargin: '300px' },\n );\n observer.observe(sentinel);\n\n return () => observer.disconnect();\n }, [isCardsView, cardsHasMore, cardsLoadMore, visibleRows.length]);\n\n const listScrollRef = useRef<HTMLDivElement | null>(null);\n const [detailSlotWidth, setDetailSlotWidth] = useState<number | undefined>(undefined);\n const [parentHasHorizontalOverflow, setParentHasHorizontalOverflow] = useState(false);\n\n // Track the list scrollport: its clientWidth sizes the detail panel to the\n // visible area (detailTable expansion), and its horizontal overflow toggles the\n // frozen actions-column shadow (shown only while columns scroll under it, so\n // there is no always-on divider line otherwise). Observing the inner table too\n // keeps both in sync when columns are toggled or the layout reflows. The\n // branch-state deps re-bind when the scroller remounts (view/skeleton/error/\n // empty transitions swap the rendered subtree).\n useEffect(() => {\n const scroller = listScrollRef.current;\n if (!scroller) return undefined;\n\n const measure = () => {\n setDetailSlotWidth(scroller.clientWidth || undefined);\n setParentHasHorizontalOverflow(scroller.scrollWidth > scroller.clientWidth + 1);\n };\n measure();\n\n const observer = new ResizeObserver(measure);\n observer.observe(scroller);\n const parentTable = scroller.querySelector('table');\n if (parentTable) observer.observe(parentTable);\n\n return () => observer.disconnect();\n }, [isCardsView, isDelegatedView, showSkeleton, error, hasRows]);\n\n const renderBody = () => {\n // Grouped view delegates the whole body to the host (it owns fetching,\n // accordions, loading and empty states for each group).\n if (isGroupedView && config.renderGroupedBody) return config.renderGroupedBody();\n if (isKanbanView && config.renderKanbanBody) return config.renderKanbanBody();\n\n if (showSkeleton)\n return isCardsView ? (\n <DataTableCardsSkeletonState cardClassName={config.cardSkeletonClassName} />\n ) : (\n <DataTableSkeletonState rows={config.skeletonRows} />\n );\n\n if (error) return <DataTableErrorState onRetry={onRetry} errorCause={errorCause} />;\n\n // A `bodyTopRow` (e.g. an inline create editor) must stay visible even with\n // zero data rows, so it takes precedence over the empty state.\n if (!hasRows && !bodyTopRow) {\n if (isFit) {\n // Embedded/editor context: skip the full illustration so surrounding\n // controls (e.g. the add-row button) stay visible in a compact dialog.\n return emptyMessage ? (\n <div className=\"py-6 text-center text-sm text-foreground-faint\">{emptyMessage}</div>\n ) : null;\n }\n return <DataTableEmptyState emptyMessage={emptyMessage} />;\n }\n\n if (isCardsView && config.renderCard) {\n // Cards render from the SAME visible rows the table uses (already searched,\n // filtered, sorted and paginated), so both views share one source. No grid:\n // flex-wrap keeps the layout responsive per the project's no-CSS-grid rule.\n return (\n <div ref={cardsScrollRef} className=\"relative min-h-0 flex-1 overflow-y-auto @container\">\n {showUpdatingBar && (\n <div className=\"absolute inset-x-0 top-0 z-10 h-0.5 animate-pulse bg-brand-hover\" aria-hidden />\n )}\n {/* Cards têm largura fixa, então uma faixa estreita demais para duas colunas\n deixa a sobra toda de um lado. Abaixo disso eles se centram; a partir de\n duas colunas o alinhamento à esquerda volta a ser o que lê melhor. */}\n <div\n className={classNames(\n 'flex flex-wrap justify-center gap-4 @md:justify-start',\n dataTableOpacityTransitionClass,\n config.cardGridClassName,\n )}\n style={contentOpacityStyle}\n >\n {visibleRows\n .filter((row) => row.depth === 0)\n .map((row) => (\n <Fragment key={row.id}>{config.renderCard?.(row.original)}</Fragment>\n ))}\n </div>\n\n {cardsInfiniteScroll?.loadingMore && (\n <div className=\"flex justify-center py-4\">\n <LoadingSpinner size={6} />\n </div>\n )}\n\n {cardsHasMore && <div ref={cardsSentinelRef} className=\"h-px w-full\" aria-hidden />}\n </div>\n );\n }\n\n // Narrow viewport with no bespoke card renderer: stack each row into a card\n // derived from the same columns, so the list stays readable without the host\n // authoring a second renderer.\n if (useAutoCards) {\n return (\n <div className=\"flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto\">\n {visibleRows\n .filter((row) => row.depth === 0)\n .map((row) => (\n <DataTableAutoCard key={row.id} row={row} columnConfigById={columnConfigById} />\n ))}\n </div>\n );\n }\n\n // The table scrolls inside this bounded region (flex-1 + min-h-0). The sticky\n // header pins to the top of the data area; the region also scrolls horizontally\n // so columns keep a minimum readable width instead of being crushed. The first\n // column and the actions column are frozen (sticky left/right) so navigation\n // anchors stay visible while the middle columns scroll past.\n return (\n <div\n ref={listScrollRef}\n onKeyDown={gridStore ? handleGridKeyDown : undefined}\n className={classNames(\n 'relative [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-border-emphasis hover:[&::-webkit-scrollbar-thumb]:bg-foreground-faint [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar]:h-2.5 [&::-webkit-scrollbar]:w-2.5',\n // The rows scroll inside this bounded region (flex-1 + min-h-0), so the\n // host provides the height (a full page, or a bounded flex parent like a\n // fixed-size dialog) and the add-row/footer below stay pinned outside it.\n 'min-h-0 flex-1 overflow-auto',\n )}\n >\n {showUpdatingBar && (\n <div className=\"absolute inset-x-0 top-0 z-10 h-0.5 animate-pulse bg-brand-hover\" aria-hidden />\n )}\n <table\n role={gridStore ? 'grid' : undefined}\n aria-multiselectable={gridStore && spreadsheet?.selection === 'range' ? true : undefined}\n className={classNames(\n // `table-fixed`: column widths come exclusively from the colgroup so\n // user resizes are honored exactly (under `table-auto` the browser\n // ignores explicit col widths and sizes by content). The slack\n // absorber (auto-width col) still soaks any leftover space.\n 'min-w-full table-fixed border-separate border-spacing-0 rounded-md border-y border-border-subtle',\n dataTableOpacityTransitionClass,\n )}\n style={{ ...contentOpacityStyle, width: totalTableWidth || undefined }}\n >\n <DataTableHead\n table={table}\n columns={config.columns}\n columnConfigById={columnConfigById}\n columnContentWidths={columnContentWidths}\n columnOrder={columnOrder}\n onColumnOrderChange={onColumnOrderChange}\n resetColumnOrder={resetColumnOrder}\n resetColumnSizing={resetColumnSizing}\n onHeaderSortClick={handleHeaderSortClick}\n resolveSortDirection={resolveSortDirection}\n hideColumnToggle={columnTogglePlacement !== 'header'}\n flexColumnId={flexColumnId}\n showActionsShadow={parentHasHorizontalOverflow}\n dense={dense}\n spacious={spacious}\n />\n\n <DataTableBody\n config={config}\n visibleRows={visibleRows}\n columnConfigById={columnConfigById}\n columnContentWidths={columnContentWidths}\n registerRow={registerRow}\n onCollapseStart={beginRowsExit}\n detailColumnsState={detailColumnsState}\n detailSlotWidth={detailSlotWidth}\n showActionsShadow={parentHasHorizontalOverflow}\n dense={dense}\n spacious={spacious}\n fillEnabled={!!spreadsheet?.fill}\n editMode={isEditMode}\n canEditCell={canEditCell}\n bodyTopRow={bodyTopRow}\n bodyTopRowColSpan={table.getVisibleLeafColumns().length}\n />\n </table>\n </div>\n );\n };\n\n // Cards normally page themselves through infinite scroll, so the pager is\n // hidden. When the narrow viewport takes the choice over, the host is still in\n // list mode and its `cardsInfiniteScroll` is not wired: without the pager the\n // user would be stranded on the first page.\n const isMobileCardsTakeover = isCardsView && viewMode !== 'cards' && !cardsInfiniteScroll;\n\n const showPagination =\n (!isCardsView || isMobileCardsTakeover) &&\n !isDelegatedView &&\n !!clientPaginationProps &&\n !showSkeleton &&\n !error &&\n hasRows &&\n clientPaginationProps.numberOfPages > 0 &&\n !(clientPaginationProps.numberOfPages === 1 && clientPaginationProps.pageSize <= DATA_TABLE_MIN_PAGE_SIZE);\n\n // The toolbar only skeletons on the very first load: a refetch (tab switch,\n // filter, search) keeps the real controls mounted, so the search term and the\n // focus survive and the row never changes height.\n const [hasLoadedOnce, setHasLoadedOnce] = useState(!loading);\n\n useEffect(() => {\n if (!loading) setHasLoadedOnce(true);\n }, [loading]);\n\n const showSearch = (!!onSearch || isClientMode) && config.searchable !== false;\n const showToolbar =\n (tabs?.length ?? 0) > 0 ||\n hasCardView ||\n showSearch ||\n !!toolbarSlot ||\n !!toolbarStartSlot ||\n columnTogglePlacement === 'toolbar';\n\n const columnToggleSlot =\n columnTogglePlacement === 'toolbar' ? (\n <DataTableColumnToggle\n table={table}\n columns={config.columns}\n columnOrder={columnOrder}\n onColumnOrderChange={onColumnOrderChange}\n resetColumnOrder={resetColumnOrder}\n resetColumnSizing={resetColumnSizing}\n variant=\"toolbar\"\n />\n ) : undefined;\n\n // O rodapé é o lugar dos controles da própria tabela (colunas e modo de edição),\n // ao lado da paginação. Ambos só existem sobre uma lista real.\n const showTableControls = !isCardsView && !isDelegatedView && !showSkeleton && !error && hasRows;\n const showFooterColumnToggle = columnTogglePlacement === 'footer' && showTableControls;\n const showFooterEditToggle = showEditModeToggle && showTableControls;\n\n // A edição em massa não depende do modo de exibição: em cards ela é a única\n // forma de editar, já que não existe célula para clicar.\n const showBulkEdit =\n hasEditableColumns && !!spreadsheet?.fill?.onFillCells && !isDelegatedView && !showSkeleton && !error && hasRows;\n\n const showFooterControls = showFooterColumnToggle || showFooterEditToggle || showBulkEdit || !!footerActionsSlot;\n const bulkEditRows = useMemo(\n () => visibleRows.filter((row) => row.depth === 0).map((row) => row.original),\n [visibleRows],\n );\n\n const activeFiltersBar =\n config.filters && filterValues && onFilterValuesChange ? (\n <ActiveFiltersBar\n fields={config.filters.fields ?? []}\n values={filterValues}\n onRemove={(key) =>\n onFilterValuesChange({\n ...filterValues,\n [key]: emptyValueForKind((config.filters?.fields ?? []).find((field) => field.key === key)?.kind ?? 'text'),\n })\n }\n onClearAll={() => onFilterValuesChange(buildEmptyFilterValues(config.filters?.fields ?? []))}\n />\n ) : null;\n\n const content = (\n <div\n className=\"flex min-h-0 w-full flex-1 flex-col gap-4\"\n onKeyDown={isUndoEnabled ? handleTableKeyDown : undefined}\n >\n {activeFiltersBar}\n {showToolbar && (\n <DataTableToolbar\n tabs={tabs}\n activeTab={activeTab}\n onTabChange={handleTabChange}\n showViewToggle={hasCardView && !hideViewToggle && !forceCardsOnMobile}\n showGroupedView={hasGroupedView}\n showKanbanView={hasKanbanView}\n viewMode={viewMode}\n onViewModeChange={handleViewModeChange}\n showSearch={showSearch}\n searchLabel={searchLabel}\n initialSearch={initialSearch}\n searchDisabled={searchDisabled}\n searchDebounceTime={isClientMode ? clientSearchDebounceMs : searchDebounceTime}\n searchMinLength={searchMinLength}\n searchAtStart={searchAtStart}\n onSearchInput={handleSearchInput}\n toolbarSlot={toolbarSlot}\n toolbarStartSlot={toolbarStartSlot}\n columnToggleSlot={columnToggleSlot}\n showSkeleton={loading && !hasLoadedOnce}\n />\n )}\n\n <div key={viewMode} className=\"flex min-h-0 flex-1 animate-fade-in flex-col\">\n {renderBody()}\n </div>\n\n {showAddRow && (\n // Sibling of the scrolling rows region, so it stays pinned below the grid\n // (outside its scroll) — the rows scroll, this control does not move.\n <div className=\"flex\">\n <ControlledButton\n variant=\"outlined\"\n className=\"flex items-center gap-1.5\"\n onClick={() => editingRows?.onAddRow?.()}\n >\n <MaterialSymbol icon=\"add\" size={16} />\n {t('dataTable.addRow')}\n </ControlledButton>\n </div>\n )}\n\n {(showFooterControls || showPagination) && (\n <div className=\"flex items-center justify-between gap-4\">\n {showFooterControls && (\n <div className=\"flex flex-wrap items-center gap-2 pb-3\">\n {showFooterColumnToggle && (\n <DataTableColumnToggle\n table={table}\n columns={config.columns}\n columnOrder={columnOrder}\n onColumnOrderChange={onColumnOrderChange}\n resetColumnOrder={resetColumnOrder}\n resetColumnSizing={resetColumnSizing}\n variant=\"toolbar\"\n />\n )}\n {showFooterEditToggle && <DataTableEditModeButton active={isEditMode} onToggle={handleEditModeToggle} />}\n {showBulkEdit && <DataTableBulkEditButton onClick={() => setIsBulkEditOpen(true)} />}\n {footerActionsSlot}\n </div>\n )}\n\n {showPagination && (\n <div className=\"flex-1\">\n <DataTablePaginationBar\n pageSize={clientPaginationProps.pageSize}\n numberOfPages={clientPaginationProps.numberOfPages}\n currentPage={clientPaginationProps.currentPage}\n setCurrentPage={clientPaginationProps.setCurrentPage}\n onPageSizeChange={clientPaginationProps.onPageSizeChange}\n totalItems={clientPaginationProps.totalItems}\n />\n </div>\n )}\n </div>\n )}\n\n {showBulkEdit && (\n <DataTableBulkEditDialog\n open={isBulkEditOpen}\n onClose={() => setIsBulkEditOpen(false)}\n columns={config.columns}\n rows={bulkEditRows}\n getRowLabel={config.getRowLabel}\n onApply={(changes) => spreadsheet?.fill?.onFillCells?.(changes)}\n />\n )}\n </div>\n );\n\n // Os providers ficam por fora do conteúdo já montado: abrir ou fechar uma célula re-renderiza\n // apenas as células editáveis, não a tabela inteira.\n const editableContent = config.editing?.clickToEdit ? (\n <DataTableCellEditingProvider>{content}</DataTableCellEditingProvider>\n ) : (\n content\n );\n\n if (!gridStore) return editableContent;\n\n return (\n <GridProvider\n store={gridStore}\n gridAreaRef={listScrollRef}\n canEditCell={canEditCell}\n onFillCommit={handleFillCommit}\n >\n {editableContent}\n </GridProvider>\n );\n};\n\nexport default DataTable;\n"],"names":["DataTablePaginationBar"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8JA,MAAM,YAAY,CAAmE;AAAA,EACnF,QAAQ;AAAA,E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A,gBACA,SAAS,OAAO;AAAA,gBAChB;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA,SAAQ;AAAA,cAAA;AAAA,YAAA;AAAA,YAGX,wBAAwB,oBAAC,yBAAA,EAAwB,QAAQ,YAAY,UAAU,sBAAsB;AAAA,YACrG,gBAAgB,oBAAC,yBAAA,EAAwB,SAAS,MAAM,kBAAkB,IAAI,GAAG;AAAA,YACjF;AAAA,UAAA,GACH;AAAA,UAGD,kBACC,oBAAC,OAAA,EAAI,WAAU,UACb,UAAA;AAAA,YAACA;AAAAA,YAAA;AAAA,cACC,UAAU,sBAAsB;AAAA,cAChC,eAAe,sBAAsB;AAAA,cACrC,aAAa,sBAAsB;AAAA,cACnC,gBAAgB,sBAAsB;AAAA,cACtC,kBAAkB,sBAAsB;AAAA,cACxC,YAAY,sBAAsB;AAAA,YAAA;AAAA,UAAA,EACpC,CACF;AAAA,QAAA,GAEJ;AAAA,QAGD,gBACC;AAAA,UAAC;AAAA,UAAA;AAAA,YACC,MAAM;AAAA,YACN,SAAS,MAAM,kBAAkB,KAAK;AAAA,YACtC,SAAS,OAAO;AAAA,YAChB,MAAM;AAAA,YACN,aAAa,OAAO;AAAA,YACpB,SAAS,CAAC,YAAY,aAAa,MAAM,cAAc,OAAO;AAAA,UAAA;AAAA,QAAA;AAAA,MAChE;AAAA,IAAA;AAAA,EAAA;AAON,QAAM,kBAAkB,OAAO,SAAS,cACtC,oBAAC,8BAAA,EAA8B,mBAAQ,IAEvC;AAGF,MAAI,CAAC,UAAW,QAAO;AAEvB,SACE;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,OAAO;AAAA,MACP,aAAa;AAAA,MACb;AAAA,MACA,cAAc;AAAA,MAEb,UAAA;AAAA,IAAA;AAAA,EAAA;AAGP;"}
|
|
@@ -21,6 +21,8 @@ export declare const useGridCellRegistry: () => IGridCellRegistry | null;
|
|
|
21
21
|
export declare const useGridCellState: (rowId: string, columnId: string) => number;
|
|
22
22
|
interface IGridProviderProps {
|
|
23
23
|
store: StoreApi<IGridState>;
|
|
24
|
+
/** The scroll region that holds the table: a press outside it releases the active cell. */
|
|
25
|
+
gridAreaRef?: React.RefObject<HTMLElement | null>;
|
|
24
26
|
canEditCell: (coord: IGridCellCoord) => boolean;
|
|
25
27
|
onFillCommit?: (result: IGridFillResult) => void;
|
|
26
28
|
children: React.ReactNode;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { jsx, jsxs } from "react/jsx-runtime";
|
|
2
2
|
import { createContext, useRef, useMemo, useEffect, useContext, useCallback, useSyncExternalStore } from "react";
|
|
3
|
+
import { LAYERED_SURFACE_SELECTOR, isPressOnLayeredSurface } from "../../../../helpers/layeredSurfaces.js";
|
|
3
4
|
import { selectGridCellState } from "./gridStore.js";
|
|
4
5
|
import { buildGridCellKey } from "./gridTypes.js";
|
|
5
6
|
const GridStoreContext = createContext(null);
|
|
@@ -55,7 +56,12 @@ const GridEditingFocus = ({
|
|
|
55
56
|
}, [editingKey, elements, store]);
|
|
56
57
|
return null;
|
|
57
58
|
};
|
|
58
|
-
const
|
|
59
|
+
const isPressAboveGrid = (target, gridArea) => {
|
|
60
|
+
const hostSurface = gridArea?.closest(LAYERED_SURFACE_SELECTOR) ?? null;
|
|
61
|
+
if (hostSurface) return isPressOnLayeredSurface(target, hostSurface);
|
|
62
|
+
return isPressOnLayeredSurface(target) || Boolean(target.closest(LAYERED_SURFACE_SELECTOR));
|
|
63
|
+
};
|
|
64
|
+
const GridProvider = ({ store, gridAreaRef, canEditCell, onFillCommit, children }) => {
|
|
59
65
|
const elementsRef = useRef(/* @__PURE__ */ new Map());
|
|
60
66
|
const onFillCommitRef = useRef(onFillCommit);
|
|
61
67
|
onFillCommitRef.current = onFillCommit;
|
|
@@ -93,6 +99,21 @@ const GridProvider = ({ store, canEditCell, onFillCommit, children }) => {
|
|
|
93
99
|
}),
|
|
94
100
|
[store]
|
|
95
101
|
);
|
|
102
|
+
useEffect(() => {
|
|
103
|
+
const handlePointerDown = (event) => {
|
|
104
|
+
const { activeCell, editingCell } = store.getState();
|
|
105
|
+
if (!activeCell && !editingCell) return;
|
|
106
|
+
const target = event.target instanceof Element ? event.target : null;
|
|
107
|
+
if (!target) return;
|
|
108
|
+
const gridArea = gridAreaRef?.current ?? null;
|
|
109
|
+
if (gridArea?.contains(target) || isPressAboveGrid(target, gridArea)) return;
|
|
110
|
+
const focused = document.activeElement;
|
|
111
|
+
if (focused instanceof HTMLElement && gridArea?.contains(focused)) focused.blur();
|
|
112
|
+
store.getState().releaseActiveCell();
|
|
113
|
+
};
|
|
114
|
+
document.addEventListener("pointerdown", handlePointerDown);
|
|
115
|
+
return () => document.removeEventListener("pointerdown", handlePointerDown);
|
|
116
|
+
}, [store, gridAreaRef]);
|
|
96
117
|
return /* @__PURE__ */ jsx(GridStoreContext.Provider, { value: store, children: /* @__PURE__ */ jsxs(GridCellRegistryContext.Provider, { value: registry, children: [
|
|
97
118
|
/* @__PURE__ */ jsx(GridEditingFocus, { store, elements: elementsRef.current }),
|
|
98
119
|
children
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"GridProvider.js","sources":["../../../../../src/components/UI/DataTable/grid/GridProvider.tsx"],"sourcesContent":["import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useSyncExternalStore } from 'react';\nimport { type StoreApi } from 'zustand/vanilla';\n\nimport { type IGridFillResult, type IGridState, selectGridCellState } from './gridStore';\nimport { buildGridCellKey, type IGridCellCoord } from './gridTypes';\n\nexport interface IGridCellRegistry {\n register: (cellKey: string, element: HTMLElement | null) => void;\n focusCell: (coord: IGridCellCoord) => void;\n /** Whether a click on this cell opens its editor. */\n canEditCell: (coord: IGridCellCoord) => boolean;\n /** Hands a finished fill drag to the host table, which owns the row data. */\n commitFill: (result: IGridFillResult) => void;\n}\n\nconst GridStoreContext = createContext<StoreApi<IGridState> | null>(null);\nconst GridCellRegistryContext = createContext<IGridCellRegistry | null>(null);\n\n/** The grid store of the closest spreadsheet-enabled table, or `null` outside one. */\nexport const useGridStoreApi = (): StoreApi<IGridState> | null => useContext(GridStoreContext);\n\nexport const useGridCellRegistry = (): IGridCellRegistry | null => useContext(GridCellRegistryContext);\n\n/**\n * Per-cell subscription to the grid state, as a bitmask. Reading a primitive\n * through `useSyncExternalStore` means moving the active cell re-renders the two\n * cells that changed, never the table.\n */\nexport const useGridCellState = (rowId: string, columnId: string): number => {\n const store = useGridStoreApi();\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => (store ? store.subscribe(onStoreChange) : () => undefined),\n [store],\n );\n\n const getSnapshot = useCallback(\n () => (store ? selectGridCellState(store.getState(), rowId, columnId) : 0),\n [store, rowId, columnId],\n );\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n};\n\nconst EDITOR_FOCUS_SELECTOR = 'input, textarea, select, [contenteditable=\"true\"], button, [tabindex]';\n\n/** Select and date editors render a read-only input that opens their popup on click. */\nconst isPickerTrigger = (element: HTMLElement): boolean => element instanceof HTMLInputElement && element.readOnly;\n\nconst isTextField = (element: HTMLElement): element is HTMLInputElement | HTMLTextAreaElement =>\n (element instanceof HTMLInputElement && !element.readOnly) || element instanceof HTMLTextAreaElement;\n\nconst placeCaretAtEnd = (field: HTMLInputElement | HTMLTextAreaElement): void => {\n // `setSelectionRange` throws on input types without a caret (email, number).\n try {\n const end = field.value.length;\n field.setSelectionRange(end, end);\n } catch {\n // The browser already put the caret somewhere usable.\n }\n};\n\n/**\n * Moves the focus into the editor once React has actually mounted it. The store\n * subscription cannot do this: it runs during the state update, before the cell\n * has swapped its read view for the editor.\n */\nconst GridEditingFocus: React.FC<{ store: StoreApi<IGridState>; elements: Map<string, HTMLElement> }> = ({\n store,\n elements,\n}) => {\n const editingKey = useSyncExternalStore(\n useCallback((onStoreChange: () => void) => store.subscribe(onStoreChange), [store]),\n () => {\n const editing = store.getState().editingCell;\n return editing ? buildGridCellKey(editing.rowId, editing.columnId) : null;\n },\n );\n\n useEffect(() => {\n if (!editingKey) return;\n\n const editor = elements.get(editingKey)?.querySelector<HTMLElement>(EDITOR_FOCUS_SELECTOR);\n if (!editor) return;\n\n editor.focus({ preventScroll: true });\n\n const { editingEntry, editingSeed } = store.getState();\n\n if (isPickerTrigger(editor)) {\n if (editingEntry !== 'keyboard') editor.click();\n return;\n }\n\n if (!isTextField(editor)) return;\n\n if (editingEntry === 'keyboard' && editingSeed == null) editor.select();\n else placeCaretAtEnd(editor);\n }, [editingKey, elements, store]);\n\n return null;\n};\n\ninterface IGridProviderProps {\n store: StoreApi<IGridState>;\n canEditCell: (coord: IGridCellCoord) => boolean;\n onFillCommit?: (result: IGridFillResult) => void;\n children: React.ReactNode;\n}\n\n/**\n * Owns the DOM side of the grid: the cell element registry and the focus/scroll\n * effect. It subscribes imperatively, so following the active cell costs no\n * render of its own.\n */\nconst GridProvider: React.FC<IGridProviderProps> = ({ store, canEditCell, onFillCommit, children }) => {\n const elementsRef = useRef(new Map<string, HTMLElement>());\n\n // Read through a ref so the registry identity never changes: it reaches every\n // cell, and a new object there would re-render the whole body.\n const onFillCommitRef = useRef(onFillCommit);\n onFillCommitRef.current = onFillCommit;\n const canEditCellRef = useRef(canEditCell);\n canEditCellRef.current = canEditCell;\n\n const registry = useMemo<IGridCellRegistry>(\n () => ({\n commitFill: (result) => onFillCommitRef.current?.(result),\n canEditCell: (coord) => canEditCellRef.current(coord),\n register: (cellKey, element) => {\n if (element) elementsRef.current.set(cellKey, element);\n else elementsRef.current.delete(cellKey);\n },\n focusCell: (coord) => {\n const element = elementsRef.current.get(buildGridCellKey(coord.rowId, coord.columnId));\n if (!element) return;\n element.focus({ preventScroll: true });\n element.scrollIntoView({ block: 'nearest', inline: 'nearest' });\n },\n }),\n [],\n );\n\n useEffect(\n () =>\n store.subscribe((state, previous) => {\n const activeChanged =\n state.activeCell?.rowId !== previous.activeCell?.rowId ||\n state.activeCell?.columnId !== previous.activeCell?.columnId;\n const editingEnded = !!previous.editingCell && !state.editingCell;\n\n if (!activeChanged && !editingEnded) return;\n if (state.editingCell) return;\n\n const coord = state.activeCell;\n if (!coord) return;\n\n const element = elementsRef.current.get(buildGridCellKey(coord.rowId, coord.columnId));\n if (!element) return;\n\n // Leaving edit mode has to claim the focus BEFORE the editor unmounts,\n // otherwise the browser drops it on the body and the arrows stop working.\n if (editingEnded || !element.contains(document.activeElement)) element.focus({ preventScroll: true });\n\n element.scrollIntoView({ block: 'nearest', inline: 'nearest' });\n }),\n [store],\n );\n\n return (\n <GridStoreContext.Provider value={store}>\n <GridCellRegistryContext.Provider value={registry}>\n <GridEditingFocus store={store} elements={elementsRef.current} />\n {children}\n </GridCellRegistryContext.Provider>\n </GridStoreContext.Provider>\n );\n};\n\nexport default GridProvider;\n"],"names":[],"mappings":";;;;AAeA,MAAM,mBAAmB,cAA2C,IAAI;AACxE,MAAM,0BAA0B,cAAwC,IAAI;AAGrE,MAAM,kBAAkB,MAAmC,WAAW,gBAAgB;AAEtF,MAAM,sBAAsB,MAAgC,WAAW,uBAAuB;AAO9F,MAAM,mBAAmB,CAAC,OAAe,aAA6B;AAC3E,QAAM,QAAQ,gBAAA;AAEd,QAAM,YAAY;AAAA,IAChB,CAAC,kBAA+B,QAAQ,MAAM,UAAU,aAAa,IAAI,MAAM;AAAA,IAC/E,CAAC,KAAK;AAAA,EAAA;AAGR,QAAM,cAAc;AAAA,IAClB,MAAO,QAAQ,oBAAoB,MAAM,YAAY,OAAO,QAAQ,IAAI;AAAA,IACxE,CAAC,OAAO,OAAO,QAAQ;AAAA,EAAA;AAGzB,SAAO,qBAAqB,WAAW,aAAa,WAAW;AACjE;AAEA,MAAM,wBAAwB;AAG9B,MAAM,kBAAkB,CAAC,YAAkC,mBAAmB,oBAAoB,QAAQ;AAE1G,MAAM,cAAc,CAAC,YAClB,mBAAmB,oBAAoB,CAAC,QAAQ,YAAa,mBAAmB;AAEnF,MAAM,kBAAkB,CAAC,UAAwD;AAE/E,MAAI;AACF,UAAM,MAAM,MAAM,MAAM;AACxB,UAAM,kBA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ider.tsx"],"sourcesContent":["import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useSyncExternalStore } from 'react';\nimport { type StoreApi } from 'zustand/vanilla';\n\nimport { isPressOnLayeredSurface, LAYERED_SURFACE_SELECTOR } from '@/helpers/layeredSurfaces';\n\nimport { type IGridFillResult, type IGridState, selectGridCellState } from './gridStore';\nimport { buildGridCellKey, type IGridCellCoord } from './gridTypes';\n\nexport interface IGridCellRegistry {\n register: (cellKey: string, element: HTMLElement | null) => void;\n focusCell: (coord: IGridCellCoord) => void;\n /** Whether a click on this cell opens its editor. */\n canEditCell: (coord: IGridCellCoord) => boolean;\n /** Hands a finished fill drag to the host table, which owns the row data. */\n commitFill: (result: IGridFillResult) => void;\n}\n\nconst GridStoreContext = createContext<StoreApi<IGridState> | null>(null);\nconst GridCellRegistryContext = createContext<IGridCellRegistry | null>(null);\n\n/** The grid store of the closest spreadsheet-enabled table, or `null` outside one. */\nexport const useGridStoreApi = (): StoreApi<IGridState> | null => useContext(GridStoreContext);\n\nexport const useGridCellRegistry = (): IGridCellRegistry | null => useContext(GridCellRegistryContext);\n\n/**\n * Per-cell subscription to the grid state, as a bitmask. Reading a primitive\n * through `useSyncExternalStore` means moving the active cell re-renders the two\n * cells that changed, never the table.\n */\nexport const useGridCellState = (rowId: string, columnId: string): number => {\n const store = useGridStoreApi();\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => (store ? store.subscribe(onStoreChange) : () => undefined),\n [store],\n );\n\n const getSnapshot = useCallback(\n () => (store ? selectGridCellState(store.getState(), rowId, columnId) : 0),\n [store, rowId, columnId],\n );\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n};\n\nconst EDITOR_FOCUS_SELECTOR = 'input, textarea, select, [contenteditable=\"true\"], button, [tabindex]';\n\n/** Select and date editors render a read-only input that opens their popup on click. */\nconst isPickerTrigger = (element: HTMLElement): boolean => element instanceof HTMLInputElement && element.readOnly;\n\nconst isTextField = (element: HTMLElement): element is HTMLInputElement | HTMLTextAreaElement =>\n (element instanceof HTMLInputElement && !element.readOnly) || element instanceof HTMLTextAreaElement;\n\nconst placeCaretAtEnd = (field: HTMLInputElement | HTMLTextAreaElement): void => {\n // `setSelectionRange` throws on input types without a caret (email, number).\n try {\n const end = field.value.length;\n field.setSelectionRange(end, end);\n } catch {\n // The browser already put the caret somewhere usable.\n }\n};\n\n/**\n * Moves the focus into the editor once React has actually mounted it. The store\n * subscription cannot do this: it runs during the state update, before the cell\n * has swapped its read view for the editor.\n */\nconst GridEditingFocus: React.FC<{ store: StoreApi<IGridState>; elements: Map<string, HTMLElement> }> = ({\n store,\n elements,\n}) => {\n const editingKey = useSyncExternalStore(\n useCallback((onStoreChange: () => void) => store.subscribe(onStoreChange), [store]),\n () => {\n const editing = store.getState().editingCell;\n return editing ? buildGridCellKey(editing.rowId, editing.columnId) : null;\n },\n );\n\n useEffect(() => {\n if (!editingKey) return;\n\n const editor = elements.get(editingKey)?.querySelector<HTMLElement>(EDITOR_FOCUS_SELECTOR);\n if (!editor) return;\n\n editor.focus({ preventScroll: true });\n\n const { editingEntry, editingSeed } = store.getState();\n\n if (isPickerTrigger(editor)) {\n if (editingEntry !== 'keyboard') editor.click();\n return;\n }\n\n if (!isTextField(editor)) return;\n\n if (editingEntry === 'keyboard' && editingSeed == null) editor.select();\n else placeCaretAtEnd(editor);\n }, [editingKey, elements, store]);\n\n return null;\n};\n\n/**\n * Whether a press outside the grid area belongs to something painted above the table (a select\n * listbox, a date picker, a toast), which is work on the open cell rather than leaving it. Inside\n * a drawer or dialog the comparison is directional, otherwise any press on that host surface would\n * count as layered and the grid would never let go.\n */\nconst isPressAboveGrid = (target: Element, gridArea: Element | null): boolean => {\n const hostSurface = gridArea?.closest(LAYERED_SURFACE_SELECTOR) ?? null;\n if (hostSurface) return isPressOnLayeredSurface(target, hostSurface);\n return isPressOnLayeredSurface(target) || Boolean(target.closest(LAYERED_SURFACE_SELECTOR));\n};\n\ninterface IGridProviderProps {\n store: StoreApi<IGridState>;\n /** The scroll region that holds the table: a press outside it releases the active cell. */\n gridAreaRef?: React.RefObject<HTMLElement | null>;\n canEditCell: (coord: IGridCellCoord) => boolean;\n onFillCommit?: (result: IGridFillResult) => void;\n children: React.ReactNode;\n}\n\n/**\n * Owns the DOM side of the grid: the cell element registry and the focus/scroll\n * effect. It subscribes imperatively, so following the active cell costs no\n * render of its own.\n */\nconst GridProvider: React.FC<IGridProviderProps> = ({ store, gridAreaRef, canEditCell, onFillCommit, children }) => {\n const elementsRef = useRef(new Map<string, HTMLElement>());\n\n // Read through a ref so the registry identity never changes: it reaches every\n // cell, and a new object there would re-render the whole body.\n const onFillCommitRef = useRef(onFillCommit);\n onFillCommitRef.current = onFillCommit;\n const canEditCellRef = useRef(canEditCell);\n canEditCellRef.current = canEditCell;\n\n const registry = useMemo<IGridCellRegistry>(\n () => ({\n commitFill: (result) => onFillCommitRef.current?.(result),\n canEditCell: (coord) => canEditCellRef.current(coord),\n register: (cellKey, element) => {\n if (element) elementsRef.current.set(cellKey, element);\n else elementsRef.current.delete(cellKey);\n },\n focusCell: (coord) => {\n const element = elementsRef.current.get(buildGridCellKey(coord.rowId, coord.columnId));\n if (!element) return;\n element.focus({ preventScroll: true });\n element.scrollIntoView({ block: 'nearest', inline: 'nearest' });\n },\n }),\n [],\n );\n\n useEffect(\n () =>\n store.subscribe((state, previous) => {\n const activeChanged =\n state.activeCell?.rowId !== previous.activeCell?.rowId ||\n state.activeCell?.columnId !== previous.activeCell?.columnId;\n const editingEnded = !!previous.editingCell && !state.editingCell;\n\n if (!activeChanged && !editingEnded) return;\n if (state.editingCell) return;\n\n const coord = state.activeCell;\n if (!coord) return;\n\n const element = elementsRef.current.get(buildGridCellKey(coord.rowId, coord.columnId));\n if (!element) return;\n\n // Leaving edit mode has to claim the focus BEFORE the editor unmounts,\n // otherwise the browser drops it on the body and the arrows stop working.\n if (editingEnded || !element.contains(document.activeElement)) element.focus({ preventScroll: true });\n\n element.scrollIntoView({ block: 'nearest', inline: 'nearest' });\n }),\n [store],\n );\n\n // Without this only another cell took the focus away: a press anywhere else on the page left\n // the editor open and the cell outlined, and a field outside the table lost its focus back to it.\n useEffect(() => {\n const handlePointerDown = (event: PointerEvent) => {\n const { activeCell, editingCell } = store.getState();\n if (!activeCell && !editingCell) return;\n\n const target = event.target instanceof Element ? event.target : null;\n if (!target) return;\n\n const gridArea = gridAreaRef?.current ?? null;\n if (gridArea?.contains(target) || isPressAboveGrid(target, gridArea)) return;\n\n // Editors that save on blur have to commit before the store unmounts them.\n const focused = document.activeElement;\n if (focused instanceof HTMLElement && gridArea?.contains(focused)) focused.blur();\n\n store.getState().releaseActiveCell();\n };\n\n document.addEventListener('pointerdown', handlePointerDown);\n return () => document.removeEventListener('pointerdown', handlePointerDown);\n }, [store, gridAreaRef]);\n\n return (\n <GridStoreContext.Provider value={store}>\n <GridCellRegistryContext.Provider value={registry}>\n <GridEditingFocus store={store} elements={elementsRef.current} />\n {children}\n </GridCellRegistryContext.Provider>\n </GridStoreContext.Provider>\n );\n};\n\nexport default GridProvider;\n"],"names":[],"mappings":";;;;;AAiBA,MAAM,mBAAmB,cAA2C,IAAI;AACxE,MAAM,0BAA0B,cAAwC,IAAI;AAGrE,MAAM,kBAAkB,MAAmC,WAAW,gBAAgB;AAEtF,MAAM,sBAAsB,MAAgC,WAAW,uBAAuB;AAO9F,MAAM,mBAAmB,CAAC,OAAe,aAA6B;AAC3E,QAAM,QAAQ,gBAAA;AAEd,QAAM,YAAY;AAAA,IAChB,CAAC,kBAA+B,QAAQ,MAAM,UAAU,aAAa,IAAI,MAAM;AAAA,IAC/E,CAAC,KAAK;AAAA,EAAA;AAGR,QAAM,cAAc;AAAA,IAClB,MAAO,QAAQ,oBAAoB,MAAM,YAAY,OAAO,QAAQ,IAAI;AAAA,IACxE,CAAC,OAAO,OAAO,QAAQ;AAAA,EAAA;AAGzB,SAAO,qBAAqB,WAAW,aAAa,WAAW;AACjE;AAEA,MAAM,wBAAwB;AAG9B,MAAM,kBAAk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AAM,EAAE,eAAe,KAAA,CAAM;AAEpG,cAAQ,eAAe,EAAE,OAAO,WAAW,QAAQ,WAAW;AAAA,IAChE,CAAC;AAAA,IACH,CAAC,KAAK;AAAA,EAAA;AAKR,YAAU,MAAM;AACd,UAAM,oBAAoB,CAAC,UAAwB;AACjD,YAAM,EAAE,YAAY,gBAAgB,MAAM,SAAA;AAC1C,UAAI,CAAC,cAAc,CAAC,YAAa;AAEjC,YAAM,SAAS,MAAM,kBAAkB,UAAU,MAAM,SAAS;AAChE,UAAI,CAAC,OAAQ;AAEb,YAAM,WAAW,aAAa,WAAW;AACzC,UAAI,UAAU,SAAS,MAAM,KAAK,iBAAiB,QAAQ,QAAQ,EAAG;AAGtE,YAAM,UAAU,SAAS;AACzB,UAAI,mBAAmB,eAAe,UAAU,SAAS,OAAO,WAAW,KAAA;AAE3E,YAAM,SAAA,EAAW,kBAAA;AAAA,IACnB;AAEA,aAAS,iBAAiB,eAAe,iBAAiB;AAC1D,WAAO,MAAM,SAAS,oBAAoB,eAAe,iBAAiB;AAAA,EAC5E,GAAG,CAAC,OAAO,WAAW,CAAC;AAEvB,SACE,oBAAC,iBAAiB,UAAjB,EAA0B,OAAO,OAChC,UAAA,qBAAC,wBAAwB,UAAxB,EAAiC,OAAO,UACvC,UAAA;AAAA,IAAA,oBAAC,kBAAA,EAAiB,OAAc,UAAU,YAAY,SAAS;AAAA,IAC9D;AAAA,EAAA,EAAA,CACH,EAAA,CACF;AAEJ;"}
|
|
@@ -61,6 +61,11 @@ export interface IGridState {
|
|
|
61
61
|
moveToEditableCell: (direction: 1 | -1, canEditCell: (coord: IGridCellCoord) => boolean) => boolean;
|
|
62
62
|
startEditing: (coord?: IGridCellCoord, options?: IGridStartEditingOptions) => void;
|
|
63
63
|
stopEditing: (outcome?: TGridEditingOutcome) => void;
|
|
64
|
+
/**
|
|
65
|
+
* The grid lets go of the user: the open editor closes keeping its value, as Enter would,
|
|
66
|
+
* and no cell stays active or selected. Used when a press lands outside the table.
|
|
67
|
+
*/
|
|
68
|
+
releaseActiveCell: () => void;
|
|
64
69
|
clearSelection: () => void;
|
|
65
70
|
startFill: () => void;
|
|
66
71
|
updateFillTarget: (coord: IGridCellCoord) => void;
|
|
@@ -178,6 +178,19 @@ const createGridStore = (selectionMode = "cell", initialEditMode = true) => crea
|
|
|
178
178
|
if (!get().editingCell) return;
|
|
179
179
|
set({ editingCell: null, editingOutcome: outcome });
|
|
180
180
|
},
|
|
181
|
+
releaseActiveCell: () => {
|
|
182
|
+
const { activeCell, editingCell, fillSourceRect } = get();
|
|
183
|
+
if (!activeCell && !editingCell && !fillSourceRect) return;
|
|
184
|
+
set({
|
|
185
|
+
activeCell: null,
|
|
186
|
+
selectionAnchor: null,
|
|
187
|
+
selectionRect: null,
|
|
188
|
+
editingCell: null,
|
|
189
|
+
...editingCell ? { editingOutcome: "commit" } : {},
|
|
190
|
+
fillSourceRect: null,
|
|
191
|
+
fillTargetRect: null
|
|
192
|
+
});
|
|
193
|
+
},
|
|
181
194
|
clearSelection: () => {
|
|
182
195
|
const { activeCell, matrix } = get();
|
|
183
196
|
set({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gridStore.js","sources":["../../../../../src/components/UI/DataTable/grid/gridStore.ts"],"sourcesContent":["import { createStore, type StoreApi } from 'zustand/vanilla';\n\nimport {\n buildGridCellKey,\n GRID_CELL_ACTIVE,\n GRID_CELL_EDITING,\n GRID_CELL_FILL_HANDLE,\n GRID_CELL_FILL_PREVIEW,\n GRID_CELL_SAVE_ERROR,\n GRID_CELL_SAVING,\n GRID_CELL_SELECTED,\n GRID_CELL_TABBABLE,\n type IGridCellCoord,\n type IGridStartEditingOptions,\n type TGridEditingEntry,\n type TGridSelectionMode,\n} from './gridTypes';\n\nexport interface IGridMatrix {\n rowIds: Array<string>;\n columnIds: Array<string>;\n rowIndexById: Map<string, number>;\n columnIndexById: Map<string, number>;\n}\n\nexport interface IGridSelectionRect {\n rowStart: number;\n rowEnd: number;\n columnStart: number;\n columnEnd: number;\n}\n\nexport interface IGridMoveOptions {\n /** Keeps the selection anchor and stretches the rectangle to the new cell. */\n extend?: boolean;\n /** Tab-style traversal: past the last column continues on the next row. */\n wrap?: boolean;\n}\n\nexport type TGridEditingOutcome = 'commit' | 'cancel';\n\nexport interface IGridState {\n /**\n * Enquanto falso a tabela é uma tabela comum: nenhuma célula é focável, o\n * clique na linha segue sendo do host e nada do grid aparece.\n */\n isEditMode: boolean;\n setEditMode: (isEditMode: boolean) => void;\n selectionMode: TGridSelectionMode;\n matrix: IGridMatrix;\n activeCell: IGridCellCoord | null;\n selectionAnchor: IGridCellCoord | null;\n selectionRect: IGridSelectionRect | null;\n editingCell: IGridCellCoord | null;\n editingEntry: TGridEditingEntry | null;\n /** Typed text that replaces the value of the cell being opened; `null` keeps the value. */\n editingSeed: string | null;\n /** How the last edit ended, so the cell knows whether to restore its value. */\n editingOutcome: TGridEditingOutcome | null;\n /** Selection snapshot taken when the fill drag started. */\n fillSourceRect: IGridSelectionRect | null;\n /** Cells the running fill drag would write. Null while the pointer is inside the source. */\n fillTargetRect: IGridSelectionRect | null;\n /** Per-cell persistence state fed by the host's commit queue. */\n cellStatuses: ReadonlyMap<string, string>;\n setCellStatuses: (statuses: ReadonlyMap<string, string>) => void;\n setSelectionMode: (mode: TGridSelectionMode) => void;\n setMatrix: (rowIds: Array<string>, columnIds: Array<string>) => void;\n setActiveCell: (coord: IGridCellCoord, options?: { extend?: boolean }) => void;\n /** Returns whether the active cell actually moved, so the host can let Tab leave the grid. */\n moveActiveCell: (rowDelta: number, columnDelta: number, options?: IGridMoveOptions) => boolean;\n moveActiveToEdge: (rowDelta: number, columnDelta: number, options?: { extend?: boolean }) => void;\n /**\n * Tab traversal over the cells that accept an editor, opening the one it lands on.\n * Returns `false` past the first/last editable cell so the focus can leave the grid.\n */\n moveToEditableCell: (direction: 1 | -1, canEditCell: (coord: IGridCellCoord) => boolean) => boolean;\n startEditing: (coord?: IGridCellCoord, options?: IGridStartEditingOptions) => void;\n stopEditing: (outcome?: TGridEditingOutcome) => void;\n clearSelection: () => void;\n startFill: () => void;\n updateFillTarget: (coord: IGridCellCoord) => void;\n /** Clears the drag state and hands back what should be written, if anything. */\n endFill: () => IGridFillResult | null;\n cancelFill: () => void;\n}\n\nexport interface IGridFillResult {\n sourceRect: IGridSelectionRect;\n targetRect: IGridSelectionRect;\n matrix: IGridMatrix;\n}\n\nconst EMPTY_MATRIX: IGridMatrix = {\n rowIds: [],\n columnIds: [],\n rowIndexById: new Map(),\n columnIndexById: new Map(),\n};\n\nconst sameIds = (current: Array<string>, next: Array<string>): boolean =>\n current.length === next.length && current.every((id, index) => id === next[index]);\n\nconst buildIndex = (ids: Array<string>): Map<string, number> => new Map(ids.map((id, index) => [id, index]));\n\nconst buildRect = (\n matrix: IGridMatrix,\n anchor: IGridCellCoord | null,\n focus: IGridCellCoord | null,\n): IGridSelectionRect | null => {\n if (!anchor || !focus) return null;\n\n const anchorRow = matrix.rowIndexById.get(anchor.rowId);\n const anchorColumn = matrix.columnIndexById.get(anchor.columnId);\n const focusRow = matrix.rowIndexById.get(focus.rowId);\n const focusColumn = matrix.columnIndexById.get(focus.columnId);\n\n if (anchorRow == null || anchorColumn == null || focusRow == null || focusColumn == null) return null;\n\n return {\n rowStart: Math.min(anchorRow, focusRow),\n rowEnd: Math.max(anchorRow, focusRow),\n columnStart: Math.min(anchorColumn, focusColumn),\n columnEnd: Math.max(anchorColumn, focusColumn),\n };\n};\n\nconst coordAt = (matrix: IGridMatrix, rowIndex: number, columnIndex: number): IGridCellCoord | null => {\n const rowId = matrix.rowIds[rowIndex];\n const columnId = matrix.columnIds[columnIndex];\n if (rowId == null || columnId == null) return null;\n\n return { rowId, columnId };\n};\n\nconst isSameCoord = (left: IGridCellCoord | null, right: IGridCellCoord | null): boolean =>\n left?.rowId === right?.rowId && left?.columnId === right?.columnId;\n\nexport const createGridStore = (\n selectionMode: TGridSelectionMode = 'cell',\n initialEditMode = true,\n): StoreApi<IGridState> =>\n createStore<IGridState>((set, get) => {\n const focusCoord = (coord: IGridCellCoord, extend: boolean) => {\n const { matrix, selectionAnchor, selectionMode: mode, editingCell } = get();\n const anchor = extend && mode === 'range' ? (selectionAnchor ?? coord) : coord;\n\n set({\n activeCell: coord,\n selectionAnchor: anchor,\n selectionRect: buildRect(matrix, anchor, coord),\n editingCell: null,\n // Moving away from an open editor keeps what was typed: only Escape discards it.\n editingOutcome: editingCell ? 'commit' : null,\n });\n };\n\n return {\n isEditMode: initialEditMode,\n selectionMode,\n matrix: EMPTY_MATRIX,\n activeCell: null,\n selectionAnchor: null,\n selectionRect: null,\n editingCell: null,\n editingEntry: null,\n editingSeed: null,\n editingOutcome: null,\n fillSourceRect: null,\n fillTargetRect: null,\n cellStatuses: new Map<string, string>(),\n\n setEditMode: (isEditMode) => {\n if (get().isEditMode === isEditMode) return;\n\n // Sair do modo devolve a tabela ao estado neutro: nada selecionado, nada\n // em edição, nenhum arraste pela metade.\n set({\n isEditMode,\n activeCell: null,\n selectionAnchor: null,\n selectionRect: null,\n editingCell: null,\n editingOutcome: null,\n fillSourceRect: null,\n fillTargetRect: null,\n });\n },\n\n setCellStatuses: (statuses) => {\n if (get().cellStatuses === statuses) return;\n set({ cellStatuses: statuses });\n },\n\n setSelectionMode: (mode) => {\n if (get().selectionMode === mode) return;\n set({ selectionMode: mode });\n },\n\n setMatrix: (rowIds, columnIds) => {\n const { matrix, activeCell, selectionAnchor, editingCell } = get();\n if (sameIds(matrix.rowIds, rowIds) && sameIds(matrix.columnIds, columnIds)) return;\n\n const nextMatrix: IGridMatrix = {\n rowIds,\n columnIds,\n rowIndexById: buildIndex(rowIds),\n columnIndexById: buildIndex(columnIds),\n };\n\n // A row or column that left the viewport (pagination, filter, column\n // hidden) takes its active/editing state with it, so the grid never\n // points at a cell the user cannot see.\n const stillExists = (coord: IGridCellCoord | null): coord is IGridCellCoord =>\n !!coord && nextMatrix.rowIndexById.has(coord.rowId) && nextMatrix.columnIndexById.has(coord.columnId);\n\n const nextActive = stillExists(activeCell) ? activeCell : null;\n const nextAnchor = stillExists(selectionAnchor) ? selectionAnchor : nextActive;\n\n set({\n matrix: nextMatrix,\n activeCell: nextActive,\n selectionAnchor: nextAnchor,\n selectionRect: buildRect(nextMatrix, nextAnchor, nextActive),\n editingCell: stillExists(editingCell) ? editingCell : null,\n });\n },\n\n setActiveCell: (coord, options) => {\n const { activeCell, editingCell } = get();\n const extend = options?.extend ?? false;\n\n // Um clique DENTRO da célula que já está sendo editada pertence ao editor,\n // não à navegação: reposicionar o cursor aqui fecharia o editor ainda no\n // mousedown, e um select nunca chegaria a abrir a lista.\n if (!extend && isSameCoord(editingCell, coord)) return;\n if (!extend && isSameCoord(activeCell, coord) && !editingCell) return;\n\n focusCoord(coord, extend);\n },\n\n moveActiveCell: (rowDelta, columnDelta, options) => {\n const { matrix, activeCell } = get();\n if (matrix.rowIds.length === 0 || matrix.columnIds.length === 0) return false;\n\n if (!activeCell) {\n const first = coordAt(matrix, 0, 0);\n if (first) focusCoord(first, false);\n return !!first;\n }\n\n const rowIndex = matrix.rowIndexById.get(activeCell.rowId);\n const columnIndex = matrix.columnIndexById.get(activeCell.columnId);\n if (rowIndex == null || columnIndex == null) return false;\n\n let nextRow = rowIndex + rowDelta;\n let nextColumn = columnIndex + columnDelta;\n\n if (options?.wrap && columnDelta !== 0) {\n if (nextColumn >= matrix.columnIds.length) {\n nextColumn = 0;\n nextRow += 1;\n } else if (nextColumn < 0) {\n nextColumn = matrix.columnIds.length - 1;\n nextRow -= 1;\n }\n }\n\n if (nextRow < 0 || nextRow >= matrix.rowIds.length) return false;\n if (nextColumn < 0 || nextColumn >= matrix.columnIds.length) return false;\n\n const next = coordAt(matrix, nextRow, nextColumn);\n if (!next) return false;\n\n focusCoord(next, options?.extend ?? false);\n return true;\n },\n\n moveActiveToEdge: (rowDelta, columnDelta, options) => {\n const { matrix, activeCell } = get();\n if (matrix.rowIds.length === 0 || matrix.columnIds.length === 0) return;\n\n const rowIndex = activeCell ? (matrix.rowIndexById.get(activeCell.rowId) ?? 0) : 0;\n const columnIndex = activeCell ? (matrix.columnIndexById.get(activeCell.columnId) ?? 0) : 0;\n\n const nextRow = rowDelta === 0 ? rowIndex : rowDelta > 0 ? matrix.rowIds.length - 1 : 0;\n const nextColumn = columnDelta === 0 ? columnIndex : columnDelta > 0 ? matrix.columnIds.length - 1 : 0;\n\n const next = coordAt(matrix, nextRow, nextColumn);\n if (next) focusCoord(next, options?.extend ?? false);\n },\n\n moveToEditableCell: (direction, canEditCell) => {\n const { matrix, activeCell } = get();\n const columnCount = matrix.columnIds.length;\n const cellCount = matrix.rowIds.length * columnCount;\n if (cellCount === 0) return false;\n\n const rowIndex = activeCell ? matrix.rowIndexById.get(activeCell.rowId) : undefined;\n const columnIndex = activeCell ? matrix.columnIndexById.get(activeCell.columnId) : undefined;\n const currentPosition = rowIndex != null && columnIndex != null ? rowIndex * columnCount + columnIndex : -1;\n\n for (let position = currentPosition + direction; position >= 0 && position < cellCount; position += direction) {\n const candidate = coordAt(matrix, Math.floor(position / columnCount), position % columnCount);\n if (!candidate || !canEditCell(candidate)) continue;\n\n focusCoord(candidate, false);\n get().startEditing(candidate, { entry: 'keyboard' });\n return true;\n }\n\n return false;\n },\n\n startEditing: (coord, options) => {\n const { activeCell, editingCell, matrix } = get();\n const target = coord ?? activeCell;\n if (!target || isSameCoord(editingCell, target)) return;\n\n set({\n activeCell: target,\n selectionAnchor: target,\n selectionRect: buildRect(matrix, target, target),\n editingCell: target,\n editingEntry: options?.entry ?? 'keyboard',\n editingSeed: options?.seed ?? null,\n editingOutcome: null,\n });\n },\n\n stopEditing: (outcome = 'commit') => {\n if (!get().editingCell) return;\n set({ editingCell: null, editingOutcome: outcome });\n },\n\n clearSelection: () => {\n const { activeCell, matrix } = get();\n set({\n selectionAnchor: activeCell,\n selectionRect: buildRect(matrix, activeCell, activeCell),\n });\n },\n\n startFill: () => {\n const { selectionRect } = get();\n if (!selectionRect) return;\n set({ fillSourceRect: selectionRect, fillTargetRect: null, editingCell: null });\n },\n\n updateFillTarget: (coord) => {\n const { fillSourceRect, fillTargetRect, matrix } = get();\n if (!fillSourceRect) return;\n\n const rowIndex = matrix.rowIndexById.get(coord.rowId);\n if (rowIndex == null) return;\n\n // Vertical only for now. The rect shape is already 2D, so a horizontal\n // drag is a second branch here and nothing else in the layer changes.\n let nextTarget: IGridSelectionRect | null = null;\n if (rowIndex > fillSourceRect.rowEnd) {\n nextTarget = { ...fillSourceRect, rowStart: fillSourceRect.rowEnd + 1, rowEnd: rowIndex };\n } else if (rowIndex < fillSourceRect.rowStart) {\n nextTarget = { ...fillSourceRect, rowStart: rowIndex, rowEnd: fillSourceRect.rowStart - 1 };\n }\n\n const isSameTarget =\n nextTarget?.rowStart === fillTargetRect?.rowStart && nextTarget?.rowEnd === fillTargetRect?.rowEnd;\n if (isSameTarget) return;\n\n set({ fillTargetRect: nextTarget });\n },\n\n endFill: () => {\n const { fillSourceRect, fillTargetRect, matrix } = get();\n set({ fillSourceRect: null, fillTargetRect: null });\n if (!fillSourceRect || !fillTargetRect) return null;\n\n return { sourceRect: fillSourceRect, targetRect: fillTargetRect, matrix };\n },\n\n cancelFill: () => {\n if (!get().fillSourceRect) return;\n set({ fillSourceRect: null, fillTargetRect: null });\n },\n };\n });\n\n/**\n * Bitmask of what this cell currently is. A primitive keeps the per-cell\n * subscription cheap: `useSyncExternalStore` compares it by value, so a cell\n * only re-renders when its own state actually changes.\n */\nconst isInsideRect = (rect: IGridSelectionRect | null, rowIndex?: number, columnIndex?: number): boolean =>\n !!rect &&\n rowIndex != null &&\n columnIndex != null &&\n rowIndex >= rect.rowStart &&\n rowIndex <= rect.rowEnd &&\n columnIndex >= rect.columnStart &&\n columnIndex <= rect.columnEnd;\n\nexport const selectGridCellState = (state: IGridState, rowId: string, columnId: string): number => {\n if (!state.isEditMode) return 0;\n\n let mask = 0;\n\n if (isSameCoord(state.activeCell, { rowId, columnId })) mask |= GRID_CELL_ACTIVE;\n if (isSameCoord(state.editingCell, { rowId, columnId })) mask |= GRID_CELL_EDITING;\n\n const rowIndex = state.matrix.rowIndexById.get(rowId);\n const columnIndex = state.matrix.columnIndexById.get(columnId);\n\n const rect = state.selectionRect;\n if (isInsideRect(rect, rowIndex, columnIndex)) mask |= GRID_CELL_SELECTED;\n if (rect && rowIndex === rect.rowEnd && columnIndex === rect.columnEnd) mask |= GRID_CELL_FILL_HANDLE;\n if (isInsideRect(state.fillTargetRect, rowIndex, columnIndex)) mask |= GRID_CELL_FILL_PREVIEW;\n\n if (state.cellStatuses.size > 0) {\n const status = state.cellStatuses.get(buildGridCellKey(rowId, columnId));\n if (status === 'saving' || status === 'pending') mask |= GRID_CELL_SAVING;\n if (status === 'error') mask |= GRID_CELL_SAVE_ERROR;\n }\n\n // Roving tabindex needs an entry point before the first interaction: without\n // an active cell the top-left cell is the one Tab reaches from outside.\n if (!state.activeCell && state.matrix.rowIds[0] === rowId && state.matrix.columnIds[0] === columnId) {\n mask |= GRID_CELL_TABBABLE;\n }\n\n return mask;\n};\n"],"names":[],"mappings":";;AA6FA,MAAM,eAA4B;AAAA,EAChC,QAAQ,CAAA;AAAA,EACR,WAAW,CAAA;AAAA,EACX,kCAAkB,IAAA;AAAA,EAClB,qCAAqB,IAAA;AACvB;AAEA,MAAM,UAAU,CAAC,SAAwB,SACvC,QAAQ,WAAW,KAAK,UAAU,QAAQ,MAAM,CAAC,IAAI,UAAU,OAAO,KAAK,KAAK,CAAC;AAEnF,MAAM,aAAa,CAAC,QAA4C,IAAI,IAAI,IAAI,IAAI,CAAC,IAAI,UAAU,CAAC,IAAI,KAAK,CAAC,CAAC;AAE3G,MAAM,YAAY,CAChB,QACA,QACA,UAC8B;AAC9B,MAAI,CAAC,UAAU,CAAC,MAAO,QAAO;AAE9B,QAAM,YAAY,OAAO,aAAa,IAAI,OAAO,KAAK;AACtD,QAAM,eAAe,OAAO,gBAAgB,IAAI,OAAO,QAAQ;AAC/D,QAAM,WAAW,OAAO,a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GAAG;AAC/B,UAAM,SAAS,MAAM,aAAa,IAAI,iBAAiB,OAAO,QAAQ,CAAC;AACvE,QAAI,WAAW,YAAY,WAAW,UAAW,SAAQ;AACzD,QAAI,WAAW,QAAS,SAAQ;AAAA,EAClC;AAIA,MAAI,CAAC,MAAM,cAAc,MAAM,OAAO,OAAO,CAAC,MAAM,SAAS,MAAM,OAAO,UAAU,CAAC,MAAM,UAAU;AACnG,YAAQ;AAAA,EACV;AAEA,SAAO;AACT;"}
|
|
1
|
+
{"version":3,"file":"gridStore.js","sources":["../../../../../src/components/UI/DataTable/grid/gridStore.ts"],"sourcesContent":["import { createStore, type StoreApi } from 'zustand/vanilla';\n\nimport {\n buildGridCellKey,\n GRID_CELL_ACTIVE,\n GRID_CELL_EDITING,\n GRID_CELL_FILL_HANDLE,\n GRID_CELL_FILL_PREVIEW,\n GRID_CELL_SAVE_ERROR,\n GRID_CELL_SAVING,\n GRID_CELL_SELECTED,\n GRID_CELL_TABBABLE,\n type IGridCellCoord,\n type IGridStartEditingOptions,\n type TGridEditingEntry,\n type TGridSelectionMode,\n} from './gridTypes';\n\nexport interface IGridMatrix {\n rowIds: Array<string>;\n columnIds: Array<string>;\n rowIndexById: Map<string, number>;\n columnIndexById: Map<string, number>;\n}\n\nexport interface IGridSelectionRect {\n rowStart: number;\n rowEnd: number;\n columnStart: number;\n columnEnd: number;\n}\n\nexport interface IGridMoveOptions {\n /** Keeps the selection anchor and stretches the rectangle to the new cell. */\n extend?: boolean;\n /** Tab-style traversal: past the last column continues on the next row. */\n wrap?: boolean;\n}\n\nexport type TGridEditingOutcome = 'commit' | 'cancel';\n\nexport interface IGridState {\n /**\n * Enquanto falso a tabela é uma tabela comum: nenhuma célula é focável, o\n * clique na linha segue sendo do host e nada do grid aparece.\n */\n isEditMode: boolean;\n setEditMode: (isEditMode: boolean) => void;\n selectionMode: TGridSelectionMode;\n matrix: IGridMatrix;\n activeCell: IGridCellCoord | null;\n selectionAnchor: IGridCellCoord | null;\n selectionRect: IGridSelectionRect | null;\n editingCell: IGridCellCoord | null;\n editingEntry: TGridEditingEntry | null;\n /** Typed text that replaces the value of the cell being opened; `null` keeps the value. */\n editingSeed: string | null;\n /** How the last edit ended, so the cell knows whether to restore its value. */\n editingOutcome: TGridEditingOutcome | null;\n /** Selection snapshot taken when the fill drag started. */\n fillSourceRect: IGridSelectionRect | null;\n /** Cells the running fill drag would write. Null while the pointer is inside the source. */\n fillTargetRect: IGridSelectionRect | null;\n /** Per-cell persistence state fed by the host's commit queue. */\n cellStatuses: ReadonlyMap<string, string>;\n setCellStatuses: (statuses: ReadonlyMap<string, string>) => void;\n setSelectionMode: (mode: TGridSelectionMode) => void;\n setMatrix: (rowIds: Array<string>, columnIds: Array<string>) => void;\n setActiveCell: (coord: IGridCellCoord, options?: { extend?: boolean }) => void;\n /** Returns whether the active cell actually moved, so the host can let Tab leave the grid. */\n moveActiveCell: (rowDelta: number, columnDelta: number, options?: IGridMoveOptions) => boolean;\n moveActiveToEdge: (rowDelta: number, columnDelta: number, options?: { extend?: boolean }) => void;\n /**\n * Tab traversal over the cells that accept an editor, opening the one it lands on.\n * Returns `false` past the first/last editable cell so the focus can leave the grid.\n */\n moveToEditableCell: (direction: 1 | -1, canEditCell: (coord: IGridCellCoord) => boolean) => boolean;\n startEditing: (coord?: IGridCellCoord, options?: IGridStartEditingOptions) => void;\n stopEditing: (outcome?: TGridEditingOutcome) => void;\n /**\n * The grid lets go of the user: the open editor closes keeping its value, as Enter would,\n * and no cell stays active or selected. Used when a press lands outside the table.\n */\n releaseActiveCell: () => void;\n clearSelection: () => void;\n startFill: () => void;\n updateFillTarget: (coord: IGridCellCoord) => void;\n /** Clears the drag state and hands back what should be written, if anything. */\n endFill: () => IGridFillResult | null;\n cancelFill: () => void;\n}\n\nexport interface IGridFillResult {\n sourceRect: IGridSelectionRect;\n targetRect: IGridSelectionRect;\n matrix: IGridMatrix;\n}\n\nconst EMPTY_MATRIX: IGridMatrix = {\n rowIds: [],\n columnIds: [],\n rowIndexById: new Map(),\n columnIndexById: new Map(),\n};\n\nconst sameIds = (current: Array<string>, next: Array<string>): boolean =>\n current.length === next.length && current.every((id, index) => id === next[index]);\n\nconst buildIndex = (ids: Array<string>): Map<string, number> => new Map(ids.map((id, index) => [id, index]));\n\nconst buildRect = (\n matrix: IGridMatrix,\n anchor: IGridCellCoord | null,\n focus: IGridCellCoord | null,\n): IGridSelectionRect | null => {\n if (!anchor || !focus) return null;\n\n const anchorRow = matrix.rowIndexById.get(anchor.rowId);\n const anchorColumn = matrix.columnIndexById.get(anchor.columnId);\n const focusRow = matrix.rowIndexById.get(focus.rowId);\n const focusColumn = matrix.columnIndexById.get(focus.columnId);\n\n if (anchorRow == null || anchorColumn == null || focusRow == null || focusColumn == null) return null;\n\n return {\n rowStart: Math.min(anchorRow, focusRow),\n rowEnd: Math.max(anchorRow, focusRow),\n columnStart: Math.min(anchorColumn, focusColumn),\n columnEnd: Math.max(anchorColumn, focusColumn),\n };\n};\n\nconst coordAt = (matrix: IGridMatrix, rowIndex: number, columnIndex: number): IGridCellCoord | null => {\n const rowId = matrix.rowIds[rowIndex];\n const columnId = matrix.columnIds[columnIndex];\n if (rowId == null || columnId == null) return null;\n\n return { rowId, columnId };\n};\n\nconst isSameCoord = (left: IGridCellCoord | null, right: IGridCellCoord | null): boolean =>\n left?.rowId === right?.rowId && left?.columnId === right?.columnId;\n\nexport const createGridStore = (\n selectionMode: TGridSelectionMode = 'cell',\n initialEditMode = true,\n): StoreApi<IGridState> =>\n createStore<IGridState>((set, get) => {\n const focusCoord = (coord: IGridCellCoord, extend: boolean) => {\n const { matrix, selectionAnchor, selectionMode: mode, editingCell } = get();\n const anchor = extend && mode === 'range' ? (selectionAnchor ?? coord) : coord;\n\n set({\n activeCell: coord,\n selectionAnchor: anchor,\n selectionRect: buildRect(matrix, anchor, coord),\n editingCell: null,\n // Moving away from an open editor keeps what was typed: only Escape discards it.\n editingOutcome: editingCell ? 'commit' : null,\n });\n };\n\n return {\n isEditMode: initialEditMode,\n selectionMode,\n matrix: EMPTY_MATRIX,\n activeCell: null,\n selectionAnchor: null,\n selectionRect: null,\n editingCell: null,\n editingEntry: null,\n editingSeed: null,\n editingOutcome: null,\n fillSourceRect: null,\n fillTargetRect: null,\n cellStatuses: new Map<string, string>(),\n\n setEditMode: (isEditMode) => {\n if (get().isEditMode === isEditMode) return;\n\n // Sair do modo devolve a tabela ao estado neutro: nada selecionado, nada\n // em edição, nenhum arraste pela metade.\n set({\n isEditMode,\n activeCell: null,\n selectionAnchor: null,\n selectionRect: null,\n editingCell: null,\n editingOutcome: null,\n fillSourceRect: null,\n fillTargetRect: null,\n });\n },\n\n setCellStatuses: (statuses) => {\n if (get().cellStatuses === statuses) return;\n set({ cellStatuses: statuses });\n },\n\n setSelectionMode: (mode) => {\n if (get().selectionMode === mode) return;\n set({ selectionMode: mode });\n },\n\n setMatrix: (rowIds, columnIds) => {\n const { matrix, activeCell, selectionAnchor, editingCell } = get();\n if (sameIds(matrix.rowIds, rowIds) && sameIds(matrix.columnIds, columnIds)) return;\n\n const nextMatrix: IGridMatrix = {\n rowIds,\n columnIds,\n rowIndexById: buildIndex(rowIds),\n columnIndexById: buildIndex(columnIds),\n };\n\n // A row or column that left the viewport (pagination, filter, column\n // hidden) takes its active/editing state with it, so the grid never\n // points at a cell the user cannot see.\n const stillExists = (coord: IGridCellCoord | null): coord is IGridCellCoord =>\n !!coord && nextMatrix.rowIndexById.has(coord.rowId) && nextMatrix.columnIndexById.has(coord.columnId);\n\n const nextActive = stillExists(activeCell) ? activeCell : null;\n const nextAnchor = stillExists(selectionAnchor) ? selectionAnchor : nextActive;\n\n set({\n matrix: nextMatrix,\n activeCell: nextActive,\n selectionAnchor: nextAnchor,\n selectionRect: buildRect(nextMatrix, nextAnchor, nextActive),\n editingCell: stillExists(editingCell) ? editingCell : null,\n });\n },\n\n setActiveCell: (coord, options) => {\n const { activeCell, editingCell } = get();\n const extend = options?.extend ?? false;\n\n // Um clique DENTRO da célula que já está sendo editada pertence ao editor,\n // não à navegação: reposicionar o cursor aqui fecharia o editor ainda no\n // mousedown, e um select nunca chegaria a abrir a lista.\n if (!extend && isSameCoord(editingCell, coord)) return;\n if (!extend && isSameCoord(activeCell, coord) && !editingCell) return;\n\n focusCoord(coord, extend);\n },\n\n moveActiveCell: (rowDelta, columnDelta, options) => {\n const { matrix, activeCell } = get();\n if (matrix.rowIds.length === 0 || matrix.columnIds.length === 0) return false;\n\n if (!activeCell) {\n const first = coordAt(matrix, 0, 0);\n if (first) focusCoord(first, false);\n return !!first;\n }\n\n const rowIndex = matrix.rowIndexById.get(activeCell.rowId);\n const columnIndex = matrix.columnIndexById.get(activeCell.columnId);\n if (rowIndex == null || columnIndex == null) return false;\n\n let nextRow = rowIndex + rowDelta;\n let nextColumn = columnIndex + columnDelta;\n\n if (options?.wrap && columnDelta !== 0) {\n if (nextColumn >= matrix.columnIds.length) {\n nextColumn = 0;\n nextRow += 1;\n } else if (nextColumn < 0) {\n nextColumn = matrix.columnIds.length - 1;\n nextRow -= 1;\n }\n }\n\n if (nextRow < 0 || nextRow >= matrix.rowIds.length) return false;\n if (nextColumn < 0 || nextColumn >= matrix.columnIds.length) return false;\n\n const next = coordAt(matrix, nextRow, nextColumn);\n if (!next) return false;\n\n focusCoord(next, options?.extend ?? false);\n return true;\n },\n\n moveActiveToEdge: (rowDelta, columnDelta, options) => {\n const { matrix, activeCell } = get();\n if (matrix.rowIds.length === 0 || matrix.columnIds.length === 0) return;\n\n const rowIndex = activeCell ? (matrix.rowIndexById.get(activeCell.rowId) ?? 0) : 0;\n const columnIndex = activeCell ? (matrix.columnIndexById.get(activeCell.columnId) ?? 0) : 0;\n\n const nextRow = rowDelta === 0 ? rowIndex : rowDelta > 0 ? matrix.rowIds.length - 1 : 0;\n const nextColumn = columnDelta === 0 ? columnIndex : columnDelta > 0 ? matrix.columnIds.length - 1 : 0;\n\n const next = coordAt(matrix, nextRow, nextColumn);\n if (next) focusCoord(next, options?.extend ?? false);\n },\n\n moveToEditableCell: (direction, canEditCell) => {\n const { matrix, activeCell } = get();\n const columnCount = matrix.columnIds.length;\n const cellCount = matrix.rowIds.length * columnCount;\n if (cellCount === 0) return false;\n\n const rowIndex = activeCell ? matrix.rowIndexById.get(activeCell.rowId) : undefined;\n const columnIndex = activeCell ? matrix.columnIndexById.get(activeCell.columnId) : undefined;\n const currentPosition = rowIndex != null && columnIndex != null ? rowIndex * columnCount + columnIndex : -1;\n\n for (let position = currentPosition + direction; position >= 0 && position < cellCount; position += direction) {\n const candidate = coordAt(matrix, Math.floor(position / columnCount), position % columnCount);\n if (!candidate || !canEditCell(candidate)) continue;\n\n focusCoord(candidate, false);\n get().startEditing(candidate, { entry: 'keyboard' });\n return true;\n }\n\n return false;\n },\n\n startEditing: (coord, options) => {\n const { activeCell, editingCell, matrix } = get();\n const target = coord ?? activeCell;\n if (!target || isSameCoord(editingCell, target)) return;\n\n set({\n activeCell: target,\n selectionAnchor: target,\n selectionRect: buildRect(matrix, target, target),\n editingCell: target,\n editingEntry: options?.entry ?? 'keyboard',\n editingSeed: options?.seed ?? null,\n editingOutcome: null,\n });\n },\n\n stopEditing: (outcome = 'commit') => {\n if (!get().editingCell) return;\n set({ editingCell: null, editingOutcome: outcome });\n },\n\n releaseActiveCell: () => {\n const { activeCell, editingCell, fillSourceRect } = get();\n if (!activeCell && !editingCell && !fillSourceRect) return;\n\n set({\n activeCell: null,\n selectionAnchor: null,\n selectionRect: null,\n editingCell: null,\n ...(editingCell ? { editingOutcome: 'commit' as const } : {}),\n fillSourceRect: null,\n fillTargetRect: null,\n });\n },\n\n clearSelection: () => {\n const { activeCell, matrix } = get();\n set({\n selectionAnchor: activeCell,\n selectionRect: buildRect(matrix, activeCell, activeCell),\n });\n },\n\n startFill: () => {\n const { selectionRect } = get();\n if (!selectionRect) return;\n set({ fillSourceRect: selectionRect, fillTargetRect: null, editingCell: null });\n },\n\n updateFillTarget: (coord) => {\n const { fillSourceRect, fillTargetRect, matrix } = get();\n if (!fillSourceRect) return;\n\n const rowIndex = matrix.rowIndexById.get(coord.rowId);\n if (rowIndex == null) return;\n\n // Vertical only for now. The rect shape is already 2D, so a horizontal\n // drag is a second branch here and nothing else in the layer changes.\n let nextTarget: IGridSelectionRect | null = null;\n if (rowIndex > fillSourceRect.rowEnd) {\n nextTarget = { ...fillSourceRect, rowStart: fillSourceRect.rowEnd + 1, rowEnd: rowIndex };\n } else if (rowIndex < fillSourceRect.rowStart) {\n nextTarget = { ...fillSourceRect, rowStart: rowIndex, rowEnd: fillSourceRect.rowStart - 1 };\n }\n\n const isSameTarget =\n nextTarget?.rowStart === fillTargetRect?.rowStart && nextTarget?.rowEnd === fillTargetRect?.rowEnd;\n if (isSameTarget) return;\n\n set({ fillTargetRect: nextTarget });\n },\n\n endFill: () => {\n const { fillSourceRect, fillTargetRect, matrix } = get();\n set({ fillSourceRect: null, fillTargetRect: null });\n if (!fillSourceRect || !fillTargetRect) return null;\n\n return { sourceRect: fillSourceRect, targetRect: fillTargetRect, matrix };\n },\n\n cancelFill: () => {\n if (!get().fillSourceRect) return;\n set({ fillSourceRect: null, fillTargetRect: null });\n },\n };\n });\n\n/**\n * Bitmask of what this cell currently is. A primitive keeps the per-cell\n * subscription cheap: `useSyncExternalStore` compares it by value, so a cell\n * only re-renders when its own state actually changes.\n */\nconst isInsideRect = (rect: IGridSelectionRect | null, rowIndex?: number, columnIndex?: number): boolean =>\n !!rect &&\n rowIndex != null &&\n columnIndex != null &&\n rowIndex >= rect.rowStart &&\n rowIndex <= rect.rowEnd &&\n columnIndex >= rect.columnStart &&\n columnIndex <= rect.columnEnd;\n\nexport const selectGridCellState = (state: IGridState, rowId: string, columnId: string): number => {\n if (!state.isEditMode) return 0;\n\n let mask = 0;\n\n if (isSameCoord(state.activeCell, { rowId, columnId })) mask |= GRID_CELL_ACTIVE;\n if (isSameCoord(state.editingCell, { rowId, columnId })) mask |= GRID_CELL_EDITING;\n\n const rowIndex = state.matrix.rowIndexById.get(rowId);\n const columnIndex = state.matrix.columnIndexById.get(columnId);\n\n const rect = state.selectionRect;\n if (isInsideRect(rect, rowIndex, columnIndex)) mask |= GRID_CELL_SELECTED;\n if (rect && rowIndex === rect.rowEnd && columnIndex === rect.columnEnd) mask |= GRID_CELL_FILL_HANDLE;\n if (isInsideRect(state.fillTargetRect, rowIndex, columnIndex)) mask |= GRID_CELL_FILL_PREVIEW;\n\n if (state.cellStatuses.size > 0) {\n const status = state.cellStatuses.get(buildGridCellKey(rowId, columnId));\n if (status === 'saving' || status === 'pending') mask |= GRID_CELL_SAVING;\n if (status === 'error') mask |= GRID_CELL_SAVE_ERROR;\n }\n\n // Roving tabindex needs an entry point before the first interaction: without\n // an active cell the top-left cell is the one Tab reaches from outside.\n if (!state.activeCell && state.matrix.rowIds[0] === rowId && state.matrix.columnIds[0] === columnId) {\n mask |= GRID_CELL_TABBABLE;\n }\n\n return mask;\n};\n"],"names":[],"mappings":";;AAkGA,MAAM,eAA4B;AAAA,EAChC,QAAQ,CAAA;AAAA,EACR,WAAW,CAAA;AAAA,EACX,kCAAkB,IAAA;AAAA,EAClB,qCAAqB,IAAA;AACvB;AAEA,MAAM,UAAU,CAAC,SAAwB,SACvC,QAAQ,WAAW,KAAK,UAAU,QAAQ,MAAM,CAAC,IAAI,UAAU,OAAO,KAAK,KAAK,CAAC;AAEnF,MAAM,aAAa,CAAC,QAA4C,IAAI,IAAI,IAAI,IAAI,CAAC,IAAI,UAAU,CAAC,IAAI,KAAK,CAAC,CAAC;AAE3G,MAAM,YAAY,CAChB,QACA,QACA,UAC8B;AAC9B,MAAI,CAAC,UAAU,CAAC,MAAO,QAAO;AAE9B,QAAM,YAAY,OAAO,aAAa,IAAI,OAAO,KAAK;AACtD,QAAM,eAAe,OAAO,gBAAgB,IAAI,OAAO,QAAQ;AAC/D,QAAM,WAAW,OAAO,aAAa,IAAI,MAAM,KAAK;AACpD,QAAM,cAAc,OAAO,gBAAgB,IAAI,MAAM,QAAQ;AAE7D,MAAI,aAAa,QAAQ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