@umodeapporg/ui 0.24.1 → 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/dist/components/UI/Flow/FlowBlockNode.js +8 -2
- package/dist/components/UI/Flow/FlowBlockNode.js.map +1 -1
- package/dist/components/UI/Flow/FlowCanvas.js +52 -3
- package/dist/components/UI/Flow/FlowCanvas.js.map +1 -1
- package/dist/components/UI/Flow/FlowInspector.js +2 -0
- package/dist/components/UI/Flow/FlowInspector.js.map +1 -1
- package/dist/components/UI/Flow/flowViewport.d.ts +25 -0
- package/dist/components/UI/Flow/flowViewport.js +31 -0
- package/dist/components/UI/Flow/flowViewport.js.map +1 -0
- package/dist/locales/en/ui.json.d.ts +3 -3
- package/dist/locales/en/ui.json.js +1 -1
- package/dist/locales/pt/ui.json.d.ts +3 -3
- package/dist/locales/pt/ui.json.js +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;AAAA,EACA;AAAA,EACA;AAAA,EACA,gBAAgB;AAAA,EAChB;AAAA,EACA,iBAAiB;AAAA,EACjB,qBAAqB;AAAA,EACrB,kBAAkB;AAAA,EAClB,gBAAgB;AAAA,EAChB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,UAAU;AAAA,EACV;AAAA,EACA,wBAAwB;AAAA,EACxB;AAAA,EACA,iBAAiB;AAAA,EACjB,SAAS;AAAA,EACT,OAAO,YAAY;AAAA,EACnB,WAAW;AAAA,EACX;AACF,MAA6B;AAC3B,QAAM,EAAE,EAAA,IAAM,eAAe,IAAI;AAEjC,QAAM,QAAQ,WAAW;AACzB,QAAM,QAAQ,CAAC,aAAa,SAAS;AACrC,QAAM,cAAc,WAAW,SAAS;AACxC,QAAM,aAAa,CAAC,CAAC,aAAa,UAAU,CAAC,CAAC,YAAY;AAE1D,QAAM,gBAAgB,WAAW,cAAc,WAAW,YAAY,MAAM,cAAc;AAC1F,QAAM,gBAAgB,CAAC,CAAC,WAAW,SAAS,gBAAgB,WAAW,QAAQ,SAAS;AACxF,QAAM,EAAE,sBAAsB,qBAA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A;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,EACR;AAAA,EACA,UAAU;AAAA,EACV,QAAQ;AAAA,EACR;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,gBAAgB;AAAA,EAChB;AAAA,EACA,iBAAiB;AAAA,EACjB,qBAAqB;AAAA,EACrB,kBAAkB;AAAA,EAClB,gBAAgB;AAAA,EAChB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,UAAU;AAAA,EACV;AAAA,EACA,wBAAwB;AAAA,EACxB;AAAA,EACA,iBAAiB;AAAA,EACjB,SAAS;AAAA,EACT,OAAO,YAAY;AAAA,EACnB,WAAW;AAAA,EACX;AACF,MAA6B;AAC3B,QAAM,EAAE,EAAA,IAAM,eAAe,IAAI;AAEjC,QAAM,QAAQ,WAAW;AACzB,QAAM,QAAQ,CAAC,aAAa,SAAS;AACrC,QAAM,cAAc,WAAW,SAAS;AACxC,QAAM,aAAa,CAAC,CAAC,aAAa,UAAU,CAAC,CAAC,YAAY;AAE1D,QAAM,gBAAgB,WAAW,cAAc,WAAW,YAAY,MAAM,cAAc;AAC1F,QAAM,gBAAgB,CAAC,CA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AAM,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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,SAAS,aAAa,EAAG,SAAQ,MAAM,EAAE,eAAe,KAAA,CAAM;AAEpG,cAAQ,eAAe,EAAE,OAAO,WAAW,QAAQ,WAAW;AAAA,IAChE,CAAC;AAAA,IACH,CAAC,KAAK;AAAA,EAAA;AAGR,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;"}
|
|
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 { 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,gBAAg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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,qCAA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AAY,MAAM,YAAY,EAAE,OAAO,SAAA,CAAU,EAAG,SAAQ;AAChE,MAAI,YAAY,MAAM,aAAa,EAAE,OAAO,SAAA,CAAU,EAAG,SAAQ;AAEjE,QAAM,WAAW,MAAM,OAAO,aAAa,IAAI,KAAK;AACpD,QAAM,cAAc,MAAM,OAAO,gBAAgB,IAAI,QAAQ;AAE7D,QAAM,OAAO,MAAM;AACnB,MAAI,aAAa,MAAM,UAAU,WAAW,EAAG,SAAQ;AACvD,MAAI,QAAQ,aAAa,KAAK,UAAU,gBAAgB,KAAK,UAAW,SAAQ;AAChF,MAAI,aAAa,MAAM,gBAAgB,UAAU,WAAW,EAAG,SAAQ;AAEvE,MAAI,MAAM,aAAa,OAAO,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,I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iC,UAAmB,gBACxE,CAAC,CAAC,QACF,YAAY,QACZ,eAAe,QACf,YAAY,KAAK,YACjB,YAAY,KAAK,UACjB,eAAe,KAAK,eACpB,eAAe,KAAK;AAEf,MAAM,sBAAsB,CAAC,OAAmB,OAAe,aAA6B;AACjG,MAAI,CAAC,MAAM,WAAY,QAAO;AAE9B,MAAI,OAAO;AAEX,MAAI,YAAY,MAAM,YAAY,EAAE,OAAO,SAAA,CAAU,EAAG,SAAQ;AAChE,MAAI,YAAY,MAAM,aAAa,EAAE,OAAO,SAAA,CAAU,EAAG,SAAQ;AAEjE,QAAM,WAAW,MAAM,OAAO,aAAa,IAAI,KAAK;AACpD,QAAM,cAAc,MAAM,OAAO,gBAAgB,IAAI,QAAQ;AAE7D,QAAM,OAAO,MAAM;AACnB,MAAI,aAAa,MAAM,UAAU,WAAW,EAAG,SAAQ;AACvD,MAAI,QAAQ,aAAa,KAAK,UAAU,gBAAgB,KAAK,UAAW,SAAQ;AAChF,MAAI,aAAa,MAAM,gBAAgB,UAAU,WAAW,EAAG,SAAQ;AAEvE,MAAI,MAAM,aAAa,OAAO,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,15 +1,21 @@
|
|
|
1
1
|
import { jsxs, jsx } from "react/jsx-runtime";
|
|
2
|
+
import { useEffect } from "react";
|
|
2
3
|
import { useTranslation } from "react-i18next";
|
|
3
4
|
import ControlledButton from "../../Form/ControlledButton.js";
|
|
4
5
|
import ControlledMenu from "../ControlledMenu.js";
|
|
5
6
|
import { MaterialSymbol } from "../MaterialSymbol/index.js";
|
|
6
|
-
import { Handle, Position } from "@xyflow/react";
|
|
7
|
+
import { useUpdateNodeInternals, Handle, Position } from "@xyflow/react";
|
|
7
8
|
import FlowNodeShell from "./FlowNodeShell.js";
|
|
8
9
|
const FLOW_INPUT_HANDLE_ID = "in";
|
|
9
10
|
const portTop = (index, count) => `${(index + 1) / (count + 1) * 100}%`;
|
|
10
|
-
const FlowBlockNode = ({ data, selected }) => {
|
|
11
|
+
const FlowBlockNode = ({ id, data, selected }) => {
|
|
11
12
|
const { t } = useTranslation("ui");
|
|
13
|
+
const updateNodeInternals = useUpdateNodeInternals();
|
|
12
14
|
const outputs = Array.isArray(data.outputs) ? data.outputs : [];
|
|
15
|
+
const handleSignature = `${data.hasInput ? FLOW_INPUT_HANDLE_ID : ""}|${outputs.join(",")}`;
|
|
16
|
+
useEffect(() => {
|
|
17
|
+
updateNodeInternals(id);
|
|
18
|
+
}, [id, handleSignature, updateNodeInternals]);
|
|
13
19
|
const connectedPorts = Array.isArray(data.connectedPorts) ? data.connectedPorts : [];
|
|
14
20
|
const addableBlocks = Array.isArray(data.addableBlocks) ? data.addableBlocks : [];
|
|
15
21
|
const showPortLabels = !(outputs.length === 1 && outputs[0] === "next");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"FlowBlockNode.js","sources":["../../../../src/components/UI/Flow/FlowBlockNode.tsx"],"sourcesContent":["import { ReactNode } from 'react';\nimport { useTranslation } from 'react-i18next';\n\nimport ControlledButton from '@/components/Form/ControlledButton';\nimport ControlledMenu from '@/components/UI/ControlledMenu';\nimport { MaterialSymbol, type SymbolCodepoints } from '@/components/UI/MaterialSymbol';\nimport { Handle, type Node, type NodeProps, Position } from '@xyflow/react';\n\nimport FlowNodeShell from './FlowNodeShell';\nimport type { TFlowIssueSeverity, TFlowPortId, TFlowRunStepStatus } from './flowTypes';\n\nexport const FLOW_INPUT_HANDLE_ID = 'in';\n\nexport interface IFlowAddableBlock {\n type: string;\n label: string;\n icon: SymbolCodepoints;\n}\n\nexport interface IFlowBlockNodeData extends Record<string, unknown> {\n icon: SymbolCodepoints;\n title: string;\n categoryLabel: string;\n summary?: ReactNode;\n hasInput: boolean;\n outputs: Array<TFlowPortId>;\n /** Ports already wired: their edge carries the label, so the port does not repeat it. */\n connectedPorts: Array<TFlowPortId>;\n portLabels: Record<TFlowPortId, string>;\n /** What a free port can grow into; empty in a read-only canvas. */\n addableBlocks: Array<IFlowAddableBlock>;\n onAddFromPort?: (port: TFlowPortId, type: string) => void;\n disabled?: boolean;\n issueSeverity?: TFlowIssueSeverity;\n issueCount: number;\n runStatus?: TFlowRunStepStatus;\n}\n\nexport type TFlowBlockNode = Node<IFlowBlockNodeData, 'flowBlock'>;\n\nconst portTop = (index: number, count: number): string => `${((index + 1) / (count + 1)) * 100}%`;\n\n/**\n * Input on the left edge, output ports spread along the right edge; a lone `next` port needs no\n * label. A free port shows a \"+\" that adds the next block already wired to it.\n */\nconst FlowBlockNode: React.FC<NodeProps<TFlowBlockNode>> = ({ data, selected }) => {\n const { t } = useTranslation('ui');\n const outputs = Array.isArray(data.outputs) ? data.outputs : [];\n const connectedPorts = Array.isArray(data.connectedPorts) ? data.connectedPorts : [];\n const addableBlocks = Array.isArray(data.addableBlocks) ? data.addableBlocks : [];\n const showPortLabels = !(outputs.length === 1 && outputs[0] === 'next');\n const canAdd = Boolean(data.onAddFromPort) && addableBlocks.length > 0;\n\n return (\n <FlowNodeShell\n icon={data.icon}\n title={data.title}\n categoryLabel={data.categoryLabel}\n summary={data.summary}\n selected={selected}\n disabled={data.disabled}\n issueSeverity={data.issueSeverity}\n issueCount={data.issueCount}\n runStatus={data.runStatus}\n className={showPortLabels ? 'pr-12' : undefined}\n >\n {data.hasInput && (\n <Handle id={FLOW_INPUT_HANDLE_ID} type=\"target\" position={Position.Left} className=\"umode-flow-handle\" />\n )}\n {outputs.map((port, index) => (\n <Handle\n key={port}\n id={port}\n type=\"source\"\n position={Position.Right}\n className=\"umode-flow-handle\"\n data-port={port}\n style={{ top: portTop(index, outputs.length) }}\n >\n {showPortLabels && !connectedPorts.includes(port) && (\n <span className=\"pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 whitespace-nowrap text-xxs font-semibold text-foreground-subtle\">\n {data.portLabels[port]}\n </span>\n )}\n </Handle>\n ))}\n {canAdd &&\n outputs.map((port, index) =>\n connectedPorts.includes(port) ? null : (\n <div\n key={`add|${port}`}\n className=\"nodrag nopan absolute -right-10 -translate-y-1/2\"\n style={{ top: portTop(index, outputs.length) }}\n >\n <ControlledMenu\n placement=\"right-start\"\n triggerTooltip={t('flow.node.addBlock')}\n items={addableBlocks.map((block) => ({\n key: block.type,\n label: block.label,\n icon: block.icon,\n onClick: () => data.onAddFromPort?.(port, block.type),\n }))}\n trigger={\n <ControlledButton\n defaultHtmlButton\n className=\"interactive flex size-6 items-center justify-center rounded-full border border-border-emphasis bg-surface text-foreground-muted shadow-sm hover:border-brand-border hover:bg-brand-soft hover:text-brand-emphasis focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n >\n <MaterialSymbol icon=\"add\" size={16} aria-hidden />\n </ControlledButton>\n }\n />\n </div>\n ),\n )}\n </FlowNodeShell>\n );\n};\n\nexport default FlowBlockNode;\n"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"FlowBlockNode.js","sources":["../../../../src/components/UI/Flow/FlowBlockNode.tsx"],"sourcesContent":["import { ReactNode, useEffect } from 'react';\nimport { useTranslation } from 'react-i18next';\n\nimport ControlledButton from '@/components/Form/ControlledButton';\nimport ControlledMenu from '@/components/UI/ControlledMenu';\nimport { MaterialSymbol, type SymbolCodepoints } from '@/components/UI/MaterialSymbol';\nimport { Handle, type Node, type NodeProps, Position, useUpdateNodeInternals } from '@xyflow/react';\n\nimport FlowNodeShell from './FlowNodeShell';\nimport type { TFlowIssueSeverity, TFlowPortId, TFlowRunStepStatus } from './flowTypes';\n\nexport const FLOW_INPUT_HANDLE_ID = 'in';\n\nexport interface IFlowAddableBlock {\n type: string;\n label: string;\n icon: SymbolCodepoints;\n}\n\nexport interface IFlowBlockNodeData extends Record<string, unknown> {\n icon: SymbolCodepoints;\n title: string;\n categoryLabel: string;\n summary?: ReactNode;\n hasInput: boolean;\n outputs: Array<TFlowPortId>;\n /** Ports already wired: their edge carries the label, so the port does not repeat it. */\n connectedPorts: Array<TFlowPortId>;\n portLabels: Record<TFlowPortId, string>;\n /** What a free port can grow into; empty in a read-only canvas. */\n addableBlocks: Array<IFlowAddableBlock>;\n onAddFromPort?: (port: TFlowPortId, type: string) => void;\n disabled?: boolean;\n issueSeverity?: TFlowIssueSeverity;\n issueCount: number;\n runStatus?: TFlowRunStepStatus;\n}\n\nexport type TFlowBlockNode = Node<IFlowBlockNodeData, 'flowBlock'>;\n\nconst portTop = (index: number, count: number): string => `${((index + 1) / (count + 1)) * 100}%`;\n\n/**\n * Input on the left edge, output ports spread along the right edge; a lone `next` port needs no\n * label. A free port shows a \"+\" that adds the next block already wired to it.\n */\nconst FlowBlockNode: React.FC<NodeProps<TFlowBlockNode>> = ({ id, data, selected }) => {\n const { t } = useTranslation('ui');\n const updateNodeInternals = useUpdateNodeInternals();\n const outputs = Array.isArray(data.outputs) ? data.outputs : [];\n const handleSignature = `${data.hasInput ? FLOW_INPUT_HANDLE_ID : ''}|${outputs.join(',')}`;\n\n // React Flow measures handle positions only when the node is resized. An edge whose handle was\n // not in that measurement is never drawn, so remeasure after mount and whenever the ports change.\n useEffect(() => {\n updateNodeInternals(id);\n }, [id, handleSignature, updateNodeInternals]);\n const connectedPorts = Array.isArray(data.connectedPorts) ? data.connectedPorts : [];\n const addableBlocks = Array.isArray(data.addableBlocks) ? data.addableBlocks : [];\n const showPortLabels = !(outputs.length === 1 && outputs[0] === 'next');\n const canAdd = Boolean(data.onAddFromPort) && addableBlocks.length > 0;\n\n return (\n <FlowNodeShell\n icon={data.icon}\n title={data.title}\n categoryLabel={data.categoryLabel}\n summary={data.summary}\n selected={selected}\n disabled={data.disabled}\n issueSeverity={data.issueSeverity}\n issueCount={data.issueCount}\n runStatus={data.runStatus}\n className={showPortLabels ? 'pr-12' : undefined}\n >\n {data.hasInput && (\n <Handle id={FLOW_INPUT_HANDLE_ID} type=\"target\" position={Position.Left} className=\"umode-flow-handle\" />\n )}\n {outputs.map((port, index) => (\n <Handle\n key={port}\n id={port}\n type=\"source\"\n position={Position.Right}\n className=\"umode-flow-handle\"\n data-port={port}\n style={{ top: portTop(index, outputs.length) }}\n >\n {showPortLabels && !connectedPorts.includes(port) && (\n <span className=\"pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 whitespace-nowrap text-xxs font-semibold text-foreground-subtle\">\n {data.portLabels[port]}\n </span>\n )}\n </Handle>\n ))}\n {canAdd &&\n outputs.map((port, index) =>\n connectedPorts.includes(port) ? null : (\n <div\n key={`add|${port}`}\n className=\"nodrag nopan absolute -right-10 -translate-y-1/2\"\n style={{ top: portTop(index, outputs.length) }}\n >\n <ControlledMenu\n placement=\"right-start\"\n triggerTooltip={t('flow.node.addBlock')}\n items={addableBlocks.map((block) => ({\n key: block.type,\n label: block.label,\n icon: block.icon,\n onClick: () => data.onAddFromPort?.(port, block.type),\n }))}\n trigger={\n <ControlledButton\n defaultHtmlButton\n className=\"interactive flex size-6 items-center justify-center rounded-full border border-border-emphasis bg-surface text-foreground-muted shadow-sm hover:border-brand-border hover:bg-brand-soft hover:text-brand-emphasis focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n >\n <MaterialSymbol icon=\"add\" size={16} aria-hidden />\n </ControlledButton>\n }\n />\n </div>\n ),\n )}\n </FlowNodeShell>\n );\n};\n\nexport default FlowBlockNode;\n"],"names":[],"mappings":";;;;;;;;AAWO,MAAM,uBAAuB;AA6BpC,MAAM,UAAU,CAAC,OAAe,UAA0B,IAAK,QAAQ,MAAM,QAAQ,KAAM,GAAG;AAM9F,MAAM,gBAAqD,CAAC,EAAE,IAAI,MAAM,eAAe;AACrF,QAAM,EAAE,EAAA,IAAM,eAAe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A,EAAK,WAAU,iIACb,UAAA,KAAK,WAAW,IAAI,EAAA,CACvB;AAAA,UAAA;AAAA,UAXG;AAAA,QAAA,CAcR;AAAA,QACA,UACC,QAAQ;AAAA,UAAI,CAAC,MAAM,UACjB,eAAe,SAAS,IAAI,IAAI,OAC9B;AAAA,YAAC;AAAA,YAAA;AAAA,cAEC,WAAU;AAAA,cACV,OAAO,EAAE,KAAK,QAAQ,OAAO,QAAQ,MAAM,EAAA;AAAA,cAE3C,UAAA;AAAA,gBAAC;AAAA,gBAAA;AAAA,kBACC,WAAU;AAAA,kBACV,gBAAgB,EAAE,oBAAoB;AAAA,kBACtC,OAAO,cAAc,IAAI,CAAC,WAAW;AAAA,oBACnC,KAAK,MAAM;AAAA,oBACX,OAAO,MAAM;AAAA,oBACb,MAAM,MAAM;AAAA,oBACZ,SAAS,MAAM,KAAK,gBAAgB,MAAM,MAAM,IAAI;AAAA,kBAAA,EACpD;AAAA,kBACF,SACE;AAAA,oBAAC;AAAA,oBAAA;AAAA,sBACC,mBAAiB;AAAA,sBACjB,WAAU;AAAA,sBAEV,8BAAC,gBAAA,EAAe,MAAK,OAAM,MAAM,IAAI,eAAW,KAAA,CAAC;AAAA,oBAAA;AAAA,kBAAA;AAAA,gBACnD;AAAA,cAAA;AAAA,YAEJ;AAAA,YArBK,OAAO,IAAI;AAAA,UAAA;AAAA,QAsBlB;AAAA,MAEJ;AAAA,IAAA;AAAA,EAAA;AAGR;"}
|
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
import { jsx, jsxs } from "react/jsx-runtime";
|
|
2
|
-
import { useMemo, useState, useCallback } from "react";
|
|
2
|
+
import { useMemo, useState, useRef, useEffect, useCallback } from "react";
|
|
3
3
|
import { useTranslation } from "react-i18next";
|
|
4
4
|
import { twMerge } from "tailwind-merge";
|
|
5
|
-
import { MarkerType, ReactFlow, Background, BackgroundVariant, MiniMap } from "@xyflow/react";
|
|
5
|
+
import { useReactFlow, useStore, MarkerType, ReactFlow, Background, BackgroundVariant, MiniMap } from "@xyflow/react";
|
|
6
6
|
import FlowBlockNode, { FLOW_INPUT_HANDLE_ID } from "./FlowBlockNode.js";
|
|
7
7
|
import { flowOutputsOf } from "./flowBlockRegistry.js";
|
|
8
8
|
import FlowConnectionEdge from "./FlowConnectionEdge.js";
|
|
9
9
|
import { useFlowBlockRegistry, useFlowEditorStore, useFlowEditor } from "./FlowEditorProvider.js";
|
|
10
10
|
import { canConnect, layoutFlowByLevels } from "./flowGraph.js";
|
|
11
|
+
import { boundsOfRects, viewportToReveal } from "./flowViewport.js";
|
|
11
12
|
import FlowZoomControls from "./FlowZoomControls.js";
|
|
12
13
|
import { useFlowLabels } from "./useFlowLabels.js";
|
|
13
14
|
import "@xyflow/react/dist/base.css";
|
|
@@ -19,6 +20,7 @@ const MINIMAP_SIZE = { width: 160, height: 104 };
|
|
|
19
20
|
const MINIMAP_MIN_NODES = 5;
|
|
20
21
|
const SNAP_GRID = [16, 16];
|
|
21
22
|
const PORTS = ["next", "true", "false", "error"];
|
|
23
|
+
const REVEAL_DURATION_MS = 200;
|
|
22
24
|
const isPortId = (value) => PORTS.includes(value);
|
|
23
25
|
const worstSeverity = (issues) => {
|
|
24
26
|
if (issues.some((issue) => issue.severity === "error")) return "error";
|
|
@@ -46,6 +48,47 @@ const FlowCanvas = ({
|
|
|
46
48
|
const canRedo = useFlowEditor((state) => state.future.length > 0);
|
|
47
49
|
const safeIssues = useMemo(() => Array.isArray(issues) ? issues : [], [issues]);
|
|
48
50
|
const [measuredSizes, setMeasuredSizes] = useState({});
|
|
51
|
+
const { getViewport, setViewport } = useReactFlow();
|
|
52
|
+
const canvasWidth = useStore((state) => state.width);
|
|
53
|
+
const canvasHeight = useStore((state) => state.height);
|
|
54
|
+
const [revealNodeIds, setRevealNodeIds] = useState([]);
|
|
55
|
+
const knownNodeIdsRef = useRef(null);
|
|
56
|
+
const pendingViewportRef = useRef(null);
|
|
57
|
+
useEffect(() => {
|
|
58
|
+
const currentIds = new Set(graph.nodes.map((node) => node.nodeId));
|
|
59
|
+
const knownIds = knownNodeIdsRef.current;
|
|
60
|
+
knownNodeIdsRef.current = currentIds;
|
|
61
|
+
const addedAndSelected = knownIds ? selectedNodeIds.filter((id) => currentIds.has(id) && !knownIds.has(id)) : [];
|
|
62
|
+
if (addedAndSelected.length > 0) {
|
|
63
|
+
setRevealNodeIds(addedAndSelected);
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
setRevealNodeIds(
|
|
67
|
+
(current) => current.length > 0 && !current.every((id) => selectedNodeIds.includes(id)) ? [] : current
|
|
68
|
+
);
|
|
69
|
+
}, [graph.nodes, selectedNodeIds]);
|
|
70
|
+
useEffect(() => {
|
|
71
|
+
if (revealNodeIds.length === 0) return;
|
|
72
|
+
const rects = [];
|
|
73
|
+
for (const nodeId of revealNodeIds) {
|
|
74
|
+
const node = graph.nodes.find((candidate) => candidate.nodeId === nodeId);
|
|
75
|
+
const size = measuredSizes[nodeId];
|
|
76
|
+
if (!node || !size) return;
|
|
77
|
+
rects.push({ ...node.position, ...size });
|
|
78
|
+
}
|
|
79
|
+
const bounds = boundsOfRects(rects);
|
|
80
|
+
if (!bounds) return;
|
|
81
|
+
const pending = pendingViewportRef.current;
|
|
82
|
+
const baseViewport = pending && pending.settlesAt > Date.now() ? pending.viewport : getViewport();
|
|
83
|
+
const target = viewportToReveal(baseViewport, bounds, { width: canvasWidth, height: canvasHeight });
|
|
84
|
+
if (!target) return;
|
|
85
|
+
pendingViewportRef.current = { viewport: target, settlesAt: Date.now() + REVEAL_DURATION_MS };
|
|
86
|
+
void setViewport(target, { duration: REVEAL_DURATION_MS });
|
|
87
|
+
}, [revealNodeIds, graph.nodes, measuredSizes, canvasWidth, canvasHeight, getViewport, setViewport]);
|
|
88
|
+
const stopRevealing = useCallback(() => {
|
|
89
|
+
pendingViewportRef.current = null;
|
|
90
|
+
setRevealNodeIds((current) => current.length > 0 ? [] : current);
|
|
91
|
+
}, []);
|
|
49
92
|
const addableBlocks = useMemo(() => {
|
|
50
93
|
if (readOnly) return [];
|
|
51
94
|
return registry.list.filter((definition) => definition.category !== "trigger").filter(
|
|
@@ -214,7 +257,13 @@ const FlowCanvas = ({
|
|
|
214
257
|
onEdgesChange: handleEdgesChange,
|
|
215
258
|
onConnect: handleConnect,
|
|
216
259
|
isValidConnection,
|
|
217
|
-
onNodeDragStart: () =>
|
|
260
|
+
onNodeDragStart: () => {
|
|
261
|
+
stopRevealing();
|
|
262
|
+
store.getState().recordHistory();
|
|
263
|
+
},
|
|
264
|
+
onMoveStart: (event) => {
|
|
265
|
+
if (event) stopRevealing();
|
|
266
|
+
},
|
|
218
267
|
onPaneClick: () => store.getState().setSelection({ nodeIds: [], edgeIds: [] }),
|
|
219
268
|
deleteKeyCode: null,
|
|
220
269
|
nodesDraggable: !readOnly,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"FlowCanvas.js","sources":["../../../../src/components/UI/Flow/FlowCanvas.tsx"],"sourcesContent":["import { KeyboardEvent, useCallback, useMemo, useState } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { twMerge } from 'tailwind-merge';\n\nimport {\n Background,\n BackgroundVariant,\n type Connection,\n type EdgeChange,\n MarkerType,\n MiniMap,\n type NodeChange,\n type PanelPosition,\n type ProOptions,\n ReactFlow,\n} from '@xyflow/react';\n\nimport FlowBlockNode, { FLOW_INPUT_HANDLE_ID, type IFlowAddableBlock, type TFlowBlockNode } from './FlowBlockNode';\nimport { flowOutputsOf } from './flowBlockRegistry';\nimport FlowConnectionEdge, { type TFlowConnectionEdge } from './FlowConnectionEdge';\nimport { useFlowBlockRegistry, useFlowEditor, useFlowEditorStore } from './FlowEditorProvider';\nimport { canConnect, layoutFlowByLevels } from './flowGraph';\nimport type { IFlowIssue, IFlowPosition, IFlowRunOverlay, TFlowIssueSeverity, TFlowPortId } from './flowTypes';\nimport FlowZoomControls from './FlowZoomControls';\nimport { useFlowLabels } from './useFlowLabels';\n\nimport '@xyflow/react/dist/base.css';\nimport '../../../styles/flow.css';\n\nconst PRO_OPTIONS: ProOptions = { hideAttribution: true };\nconst NODE_TYPES = { flowBlock: FlowBlockNode };\nconst EDGE_TYPES = { flowConnection: FlowConnectionEdge };\nconst MINIMAP_SIZE = { width: 160, height: 104 };\n/** A small flow fits on screen whole, where a minimap only covers blocks. */\nconst MINIMAP_MIN_NODES = 5;\nconst SNAP_GRID: [number, number] = [16, 16];\nconst PORTS: Array<TFlowPortId> = ['next', 'true', 'false', 'error'];\n\nexport interface IFlowCanvasProps {\n issues?: Array<IFlowIssue>;\n runOverlay?: IFlowRunOverlay | null;\n readOnly?: boolean;\n /** Accessible name of the canvas region, from `t()`. Defaults to the library label. */\n ariaLabel?: string;\n className?: string;\n /** Where the zoom and history controls sit. */\n controlsPosition?: PanelPosition;\n /** The dot grid behind the blocks. Blocks still snap to the grid when it is hidden. */\n background?: 'dots' | 'none';\n}\n\nconst isPortId = (value: string | null | undefined): value is TFlowPortId => PORTS.includes(value as TFlowPortId);\n\nconst worstSeverity = (issues: Array<IFlowIssue>): TFlowIssueSeverity | undefined => {\n if (issues.some((issue) => issue.severity === 'error')) return 'error';\n if (issues.some((issue) => issue.severity === 'warning')) return 'warning';\n return undefined;\n};\n\nconst isTypingTarget = (target: EventTarget | null): boolean =>\n target instanceof HTMLElement &&\n (target.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(target.tagName));\n\n/**\n * The editing surface. Renders the graph held by `FlowEditorProvider` and turns every\n * gesture (drag, connect, select, delete, shortcuts) into a store action, so undo\n * and the dirty flag see all of them.\n */\nconst FlowCanvas: React.FC<IFlowCanvasProps> = ({\n issues = [],\n runOverlay,\n readOnly = false,\n ariaLabel,\n className,\n controlsPosition,\n background = 'dots',\n}) => {\n const { t } = useTranslation('ui');\n const labels = useFlowLabels();\n const registry = useFlowBlockRegistry();\n const store = useFlowEditorStore();\n\n const graph = useFlowEditor((state) => state.graph);\n const selectedNodeIds = useFlowEditor((state) => state.selectedNodeIds);\n const selectedEdgeIds = useFlowEditor((state) => state.selectedEdgeIds);\n const canUndo = useFlowEditor((state) => state.past.length > 0);\n const canRedo = useFlowEditor((state) => state.future.length > 0);\n\n const safeIssues = useMemo(() => (Array.isArray(issues) ? issues : []), [issues]);\n // Measured sizes are view state, not part of the flow: kept here so the minimap can draw the blocks.\n const [measuredSizes, setMeasuredSizes] = useState<Record<string, { width: number; height: number }>>({});\n\n const addableBlocks = useMemo<Array<IFlowAddableBlock>>(() => {\n if (readOnly) return [];\n return registry.list\n .filter((definition) => definition.category !== 'trigger')\n .filter(\n (definition) =>\n definition.maxInstances === undefined ||\n graph.nodes.filter((node) => node.type === definition.type).length < definition.maxInstances,\n )\n .map((definition) => ({ type: definition.type, label: definition.label, icon: definition.icon }));\n }, [registry, graph.nodes, readOnly]);\n\n // A block in the middle of an edge needs an output to carry the flow on to the old target.\n const insertableBlocks = useMemo<Array<IFlowAddableBlock>>(\n () =>\n addableBlocks.filter((block) => {\n const definition = registry.get(block.type);\n return definition ? flowOutputsOf(definition, definition.createDefaultConfig()).length > 0 : false;\n }),\n [addableBlocks, registry],\n );\n\n const nodes = useMemo<Array<TFlowBlockNode>>(\n () =>\n graph.nodes.map((node) => {\n const definition = registry.get(node.type);\n const nodeIssues = safeIssues.filter((issue) => issue.nodeId === node.nodeId);\n return {\n id: node.nodeId,\n type: 'flowBlock',\n position: node.position,\n measured: measuredSizes[node.nodeId],\n selected: selectedNodeIds.includes(node.nodeId),\n draggable: !readOnly,\n connectable: !readOnly,\n data: {\n icon: definition?.resolveIcon?.(node.config) ?? definition?.icon ?? 'help',\n title: node.label ?? definition?.resolveLabel?.(node.config) ?? definition?.label ?? node.type,\n categoryLabel: definition ? labels.categories[definition.category] : '',\n summary: definition\n ? definition.renderSummary(node.config)\n : labels.issueMessage({ code: 'unknownBlock', severity: 'error' }),\n hasInput: definition ? definition.category !== 'trigger' : true,\n outputs: flowOutputsOf(definition, node.config),\n connectedPorts: graph.edges.filter((edge) => edge.source === node.nodeId).map((edge) => edge.sourcePort),\n portLabels: labels.ports,\n addableBlocks,\n onAddFromPort: readOnly\n ? undefined\n : (port, type) => store.getState().addNodeFromPort(type, node.nodeId, port),\n disabled: node.disabled,\n issueSeverity: worstSeverity(nodeIssues),\n issueCount: nodeIssues.length,\n runStatus: runOverlay?.steps?.[node.nodeId],\n },\n };\n }),\n [\n graph.nodes,\n graph.edges,\n registry,\n safeIssues,\n selectedNodeIds,\n readOnly,\n labels,\n runOverlay,\n measuredSizes,\n addableBlocks,\n store,\n ],\n );\n\n const edges = useMemo<Array<TFlowConnectionEdge>>(() => {\n const traversed = new Set(runOverlay?.traversedEdgeIds ?? []);\n return graph.edges.map((edge) => ({\n id: edge.edgeId,\n type: 'flowConnection',\n source: edge.source,\n sourceHandle: edge.sourcePort,\n target: edge.target,\n targetHandle: FLOW_INPUT_HANDLE_ID,\n selected: selectedEdgeIds.includes(edge.edgeId),\n markerEnd: { type: MarkerType.ArrowClosed, width: 16, height: 16 },\n data: {\n label: edge.sourcePort === 'next' ? undefined : labels.ports[edge.sourcePort],\n traversed: traversed.has(edge.edgeId),\n issueSeverity: worstSeverity(safeIssues.filter((issue) => issue.edgeId === edge.edgeId)),\n insertableBlocks,\n onInsert: readOnly ? undefined : (type: string) => store.getState().insertNodeOnEdge(type, edge.edgeId),\n },\n }));\n }, [graph.edges, selectedEdgeIds, runOverlay, labels, safeIssues, insertableBlocks, readOnly, store]);\n\n const handleNodesChange = useCallback(\n (changes: Array<NodeChange<TFlowBlockNode>>) => {\n const positions: Record<string, IFlowPosition> = {};\n const sizes: Record<string, { width: number; height: number }> = {};\n let selection: Array<string> | null = null;\n for (const change of changes) {\n if (change.type === 'dimensions' && change.dimensions) sizes[change.id] = change.dimensions;\n if (change.type === 'position' && change.position && !readOnly) positions[change.id] = change.position;\n if (change.type === 'select') {\n const current: Array<string> = selection ?? store.getState().selectedNodeIds;\n selection = change.selected\n ? [...new Set([...current, change.id])]\n : current.filter((id) => id !== change.id);\n }\n }\n if (Object.keys(sizes).length > 0) setMeasuredSizes((current) => ({ ...current, ...sizes }));\n if (Object.keys(positions).length > 0) store.getState().moveNodes(positions);\n if (selection) store.getState().setSelection({ nodeIds: selection });\n },\n [store, readOnly],\n );\n\n const handleEdgesChange = useCallback(\n (changes: Array<EdgeChange<TFlowConnectionEdge>>) => {\n let selection: Array<string> | null = null;\n for (const change of changes) {\n if (change.type !== 'select') continue;\n const current: Array<string> = selection ?? store.getState().selectedEdgeIds;\n selection = change.selected ? [...new Set([...current, change.id])] : current.filter((id) => id !== change.id);\n }\n if (selection) store.getState().setSelection({ edgeIds: selection });\n },\n [store],\n );\n\n const handleConnect = useCallback(\n (connection: Connection) => {\n if (readOnly || !isPortId(connection.sourceHandle)) return;\n store.getState().connect(connection.source, connection.sourceHandle, connection.target);\n },\n [store, readOnly],\n );\n\n const isValidConnection = useCallback(\n (connection: Connection | TFlowConnectionEdge) =>\n isPortId(connection.sourceHandle) &&\n canConnect(store.getState().graph, registry, {\n source: connection.source,\n sourcePort: connection.sourceHandle,\n target: connection.target,\n }),\n [store, registry],\n );\n\n const handleKeyDown = useCallback(\n (event: KeyboardEvent<HTMLDivElement>) => {\n if (readOnly || isTypingTarget(event.target)) return;\n const state = store.getState();\n const withModifier = event.metaKey || event.ctrlKey;\n const key = event.key.toLowerCase();\n\n if (event.key === 'Delete' || event.key === 'Backspace') state.removeSelected();\n else if (withModifier && key === 'z' && event.shiftKey) state.redo();\n else if (withModifier && key === 'z') state.undo();\n else if (withModifier && key === 'y') state.redo();\n else if (withModifier && key === 'c') state.copySelected();\n else if (withModifier && key === 'v') state.paste();\n else if (withModifier && key === 'd') state.duplicateSelected();\n else return;\n event.preventDefault();\n },\n [store, readOnly],\n );\n\n const handleLayout = useCallback(() => {\n const state = store.getState();\n state.recordHistory();\n state.moveNodes(layoutFlowByLevels(state.graph, registry));\n }, [store, registry]);\n\n return (\n <div\n role=\"region\"\n aria-label={ariaLabel ?? t('flow.canvas')}\n tabIndex={0}\n onKeyDown={handleKeyDown}\n className={twMerge(\n 'umode-flow relative h-full min-h-[24rem] w-full rounded-xl bg-canvas focus:outline-none',\n className,\n )}\n >\n <ReactFlow<TFlowBlockNode, TFlowConnectionEdge>\n nodes={nodes}\n edges={edges}\n nodeTypes={NODE_TYPES}\n edgeTypes={EDGE_TYPES}\n onNodesChange={handleNodesChange}\n onEdgesChange={handleEdgesChange}\n onConnect={handleConnect}\n isValidConnection={isValidConnection}\n onNodeDragStart={() => store.getState().recordHistory()}\n onPaneClick={() => store.getState().setSelection({ nodeIds: [], edgeIds: [] })}\n deleteKeyCode={null}\n nodesDraggable={!readOnly}\n nodesConnectable={!readOnly}\n snapToGrid\n snapGrid={SNAP_GRID}\n minZoom={0.25}\n maxZoom={2}\n fitView\n fitViewOptions={{ padding: 0.2, maxZoom: 1 }}\n proOptions={PRO_OPTIONS}\n >\n {background === 'dots' && <Background variant={BackgroundVariant.Dots} gap={16} size={1} />}\n {nodes.length >= MINIMAP_MIN_NODES && (\n <MiniMap pannable zoomable position=\"bottom-right\" style={MINIMAP_SIZE} />\n )}\n <FlowZoomControls\n onUndo={readOnly ? undefined : () => store.getState().undo()}\n onRedo={readOnly ? undefined : () => store.getState().redo()}\n canUndo={canUndo}\n canRedo={canRedo}\n onLayout={readOnly ? undefined : handleLayout}\n position={controlsPosition}\n />\n </ReactFlow>\n </div>\n );\n};\n\nexport default FlowCanvas;\n"],"names":[],"mappings":";;;;;;;;;;;;;;AA6BA,MAAM,cAA0B,EAAE,iBAAiB,KAAA;AACnD,MAAM,aAAa,EAAE,WAAW,cAAA;AAChC,MAAM,aAAa,EAAE,gBAAgB,mBAAA;AACrC,MAAM,eAAe,EAAE,OAAO,KAAK,QAAQ,IAAA;AAE3C,MAAM,oBAAoB;AAC1B,MAAM,YAA8B,CAAC,IAAI,EAAE;AAC3C,MAAM,QAA4B,CAAC,QAAQ,QAAQ,SAAS,OAAO;AAenE,MAAM,WAAW,CAAC,UAA2D,MAAM,SAAS,KAAoB;AAE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AAA,cAAA;AAAA,YAAA;AAAA,UACZ;AAAA,QAAA;AAAA,MAAA;AAAA,IACF;AAAA,EAAA;AAGN;"}
|
|
1
|
+
{"version":3,"file":"FlowCanvas.js","sources":["../../../../src/components/UI/Flow/FlowCanvas.tsx"],"sourcesContent":["import { KeyboardEvent, useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { useTranslation } from 'react-i18next';\nimport { twMerge } from 'tailwind-merge';\n\nimport {\n Background,\n BackgroundVariant,\n type Connection,\n type EdgeChange,\n MarkerType,\n MiniMap,\n type NodeChange,\n type PanelPosition,\n type ProOptions,\n ReactFlow,\n useReactFlow,\n useStore as useReactFlowStore,\n} from '@xyflow/react';\n\nimport FlowBlockNode, { FLOW_INPUT_HANDLE_ID, type IFlowAddableBlock, type TFlowBlockNode } from './FlowBlockNode';\nimport { flowOutputsOf } from './flowBlockRegistry';\nimport FlowConnectionEdge, { type TFlowConnectionEdge } from './FlowConnectionEdge';\nimport { useFlowBlockRegistry, useFlowEditor, useFlowEditorStore } from './FlowEditorProvider';\nimport { canConnect, layoutFlowByLevels } from './flowGraph';\nimport type { IFlowIssue, IFlowPosition, IFlowRunOverlay, TFlowIssueSeverity, TFlowPortId } from './flowTypes';\nimport { boundsOfRects, type IFlowRect, type IFlowViewport, viewportToReveal } from './flowViewport';\nimport FlowZoomControls from './FlowZoomControls';\nimport { useFlowLabels } from './useFlowLabels';\n\nimport '@xyflow/react/dist/base.css';\nimport '../../../styles/flow.css';\n\nconst PRO_OPTIONS: ProOptions = { hideAttribution: true };\nconst NODE_TYPES = { flowBlock: FlowBlockNode };\nconst EDGE_TYPES = { flowConnection: FlowConnectionEdge };\nconst MINIMAP_SIZE = { width: 160, height: 104 };\n/** A small flow fits on screen whole, where a minimap only covers blocks. */\nconst MINIMAP_MIN_NODES = 5;\nconst SNAP_GRID: [number, number] = [16, 16];\nconst PORTS: Array<TFlowPortId> = ['next', 'true', 'false', 'error'];\nconst REVEAL_DURATION_MS = 200;\n\nexport interface IFlowCanvasProps {\n issues?: Array<IFlowIssue>;\n runOverlay?: IFlowRunOverlay | null;\n readOnly?: boolean;\n /** Accessible name of the canvas region, from `t()`. Defaults to the library label. */\n ariaLabel?: string;\n className?: string;\n /** Where the zoom and history controls sit. */\n controlsPosition?: PanelPosition;\n /** The dot grid behind the blocks. Blocks still snap to the grid when it is hidden. */\n background?: 'dots' | 'none';\n}\n\nconst isPortId = (value: string | null | undefined): value is TFlowPortId => PORTS.includes(value as TFlowPortId);\n\nconst worstSeverity = (issues: Array<IFlowIssue>): TFlowIssueSeverity | undefined => {\n if (issues.some((issue) => issue.severity === 'error')) return 'error';\n if (issues.some((issue) => issue.severity === 'warning')) return 'warning';\n return undefined;\n};\n\nconst isTypingTarget = (target: EventTarget | null): boolean =>\n target instanceof HTMLElement &&\n (target.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(target.tagName));\n\n/**\n * The editing surface. Renders the graph held by `FlowEditorProvider` and turns every\n * gesture (drag, connect, select, delete, shortcuts) into a store action, so undo\n * and the dirty flag see all of them.\n */\nconst FlowCanvas: React.FC<IFlowCanvasProps> = ({\n issues = [],\n runOverlay,\n readOnly = false,\n ariaLabel,\n className,\n controlsPosition,\n background = 'dots',\n}) => {\n const { t } = useTranslation('ui');\n const labels = useFlowLabels();\n const registry = useFlowBlockRegistry();\n const store = useFlowEditorStore();\n\n const graph = useFlowEditor((state) => state.graph);\n const selectedNodeIds = useFlowEditor((state) => state.selectedNodeIds);\n const selectedEdgeIds = useFlowEditor((state) => state.selectedEdgeIds);\n const canUndo = useFlowEditor((state) => state.past.length > 0);\n const canRedo = useFlowEditor((state) => state.future.length > 0);\n\n const safeIssues = useMemo(() => (Array.isArray(issues) ? issues : []), [issues]);\n // Measured sizes are view state, not part of the flow: kept here so the minimap can draw the blocks.\n const [measuredSizes, setMeasuredSizes] = useState<Record<string, { width: number; height: number }>>({});\n\n const { getViewport, setViewport } = useReactFlow<TFlowBlockNode, TFlowConnectionEdge>();\n const canvasWidth = useReactFlowStore((state) => state.width);\n const canvasHeight = useReactFlowStore((state) => state.height);\n // Blocks just added and selected: kept in view until the user moves the view or the selection, so\n // the host panel that opens on selection (and narrows the canvas) cannot hide them.\n const [revealNodeIds, setRevealNodeIds] = useState<Array<string>>([]);\n const knownNodeIdsRef = useRef<Set<string> | null>(null);\n const pendingViewportRef = useRef<{ viewport: IFlowViewport; settlesAt: number } | null>(null);\n\n useEffect(() => {\n const currentIds = new Set(graph.nodes.map((node) => node.nodeId));\n const knownIds = knownNodeIdsRef.current;\n knownNodeIdsRef.current = currentIds;\n const addedAndSelected = knownIds ? selectedNodeIds.filter((id) => currentIds.has(id) && !knownIds.has(id)) : [];\n if (addedAndSelected.length > 0) {\n setRevealNodeIds(addedAndSelected);\n return;\n }\n setRevealNodeIds((current) =>\n current.length > 0 && !current.every((id) => selectedNodeIds.includes(id)) ? [] : current,\n );\n }, [graph.nodes, selectedNodeIds]);\n\n useEffect(() => {\n if (revealNodeIds.length === 0) return;\n const rects: Array<IFlowRect> = [];\n for (const nodeId of revealNodeIds) {\n const node = graph.nodes.find((candidate) => candidate.nodeId === nodeId);\n const size = measuredSizes[nodeId];\n if (!node || !size) return;\n rects.push({ ...node.position, ...size });\n }\n const bounds = boundsOfRects(rects);\n if (!bounds) return;\n // A pan still animating reports an in-between viewport; build on where it is heading instead.\n const pending = pendingViewportRef.current;\n const baseViewport = pending && pending.settlesAt > Date.now() ? pending.viewport : getViewport();\n const target = viewportToReveal(baseViewport, bounds, { width: canvasWidth, height: canvasHeight });\n if (!target) return;\n pendingViewportRef.current = { viewport: target, settlesAt: Date.now() + REVEAL_DURATION_MS };\n void setViewport(target, { duration: REVEAL_DURATION_MS });\n }, [revealNodeIds, graph.nodes, measuredSizes, canvasWidth, canvasHeight, getViewport, setViewport]);\n\n const stopRevealing = useCallback(() => {\n pendingViewportRef.current = null;\n setRevealNodeIds((current) => (current.length > 0 ? [] : current));\n }, []);\n\n const addableBlocks = useMemo<Array<IFlowAddableBlock>>(() => {\n if (readOnly) return [];\n return registry.list\n .filter((definition) => definition.category !== 'trigger')\n .filter(\n (definition) =>\n definition.maxInstances === undefined ||\n graph.nodes.filter((node) => node.type === definition.type).length < definition.maxInstances,\n )\n .map((definition) => ({ type: definition.type, label: definition.label, icon: definition.icon }));\n }, [registry, graph.nodes, readOnly]);\n\n // A block in the middle of an edge needs an output to carry the flow on to the old target.\n const insertableBlocks = useMemo<Array<IFlowAddableBlock>>(\n () =>\n addableBlocks.filter((block) => {\n const definition = registry.get(block.type);\n return definition ? flowOutputsOf(definition, definition.createDefaultConfig()).length > 0 : false;\n }),\n [addableBlocks, registry],\n );\n\n const nodes = useMemo<Array<TFlowBlockNode>>(\n () =>\n graph.nodes.map((node) => {\n const definition = registry.get(node.type);\n const nodeIssues = safeIssues.filter((issue) => issue.nodeId === node.nodeId);\n return {\n id: node.nodeId,\n type: 'flowBlock',\n position: node.position,\n measured: measuredSizes[node.nodeId],\n selected: selectedNodeIds.includes(node.nodeId),\n draggable: !readOnly,\n connectable: !readOnly,\n data: {\n icon: definition?.resolveIcon?.(node.config) ?? definition?.icon ?? 'help',\n title: node.label ?? definition?.resolveLabel?.(node.config) ?? definition?.label ?? node.type,\n categoryLabel: definition ? labels.categories[definition.category] : '',\n summary: definition\n ? definition.renderSummary(node.config)\n : labels.issueMessage({ code: 'unknownBlock', severity: 'error' }),\n hasInput: definition ? definition.category !== 'trigger' : true,\n outputs: flowOutputsOf(definition, node.config),\n connectedPorts: graph.edges.filter((edge) => edge.source === node.nodeId).map((edge) => edge.sourcePort),\n portLabels: labels.ports,\n addableBlocks,\n onAddFromPort: readOnly\n ? undefined\n : (port, type) => store.getState().addNodeFromPort(type, node.nodeId, port),\n disabled: node.disabled,\n issueSeverity: worstSeverity(nodeIssues),\n issueCount: nodeIssues.length,\n runStatus: runOverlay?.steps?.[node.nodeId],\n },\n };\n }),\n [\n graph.nodes,\n graph.edges,\n registry,\n safeIssues,\n selectedNodeIds,\n readOnly,\n labels,\n runOverlay,\n measuredSizes,\n addableBlocks,\n store,\n ],\n );\n\n const edges = useMemo<Array<TFlowConnectionEdge>>(() => {\n const traversed = new Set(runOverlay?.traversedEdgeIds ?? []);\n return graph.edges.map((edge) => ({\n id: edge.edgeId,\n type: 'flowConnection',\n source: edge.source,\n sourceHandle: edge.sourcePort,\n target: edge.target,\n targetHandle: FLOW_INPUT_HANDLE_ID,\n selected: selectedEdgeIds.includes(edge.edgeId),\n markerEnd: { type: MarkerType.ArrowClosed, width: 16, height: 16 },\n data: {\n label: edge.sourcePort === 'next' ? undefined : labels.ports[edge.sourcePort],\n traversed: traversed.has(edge.edgeId),\n issueSeverity: worstSeverity(safeIssues.filter((issue) => issue.edgeId === edge.edgeId)),\n insertableBlocks,\n onInsert: readOnly ? undefined : (type: string) => store.getState().insertNodeOnEdge(type, edge.edgeId),\n },\n }));\n }, [graph.edges, selectedEdgeIds, runOverlay, labels, safeIssues, insertableBlocks, readOnly, store]);\n\n const handleNodesChange = useCallback(\n (changes: Array<NodeChange<TFlowBlockNode>>) => {\n const positions: Record<string, IFlowPosition> = {};\n const sizes: Record<string, { width: number; height: number }> = {};\n let selection: Array<string> | null = null;\n for (const change of changes) {\n if (change.type === 'dimensions' && change.dimensions) sizes[change.id] = change.dimensions;\n if (change.type === 'position' && change.position && !readOnly) positions[change.id] = change.position;\n if (change.type === 'select') {\n const current: Array<string> = selection ?? store.getState().selectedNodeIds;\n selection = change.selected\n ? [...new Set([...current, change.id])]\n : current.filter((id) => id !== change.id);\n }\n }\n if (Object.keys(sizes).length > 0) setMeasuredSizes((current) => ({ ...current, ...sizes }));\n if (Object.keys(positions).length > 0) store.getState().moveNodes(positions);\n if (selection) store.getState().setSelection({ nodeIds: selection });\n },\n [store, readOnly],\n );\n\n const handleEdgesChange = useCallback(\n (changes: Array<EdgeChange<TFlowConnectionEdge>>) => {\n let selection: Array<string> | null = null;\n for (const change of changes) {\n if (change.type !== 'select') continue;\n const current: Array<string> = selection ?? store.getState().selectedEdgeIds;\n selection = change.selected ? [...new Set([...current, change.id])] : current.filter((id) => id !== change.id);\n }\n if (selection) store.getState().setSelection({ edgeIds: selection });\n },\n [store],\n );\n\n const handleConnect = useCallback(\n (connection: Connection) => {\n if (readOnly || !isPortId(connection.sourceHandle)) return;\n store.getState().connect(connection.source, connection.sourceHandle, connection.target);\n },\n [store, readOnly],\n );\n\n const isValidConnection = useCallback(\n (connection: Connection | TFlowConnectionEdge) =>\n isPortId(connection.sourceHandle) &&\n canConnect(store.getState().graph, registry, {\n source: connection.source,\n sourcePort: connection.sourceHandle,\n target: connection.target,\n }),\n [store, registry],\n );\n\n const handleKeyDown = useCallback(\n (event: KeyboardEvent<HTMLDivElement>) => {\n if (readOnly || isTypingTarget(event.target)) return;\n const state = store.getState();\n const withModifier = event.metaKey || event.ctrlKey;\n const key = event.key.toLowerCase();\n\n if (event.key === 'Delete' || event.key === 'Backspace') state.removeSelected();\n else if (withModifier && key === 'z' && event.shiftKey) state.redo();\n else if (withModifier && key === 'z') state.undo();\n else if (withModifier && key === 'y') state.redo();\n else if (withModifier && key === 'c') state.copySelected();\n else if (withModifier && key === 'v') state.paste();\n else if (withModifier && key === 'd') state.duplicateSelected();\n else return;\n event.preventDefault();\n },\n [store, readOnly],\n );\n\n const handleLayout = useCallback(() => {\n const state = store.getState();\n state.recordHistory();\n state.moveNodes(layoutFlowByLevels(state.graph, registry));\n }, [store, registry]);\n\n return (\n <div\n role=\"region\"\n aria-label={ariaLabel ?? t('flow.canvas')}\n tabIndex={0}\n onKeyDown={handleKeyDown}\n className={twMerge(\n 'umode-flow relative h-full min-h-[24rem] w-full rounded-xl bg-canvas focus:outline-none',\n className,\n )}\n >\n <ReactFlow<TFlowBlockNode, TFlowConnectionEdge>\n nodes={nodes}\n edges={edges}\n nodeTypes={NODE_TYPES}\n edgeTypes={EDGE_TYPES}\n onNodesChange={handleNodesChange}\n onEdgesChange={handleEdgesChange}\n onConnect={handleConnect}\n isValidConnection={isValidConnection}\n onNodeDragStart={() => {\n stopRevealing();\n store.getState().recordHistory();\n }}\n onMoveStart={(event) => {\n if (event) stopRevealing();\n }}\n onPaneClick={() => store.getState().setSelection({ nodeIds: [], edgeIds: [] })}\n deleteKeyCode={null}\n nodesDraggable={!readOnly}\n nodesConnectable={!readOnly}\n snapToGrid\n snapGrid={SNAP_GRID}\n minZoom={0.25}\n maxZoom={2}\n fitView\n fitViewOptions={{ padding: 0.2, maxZoom: 1 }}\n proOptions={PRO_OPTIONS}\n >\n {background === 'dots' && <Background variant={BackgroundVariant.Dots} gap={16} size={1} />}\n {nodes.length >= MINIMAP_MIN_NODES && (\n <MiniMap pannable zoomable position=\"bottom-right\" style={MINIMAP_SIZE} />\n )}\n <FlowZoomControls\n onUndo={readOnly ? undefined : () => store.getState().undo()}\n onRedo={readOnly ? undefined : () => store.getState().redo()}\n canUndo={canUndo}\n canRedo={canRedo}\n onLayout={readOnly ? undefined : handleLayout}\n position={controlsPosition}\n />\n </ReactFlow>\n </div>\n );\n};\n\nexport default FlowCanvas;\n"],"names":["useReactFlowStore"],"mappings":";;;;;;;;;;;;;;;AAgCA,MAAM,cAA0B,EAAE,iBAAiB,KAAA;AACnD,MAAM,aAAa,EAAE,WAAW,cAAA;AAChC,MAAM,aAAa,EAAE,gBAAgB,mBAAA;AACrC,MAAM,eAAe,EAAE,OAAO,KAAK,QAAQ,IAAA;AAE3C,MAAM,oBAAoB;AAC1B,MAAM,YAA8B,CAAC,IAAI,EAAE;AAC3C,MAAM,QAA4B,CAAC,QAAQ,QAAQ,SAAS,OAAO;AACnE,MAAM,qBAAqB;AAe3B,MAAM,WAAW,CAAC,UAA2D,MAAM,SAAS,KAAoB;AAEhH,MAAM,gBAAgB,CAAC,WAA8D;AACnF,MAAI,OAAO,KAAK,CAAC,UAAU,MAAM,aAAa,OAAO,EAAG,QAAO;AAC/D,MAAI,OAAO,KAAK,CAAC,UAAU,MAAM,aAAa,SAAS,EAAG,QAAO;AACjE,SAAO;AACT;AAEA,MAAM,iBA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A,CAAG;AAAA,YACxF,MAAM,UAAU,qBACf,oBAAC,SAAA,EAAQ,UAAQ,MAAC,UAAQ,MAAC,UAAS,gBAAe,OAAO,aAAA,CAAc;AAAA,YAE1E;AAAA,cAAC;AAAA,cAAA;AAAA,gBACC,QAAQ,WAAW,SAAY,MAAM,MAAM,SAAA,EAAW,KAAA;AAAA,gBACtD,QAAQ,WAAW,SAAY,MAAM,MAAM,SAAA,EAAW,KAAA;AAAA,gBACtD;AAAA,gBACA;AAAA,gBACA,UAAU,WAAW,SAAY;AAAA,gBACjC,UAAU;AAAA,cAAA;AAAA,YAAA;AAAA,UACZ;AAAA,QAAA;AAAA,MAAA;AAAA,IACF;AAAA,EAAA;AAGN;"}
|
|
@@ -98,6 +98,7 @@ const FlowInspector = ({
|
|
|
98
98
|
size: "sm",
|
|
99
99
|
variant: "outlined",
|
|
100
100
|
tone: "neutral",
|
|
101
|
+
className: "normal-case",
|
|
101
102
|
onClick: () => store.getState().duplicateSelected(),
|
|
102
103
|
children: [
|
|
103
104
|
/* @__PURE__ */ jsx(MaterialSymbol, { icon: "content_copy", size: 16, "aria-hidden": true }),
|
|
@@ -111,6 +112,7 @@ const FlowInspector = ({
|
|
|
111
112
|
size: "sm",
|
|
112
113
|
variant: "outlined",
|
|
113
114
|
tone: "danger",
|
|
115
|
+
className: "normal-case",
|
|
114
116
|
onClick: () => store.getState().removeSelected(),
|
|
115
117
|
children: [
|
|
116
118
|
/* @__PURE__ */ jsx(MaterialSymbol, { icon: "delete", size: 16, "aria-hidden": true }),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"FlowInspector.js","sources":["../../../../src/components/UI/Flow/FlowInspector.tsx"],"sourcesContent":["import { useTranslation } from 'react-i18next';\nimport { twMerge } from 'tailwind-merge';\n\nimport ControlledButton from '@/components/Form/ControlledButton';\nimport ControlledInput from '@/components/Form/ControlledInput';\nimport ControlledTooltip from '@/components/UI/ControlledTooltip';\nimport { MaterialSymbol } from '@/components/UI/MaterialSymbol';\nimport NoDataFound from '@/components/UI/NoDataFound';\n\nimport { useFlowBlockRegistry, useFlowEditor, useFlowEditorStore } from './FlowEditorProvider';\nimport { isFlowNodeRemovable } from './flowGraph';\nimport type { IFlowIssue } from './flowTypes';\nimport { useFlowLabels } from './useFlowLabels';\n\ninterface IFlowInspectorProps {\n issues?: Array<IFlowIssue>;\n readOnly?: boolean;\n /** Renders nothing while no block is selected, instead of the empty state. */\n hideWhenEmpty?: boolean;\n className?: string;\n}\n\n/** The side panel of the selected block: its name, its own settings panel and its issues. */\nconst FlowInspector: React.FC<IFlowInspectorProps> = ({\n issues = [],\n readOnly = false,\n hideWhenEmpty = false,\n className,\n}) => {\n const { t } = useTranslation('ui');\n const labels = useFlowLabels();\n const registry = useFlowBlockRegistry();\n const store = useFlowEditorStore();\n const selectedNodeIds = useFlowEditor((state) => state.selectedNodeIds);\n const selectedNode = useFlowEditor((state) =>\n state.selectedNodeIds.length === 1\n ? state.graph.nodes.find((node) => node.nodeId === state.selectedNodeIds[0])\n : undefined,\n );\n\n const shellClass = twMerge(\n 'flex h-full min-h-0 flex-col gap-y-3 rounded-xl border border-border bg-surface p-4',\n className,\n );\n\n if (!selectedNode || selectedNodeIds.length !== 1) {\n if (hideWhenEmpty) return null;\n return (\n <aside className={shellClass} aria-label={t('flow.inspector.title')}>\n <NoDataFound size=\"sm\" variant=\"waiting\" message={t('flow.inspector.empty')} />\n </aside>\n );\n }\n\n const definition = registry.get(selectedNode.type);\n const nodeIssues = (Array.isArray(issues) ? issues : []).filter((issue) => issue.nodeId === selectedNode.nodeId);\n const ConfigPanel = definition?.ConfigPanel;\n const canDuplicate = definition?.category !== 'trigger';\n const canRemove = isFlowNodeRemovable(selectedNode, registry);\n\n return (\n <aside className={shellClass} aria-label={t('flow.inspector.title')}>\n <div className=\"flex items-center gap-x-2\">\n <span className=\"flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted text-foreground-muted\">\n <MaterialSymbol\n icon={definition?.resolveIcon?.(selectedNode.config) ?? definition?.icon ?? 'help'}\n size={18}\n aria-hidden\n />\n </span>\n <div className=\"flex min-w-0 flex-col\">\n {definition && (\n <span className=\"text-xxs font-semibold uppercase tracking-wide text-foreground-subtle\">\n {labels.categories[definition.category]}\n </span>\n )}\n <span className=\"truncate text-sm font-semibold text-foreground\">\n {definition?.resolveLabel?.(selectedNode.config) ?? definition?.label ?? selectedNode.type}\n </span>\n </div>\n <ControlledTooltip content={t('flow.inspector.close')} placement=\"left\">\n <ControlledButton\n defaultHtmlButton\n onClick={() => store.getState().setSelection({ nodeIds: [], edgeIds: [] })}\n className=\"interactive ml-auto flex size-8 shrink-0 items-center justify-center rounded-lg text-foreground-muted hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n >\n <MaterialSymbol icon=\"close\" size={18} aria-hidden />\n </ControlledButton>\n </ControlledTooltip>\n </div>\n\n <ControlledInput\n label={t('flow.inspector.label')}\n value={selectedNode.label ?? ''}\n disabled={readOnly}\n onChange={(event) => store.getState().updateNodeLabel(selectedNode.nodeId, event.target.value)}\n />\n\n <div className=\"flex min-h-0 flex-1 flex-col gap-y-3 overflow-y-auto\">\n {ConfigPanel ? (\n <ConfigPanel\n config={selectedNode.config}\n readOnly={readOnly}\n onChange={(next) => store.getState().updateNodeConfig(selectedNode.nodeId, next)}\n />\n ) : (\n <NoDataFound compact variant=\"error\" message={t('flow.inspector.unknownBlock')} />\n )}\n\n {nodeIssues.length > 0 && (\n <ul className=\"flex flex-col gap-y-1\">\n {nodeIssues.map((issue) => (\n <li key={`${issue.code}|${issue.edgeId ?? ''}`} className=\"flex items-start gap-x-2\">\n <MaterialSymbol\n icon={issue.severity === 'error' ? 'error' : 'warning'}\n size={16}\n className={issue.severity === 'error' ? 'text-danger-emphasis' : 'text-warning-emphasis'}\n aria-hidden\n />\n <span className=\"text-xs text-foreground-muted\">{labels.issueMessage(issue)}</span>\n </li>\n ))}\n </ul>\n )}\n </div>\n\n {!readOnly && (canDuplicate || canRemove) && (\n <div className=\"flex gap-x-2\">\n {canDuplicate && (\n <ControlledButton\n size=\"sm\"\n variant=\"outlined\"\n tone=\"neutral\"\n onClick={() => store.getState().duplicateSelected()}\n >\n <MaterialSymbol icon=\"content_copy\" size={16} aria-hidden />\n {t('flow.inspector.duplicate')}\n </ControlledButton>\n )}\n {canRemove && (\n <ControlledButton\n size=\"sm\"\n variant=\"outlined\"\n tone=\"danger\"\n onClick={() => store.getState().removeSelected()}\n >\n <MaterialSymbol icon=\"delete\" size={16} aria-hidden />\n {t('flow.inspector.delete')}\n </ControlledButton>\n )}\n </div>\n )}\n </aside>\n );\n};\n\nexport default FlowInspector;\n"],"names":[],"mappings":";;;;;;;;;;;AAuBA,MAAM,gBAA+C,CAAC;AAAA,EACpD,SAAS,CAAA;AAAA,EACT,WAAW;AAAA,EACX,gBAAgB;AAAA,EAChB;AACF,MAAM;AACJ,QAAM,EAAE,EAAA,IAAM,eAAe,IAAI;AACjC,QAAM,SAAS,cAAA;AACf,QAAM,WAAW,qBAAA;AACjB,QAAM,QAAQ,mBAAA;AACd,QAAM,kBAAkB,cAAc,CAAC,UAAU,MAAM,eAAe;AACtE,QAAM,eAAe;AAAA,IAAc,CAAC,UAClC,MAAM,gBAAgB,WAAW,IAC7B,MAAM,MAAM,MAAM,KAAK,CAAC,SAAS,KAAK,WAAW,MAAM,gBAAgB,CAAC,CAAC,IACzE;AAAA,EAAA;AAGN,QAAM,aAAa;AAAA,IACjB;AAAA,IACA;AAAA,EAAA;AAGF,MAAI,CAAC,gBAAgB,gBAAgB,WAAW,GAAG;AACjD,QAAI,cAAe,QAAO;AAC1B,+BACG,SAAA,EAAM,WAAW,YAAY,cAAY,EAAE,sBAAsB,GAChE,UAAA,oBAAC,aAAA,EAAY,MAAK,MAAK,SAAQ,WAAU,SAAS,EAAE,sBAAsB,GAAG,GAC/E;AAAA,EAEJ;AAEA,QAAM,aAAa,SAAS,IAAI,aAAa,IAAI;AACjD,QAAM,cAA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UAAA;AAAA,QAAA;AAAA,MAAA;AAAA,MAGhC,aACC;AAAA,QAAC;AAAA,QAAA;AAAA,UACC,MAAK;AAAA,UACL,SAAQ;AAAA,UACR,MAAK;AAAA,UACL,SAAS,MAAM,MAAM,SAAA,EAAW,eAAA;AAAA,UAEhC,UAAA;AAAA,YAAA,oBAAC,kBAAe,MAAK,UAAS,MAAM,IAAI,eAAW,MAAC;AAAA,YACnD,EAAE,uBAAuB;AAAA,UAAA;AAAA,QAAA;AAAA,MAAA;AAAA,IAC5B,EAAA,CAEJ;AAAA,EAAA,GAEJ;AAEJ;"}
|
|
1
|
+
{"version":3,"file":"FlowInspector.js","sources":["../../../../src/components/UI/Flow/FlowInspector.tsx"],"sourcesContent":["import { useTranslation } from 'react-i18next';\nimport { twMerge } from 'tailwind-merge';\n\nimport ControlledButton from '@/components/Form/ControlledButton';\nimport ControlledInput from '@/components/Form/ControlledInput';\nimport ControlledTooltip from '@/components/UI/ControlledTooltip';\nimport { MaterialSymbol } from '@/components/UI/MaterialSymbol';\nimport NoDataFound from '@/components/UI/NoDataFound';\n\nimport { useFlowBlockRegistry, useFlowEditor, useFlowEditorStore } from './FlowEditorProvider';\nimport { isFlowNodeRemovable } from './flowGraph';\nimport type { IFlowIssue } from './flowTypes';\nimport { useFlowLabels } from './useFlowLabels';\n\ninterface IFlowInspectorProps {\n issues?: Array<IFlowIssue>;\n readOnly?: boolean;\n /** Renders nothing while no block is selected, instead of the empty state. */\n hideWhenEmpty?: boolean;\n className?: string;\n}\n\n/** The side panel of the selected block: its name, its own settings panel and its issues. */\nconst FlowInspector: React.FC<IFlowInspectorProps> = ({\n issues = [],\n readOnly = false,\n hideWhenEmpty = false,\n className,\n}) => {\n const { t } = useTranslation('ui');\n const labels = useFlowLabels();\n const registry = useFlowBlockRegistry();\n const store = useFlowEditorStore();\n const selectedNodeIds = useFlowEditor((state) => state.selectedNodeIds);\n const selectedNode = useFlowEditor((state) =>\n state.selectedNodeIds.length === 1\n ? state.graph.nodes.find((node) => node.nodeId === state.selectedNodeIds[0])\n : undefined,\n );\n\n const shellClass = twMerge(\n 'flex h-full min-h-0 flex-col gap-y-3 rounded-xl border border-border bg-surface p-4',\n className,\n );\n\n if (!selectedNode || selectedNodeIds.length !== 1) {\n if (hideWhenEmpty) return null;\n return (\n <aside className={shellClass} aria-label={t('flow.inspector.title')}>\n <NoDataFound size=\"sm\" variant=\"waiting\" message={t('flow.inspector.empty')} />\n </aside>\n );\n }\n\n const definition = registry.get(selectedNode.type);\n const nodeIssues = (Array.isArray(issues) ? issues : []).filter((issue) => issue.nodeId === selectedNode.nodeId);\n const ConfigPanel = definition?.ConfigPanel;\n const canDuplicate = definition?.category !== 'trigger';\n const canRemove = isFlowNodeRemovable(selectedNode, registry);\n\n return (\n <aside className={shellClass} aria-label={t('flow.inspector.title')}>\n <div className=\"flex items-center gap-x-2\">\n <span className=\"flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted text-foreground-muted\">\n <MaterialSymbol\n icon={definition?.resolveIcon?.(selectedNode.config) ?? definition?.icon ?? 'help'}\n size={18}\n aria-hidden\n />\n </span>\n <div className=\"flex min-w-0 flex-col\">\n {definition && (\n <span className=\"text-xxs font-semibold uppercase tracking-wide text-foreground-subtle\">\n {labels.categories[definition.category]}\n </span>\n )}\n <span className=\"truncate text-sm font-semibold text-foreground\">\n {definition?.resolveLabel?.(selectedNode.config) ?? definition?.label ?? selectedNode.type}\n </span>\n </div>\n <ControlledTooltip content={t('flow.inspector.close')} placement=\"left\">\n <ControlledButton\n defaultHtmlButton\n onClick={() => store.getState().setSelection({ nodeIds: [], edgeIds: [] })}\n className=\"interactive ml-auto flex size-8 shrink-0 items-center justify-center rounded-lg text-foreground-muted hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n >\n <MaterialSymbol icon=\"close\" size={18} aria-hidden />\n </ControlledButton>\n </ControlledTooltip>\n </div>\n\n <ControlledInput\n label={t('flow.inspector.label')}\n value={selectedNode.label ?? ''}\n disabled={readOnly}\n onChange={(event) => store.getState().updateNodeLabel(selectedNode.nodeId, event.target.value)}\n />\n\n <div className=\"flex min-h-0 flex-1 flex-col gap-y-3 overflow-y-auto\">\n {ConfigPanel ? (\n <ConfigPanel\n config={selectedNode.config}\n readOnly={readOnly}\n onChange={(next) => store.getState().updateNodeConfig(selectedNode.nodeId, next)}\n />\n ) : (\n <NoDataFound compact variant=\"error\" message={t('flow.inspector.unknownBlock')} />\n )}\n\n {nodeIssues.length > 0 && (\n <ul className=\"flex flex-col gap-y-1\">\n {nodeIssues.map((issue) => (\n <li key={`${issue.code}|${issue.edgeId ?? ''}`} className=\"flex items-start gap-x-2\">\n <MaterialSymbol\n icon={issue.severity === 'error' ? 'error' : 'warning'}\n size={16}\n className={issue.severity === 'error' ? 'text-danger-emphasis' : 'text-warning-emphasis'}\n aria-hidden\n />\n <span className=\"text-xs text-foreground-muted\">{labels.issueMessage(issue)}</span>\n </li>\n ))}\n </ul>\n )}\n </div>\n\n {!readOnly && (canDuplicate || canRemove) && (\n <div className=\"flex gap-x-2\">\n {canDuplicate && (\n <ControlledButton\n size=\"sm\"\n variant=\"outlined\"\n tone=\"neutral\"\n className=\"normal-case\"\n onClick={() => store.getState().duplicateSelected()}\n >\n <MaterialSymbol icon=\"content_copy\" size={16} aria-hidden />\n {t('flow.inspector.duplicate')}\n </ControlledButton>\n )}\n {canRemove && (\n <ControlledButton\n size=\"sm\"\n variant=\"outlined\"\n tone=\"danger\"\n className=\"normal-case\"\n onClick={() => store.getState().removeSelected()}\n >\n <MaterialSymbol icon=\"delete\" size={16} aria-hidden />\n {t('flow.inspector.delete')}\n </ControlledButton>\n )}\n </div>\n )}\n </aside>\n );\n};\n\nexport default FlowInspector;\n"],"names":[],"mappings":";;;;;;;;;;;AAuBA,MAAM,gBAA+C,CAAC;AAAA,EACpD,SAAS,CAAA;AAAA,EACT,WAAW;AAAA,EACX,gBAAgB;AAAA,EAChB;AACF,MAAM;AACJ,QAAM,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|
|
8
|
+
y: number;
|
|
9
|
+
width: number;
|
|
10
|
+
height: number;
|
|
11
|
+
}
|
|
12
|
+
export interface IFlowSize {
|
|
13
|
+
width: number;
|
|
14
|
+
height: number;
|
|
15
|
+
}
|
|
16
|
+
/** Breathing room between a revealed block and the edge of the canvas, in screen pixels. */
|
|
17
|
+
export declare const FLOW_REVEAL_PADDING = 32;
|
|
18
|
+
/**
|
|
19
|
+
* The smallest pan that brings `rect` (flow coordinates) fully inside a canvas of `canvasSize`
|
|
20
|
+
* (screen pixels), keeping the zoom. Returns null when the rect is already fully visible, so a
|
|
21
|
+
* block on screen never moves the view. A rect larger than the canvas is aligned to its top-left.
|
|
22
|
+
*/
|
|
23
|
+
export declare const viewportToReveal: (viewport: IFlowViewport, rect: IFlowRect, canvasSize: IFlowSize, padding?: number) => IFlowViewport | null;
|
|
24
|
+
/** The box around several rects; null for none. */
|
|
25
|
+
export declare const boundsOfRects: (rects: Array<IFlowRect>) => IFlowRect | null;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
const FLOW_REVEAL_PADDING = 32;
|
|
2
|
+
const shiftOnAxis = (start, end, min, max) => {
|
|
3
|
+
if (start < min) return min - start;
|
|
4
|
+
if (end > max) return Math.max(max - end, min - start);
|
|
5
|
+
return 0;
|
|
6
|
+
};
|
|
7
|
+
const viewportToReveal = (viewport, rect, canvasSize, padding = FLOW_REVEAL_PADDING) => {
|
|
8
|
+
if (canvasSize.width <= 0 || canvasSize.height <= 0) return null;
|
|
9
|
+
const left = viewport.x + rect.x * viewport.zoom;
|
|
10
|
+
const top = viewport.y + rect.y * viewport.zoom;
|
|
11
|
+
const right = left + rect.width * viewport.zoom;
|
|
12
|
+
const bottom = top + rect.height * viewport.zoom;
|
|
13
|
+
const deltaX = shiftOnAxis(left, right, padding, canvasSize.width - padding);
|
|
14
|
+
const deltaY = shiftOnAxis(top, bottom, padding, canvasSize.height - padding);
|
|
15
|
+
if (deltaX === 0 && deltaY === 0) return null;
|
|
16
|
+
return { x: viewport.x + deltaX, y: viewport.y + deltaY, zoom: viewport.zoom };
|
|
17
|
+
};
|
|
18
|
+
const boundsOfRects = (rects) => {
|
|
19
|
+
if (rects.length === 0) return null;
|
|
20
|
+
const minX = Math.min(...rects.map((rect) => rect.x));
|
|
21
|
+
const minY = Math.min(...rects.map((rect) => rect.y));
|
|
22
|
+
const maxX = Math.max(...rects.map((rect) => rect.x + rect.width));
|
|
23
|
+
const maxY = Math.max(...rects.map((rect) => rect.y + rect.height));
|
|
24
|
+
return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
|
|
25
|
+
};
|
|
26
|
+
export {
|
|
27
|
+
FLOW_REVEAL_PADDING,
|
|
28
|
+
boundsOfRects,
|
|
29
|
+
viewportToReveal
|
|
30
|
+
};
|
|
31
|
+
//# sourceMappingURL=flowViewport.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"flowViewport.js","sources":["../../../../src/components/UI/Flow/flowViewport.ts"],"sourcesContent":["export interface IFlowViewport {\n x: number;\n y: number;\n zoom: number;\n}\n\nexport interface IFlowRect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\nexport interface IFlowSize {\n width: number;\n height: number;\n}\n\n/** Breathing room between a revealed block and the edge of the canvas, in screen pixels. */\nexport const FLOW_REVEAL_PADDING = 32;\n\nconst shiftOnAxis = (start: number, end: number, min: number, max: number): number => {\n if (start < min) return min - start;\n if (end > max) return Math.max(max - end, min - start);\n return 0;\n};\n\n/**\n * The smallest pan that brings `rect` (flow coordinates) fully inside a canvas of `canvasSize`\n * (screen pixels), keeping the zoom. Returns null when the rect is already fully visible, so a\n * block on screen never moves the view. A rect larger than the canvas is aligned to its top-left.\n */\nexport const viewportToReveal = (\n viewport: IFlowViewport,\n rect: IFlowRect,\n canvasSize: IFlowSize,\n padding: number = FLOW_REVEAL_PADDING,\n): IFlowViewport | null => {\n if (canvasSize.width <= 0 || canvasSize.height <= 0) return null;\n const left = viewport.x + rect.x * viewport.zoom;\n const top = viewport.y + rect.y * viewport.zoom;\n const right = left + rect.width * viewport.zoom;\n const bottom = top + rect.height * viewport.zoom;\n\n const deltaX = shiftOnAxis(left, right, padding, canvasSize.width - padding);\n const deltaY = shiftOnAxis(top, bottom, padding, canvasSize.height - padding);\n if (deltaX === 0 && deltaY === 0) return null;\n return { x: viewport.x + deltaX, y: viewport.y + deltaY, zoom: viewport.zoom };\n};\n\n/** The box around several rects; null for none. */\nexport const boundsOfRects = (rects: Array<IFlowRect>): IFlowRect | null => {\n if (rects.length === 0) return null;\n const minX = Math.min(...rects.map((rect) => rect.x));\n const minY = Math.min(...rects.map((rect) => rect.y));\n const maxX = Math.max(...rects.map((rect) => rect.x + rect.width));\n const maxY = Math.max(...rects.map((rect) => rect.y + rect.height));\n return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };\n};\n"],"names":[],"mappings":"AAmBO,MAAM,sBAAsB;AAEnC,MAAM,cAAc,CAAC,OAAe,KAAa,KAAa,QAAwB;AACpF,MAAI,QAAQ,IAAK,QAAO,MAAM;AAC9B,MAAI,MAAM,IAAK,QAAO,KAAK,IAAI,MAAM,KAAK,MAAM,KAAK;AACrD,SAAO;AACT;AAOO,MAAM,mBAAmB,CAC9B,UACA,MACA,YACA,UAAkB,wBACO;AACzB,MAAI,WAAW,SAAS,KAAK,WAAW,UAAU,EAAG,QAAO;AAC5D,QAAM,OAAO,SAAS,IAAI,KAAK,IAAI,SAAS;AAC5C,QAAM,MAAM,SAAS,IAAI,KAAK,IAAI,SAAS;AAC3C,QAAM,QAAQ,OAAO,KAAK,QAAQ,SAAS;AAC3C,QAAM,SAAS,MAAM,KAAK,SAAS,SAAS;AAE5C,QAAM,SAAS,YAAY,MAAM,OAAO,SAAS,WAAW,QAAQ,OAAO;AAC3E,QAAM,SAAS,YAAY,KAAK,QAAQ,SAAS,WAAW,SAAS,OAAO;AAC5E,MAAI,WAAW,KAAK,WAAW,EAAG,QAAO;AACzC,SAAO,EAAE,GAAG,SAAS,IAAI,QAAQ,GAAG,SAAS,IAAI,QAAQ,MAAM,SAAS,KAAA;AAC1E;AAGO,MAAM,gBAAgB,CAAC,UAA8C;AAC1E,MAAI,MAAM,WAAW,EAAG,QAAO;AAC/B,QAAM,OAAO,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC,SAAS,KAAK,CAAC,CAAC;AACpD,QAAM,OAAO,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC,SAAS,KAAK,CAAC,CAAC;AACpD,QAAM,OAAO,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC,SAAS,KAAK,IAAI,KAAK,KAAK,CAAC;AACjE,QAAM,OAAO,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC,SAAS,KAAK,IAAI,KAAK,MAAM,CAAC;AAClE,SAAO,EAAE,GAAG,MAAM,GAAG,MAAM,OAAO,OAAO,MAAM,QAAQ,OAAO,KAAA;AAChE;"}
|
|
@@ -226,9 +226,9 @@ declare const _default: {
|
|
|
226
226
|
"error": "Error"
|
|
227
227
|
},
|
|
228
228
|
"categories": {
|
|
229
|
-
"trigger": "
|
|
230
|
-
"condition": "
|
|
231
|
-
"action": "
|
|
229
|
+
"trigger": "Trigger",
|
|
230
|
+
"condition": "Condition",
|
|
231
|
+
"action": "Action"
|
|
232
232
|
},
|
|
233
233
|
"inspector": {
|
|
234
234
|
"title": "Block settings",
|
|
@@ -12,7 +12,7 @@ const detailsTable = { "size": "Size", "quantity": "Qty" };
|
|
|
12
12
|
const errorPage = { "message": "This screen could not load", "headline": "Something unexpected happened while building the page. Refreshing usually fixes it. If it happens again, contact support and tell them what you were doing.", "backToStart": "Back to start" };
|
|
13
13
|
const filters = { "activeFilters": "Applied filters", "appliedCount_one": "{{count}} filter applied", "appliedCount_other": "{{count}} filters applied", "clearAll": "Clear all", "noFields": "No filters available for this list.", "noOptions": "No options found.", "optionsError": "Could not load the options for {{field}}.", "rangeMax": "Maximum", "rangeMin": "Minimum", "rangeSeparator": "to", "searchOptions": "Search options" };
|
|
14
14
|
const filtersDrawer = { "selectedFilters": "Selected filters:", "pendingChanges": "Pending changes", "discardChangesTitle": "Discard changes?", "discardChangesMessage": "You have unapplied filter changes. Discard them?", "keepEditing": "Keep editing", "discard": "Discard" };
|
|
15
|
-
const flow = { "canvas": "Flow editor", "resizePanel": "Drag to adjust the width. Double click resets", "ports": { "next": "Next", "true": "Yes", "false": "No", "error": "Error" }, "categories": { "trigger": "
|
|
15
|
+
const flow = { "canvas": "Flow editor", "resizePanel": "Drag to adjust the width. Double click resets", "ports": { "next": "Next", "true": "Yes", "false": "No", "error": "Error" }, "categories": { "trigger": "Trigger", "condition": "Condition", "action": "Action" }, "inspector": { "title": "Block settings", "empty": "Select a block to configure it", "label": "Block name", "delete": "Delete block", "duplicate": "Duplicate block", "unknownBlock": "This block type no longer exists", "close": "Close" }, "issues": { "title": "Issues", "none": "No issues", "missingTrigger": "The flow needs a trigger", "multipleTriggers": "A flow can have only one trigger", "unknownBlock": "Block of a type that no longer exists", "unreachableNode": "Loose block: no path from the trigger reaches it", "multipleInputs": "Block with more than one input", "portFanOut": "An output can connect to one block only", "cycle": "The blocks form a cycle", "missingTrueBranch": "The condition has no yes path" }, "run": { "passed": "Passed", "failed": "Did not pass", "skipped": "Skipped", "wouldRun": "Would run", "error": "Error", "blocked": "Blocked" }, "controls": { "zoomIn": "Zoom in", "zoomOut": "Zoom out", "fitView": "Fit view", "undo": "Undo", "redo": "Redo", "layout": "Arrange blocks" }, "edge": { "insertBlock": "Insert a block here" }, "node": { "disabled": "Disabled", "addBlock": "Add the next block", "issueCount_one": "{{count}} issue", "issueCount_other": "{{count}} issues" }, "laneMap": { "label": "Flow map" } };
|
|
16
16
|
const followUp = { "messages": "Messages", "chat": { "loadingMessages": "Loading messages", "placeholder": "Write a message...", "invalidMessage": "Please enter a valid message", "noMessagesYet": "No messages yet", "startConversation": "Start a conversation by adding the first message", "loadError": "Messages could not be loaded", "sendFailed": "The message could not be sent. Try again.", "sendFailedInline": "Failed to send", "resend": "Resend", "discard": "Discard", "today": "Today", "yesterday": "Yesterday", "typingOne": "{{name}} is typing...", "typingMany": "{{count}} people are typing...", "someone": "Someone", "you": "You", "newMessages": "New messages", "backToLatest": "Back to latest", "deletedMessage": "Message deleted", "edited": "edited", "readBy": "Read by {{names}}", "copied": "Message copied", "replyingTo": "Replying to {{name}}", "attachmentFallback": "Attachment", "editTitle": "Edit message", "deleteTitle": "Delete message?", "deleteSubtitle": "The message will be shown as deleted for every participant", "sendHint": "Enter sends, Shift+Enter adds a line break", "formatting": "Formatting" }, "actions": { "reply": "Reply", "copy": "Copy text", "edit": "Edit", "delete": "Delete" }, "attachments": { "attach": "Attach", "pickFile": "File", "pickImage": "Image", "takePhoto": "Take photo", "dropHere": "Drop files to attach", "tooMany": "Limit of {{max}} attachments per message", "tooLarge": "The file {{name}} exceeds the 50 MB limit", "uploadFailed": "Upload failed", "uploading": "Uploading attachments...", "imagePreview": "Preview image", "showTranscript": "Show transcript", "hideTranscript": "Hide transcript" }, "voice": { "record": "Record audio", "recording": "Recording", "stop": "Finish recording", "cancel": "Cancel recording", "rerecord": "Record again", "attach": "Add to message", "discard": "Discard", "transcriptLabel": "Transcript", "transcriptPlaceholder": "The speech transcript appears here and can be edited" }, "camera": { "title": "Take photo", "unavailable": "Camera unavailable", "unavailableHint": "Check the browser camera permission", "switch": "Switch camera", "capture": "Capture photo" }, "search": { "open": "Search in conversation", "placeholder": "Search messages", "noResults": "No messages found", "error": "Messages could not be searched" } };
|
|
17
17
|
const generatedByAI = { "tooltip": "Generated by AI" };
|
|
18
18
|
const imageAiAdjust = { "action": "Adjust with AI", "title": "Adjust image with AI", "subtitle": "Describe the adjustment. The AI changes only what you ask and preserves the rest of the image.", "original": "Original", "result": "Result", "resultHint": "Describe the adjustment and click Generate to see the result here.", "promptLabel": "Desired adjustment", "promptPlaceholder": "E.g. remove the background and make it white, smooth the sleeve creases, brighten the lighting", "generate": "Generate", "generating": "Generating the image...", "tryAgain": "Generate another", "useResult": "Use this image", "errorGenerate": "Could not adjust the image with AI", "errorSave": "Could not save the adjusted image", "errorRefused": "The AI could not make this adjustment: {{reason}}", "mask": { "start": "Mark the area", "stop": "Use the whole image", "hint": "Paint the area the AI may change. The rest of the image is kept." }, "verification": { "changedMoreThanRequested": "The AI changed more than requested. Check the areas outside the adjustment before using it.", "colorMismatch": "The garment color ({{dominant}}) differs from the requested color ({{target}})." } };
|
|
@@ -226,9 +226,9 @@ declare const _default: {
|
|
|
226
226
|
"error": "Erro"
|
|
227
227
|
},
|
|
228
228
|
"categories": {
|
|
229
|
-
"trigger": "
|
|
230
|
-
"condition": "
|
|
231
|
-
"action": "
|
|
229
|
+
"trigger": "Gatilho",
|
|
230
|
+
"condition": "Condição",
|
|
231
|
+
"action": "Ação"
|
|
232
232
|
},
|
|
233
233
|
"inspector": {
|
|
234
234
|
"title": "Configuração do bloco",
|
|
@@ -12,7 +12,7 @@ const detailsTable = { "size": "Tam", "quantity": "Qtd" };
|
|
|
12
12
|
const errorPage = { "message": "Esta tela não conseguiu carregar", "headline": "Algo inesperado aconteceu ao montar a página. Atualizar costuma resolver. Se acontecer de novo, fale com o suporte contando o que você estava fazendo.", "backToStart": "Voltar para o início" };
|
|
13
13
|
const filters = { "activeFilters": "Filtros aplicados", "appliedCount_one": "{{count}} filtro aplicado", "appliedCount_other": "{{count}} filtros aplicados", "clearAll": "Limpar tudo", "noFields": "Nenhum filtro disponível para esta listagem.", "noOptions": "Nenhuma opção encontrada.", "optionsError": "Não foi possível carregar as opções de {{field}}.", "rangeMax": "Máximo", "rangeMin": "Mínimo", "rangeSeparator": "até", "searchOptions": "Buscar opções" };
|
|
14
14
|
const filtersDrawer = { "selectedFilters": "Filtros Selecionados:", "pendingChanges": "Alterações pendentes", "discardChangesTitle": "Descartar alterações?", "discardChangesMessage": "Você tem alterações de filtro não aplicadas. Deseja descartá-las?", "keepEditing": "Continuar editando", "discard": "Descartar" };
|
|
15
|
-
const flow = { "canvas": "Editor de fluxo", "resizePanel": "Arraste para ajustar a largura. Clique duplo restaura", "ports": { "next": "Próximo", "true": "Sim", "false": "Não", "error": "Erro" }, "categories": { "trigger": "
|
|
15
|
+
const flow = { "canvas": "Editor de fluxo", "resizePanel": "Arraste para ajustar a largura. Clique duplo restaura", "ports": { "next": "Próximo", "true": "Sim", "false": "Não", "error": "Erro" }, "categories": { "trigger": "Gatilho", "condition": "Condição", "action": "Ação" }, "inspector": { "title": "Configuração do bloco", "empty": "Selecione um bloco para configurar", "label": "Nome do bloco", "delete": "Excluir bloco", "duplicate": "Duplicar bloco", "unknownBlock": "Este tipo de bloco não existe mais", "close": "Fechar" }, "issues": { "title": "Pendências", "none": "Nenhuma pendência", "missingTrigger": "O fluxo precisa de um gatilho", "multipleTriggers": "O fluxo só pode ter um gatilho", "unknownBlock": "Bloco de um tipo que não existe mais", "unreachableNode": "Bloco solto: nenhum caminho do gatilho chega até ele", "multipleInputs": "Bloco com mais de uma entrada", "portFanOut": "Uma saída só pode ligar a um bloco", "cycle": "Os blocos formam um ciclo", "missingTrueBranch": "A condição não tem o caminho do sim" }, "run": { "passed": "Passou", "failed": "Não passou", "skipped": "Pulado", "wouldRun": "Executaria", "error": "Erro", "blocked": "Bloqueado" }, "controls": { "zoomIn": "Aproximar", "zoomOut": "Afastar", "fitView": "Enquadrar", "undo": "Desfazer", "redo": "Refazer", "layout": "Organizar blocos" }, "edge": { "insertBlock": "Inserir um bloco aqui" }, "node": { "disabled": "Desativado", "addBlock": "Adicionar o próximo bloco", "issueCount_one": "{{count}} pendência", "issueCount_other": "{{count}} pendências" }, "laneMap": { "label": "Mapa do fluxo" } };
|
|
16
16
|
const followUp = { "messages": "Mensagens", "chat": { "loadingMessages": "Carregando mensagens", "placeholder": "Escrever mensagem...", "invalidMessage": "Por favor, insira uma mensagem válida", "noMessagesYet": "Nenhuma mensagem por enquanto", "startConversation": "Inicie uma conversa adicionando a primeira mensagem", "loadError": "Não foi possível carregar as mensagens", "sendFailed": "Não foi possível enviar a mensagem. Tente novamente.", "sendFailedInline": "Falha no envio", "resend": "Reenviar", "discard": "Descartar", "today": "Hoje", "yesterday": "Ontem", "typingOne": "{{name}} está digitando...", "typingMany": "{{count}} pessoas estão digitando...", "someone": "Alguém", "you": "Você", "newMessages": "Novas mensagens", "backToLatest": "Voltar para as recentes", "deletedMessage": "Mensagem apagada", "edited": "editada", "readBy": "Lida por {{names}}", "copied": "Mensagem copiada", "replyingTo": "Respondendo a {{name}}", "attachmentFallback": "Anexo", "editTitle": "Editar mensagem", "deleteTitle": "Apagar mensagem?", "deleteSubtitle": "A mensagem será marcada como apagada para todos os participantes", "sendHint": "Enter envia, Shift+Enter quebra a linha", "formatting": "Formatação" }, "actions": { "reply": "Responder", "copy": "Copiar texto", "edit": "Editar", "delete": "Apagar" }, "attachments": { "attach": "Anexar", "pickFile": "Arquivo", "pickImage": "Imagem", "takePhoto": "Tirar foto", "dropHere": "Solte os arquivos para anexar", "tooMany": "Limite de {{max}} anexos por mensagem", "tooLarge": "O arquivo {{name}} passa do limite de 50 MB", "uploadFailed": "Falha no upload", "uploading": "Enviando anexos...", "imagePreview": "Visualizar imagem", "showTranscript": "Ver transcrição", "hideTranscript": "Ocultar transcrição" }, "voice": { "record": "Gravar áudio", "recording": "Gravando", "stop": "Concluir gravação", "cancel": "Cancelar gravação", "rerecord": "Regravar", "attach": "Adicionar ao envio", "discard": "Descartar", "transcriptLabel": "Transcrição", "transcriptPlaceholder": "A transcrição da fala aparece aqui e pode ser editada" }, "camera": { "title": "Tirar foto", "unavailable": "Câmera indisponível", "unavailableHint": "Verifique a permissão de câmera do navegador", "switch": "Alternar câmera", "capture": "Capturar foto" }, "search": { "open": "Buscar na conversa", "placeholder": "Buscar mensagens", "noResults": "Nenhuma mensagem encontrada", "error": "Não foi possível buscar as mensagens" } };
|
|
17
17
|
const generatedByAI = { "tooltip": "Gerado por IA" };
|
|
18
18
|
const imageAiAdjust = { "action": "Ajustar com IA", "title": "Ajustar imagem com IA", "subtitle": "Descreva o ajuste. A IA altera só o que você pedir e preserva o resto da imagem.", "original": "Original", "result": "Resultado", "resultHint": "Descreva o ajuste e clique em Gerar para ver o resultado aqui.", "promptLabel": "Ajuste desejado", "promptPlaceholder": "Ex.: remover o fundo e deixar branco, tirar os vincos da manga, clarear a iluminação", "generate": "Gerar", "generating": "Gerando a imagem...", "tryAgain": "Gerar outra", "useResult": "Usar esta imagem", "errorGenerate": "Não foi possível ajustar a imagem com IA", "errorSave": "Não foi possível salvar a imagem ajustada", "errorRefused": "A IA não conseguiu fazer este ajuste: {{reason}}", "mask": { "start": "Marcar a área", "stop": "Usar a imagem toda", "hint": "Pinte a área que a IA pode alterar. O resto da imagem é mantido." }, "verification": { "changedMoreThanRequested": "A IA mudou mais do que o pedido. Confira as áreas fora do ajuste antes de usar.", "colorMismatch": "A cor da peça ({{dominant}}) ficou diferente da cor pedida ({{target}})." } };
|