tempest-react-sdk 0.35.0 → 0.37.0
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/README.md +72 -70
- package/dist/audio/audio-output.cjs +2 -0
- package/dist/audio/audio-output.cjs.map +1 -0
- package/dist/audio/audio-output.js +17 -0
- package/dist/audio/audio-output.js.map +1 -0
- package/dist/audio/audio-player.cjs +1 -1
- package/dist/audio/audio-player.cjs.map +1 -1
- package/dist/audio/audio-player.js +21 -20
- package/dist/audio/audio-player.js.map +1 -1
- package/dist/audio/audio-recorder.cjs +2 -0
- package/dist/audio/audio-recorder.cjs.map +1 -0
- package/dist/audio/audio-recorder.js +30 -0
- package/dist/audio/audio-recorder.js.map +1 -0
- package/dist/audio/duration.cjs +2 -0
- package/dist/audio/duration.cjs.map +1 -0
- package/dist/audio/duration.js +10 -0
- package/dist/audio/duration.js.map +1 -0
- package/dist/audio/level-meter.cjs +2 -0
- package/dist/audio/level-meter.cjs.map +1 -0
- package/dist/audio/level-meter.js +34 -0
- package/dist/audio/level-meter.js.map +1 -0
- package/dist/audio/media-access.cjs +2 -0
- package/dist/audio/media-access.cjs.map +1 -0
- package/dist/audio/media-access.js +51 -0
- package/dist/audio/media-access.js.map +1 -0
- package/dist/audio/use-audio-recorder.cjs +2 -0
- package/dist/audio/use-audio-recorder.cjs.map +1 -0
- package/dist/audio/use-audio-recorder.js +94 -0
- package/dist/audio/use-audio-recorder.js.map +1 -0
- package/dist/audio/use-audio.cjs.map +1 -1
- package/dist/audio/use-audio.js.map +1 -1
- package/dist/audio/use-microphone.cjs +2 -0
- package/dist/audio/use-microphone.cjs.map +1 -0
- package/dist/audio/use-microphone.js +54 -0
- package/dist/audio/use-microphone.js.map +1 -0
- package/dist/audio/wav.cjs +2 -0
- package/dist/audio/wav.cjs.map +1 -0
- package/dist/audio/wav.js +49 -0
- package/dist/audio/wav.js.map +1 -0
- package/dist/auth/passkey.cjs +2 -0
- package/dist/auth/passkey.cjs.map +1 -0
- package/dist/auth/passkey.js +171 -0
- package/dist/auth/passkey.js.map +1 -0
- package/dist/auth/use-passkey.cjs +2 -0
- package/dist/auth/use-passkey.cjs.map +1 -0
- package/dist/auth/use-passkey.js +120 -0
- package/dist/auth/use-passkey.js.map +1 -0
- package/dist/br/PixQRCode.cjs +2 -0
- package/dist/br/PixQRCode.cjs.map +1 -0
- package/dist/br/PixQRCode.js +70 -0
- package/dist/br/PixQRCode.js.map +1 -0
- package/dist/br/PixQRCode.module.cjs +2 -0
- package/dist/br/PixQRCode.module.cjs.map +1 -0
- package/dist/br/PixQRCode.module.js +15 -0
- package/dist/br/PixQRCode.module.js.map +1 -0
- package/dist/br/boleto.cjs +2 -0
- package/dist/br/boleto.cjs.map +1 -0
- package/dist/br/boleto.js +225 -0
- package/dist/br/boleto.js.map +1 -0
- package/dist/br/holidays.cjs +2 -0
- package/dist/br/holidays.cjs.map +1 -0
- package/dist/br/holidays.js +148 -0
- package/dist/br/holidays.js.map +1 -0
- package/dist/br/nfe.cjs +2 -0
- package/dist/br/nfe.cjs.map +1 -0
- package/dist/br/nfe.js +104 -0
- package/dist/br/nfe.js.map +1 -0
- package/dist/br/pix.cjs +2 -0
- package/dist/br/pix.cjs.map +1 -0
- package/dist/br/pix.js +148 -0
- package/dist/br/pix.js.map +1 -0
- package/dist/br.cjs +1 -1
- package/dist/br.cjs.map +1 -1
- package/dist/br.d.ts +878 -0
- package/dist/br.js +7 -2
- package/dist/br.js.map +1 -1
- package/dist/capture/barcode.cjs +2 -0
- package/dist/capture/barcode.cjs.map +1 -0
- package/dist/capture/barcode.js +59 -0
- package/dist/capture/barcode.js.map +1 -0
- package/dist/capture/media-recorder.cjs +2 -0
- package/dist/capture/media-recorder.cjs.map +1 -0
- package/dist/capture/media-recorder.js +64 -0
- package/dist/capture/media-recorder.js.map +1 -0
- package/dist/capture/use-barcode-scanner.cjs +2 -0
- package/dist/capture/use-barcode-scanner.cjs.map +1 -0
- package/dist/capture/use-barcode-scanner.js +86 -0
- package/dist/capture/use-barcode-scanner.js.map +1 -0
- package/dist/capture/use-screen-capture.cjs +2 -0
- package/dist/capture/use-screen-capture.cjs.map +1 -0
- package/dist/capture/use-screen-capture.js +79 -0
- package/dist/capture/use-screen-capture.js.map +1 -0
- package/dist/capture/use-speech-recognition.cjs +2 -0
- package/dist/capture/use-speech-recognition.cjs.map +1 -0
- package/dist/capture/use-speech-recognition.js +118 -0
- package/dist/capture/use-speech-recognition.js.map +1 -0
- package/dist/capture/use-torch.cjs +2 -0
- package/dist/capture/use-torch.cjs.map +1 -0
- package/dist/capture/use-torch.js +33 -0
- package/dist/capture/use-torch.js.map +1 -0
- package/dist/capture/use-video-recorder.cjs +2 -0
- package/dist/capture/use-video-recorder.cjs.map +1 -0
- package/dist/capture/use-video-recorder.js +90 -0
- package/dist/capture/use-video-recorder.js.map +1 -0
- package/dist/capture/video-recorder.cjs +2 -0
- package/dist/capture/video-recorder.cjs.map +1 -0
- package/dist/capture/video-recorder.js +31 -0
- package/dist/capture/video-recorder.js.map +1 -0
- package/dist/components/AIChat/AIChat.cjs +1 -1
- package/dist/components/AIChat/AIChat.cjs.map +1 -1
- package/dist/components/AIChat/AIChat.js +93 -97
- package/dist/components/AIChat/AIChat.js.map +1 -1
- package/dist/components/AIChat/AIChatComposer.cjs +1 -1
- package/dist/components/AIChat/AIChatComposer.cjs.map +1 -1
- package/dist/components/AIChat/AIChatComposer.js +2 -1
- package/dist/components/AIChat/AIChatComposer.js.map +1 -1
- package/dist/components/AIChat/AIChatTurn.cjs +2 -2
- package/dist/components/AIChat/AIChatTurn.js +6 -6
- package/dist/components/AIChat/AIChatTurn.js.map +1 -1
- package/dist/components/Alert/Alert.module.cjs.map +1 -1
- package/dist/components/Alert/Alert.module.js.map +1 -1
- package/dist/components/AudioPlayer/AudioPlayer.cjs +2 -0
- package/dist/components/AudioPlayer/AudioPlayer.cjs.map +1 -0
- package/dist/components/AudioPlayer/AudioPlayer.js +123 -0
- package/dist/components/AudioPlayer/AudioPlayer.js.map +1 -0
- package/dist/components/AudioPlayer/AudioPlayer.module.cjs +2 -0
- package/dist/components/AudioPlayer/AudioPlayer.module.cjs.map +1 -0
- package/dist/components/AudioPlayer/AudioPlayer.module.js +12 -0
- package/dist/components/AudioPlayer/AudioPlayer.module.js.map +1 -0
- package/dist/components/AudioRecorder/AudioRecorder.cjs +2 -0
- package/dist/components/AudioRecorder/AudioRecorder.cjs.map +1 -0
- package/dist/components/AudioRecorder/AudioRecorder.js +179 -0
- package/dist/components/AudioRecorder/AudioRecorder.js.map +1 -0
- package/dist/components/AudioRecorder/AudioRecorder.module.cjs +2 -0
- package/dist/components/AudioRecorder/AudioRecorder.module.cjs.map +1 -0
- package/dist/components/AudioRecorder/AudioRecorder.module.js +19 -0
- package/dist/components/AudioRecorder/AudioRecorder.module.js.map +1 -0
- package/dist/components/Badge/Badge.module.cjs.map +1 -1
- package/dist/components/Badge/Badge.module.js.map +1 -1
- package/dist/components/BarcodeScanner/BarcodeScanner.cjs +2 -0
- package/dist/components/BarcodeScanner/BarcodeScanner.cjs.map +1 -0
- package/dist/components/BarcodeScanner/BarcodeScanner.js +123 -0
- package/dist/components/BarcodeScanner/BarcodeScanner.js.map +1 -0
- package/dist/components/BarcodeScanner/BarcodeScanner.module.cjs +2 -0
- package/dist/components/BarcodeScanner/BarcodeScanner.module.cjs.map +1 -0
- package/dist/components/BarcodeScanner/BarcodeScanner.module.js +22 -0
- package/dist/components/BarcodeScanner/BarcodeScanner.module.js.map +1 -0
- package/dist/components/BottomNavigation/BottomNavigation.module.cjs.map +1 -1
- package/dist/components/BottomNavigation/BottomNavigation.module.js.map +1 -1
- package/dist/components/Button/Button.module.cjs.map +1 -1
- package/dist/components/Button/Button.module.js.map +1 -1
- package/dist/components/Combobox/Combobox.module.cjs.map +1 -1
- package/dist/components/Combobox/Combobox.module.js.map +1 -1
- package/dist/components/DataTable/DataTable.cjs +1 -1
- package/dist/components/DataTable/DataTable.cjs.map +1 -1
- package/dist/components/DataTable/DataTable.js +203 -66
- package/dist/components/DataTable/DataTable.js.map +1 -1
- package/dist/components/DataTable/DataTable.module.cjs +1 -1
- package/dist/components/DataTable/DataTable.module.cjs.map +1 -1
- package/dist/components/DataTable/DataTable.module.js +9 -3
- package/dist/components/DataTable/DataTable.module.js.map +1 -1
- package/dist/components/DataTable/EditableCell.cjs +2 -0
- package/dist/components/DataTable/EditableCell.cjs.map +1 -0
- package/dist/components/DataTable/EditableCell.js +77 -0
- package/dist/components/DataTable/EditableCell.js.map +1 -0
- package/dist/components/DataTable/edit-labels.cjs +2 -0
- package/dist/components/DataTable/edit-labels.cjs.map +1 -0
- package/dist/components/DataTable/edit-labels.js +11 -0
- package/dist/components/DataTable/edit-labels.js.map +1 -0
- package/dist/components/DateRangePicker/DateRangePicker.module.cjs.map +1 -1
- package/dist/components/DateRangePicker/DateRangePicker.module.js.map +1 -1
- package/dist/components/MultiSelect/MultiSelect.module.cjs.map +1 -1
- package/dist/components/MultiSelect/MultiSelect.module.js.map +1 -1
- package/dist/components/NavigationRail/NavigationRail.module.cjs.map +1 -1
- package/dist/components/NavigationRail/NavigationRail.module.js.map +1 -1
- package/dist/components/SyncStatusBadge/SyncStatusBadge.cjs +1 -1
- package/dist/components/SyncStatusBadge/SyncStatusBadge.cjs.map +1 -1
- package/dist/components/SyncStatusBadge/SyncStatusBadge.js +33 -32
- package/dist/components/SyncStatusBadge/SyncStatusBadge.js.map +1 -1
- package/dist/components/Toast/ToastProvider.cjs +1 -1
- package/dist/components/Toast/ToastProvider.cjs.map +1 -1
- package/dist/components/Toast/ToastProvider.js +1 -2
- package/dist/components/Toast/ToastProvider.js.map +1 -1
- package/dist/hooks/use-announce.cjs +2 -0
- package/dist/hooks/use-announce.cjs.map +1 -0
- package/dist/hooks/use-announce.js +50 -0
- package/dist/hooks/use-announce.js.map +1 -0
- package/dist/hooks/use-media-devices.cjs +2 -0
- package/dist/hooks/use-media-devices.cjs.map +1 -0
- package/dist/hooks/use-media-devices.js +46 -0
- package/dist/hooks/use-media-devices.js.map +1 -0
- package/dist/hooks/use-media-permission.cjs +2 -0
- package/dist/hooks/use-media-permission.cjs.map +1 -0
- package/dist/hooks/use-media-permission.js +33 -0
- package/dist/hooks/use-media-permission.js.map +1 -0
- package/dist/http/resumable-upload.cjs +2 -0
- package/dist/http/resumable-upload.cjs.map +1 -0
- package/dist/http/resumable-upload.js +249 -0
- package/dist/http/resumable-upload.js.map +1 -0
- package/dist/styles.css +1 -1
- package/dist/tempest-react-sdk.cjs +1 -1
- package/dist/tempest-react-sdk.d.ts +2485 -29
- package/dist/tempest-react-sdk.js +268 -244
- package/dist/vision/core/graph.cjs +2 -0
- package/dist/vision/core/graph.cjs.map +1 -0
- package/dist/vision/core/graph.js +17 -0
- package/dist/vision/core/graph.js.map +1 -0
- package/dist/vision/core/session.cjs +1 -1
- package/dist/vision/core/session.cjs.map +1 -1
- package/dist/vision/core/session.js +19 -9
- package/dist/vision/core/session.js.map +1 -1
- package/dist/vision/index.cjs +1 -1
- package/dist/vision/index.cjs.map +1 -1
- package/dist/vision/index.js +14 -13
- package/dist/vision/index.js.map +1 -1
- package/dist/vision/tasks/classifier.cjs +1 -1
- package/dist/vision/tasks/classifier.cjs.map +1 -1
- package/dist/vision/tasks/classifier.js +33 -25
- package/dist/vision/tasks/classifier.js.map +1 -1
- package/dist/vision/tasks/detector.cjs +1 -1
- package/dist/vision/tasks/detector.cjs.map +1 -1
- package/dist/vision/tasks/detector.js +28 -20
- package/dist/vision/tasks/detector.js.map +1 -1
- package/dist/vision/tasks/segmenter.cjs +1 -1
- package/dist/vision/tasks/segmenter.cjs.map +1 -1
- package/dist/vision/tasks/segmenter.js +23 -15
- package/dist/vision/tasks/segmenter.js.map +1 -1
- package/dist/vision/use-camera-stream.cjs +1 -1
- package/dist/vision/use-camera-stream.cjs.map +1 -1
- package/dist/vision/use-camera-stream.js +40 -57
- package/dist/vision/use-camera-stream.js.map +1 -1
- package/dist/vision.cjs +1 -1
- package/dist/vision.d.ts +149 -8
- package/dist/vision.js +22 -21
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DataTable.cjs","names":[],"sources":["../../../src/components/DataTable/DataTable.tsx"],"sourcesContent":["import { useEffect, useMemo, useState } from \"react\";\nimport type { HTMLAttributes, ReactNode } from \"react\";\nimport { cn } from \"@/utils/cn\";\nimport { compareValues } from \"@/utils/compare-values\";\nimport { usePagination } from \"@/hooks\";\nimport { Table, type TableAlign, type TableColumn, type TablePriority } from \"../Table\";\nimport { Pagination } from \"../Pagination\";\nimport { SearchBar } from \"../SearchBar\";\nimport styles from \"./DataTable.module.css\";\n\nexport type SortDirection = \"asc\" | \"desc\";\n\nexport interface DataTableSort<T> {\n key: keyof T;\n direction: SortDirection;\n}\n\n/**\n * Column definition for {@link DataTable}. Extends the headless {@link Table}\n * column shape with a typed `key`, opt-in sorting, and the visual options that\n * are forwarded to the underlying Table cell.\n */\nexport interface DataTableColumn<T> {\n /** Property of the row this column reads from. Doubles as the cell key. */\n key: keyof T;\n /** Column heading. */\n header: ReactNode;\n /** Custom cell renderer. Defaults to `String(row[key])`. */\n render?: (row: T) => ReactNode;\n /** Enable click-to-sort on this column's header. */\n sortable?: boolean;\n /** Text alignment forwarded to the Table cell. */\n align?: TableAlign;\n /** Responsive visibility priority forwarded to the Table cell. */\n priority?: TablePriority;\n /** Fixed column width forwarded to the Table cell. */\n width?: string | number;\n}\n\nexport interface DataTableProps<T> extends HTMLAttributes<HTMLDivElement> {\n /** Full, unfiltered dataset. Sorting/filtering/pagination happen client-side. */\n data: T[];\n /** Column definitions. */\n columns: DataTableColumn<T>[];\n /** Rows per page. Default 10. */\n pageSize?: number;\n /** Render a search input above the table. Default false. */\n searchable?: boolean;\n /**\n * Keys to match the search term against. When omitted, every column whose\n * value is a string or number is searched.\n */\n searchKeys?: (keyof T)[];\n /** Initial sort applied before any header interaction. */\n initialSort?: DataTableSort<T>;\n /** Stable key extractor for rows. Defaults to the row index. */\n rowKey?: (row: T, index: number) => string | number;\n /** Content shown when no rows match. */\n emptyMessage?: ReactNode;\n}\n\n/**\n * Stateful, headless data table built on top of {@link Table}. Adds\n * client-side searching, click-to-sort columns, and pagination while\n * delegating all table markup to the underlying Table component.\n *\n * - Clicking a sortable header cycles asc → desc → unsorted.\n * - Search matches a case-insensitive substring across `searchKeys`\n * (or every string/number column when not provided).\n * - Pagination is hidden when the result fits on a single page.\n *\n * The header memo depends on `columns` and `sort` only: `toggleSort` is\n * recreated each render but always closes over the same setter, so including it\n * would rebuild every header on every render without changing behaviour. That\n * is why `exhaustive-deps` is silenced on that dependency array.\n */\nexport function DataTable<T>({\n data,\n columns,\n pageSize = 10,\n searchable = false,\n searchKeys,\n initialSort,\n rowKey = (_row, index) => index,\n emptyMessage,\n className,\n ...rest\n}: DataTableProps<T>) {\n const [search, setSearch] = useState<string>(\"\");\n const [sort, setSort] = useState<DataTableSort<T> | null>(initialSort ?? null);\n const { page, setPage } = usePagination(1, pageSize);\n\n const effectiveSearchKeys = useMemo<(keyof T)[]>(() => {\n if (searchKeys && searchKeys.length > 0) return searchKeys;\n return columns\n .filter((column) => {\n const sample = data.find((row) => row[column.key] != null);\n const value = sample ? sample[column.key] : undefined;\n return typeof value === \"string\" || typeof value === \"number\";\n })\n .map((column) => column.key);\n }, [searchKeys, columns, data]);\n\n const filtered = useMemo<T[]>(() => {\n const term = search.trim().toLowerCase();\n if (!term || !searchable) return data;\n return data.filter((row) =>\n effectiveSearchKeys.some((key) => {\n const value = row[key];\n return value != null && String(value).toLowerCase().includes(term);\n }),\n );\n }, [data, search, searchable, effectiveSearchKeys]);\n\n const sorted = useMemo<T[]>(() => {\n if (!sort) return filtered;\n const factor = sort.direction === \"asc\" ? 1 : -1;\n return [...filtered].sort((a, b) => compareValues(a[sort.key], b[sort.key]) * factor);\n }, [filtered, sort]);\n\n const totalPages = Math.max(1, Math.ceil(sorted.length / pageSize));\n\n // Clamp the current page when the dataset shrinks (e.g. after filtering).\n useEffect(() => {\n if (page > totalPages) setPage(totalPages);\n }, [page, totalPages, setPage]);\n\n const safePage = Math.min(page, totalPages);\n const pageRows = useMemo<T[]>(() => {\n const start = (safePage - 1) * pageSize;\n return sorted.slice(start, start + pageSize);\n }, [sorted, safePage, pageSize]);\n\n function toggleSort(key: keyof T): void {\n setSort((current) => {\n if (!current || current.key !== key) return { key, direction: \"asc\" };\n if (current.direction === \"asc\") return { key, direction: \"desc\" };\n return null;\n });\n }\n\n const tableColumns = useMemo<TableColumn<T>[]>(\n () =>\n columns.map((column) => {\n const isSorted = sort?.key === column.key;\n const indicator = isSorted ? (sort?.direction === \"asc\" ? \" ▲\" : \" ▼\") : \"\";\n const header = column.sortable ? (\n <button\n type=\"button\"\n className={styles.sortButton}\n onClick={() => toggleSort(column.key)}\n aria-label={`Ordenar por ${\n typeof column.header === \"string\" ? column.header : String(column.key)\n }`}\n >\n {column.header}\n <span className={styles.sortIndicator} aria-hidden>\n {indicator}\n </span>\n </button>\n ) : (\n column.header\n );\n\n return {\n key: String(column.key),\n header,\n align: column.align,\n priority: column.priority,\n width: column.width,\n render: column.render\n ? (row: T) => column.render!(row)\n : (row: T) => (row[column.key] as ReactNode) ?? null,\n };\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [columns, sort],\n );\n\n return (\n <div className={cn(styles.wrapper, className)} {...rest}>\n {searchable && (\n <SearchBar\n value={search}\n onChange={(value) => {\n setSearch(value);\n setPage(1);\n }}\n wrapperClassName={styles.search}\n />\n )}\n <Table\n columns={tableColumns}\n data={pageRows}\n rowKey={(row, index) => rowKey(row, (safePage - 1) * pageSize + index)}\n emptyMessage={emptyMessage}\n />\n {totalPages > 1 && (\n <Pagination\n page={safePage}\n totalPages={totalPages}\n onPageChange={setPage}\n totalItems={sorted.length}\n />\n )}\n </div>\n );\n}\n"],"mappings":"0UA4EA,SAAgB,EAAa,CACzB,OACA,UACA,WAAW,GACX,aAAa,GACb,aACA,cACA,UAAU,EAAM,IAAU,EAC1B,eACA,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AA,IAAA,CAAC,EAAA,UAAD,CACI,MAAO,EACP,SAAW,GAAU,CACjB,EAAU,CAAK,EACf,EAAQ,CAAC,CACb,EACA,iBAAkB,EAAA,QAAO,MAC5B,CAAA,GAEL,EAAA,EAAA,IAAA,CAAC,EAAA,MAAD,CACI,QAAS,EACT,KAAM,EACN,QAAS,EAAK,IAAU,EAAO,GAAM,EAAW,GAAK,EAAW,CAAK,EACvD,cACjB,CAAA,EACA,EAAa,IACV,EAAA,EAAA,IAAA,CAAC,EAAA,WAAD,CACI,KAAM,EACM,aACZ,aAAc,EACd,WAAY,EAAO,MACtB,CAAA,CAEJ,GAEb"}
|
|
1
|
+
{"version":3,"file":"DataTable.cjs","names":[],"sources":["../../../src/components/DataTable/DataTable.tsx"],"sourcesContent":["import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { HTMLAttributes, ReactNode } from \"react\";\nimport { cn } from \"@/utils/cn\";\nimport { compareValues } from \"@/utils/compare-values\";\nimport { usePagination } from \"@/hooks\";\nimport { useAnnounce } from \"@/hooks/use-announce\";\nimport { Table, type TableAlign, type TableColumn, type TablePriority } from \"../Table\";\nimport { Pagination } from \"../Pagination\";\nimport { SearchBar } from \"../SearchBar\";\nimport { EditableCell } from \"./EditableCell\";\nimport { DEFAULT_EDIT_LABELS, type CellCommitMove, type DataTableEditLabels } from \"./edit-labels\";\nimport styles from \"./DataTable.module.css\";\n\nexport type SortDirection = \"asc\" | \"desc\";\n\nexport interface DataTableSort<T> {\n key: keyof T;\n direction: SortDirection;\n}\n\n/** Input types an editable column can use. */\nexport type DataTableEditorType = \"text\" | \"number\" | \"date\" | \"email\" | \"tel\" | \"url\";\n\n/** One accepted cell edit, handed to `onCellChange`. */\nexport interface DataTableCellChange<T> {\n /** The row as it was before the edit. */\n row: T;\n /** Which column changed. */\n key: keyof T;\n /** The parsed new value. */\n value: unknown;\n /** The value that was displayed before the edit. */\n previous: unknown;\n /** Index of the row in the full `data` array. */\n rowIndex: number;\n}\n\n/**\n * Column definition for {@link DataTable}. Extends the headless {@link Table}\n * column shape with a typed `key`, opt-in sorting, opt-in inline editing, and the\n * visual options that are forwarded to the underlying Table cell.\n */\nexport interface DataTableColumn<T> {\n /** Property of the row this column reads from. Doubles as the cell key. */\n key: keyof T;\n /** Column heading. */\n header: ReactNode;\n /** Custom cell renderer. Defaults to `String(row[key])`. */\n render?: (row: T) => ReactNode;\n /** Enable click-to-sort on this column's header. */\n sortable?: boolean;\n /** Text alignment forwarded to the Table cell. */\n align?: TableAlign;\n /** Responsive visibility priority forwarded to the Table cell. */\n priority?: TablePriority;\n /** Fixed column width forwarded to the Table cell. */\n width?: string | number;\n /**\n * Let cells in this column be edited in place. Requires `onCellChange` on the\n * table; without it the column stays read-only.\n */\n editable?: boolean;\n /** Editor input type. Default `\"text\"`. */\n editorType?: DataTableEditorType;\n /** Text the editor opens with. Defaults to `String(value ?? \"\")`. */\n formatEdit?: (row: T) => string;\n /**\n * Turn the typed string into the stored value. Defaults to the trimmed string,\n * or `Number(raw)` when `editorType` is `\"number\"`.\n */\n parse?: (raw: string, row: T) => unknown;\n /** Return a message to reject the edit, or `null` to accept it. */\n validate?: (value: unknown, row: T) => string | null;\n}\n\nexport interface DataTableProps<T> extends HTMLAttributes<HTMLDivElement> {\n /** Full, unfiltered dataset. Sorting/filtering/pagination happen client-side. */\n data: T[];\n /** Column definitions. */\n columns: DataTableColumn<T>[];\n /** Rows per page. Default 10. */\n pageSize?: number;\n /** Render a search input above the table. Default false. */\n searchable?: boolean;\n /**\n * Keys to match the search term against. When omitted, every column whose\n * value is a string or number is searched.\n */\n searchKeys?: (keyof T)[];\n /** Initial sort applied before any header interaction. */\n initialSort?: DataTableSort<T>;\n /** Stable key extractor for rows. Defaults to the row index. */\n rowKey?: (row: T, index: number) => string | number;\n /** Content shown when no rows match. */\n emptyMessage?: ReactNode;\n /**\n * Persist an accepted cell edit. Return a promise: while it is pending the cell\n * already shows the new value, and a rejection rolls that back and surfaces the\n * error in the cell. Without this prop no column is editable.\n */\n onCellChange?: (change: DataTableCellChange<T>) => void | Promise<void>;\n /** Override the PT-BR copy of the editing affordances. */\n editLabels?: Partial<DataTableEditLabels>;\n}\n\n/** Identity of one cell, stable across re-renders and pagination. */\nfunction cellId(rowKeyValue: string | number, columnKey: PropertyKey): string {\n return `${String(rowKeyValue)}::${String(columnKey)}`;\n}\n\nfunction headerText<T>(column: DataTableColumn<T>): string {\n return typeof column.header === \"string\" ? column.header : String(column.key);\n}\n\n/**\n * Stateful, headless data table built on top of {@link Table}. Adds\n * client-side searching, click-to-sort columns, pagination and opt-in inline\n * editing while delegating all table markup to the underlying Table component.\n *\n * - Clicking a sortable header cycles asc → desc → unsorted.\n * - Search matches a case-insensitive substring across `searchKeys`\n * (or every string/number column when not provided).\n * - Pagination is hidden when the result fits on a single page.\n * - A column with `editable` renders a button that opens an inline editor;\n * `Enter` commits, `Escape` discards, `Tab` walks to the next editable cell.\n *\n * Editing is strictly opt-in: with no `editable` column (or no `onCellChange`) the\n * rendered markup is byte-for-byte what it was before the feature existed, which\n * matters because the component is published.\n *\n * ## Optimistic, with a visible rollback\n *\n * An accepted edit is shown immediately and `onCellChange` runs in the background.\n * If it rejects, the cell returns to the old value **and** shows the reason as a\n * `role=\"alert\"` tied to the cell. A silent revert is worse than no optimistic\n * update at all: the user watched their edit appear and has no reason to doubt it.\n *\n * The header memo depends on `columns`, `sort` and the editing state only:\n * `toggleSort` and the commit callbacks are recreated each render but always close\n * over the same setters, so including them would rebuild every header on every\n * render without changing behaviour. That is why `exhaustive-deps` is silenced on\n * that dependency array.\n */\nexport function DataTable<T>({\n data,\n columns,\n pageSize = 10,\n searchable = false,\n searchKeys,\n initialSort,\n rowKey = (_row, index) => index,\n emptyMessage,\n onCellChange,\n editLabels,\n className,\n ...rest\n}: DataTableProps<T>) {\n const [search, setSearch] = useState<string>(\"\");\n const [sort, setSort] = useState<DataTableSort<T> | null>(initialSort ?? null);\n const { page, setPage } = usePagination(1, pageSize);\n const announce = useAnnounce();\n\n const [editing, setEditing] = useState<string | null>(null);\n const [refocus, setRefocus] = useState<string | null>(null);\n const [overrides, setOverrides] = useState<Record<string, unknown>>({});\n const [errors, setErrors] = useState<Record<string, string>>({});\n const [saving, setSaving] = useState<Record<string, boolean>>({});\n\n const labels = useMemo<DataTableEditLabels>(\n () => ({ ...DEFAULT_EDIT_LABELS, ...editLabels }),\n [editLabels],\n );\n const editingEnabled = onCellChange !== undefined && columns.some((column) => column.editable);\n\n const effectiveSearchKeys = useMemo<(keyof T)[]>(() => {\n if (searchKeys && searchKeys.length > 0) return searchKeys;\n return columns\n .filter((column) => {\n const sample = data.find((row) => row[column.key] != null);\n const value = sample ? sample[column.key] : undefined;\n return typeof value === \"string\" || typeof value === \"number\";\n })\n .map((column) => column.key);\n }, [searchKeys, columns, data]);\n\n const filtered = useMemo<T[]>(() => {\n const term = search.trim().toLowerCase();\n if (!term || !searchable) return data;\n return data.filter((row) =>\n effectiveSearchKeys.some((key) => {\n const value = row[key];\n return value != null && String(value).toLowerCase().includes(term);\n }),\n );\n }, [data, search, searchable, effectiveSearchKeys]);\n\n const sorted = useMemo<T[]>(() => {\n if (!sort) return filtered;\n const factor = sort.direction === \"asc\" ? 1 : -1;\n return [...filtered].sort((a, b) => compareValues(a[sort.key], b[sort.key]) * factor);\n }, [filtered, sort]);\n\n const totalPages = Math.max(1, Math.ceil(sorted.length / pageSize));\n\n // Clamp the current page when the dataset shrinks (e.g. after filtering).\n useEffect(() => {\n if (page > totalPages) setPage(totalPages);\n }, [page, totalPages, setPage]);\n\n const safePage = Math.min(page, totalPages);\n const pageRows = useMemo<T[]>(() => {\n const start = (safePage - 1) * pageSize;\n return sorted.slice(start, start + pageSize);\n }, [sorted, safePage, pageSize]);\n\n function toggleSort(key: keyof T): void {\n setSort((current) => {\n if (!current || current.key !== key) return { key, direction: \"asc\" };\n if (current.direction === \"asc\") return { key, direction: \"desc\" };\n return null;\n });\n }\n\n const absoluteIndex = useCallback(\n (pageIndex: number) => (safePage - 1) * pageSize + pageIndex,\n [safePage, pageSize],\n );\n\n /**\n * Every editable cell on the page, row-major — the order `Tab` walks.\n *\n * Row-major and not column-major because a row is the record a user is\n * correcting; walking down a column would make them re-find their place on\n * every keystroke.\n */\n const editableCellIds = useMemo<string[]>(() => {\n if (!editingEnabled) return [];\n const ids: string[] = [];\n pageRows.forEach((row, index) => {\n const key = rowKey(row, absoluteIndex(index));\n for (const column of columns) {\n if (column.editable) ids.push(cellId(key, column.key));\n }\n });\n return ids;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [editingEnabled, pageRows, columns, absoluteIndex]);\n\n const displayed = useCallback(\n (row: T, column: DataTableColumn<T>, id: string): unknown =>\n id in overrides ? overrides[id] : row[column.key],\n [overrides],\n );\n\n /**\n * Run the caller's `onCellChange` behind the optimistic update.\n *\n * Only the *success* is announced. The failure already renders as a\n * `role=\"alert\"` inside the cell, which screen readers read on insertion —\n * announcing it again from the shared region would read it twice and put the\n * same text in the document twice.\n */\n const persist = useCallback(\n async (id: string, column: DataTableColumn<T>, change: DataTableCellChange<T>) => {\n setSaving((current) => ({ ...current, [id]: true }));\n try {\n await onCellChange?.(change);\n announce(labels.saved(headerText(column)));\n } catch (error) {\n setOverrides((current) => {\n const next = { ...current };\n delete next[id];\n return next;\n });\n const message =\n error instanceof Error && error.message\n ? error.message\n : labels.saveFailed(headerText(column));\n setErrors((current) => ({ ...current, [id]: message }));\n } finally {\n setSaving((current) => {\n const next = { ...current };\n delete next[id];\n return next;\n });\n }\n },\n [onCellChange, announce, labels],\n );\n\n const moveFrom = useCallback(\n (id: string, move: CellCommitMove): void => {\n if (move === \"none\") {\n setEditing(null);\n setRefocus(id);\n return;\n }\n const index = editableCellIds.indexOf(id);\n const target = editableCellIds[index + (move === \"next\" ? 1 : -1)];\n if (target === undefined) {\n setEditing(null);\n setRefocus(id);\n return;\n }\n setEditing(target);\n setRefocus(null);\n },\n [editableCellIds],\n );\n\n /**\n * Parse, validate, stage optimistically, then save in the background.\n *\n * Validation runs before anything is staged, and a rejection leaves the editor\n * open with the message attached to the input — the user has to be able to fix\n * what they typed without retyping it.\n */\n const commit = useCallback(\n (\n row: T,\n column: DataTableColumn<T>,\n id: string,\n pageIndex: number,\n raw: string,\n move: CellCommitMove,\n ): void => {\n const previous = displayed(row, column, id);\n const currentText = column.formatEdit ? column.formatEdit(row) : String(previous ?? \"\");\n if (raw === currentText) {\n moveFrom(id, move);\n return;\n }\n\n const value = column.parse\n ? column.parse(raw, row)\n : column.editorType === \"number\"\n ? Number(raw)\n : raw.trim();\n\n const invalid = column.validate?.(value, row) ?? null;\n if (invalid) {\n setErrors((current) => ({ ...current, [id]: invalid }));\n return;\n }\n\n setErrors((current) => {\n const next = { ...current };\n delete next[id];\n return next;\n });\n setOverrides((current) => ({ ...current, [id]: value }));\n moveFrom(id, move);\n void persist(id, column, {\n row,\n key: column.key,\n value,\n previous,\n rowIndex: absoluteIndex(pageIndex),\n });\n },\n [displayed, moveFrom, persist, absoluteIndex],\n );\n\n const tableColumns = useMemo<TableColumn<T>[]>(\n () =>\n columns.map((column) => {\n const isSorted = sort?.key === column.key;\n const indicator = isSorted ? (sort?.direction === \"asc\" ? \" ▲\" : \" ▼\") : \"\";\n const header = column.sortable ? (\n <button\n type=\"button\"\n className={styles.sortButton}\n onClick={() => toggleSort(column.key)}\n aria-label={`Ordenar por ${headerText(column)}`}\n >\n {column.header}\n <span className={styles.sortIndicator} aria-hidden>\n {indicator}\n </span>\n </button>\n ) : (\n column.header\n );\n\n const plainCell = (row: T): ReactNode => {\n if (column.render) return column.render(row);\n return (row[column.key] as ReactNode) ?? null;\n };\n\n /**\n * Render an editable cell's content against the optimistic value.\n *\n * The row is shallow-patched rather than the value passed alongside it,\n * because a column with a custom `render` (a `<Money>`, a badge) reads\n * the row — handing it the stale row would show the old number under a\n * cell the user just changed.\n */\n const patchedCell = (row: T, value: unknown): ReactNode => {\n const patched = { ...row, [column.key]: value } as T;\n if (column.render) return column.render(patched);\n return (patched[column.key] as ReactNode) ?? null;\n };\n\n const editable = editingEnabled && column.editable === true;\n\n return {\n key: String(column.key),\n header,\n align: column.align,\n priority: column.priority,\n width: column.width,\n render: editable\n ? (row: T, index: number) => {\n const id = cellId(rowKey(row, absoluteIndex(index)), column.key);\n const value = displayed(row, column, id);\n const text = column.formatEdit\n ? column.formatEdit(row)\n : String(value ?? \"\");\n return (\n <EditableCell\n text={text}\n columnLabel={headerText(column)}\n rowNumber={index + 1}\n inputType={column.editorType ?? \"text\"}\n editing={editing === id}\n refocus={refocus === id}\n saving={saving[id] === true}\n error={errors[id] ?? null}\n errorId={`tempest-cell-error-${id.replace(/[^\\w-]/g, \"_\")}`}\n labels={labels}\n onOpen={() => {\n setEditing(id);\n setRefocus(null);\n }}\n onCommit={(raw, move) =>\n commit(row, column, id, index, raw, move)\n }\n onCancel={() => {\n setEditing(null);\n setRefocus(id);\n setErrors((current) => {\n const next = { ...current };\n delete next[id];\n return next;\n });\n }}\n >\n {patchedCell(row, value)}\n </EditableCell>\n );\n }\n : plainCell,\n };\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n columns,\n sort,\n editingEnabled,\n editing,\n refocus,\n saving,\n errors,\n labels,\n overrides,\n absoluteIndex,\n commit,\n ],\n );\n\n return (\n <div className={cn(styles.wrapper, className)} {...rest}>\n {searchable && (\n <SearchBar\n value={search}\n onChange={(value) => {\n setSearch(value);\n setPage(1);\n }}\n wrapperClassName={styles.search}\n />\n )}\n <Table\n columns={tableColumns}\n data={pageRows}\n rowKey={(row, index) => rowKey(row, absoluteIndex(index))}\n emptyMessage={emptyMessage}\n />\n {totalPages > 1 && (\n <Pagination\n page={safePage}\n totalPages={totalPages}\n onPageChange={setPage}\n totalItems={sorted.length}\n />\n )}\n </div>\n );\n}\n"],"mappings":"mbA0GA,SAAS,EAAO,EAA8B,EAAgC,CAC1E,MAAO,GAAG,OAAO,CAAW,EAAE,IAAI,OAAO,CAAS,GACtD,CAEA,SAAS,EAAc,EAAoC,CACvD,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,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,CACJ,CACJ,EAEA,OACI,EAAA,EAAA,KAAA,CAAC,MAAD,CAAK,UAAW,EAAA,GAAG,EAAA,QAAO,QAAS,EAAS,EAAG,GAAI,YAAnD,CACK,IACG,EAAA,EAAA,IAAA,CAAC,EAAA,UAAD,CACI,MAAO,EACP,SAAW,GAAU,CACjB,EAAU,CAAK,EACf,EAAQ,CAAC,CACb,EACA,iBAAkB,EAAA,QAAO,MAC5B,CAAA,GAEL,EAAA,EAAA,IAAA,CAAC,EAAA,MAAD,CACI,QAAS,GACT,KAAM,EACN,QAAS,EAAK,IAAU,EAAO,EAAK,EAAc,CAAK,CAAC,EAC1C,eACjB,CAAA,EACA,EAAa,IACV,EAAA,EAAA,IAAA,CAAC,EAAA,WAAD,CACI,KAAM,EACM,aACZ,aAAc,EACd,WAAY,EAAO,MACtB,CAAA,CAEJ,GAEb"}
|
|
@@ -1,54 +1,66 @@
|
|
|
1
1
|
import { cn as e } from "../../utils/cn.js";
|
|
2
2
|
import { usePagination as t } from "../../hooks/use-pagination.js";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import o from "
|
|
8
|
-
import
|
|
9
|
-
import {
|
|
3
|
+
import { useAnnounce as n } from "../../hooks/use-announce.js";
|
|
4
|
+
import { Pagination as r } from "../Pagination/Pagination.js";
|
|
5
|
+
import { SearchBar as i } from "../SearchBar/SearchBar.js";
|
|
6
|
+
import { Table as a } from "../Table/Table.js";
|
|
7
|
+
import { compareValues as o } from "../../utils/compare-values.js";
|
|
8
|
+
import s from "./DataTable.module.js";
|
|
9
|
+
import { EditableCell as c } from "./EditableCell.js";
|
|
10
|
+
import { DEFAULT_EDIT_LABELS as ee } from "./edit-labels.js";
|
|
11
|
+
import { useCallback as l, useEffect as te, useMemo as u, useState as d } from "react";
|
|
12
|
+
import { jsx as f, jsxs as p } from "react/jsx-runtime";
|
|
10
13
|
//#region src/components/DataTable/DataTable.tsx
|
|
11
|
-
function
|
|
12
|
-
|
|
13
|
-
|
|
14
|
+
function m(e, t) {
|
|
15
|
+
return `${String(e)}::${String(t)}`;
|
|
16
|
+
}
|
|
17
|
+
function h(e) {
|
|
18
|
+
return typeof e.header == "string" ? e.header : String(e.key);
|
|
19
|
+
}
|
|
20
|
+
function g({ data: g, columns: _, pageSize: v = 10, searchable: y = !1, searchKeys: b, initialSort: ne, rowKey: x = (e, t) => t, emptyMessage: re, onCellChange: S, editLabels: C, className: w, ...ie }) {
|
|
21
|
+
let [T, ae] = d(""), [E, oe] = d(ne ?? null), { page: D, setPage: O } = t(1, v), k = n(), [A, j] = d(null), [M, N] = d(null), [P, F] = d({}), [I, L] = d({}), [R, z] = d({}), B = u(() => ({
|
|
22
|
+
...ee,
|
|
23
|
+
...C
|
|
24
|
+
}), [C]), V = S !== void 0 && _.some((e) => e.editable), H = u(() => b && b.length > 0 ? b : _.filter((e) => {
|
|
25
|
+
let t = g.find((t) => t[e.key] != null), n = t ? t[e.key] : void 0;
|
|
14
26
|
return typeof n == "string" || typeof n == "number";
|
|
15
27
|
}).map((e) => e.key), [
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
]),
|
|
20
|
-
let e =
|
|
21
|
-
return !e || !
|
|
28
|
+
b,
|
|
29
|
+
_,
|
|
30
|
+
g
|
|
31
|
+
]), U = u(() => {
|
|
32
|
+
let e = T.trim().toLowerCase();
|
|
33
|
+
return !e || !y ? g : g.filter((t) => H.some((n) => {
|
|
22
34
|
let r = t[n];
|
|
23
35
|
return r != null && String(r).toLowerCase().includes(e);
|
|
24
36
|
}));
|
|
25
37
|
}, [
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
]),
|
|
31
|
-
if (!
|
|
32
|
-
let e =
|
|
33
|
-
return [...
|
|
34
|
-
}, [
|
|
35
|
-
|
|
36
|
-
|
|
38
|
+
g,
|
|
39
|
+
T,
|
|
40
|
+
y,
|
|
41
|
+
H
|
|
42
|
+
]), W = u(() => {
|
|
43
|
+
if (!E) return U;
|
|
44
|
+
let e = E.direction === "asc" ? 1 : -1;
|
|
45
|
+
return [...U].sort((t, n) => o(t[E.key], n[E.key]) * e);
|
|
46
|
+
}, [U, E]), G = Math.max(1, Math.ceil(W.length / v));
|
|
47
|
+
te(() => {
|
|
48
|
+
D > G && O(G);
|
|
37
49
|
}, [
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
50
|
+
D,
|
|
51
|
+
G,
|
|
52
|
+
O
|
|
41
53
|
]);
|
|
42
|
-
let
|
|
43
|
-
let e = (
|
|
44
|
-
return
|
|
54
|
+
let K = Math.min(D, G), q = u(() => {
|
|
55
|
+
let e = (K - 1) * v;
|
|
56
|
+
return W.slice(e, e + v);
|
|
45
57
|
}, [
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
58
|
+
W,
|
|
59
|
+
K,
|
|
60
|
+
v
|
|
49
61
|
]);
|
|
50
|
-
function
|
|
51
|
-
|
|
62
|
+
function se(e) {
|
|
63
|
+
oe((t) => !t || t.key !== e ? {
|
|
52
64
|
key: e,
|
|
53
65
|
direction: "asc"
|
|
54
66
|
} : t.direction === "asc" ? {
|
|
@@ -56,54 +68,179 @@ function f({ data: f, columns: p, pageSize: m = 10, searchable: h = !1, searchKe
|
|
|
56
68
|
direction: "desc"
|
|
57
69
|
} : null);
|
|
58
70
|
}
|
|
59
|
-
let
|
|
60
|
-
|
|
71
|
+
let J = l((e) => (K - 1) * v + e, [K, v]), Y = u(() => {
|
|
72
|
+
if (!V) return [];
|
|
73
|
+
let e = [];
|
|
74
|
+
return q.forEach((t, n) => {
|
|
75
|
+
let r = x(t, J(n));
|
|
76
|
+
for (let t of _) t.editable && e.push(m(r, t.key));
|
|
77
|
+
}), e;
|
|
78
|
+
}, [
|
|
79
|
+
V,
|
|
80
|
+
q,
|
|
81
|
+
_,
|
|
82
|
+
J
|
|
83
|
+
]), X = l((e, t, n) => n in P ? P[n] : e[t.key], [P]), Z = l(async (e, t, n) => {
|
|
84
|
+
z((t) => ({
|
|
85
|
+
...t,
|
|
86
|
+
[e]: !0
|
|
87
|
+
}));
|
|
88
|
+
try {
|
|
89
|
+
await S?.(n), k(B.saved(h(t)));
|
|
90
|
+
} catch (n) {
|
|
91
|
+
F((t) => {
|
|
92
|
+
let n = { ...t };
|
|
93
|
+
return delete n[e], n;
|
|
94
|
+
});
|
|
95
|
+
let r = n instanceof Error && n.message ? n.message : B.saveFailed(h(t));
|
|
96
|
+
L((t) => ({
|
|
97
|
+
...t,
|
|
98
|
+
[e]: r
|
|
99
|
+
}));
|
|
100
|
+
} finally {
|
|
101
|
+
z((t) => {
|
|
102
|
+
let n = { ...t };
|
|
103
|
+
return delete n[e], n;
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
}, [
|
|
107
|
+
S,
|
|
108
|
+
k,
|
|
109
|
+
B
|
|
110
|
+
]), Q = l((e, t) => {
|
|
111
|
+
if (t === "none") {
|
|
112
|
+
j(null), N(e);
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
let n = Y.indexOf(e), r = Y[n + (t === "next" ? 1 : -1)];
|
|
116
|
+
if (r === void 0) {
|
|
117
|
+
j(null), N(e);
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
j(r), N(null);
|
|
121
|
+
}, [Y]), $ = l((e, t, n, r, i, a) => {
|
|
122
|
+
let o = X(e, t, n);
|
|
123
|
+
if (i === (t.formatEdit ? t.formatEdit(e) : String(o ?? ""))) {
|
|
124
|
+
Q(n, a);
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
let s = t.parse ? t.parse(i, e) : t.editorType === "number" ? Number(i) : i.trim(), c = t.validate?.(s, e) ?? null;
|
|
128
|
+
if (c) {
|
|
129
|
+
L((e) => ({
|
|
130
|
+
...e,
|
|
131
|
+
[n]: c
|
|
132
|
+
}));
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
L((e) => {
|
|
136
|
+
let t = { ...e };
|
|
137
|
+
return delete t[n], t;
|
|
138
|
+
}), F((e) => ({
|
|
139
|
+
...e,
|
|
140
|
+
[n]: s
|
|
141
|
+
})), Q(n, a), Z(n, t, {
|
|
142
|
+
row: e,
|
|
143
|
+
key: t.key,
|
|
144
|
+
value: s,
|
|
145
|
+
previous: o,
|
|
146
|
+
rowIndex: J(r)
|
|
147
|
+
});
|
|
148
|
+
}, [
|
|
149
|
+
X,
|
|
150
|
+
Q,
|
|
151
|
+
Z,
|
|
152
|
+
J
|
|
153
|
+
]), ce = u(() => _.map((e) => {
|
|
154
|
+
let t = E?.key === e.key ? E?.direction === "asc" ? " ▲" : " ▼" : "", n = e.sortable ? /* @__PURE__ */ p("button", {
|
|
61
155
|
type: "button",
|
|
62
|
-
className:
|
|
63
|
-
onClick: () =>
|
|
64
|
-
"aria-label": `Ordenar por ${
|
|
65
|
-
children: [e.header, /* @__PURE__ */
|
|
66
|
-
className:
|
|
156
|
+
className: s.sortButton,
|
|
157
|
+
onClick: () => se(e.key),
|
|
158
|
+
"aria-label": `Ordenar por ${h(e)}`,
|
|
159
|
+
children: [e.header, /* @__PURE__ */ f("span", {
|
|
160
|
+
className: s.sortIndicator,
|
|
67
161
|
"aria-hidden": !0,
|
|
68
162
|
children: t
|
|
69
163
|
})]
|
|
70
|
-
}) : e.header
|
|
164
|
+
}) : e.header, r = (t) => e.render ? e.render(t) : t[e.key] ?? null, i = (t, n) => {
|
|
165
|
+
let r = {
|
|
166
|
+
...t,
|
|
167
|
+
[e.key]: n
|
|
168
|
+
};
|
|
169
|
+
return e.render ? e.render(r) : r[e.key] ?? null;
|
|
170
|
+
}, a = V && e.editable === !0;
|
|
71
171
|
return {
|
|
72
172
|
key: String(e.key),
|
|
73
173
|
header: n,
|
|
74
174
|
align: e.align,
|
|
75
175
|
priority: e.priority,
|
|
76
176
|
width: e.width,
|
|
77
|
-
render:
|
|
177
|
+
render: a ? (t, n) => {
|
|
178
|
+
let r = m(x(t, J(n)), e.key), a = X(t, e, r);
|
|
179
|
+
return /* @__PURE__ */ f(c, {
|
|
180
|
+
text: e.formatEdit ? e.formatEdit(t) : String(a ?? ""),
|
|
181
|
+
columnLabel: h(e),
|
|
182
|
+
rowNumber: n + 1,
|
|
183
|
+
inputType: e.editorType ?? "text",
|
|
184
|
+
editing: A === r,
|
|
185
|
+
refocus: M === r,
|
|
186
|
+
saving: R[r] === !0,
|
|
187
|
+
error: I[r] ?? null,
|
|
188
|
+
errorId: `tempest-cell-error-${r.replace(/[^\w-]/g, "_")}`,
|
|
189
|
+
labels: B,
|
|
190
|
+
onOpen: () => {
|
|
191
|
+
j(r), N(null);
|
|
192
|
+
},
|
|
193
|
+
onCommit: (i, a) => $(t, e, r, n, i, a),
|
|
194
|
+
onCancel: () => {
|
|
195
|
+
j(null), N(r), L((e) => {
|
|
196
|
+
let t = { ...e };
|
|
197
|
+
return delete t[r], t;
|
|
198
|
+
});
|
|
199
|
+
},
|
|
200
|
+
children: i(t, a)
|
|
201
|
+
});
|
|
202
|
+
} : r
|
|
78
203
|
};
|
|
79
|
-
}), [
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
204
|
+
}), [
|
|
205
|
+
_,
|
|
206
|
+
E,
|
|
207
|
+
V,
|
|
208
|
+
A,
|
|
209
|
+
M,
|
|
210
|
+
R,
|
|
211
|
+
I,
|
|
212
|
+
B,
|
|
213
|
+
P,
|
|
214
|
+
J,
|
|
215
|
+
$
|
|
216
|
+
]);
|
|
217
|
+
return /* @__PURE__ */ p("div", {
|
|
218
|
+
className: e(s.wrapper, w),
|
|
219
|
+
...ie,
|
|
83
220
|
children: [
|
|
84
|
-
|
|
85
|
-
value:
|
|
221
|
+
y && /* @__PURE__ */ f(i, {
|
|
222
|
+
value: T,
|
|
86
223
|
onChange: (e) => {
|
|
87
|
-
|
|
224
|
+
ae(e), O(1);
|
|
88
225
|
},
|
|
89
|
-
wrapperClassName:
|
|
226
|
+
wrapperClassName: s.search
|
|
90
227
|
}),
|
|
91
|
-
/* @__PURE__ */
|
|
92
|
-
columns:
|
|
93
|
-
data:
|
|
94
|
-
rowKey: (e, t) =>
|
|
95
|
-
emptyMessage:
|
|
228
|
+
/* @__PURE__ */ f(a, {
|
|
229
|
+
columns: ce,
|
|
230
|
+
data: q,
|
|
231
|
+
rowKey: (e, t) => x(e, J(t)),
|
|
232
|
+
emptyMessage: re
|
|
96
233
|
}),
|
|
97
|
-
|
|
98
|
-
page:
|
|
99
|
-
totalPages:
|
|
100
|
-
onPageChange:
|
|
101
|
-
totalItems:
|
|
234
|
+
G > 1 && /* @__PURE__ */ f(r, {
|
|
235
|
+
page: K,
|
|
236
|
+
totalPages: G,
|
|
237
|
+
onPageChange: O,
|
|
238
|
+
totalItems: W.length
|
|
102
239
|
})
|
|
103
240
|
]
|
|
104
241
|
});
|
|
105
242
|
}
|
|
106
243
|
//#endregion
|
|
107
|
-
export {
|
|
244
|
+
export { g as DataTable };
|
|
108
245
|
|
|
109
246
|
//# sourceMappingURL=DataTable.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DataTable.js","names":[],"sources":["../../../src/components/DataTable/DataTable.tsx"],"sourcesContent":["import { useEffect, useMemo, useState } from \"react\";\nimport type { HTMLAttributes, ReactNode } from \"react\";\nimport { cn } from \"@/utils/cn\";\nimport { compareValues } from \"@/utils/compare-values\";\nimport { usePagination } from \"@/hooks\";\nimport { Table, type TableAlign, type TableColumn, type TablePriority } from \"../Table\";\nimport { Pagination } from \"../Pagination\";\nimport { SearchBar } from \"../SearchBar\";\nimport styles from \"./DataTable.module.css\";\n\nexport type SortDirection = \"asc\" | \"desc\";\n\nexport interface DataTableSort<T> {\n key: keyof T;\n direction: SortDirection;\n}\n\n/**\n * Column definition for {@link DataTable}. Extends the headless {@link Table}\n * column shape with a typed `key`, opt-in sorting, and the visual options that\n * are forwarded to the underlying Table cell.\n */\nexport interface DataTableColumn<T> {\n /** Property of the row this column reads from. Doubles as the cell key. */\n key: keyof T;\n /** Column heading. */\n header: ReactNode;\n /** Custom cell renderer. Defaults to `String(row[key])`. */\n render?: (row: T) => ReactNode;\n /** Enable click-to-sort on this column's header. */\n sortable?: boolean;\n /** Text alignment forwarded to the Table cell. */\n align?: TableAlign;\n /** Responsive visibility priority forwarded to the Table cell. */\n priority?: TablePriority;\n /** Fixed column width forwarded to the Table cell. */\n width?: string | number;\n}\n\nexport interface DataTableProps<T> extends HTMLAttributes<HTMLDivElement> {\n /** Full, unfiltered dataset. Sorting/filtering/pagination happen client-side. */\n data: T[];\n /** Column definitions. */\n columns: DataTableColumn<T>[];\n /** Rows per page. Default 10. */\n pageSize?: number;\n /** Render a search input above the table. Default false. */\n searchable?: boolean;\n /**\n * Keys to match the search term against. When omitted, every column whose\n * value is a string or number is searched.\n */\n searchKeys?: (keyof T)[];\n /** Initial sort applied before any header interaction. */\n initialSort?: DataTableSort<T>;\n /** Stable key extractor for rows. Defaults to the row index. */\n rowKey?: (row: T, index: number) => string | number;\n /** Content shown when no rows match. */\n emptyMessage?: ReactNode;\n}\n\n/**\n * Stateful, headless data table built on top of {@link Table}. Adds\n * client-side searching, click-to-sort columns, and pagination while\n * delegating all table markup to the underlying Table component.\n *\n * - Clicking a sortable header cycles asc → desc → unsorted.\n * - Search matches a case-insensitive substring across `searchKeys`\n * (or every string/number column when not provided).\n * - Pagination is hidden when the result fits on a single page.\n *\n * The header memo depends on `columns` and `sort` only: `toggleSort` is\n * recreated each render but always closes over the same setter, so including it\n * would rebuild every header on every render without changing behaviour. That\n * is why `exhaustive-deps` is silenced on that dependency array.\n */\nexport function DataTable<T>({\n data,\n columns,\n pageSize = 10,\n searchable = false,\n searchKeys,\n initialSort,\n rowKey = (_row, index) => index,\n emptyMessage,\n className,\n ...rest\n}: DataTableProps<T>) {\n const [search, setSearch] = useState<string>(\"\");\n const [sort, setSort] = useState<DataTableSort<T> | null>(initialSort ?? null);\n const { page, setPage } = usePagination(1, pageSize);\n\n const effectiveSearchKeys = useMemo<(keyof T)[]>(() => {\n if (searchKeys && searchKeys.length > 0) return searchKeys;\n return columns\n .filter((column) => {\n const sample = data.find((row) => row[column.key] != null);\n const value = sample ? sample[column.key] : undefined;\n return typeof value === \"string\" || typeof value === \"number\";\n })\n .map((column) => column.key);\n }, [searchKeys, columns, data]);\n\n const filtered = useMemo<T[]>(() => {\n const term = search.trim().toLowerCase();\n if (!term || !searchable) return data;\n return data.filter((row) =>\n effectiveSearchKeys.some((key) => {\n const value = row[key];\n return value != null && String(value).toLowerCase().includes(term);\n }),\n );\n }, [data, search, searchable, effectiveSearchKeys]);\n\n const sorted = useMemo<T[]>(() => {\n if (!sort) return filtered;\n const factor = sort.direction === \"asc\" ? 1 : -1;\n return [...filtered].sort((a, b) => compareValues(a[sort.key], b[sort.key]) * factor);\n }, [filtered, sort]);\n\n const totalPages = Math.max(1, Math.ceil(sorted.length / pageSize));\n\n // Clamp the current page when the dataset shrinks (e.g. after filtering).\n useEffect(() => {\n if (page > totalPages) setPage(totalPages);\n }, [page, totalPages, setPage]);\n\n const safePage = Math.min(page, totalPages);\n const pageRows = useMemo<T[]>(() => {\n const start = (safePage - 1) * pageSize;\n return sorted.slice(start, start + pageSize);\n }, [sorted, safePage, pageSize]);\n\n function toggleSort(key: keyof T): void {\n setSort((current) => {\n if (!current || current.key !== key) return { key, direction: \"asc\" };\n if (current.direction === \"asc\") return { key, direction: \"desc\" };\n return null;\n });\n }\n\n const tableColumns = useMemo<TableColumn<T>[]>(\n () =>\n columns.map((column) => {\n const isSorted = sort?.key === column.key;\n const indicator = isSorted ? (sort?.direction === \"asc\" ? \" ▲\" : \" ▼\") : \"\";\n const header = column.sortable ? (\n <button\n type=\"button\"\n className={styles.sortButton}\n onClick={() => toggleSort(column.key)}\n aria-label={`Ordenar por ${\n typeof column.header === \"string\" ? column.header : String(column.key)\n }`}\n >\n {column.header}\n <span className={styles.sortIndicator} aria-hidden>\n {indicator}\n </span>\n </button>\n ) : (\n column.header\n );\n\n return {\n key: String(column.key),\n header,\n align: column.align,\n priority: column.priority,\n width: column.width,\n render: column.render\n ? (row: T) => column.render!(row)\n : (row: T) => (row[column.key] as ReactNode) ?? null,\n };\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [columns, sort],\n );\n\n return (\n <div className={cn(styles.wrapper, className)} {...rest}>\n {searchable && (\n <SearchBar\n value={search}\n onChange={(value) => {\n setSearch(value);\n setPage(1);\n }}\n wrapperClassName={styles.search}\n />\n )}\n <Table\n columns={tableColumns}\n data={pageRows}\n rowKey={(row, index) => rowKey(row, (safePage - 1) * pageSize + index)}\n emptyMessage={emptyMessage}\n />\n {totalPages > 1 && (\n <Pagination\n page={safePage}\n totalPages={totalPages}\n onPageChange={setPage}\n totalItems={sorted.length}\n />\n )}\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;AA4EA,SAAgB,EAAa,EACzB,SACA,YACA,cAAW,IACX,gBAAa,IACb,eACA,gBACA,aAAU,GAAM,MAAU,GAC1B,iBACA,cACA,GAAG,KACe;CAClB,IAAM,CAAC,GAAQ,KAAa,EAAiB,EAAE,GACzC,CAAC,GAAM,KAAW,EAAkC,KAAe,IAAI,GACvE,EAAE,SAAM,eAAY,EAAc,GAAG,CAAQ,GAE7C,IAAsB,QACpB,KAAc,EAAW,SAAS,IAAU,IACzC,EACF,QAAQ,MAAW;EAChB,IAAM,IAAS,EAAK,MAAM,MAAQ,EAAI,EAAO,QAAQ,IAAI,GACnD,IAAQ,IAAS,EAAO,EAAO,OAAO,KAAA;EAC5C,OAAO,OAAO,KAAU,YAAY,OAAO,KAAU;CACzD,CAAC,CAAC,CACD,KAAK,MAAW,EAAO,GAAG,GAChC;EAAC;EAAY;EAAS;CAAI,CAAC,GAExB,IAAW,QAAmB;EAChC,IAAM,IAAO,EAAO,KAAK,CAAC,CAAC,YAAY;EAEvC,OADI,CAAC,KAAQ,CAAC,IAAmB,IAC1B,EAAK,QAAQ,MAChB,EAAoB,MAAM,MAAQ;GAC9B,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R,kBAAC,QAAD;IAAM,WAAW,EAAO;IAAe,eAAA;cAClC;GACC,CAAA,CACF;OAER,EAAO;EAGX,OAAO;GACH,KAAK,OAAO,EAAO,GAAG;GACtB;GACA,OAAO,EAAO;GACd,UAAU,EAAO;GACjB,OAAO,EAAO;GACd,QAAQ,EAAO,UACR,MAAW,EAAO,OAAQ,CAAG,KAC7B,MAAY,EAAI,EAAO,QAAsB;EACxD;CACJ,CAAC,GAEL,CAAC,GAAS,CAAI,CAClB;CAEA,OACI,kBAAC,OAAD;EAAK,WAAW,EAAG,EAAO,SAAS,CAAS;EAAG,GAAI;YAAnD;GACK,KACG,kBAAC,GAAD;IACI,OAAO;IACP,WAAW,MAAU;KAEjB,AADA,EAAU,CAAK,GACf,EAAQ,CAAC;IACb;IACA,kBAAkB,EAAO;GAC5B,CAAA;GAEL,kBAAC,GAAD;IACI,SAAS;IACT,MAAM;IACN,SAAS,GAAK,MAAU,EAAO,IAAM,IAAW,KAAK,IAAW,CAAK;IACvD;GACjB,CAAA;GACA,IAAa,KACV,kBAAC,GAAD;IACI,MAAM;IACM;IACZ,cAAc;IACd,YAAY,EAAO;GACtB,CAAA;EAEJ;;AAEb"}
|
|
1
|
+
{"version":3,"file":"DataTable.js","names":[],"sources":["../../../src/components/DataTable/DataTable.tsx"],"sourcesContent":["import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { HTMLAttributes, ReactNode } from \"react\";\nimport { cn } from \"@/utils/cn\";\nimport { compareValues } from \"@/utils/compare-values\";\nimport { usePagination } from \"@/hooks\";\nimport { useAnnounce } from \"@/hooks/use-announce\";\nimport { Table, type TableAlign, type TableColumn, type TablePriority } from \"../Table\";\nimport { Pagination } from \"../Pagination\";\nimport { SearchBar } from \"../SearchBar\";\nimport { EditableCell } from \"./EditableCell\";\nimport { DEFAULT_EDIT_LABELS, type CellCommitMove, type DataTableEditLabels } from \"./edit-labels\";\nimport styles from \"./DataTable.module.css\";\n\nexport type SortDirection = \"asc\" | \"desc\";\n\nexport interface DataTableSort<T> {\n key: keyof T;\n direction: SortDirection;\n}\n\n/** Input types an editable column can use. */\nexport type DataTableEditorType = \"text\" | \"number\" | \"date\" | \"email\" | \"tel\" | \"url\";\n\n/** One accepted cell edit, handed to `onCellChange`. */\nexport interface DataTableCellChange<T> {\n /** The row as it was before the edit. */\n row: T;\n /** Which column changed. */\n key: keyof T;\n /** The parsed new value. */\n value: unknown;\n /** The value that was displayed before the edit. */\n previous: unknown;\n /** Index of the row in the full `data` array. */\n rowIndex: number;\n}\n\n/**\n * Column definition for {@link DataTable}. Extends the headless {@link Table}\n * column shape with a typed `key`, opt-in sorting, opt-in inline editing, and the\n * visual options that are forwarded to the underlying Table cell.\n */\nexport interface DataTableColumn<T> {\n /** Property of the row this column reads from. Doubles as the cell key. */\n key: keyof T;\n /** Column heading. */\n header: ReactNode;\n /** Custom cell renderer. Defaults to `String(row[key])`. */\n render?: (row: T) => ReactNode;\n /** Enable click-to-sort on this column's header. */\n sortable?: boolean;\n /** Text alignment forwarded to the Table cell. */\n align?: TableAlign;\n /** Responsive visibility priority forwarded to the Table cell. */\n priority?: TablePriority;\n /** Fixed column width forwarded to the Table cell. */\n width?: string | number;\n /**\n * Let cells in this column be edited in place. Requires `onCellChange` on the\n * table; without it the column stays read-only.\n */\n editable?: boolean;\n /** Editor input type. Default `\"text\"`. */\n editorType?: DataTableEditorType;\n /** Text the editor opens with. Defaults to `String(value ?? \"\")`. */\n formatEdit?: (row: T) => string;\n /**\n * Turn the typed string into the stored value. Defaults to the trimmed string,\n * or `Number(raw)` when `editorType` is `\"number\"`.\n */\n parse?: (raw: string, row: T) => unknown;\n /** Return a message to reject the edit, or `null` to accept it. */\n validate?: (value: unknown, row: T) => string | null;\n}\n\nexport interface DataTableProps<T> extends HTMLAttributes<HTMLDivElement> {\n /** Full, unfiltered dataset. Sorting/filtering/pagination happen client-side. */\n data: T[];\n /** Column definitions. */\n columns: DataTableColumn<T>[];\n /** Rows per page. Default 10. */\n pageSize?: number;\n /** Render a search input above the table. Default false. */\n searchable?: boolean;\n /**\n * Keys to match the search term against. When omitted, every column whose\n * value is a string or number is searched.\n */\n searchKeys?: (keyof T)[];\n /** Initial sort applied before any header interaction. */\n initialSort?: DataTableSort<T>;\n /** Stable key extractor for rows. Defaults to the row index. */\n rowKey?: (row: T, index: number) => string | number;\n /** Content shown when no rows match. */\n emptyMessage?: ReactNode;\n /**\n * Persist an accepted cell edit. Return a promise: while it is pending the cell\n * already shows the new value, and a rejection rolls that back and surfaces the\n * error in the cell. Without this prop no column is editable.\n */\n onCellChange?: (change: DataTableCellChange<T>) => void | Promise<void>;\n /** Override the PT-BR copy of the editing affordances. */\n editLabels?: Partial<DataTableEditLabels>;\n}\n\n/** Identity of one cell, stable across re-renders and pagination. */\nfunction cellId(rowKeyValue: string | number, columnKey: PropertyKey): string {\n return `${String(rowKeyValue)}::${String(columnKey)}`;\n}\n\nfunction headerText<T>(column: DataTableColumn<T>): string {\n return typeof column.header === \"string\" ? column.header : String(column.key);\n}\n\n/**\n * Stateful, headless data table built on top of {@link Table}. Adds\n * client-side searching, click-to-sort columns, pagination and opt-in inline\n * editing while delegating all table markup to the underlying Table component.\n *\n * - Clicking a sortable header cycles asc → desc → unsorted.\n * - Search matches a case-insensitive substring across `searchKeys`\n * (or every string/number column when not provided).\n * - Pagination is hidden when the result fits on a single page.\n * - A column with `editable` renders a button that opens an inline editor;\n * `Enter` commits, `Escape` discards, `Tab` walks to the next editable cell.\n *\n * Editing is strictly opt-in: with no `editable` column (or no `onCellChange`) the\n * rendered markup is byte-for-byte what it was before the feature existed, which\n * matters because the component is published.\n *\n * ## Optimistic, with a visible rollback\n *\n * An accepted edit is shown immediately and `onCellChange` runs in the background.\n * If it rejects, the cell returns to the old value **and** shows the reason as a\n * `role=\"alert\"` tied to the cell. A silent revert is worse than no optimistic\n * update at all: the user watched their edit appear and has no reason to doubt it.\n *\n * The header memo depends on `columns`, `sort` and the editing state only:\n * `toggleSort` and the commit callbacks are recreated each render but always close\n * over the same setters, so including them would rebuild every header on every\n * render without changing behaviour. That is why `exhaustive-deps` is silenced on\n * that dependency array.\n */\nexport function DataTable<T>({\n data,\n columns,\n pageSize = 10,\n searchable = false,\n searchKeys,\n initialSort,\n rowKey = (_row, index) => index,\n emptyMessage,\n onCellChange,\n editLabels,\n className,\n ...rest\n}: DataTableProps<T>) {\n const [search, setSearch] = useState<string>(\"\");\n const [sort, setSort] = useState<DataTableSort<T> | null>(initialSort ?? null);\n const { page, setPage } = usePagination(1, pageSize);\n const announce = useAnnounce();\n\n const [editing, setEditing] = useState<string | null>(null);\n const [refocus, setRefocus] = useState<string | null>(null);\n const [overrides, setOverrides] = useState<Record<string, unknown>>({});\n const [errors, setErrors] = useState<Record<string, string>>({});\n const [saving, setSaving] = useState<Record<string, boolean>>({});\n\n const labels = useMemo<DataTableEditLabels>(\n () => ({ ...DEFAULT_EDIT_LABELS, ...editLabels }),\n [editLabels],\n );\n const editingEnabled = onCellChange !== undefined && columns.some((column) => column.editable);\n\n const effectiveSearchKeys = useMemo<(keyof T)[]>(() => {\n if (searchKeys && searchKeys.length > 0) return searchKeys;\n return columns\n .filter((column) => {\n const sample = data.find((row) => row[column.key] != null);\n const value = sample ? sample[column.key] : undefined;\n return typeof value === \"string\" || typeof value === \"number\";\n })\n .map((column) => column.key);\n }, [searchKeys, columns, data]);\n\n const filtered = useMemo<T[]>(() => {\n const term = search.trim().toLowerCase();\n if (!term || !searchable) return data;\n return data.filter((row) =>\n effectiveSearchKeys.some((key) => {\n const value = row[key];\n return value != null && String(value).toLowerCase().includes(term);\n }),\n );\n }, [data, search, searchable, effectiveSearchKeys]);\n\n const sorted = useMemo<T[]>(() => {\n if (!sort) return filtered;\n const factor = sort.direction === \"asc\" ? 1 : -1;\n return [...filtered].sort((a, b) => compareValues(a[sort.key], b[sort.key]) * factor);\n }, [filtered, sort]);\n\n const totalPages = Math.max(1, Math.ceil(sorted.length / pageSize));\n\n // Clamp the current page when the dataset shrinks (e.g. after filtering).\n useEffect(() => {\n if (page > totalPages) setPage(totalPages);\n }, [page, totalPages, setPage]);\n\n const safePage = Math.min(page, totalPages);\n const pageRows = useMemo<T[]>(() => {\n const start = (safePage - 1) * pageSize;\n return sorted.slice(start, start + pageSize);\n }, [sorted, safePage, pageSize]);\n\n function toggleSort(key: keyof T): void {\n setSort((current) => {\n if (!current || current.key !== key) return { key, direction: \"asc\" };\n if (current.direction === \"asc\") return { key, direction: \"desc\" };\n return null;\n });\n }\n\n const absoluteIndex = useCallback(\n (pageIndex: number) => (safePage - 1) * pageSize + pageIndex,\n [safePage, pageSize],\n );\n\n /**\n * Every editable cell on the page, row-major — the order `Tab` walks.\n *\n * Row-major and not column-major because a row is the record a user is\n * correcting; walking down a column would make them re-find their place on\n * every keystroke.\n */\n const editableCellIds = useMemo<string[]>(() => {\n if (!editingEnabled) return [];\n const ids: string[] = [];\n pageRows.forEach((row, index) => {\n const key = rowKey(row, absoluteIndex(index));\n for (const column of columns) {\n if (column.editable) ids.push(cellId(key, column.key));\n }\n });\n return ids;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [editingEnabled, pageRows, columns, absoluteIndex]);\n\n const displayed = useCallback(\n (row: T, column: DataTableColumn<T>, id: string): unknown =>\n id in overrides ? overrides[id] : row[column.key],\n [overrides],\n );\n\n /**\n * Run the caller's `onCellChange` behind the optimistic update.\n *\n * Only the *success* is announced. The failure already renders as a\n * `role=\"alert\"` inside the cell, which screen readers read on insertion —\n * announcing it again from the shared region would read it twice and put the\n * same text in the document twice.\n */\n const persist = useCallback(\n async (id: string, column: DataTableColumn<T>, change: DataTableCellChange<T>) => {\n setSaving((current) => ({ ...current, [id]: true }));\n try {\n await onCellChange?.(change);\n announce(labels.saved(headerText(column)));\n } catch (error) {\n setOverrides((current) => {\n const next = { ...current };\n delete next[id];\n return next;\n });\n const message =\n error instanceof Error && error.message\n ? error.message\n : labels.saveFailed(headerText(column));\n setErrors((current) => ({ ...current, [id]: message }));\n } finally {\n setSaving((current) => {\n const next = { ...current };\n delete next[id];\n return next;\n });\n }\n },\n [onCellChange, announce, labels],\n );\n\n const moveFrom = useCallback(\n (id: string, move: CellCommitMove): void => {\n if (move === \"none\") {\n setEditing(null);\n setRefocus(id);\n return;\n }\n const index = editableCellIds.indexOf(id);\n const target = editableCellIds[index + (move === \"next\" ? 1 : -1)];\n if (target === undefined) {\n setEditing(null);\n setRefocus(id);\n return;\n }\n setEditing(target);\n setRefocus(null);\n },\n [editableCellIds],\n );\n\n /**\n * Parse, validate, stage optimistically, then save in the background.\n *\n * Validation runs before anything is staged, and a rejection leaves the editor\n * open with the message attached to the input — the user has to be able to fix\n * what they typed without retyping it.\n */\n const commit = useCallback(\n (\n row: T,\n column: DataTableColumn<T>,\n id: string,\n pageIndex: number,\n raw: string,\n move: CellCommitMove,\n ): void => {\n const previous = displayed(row, column, id);\n const currentText = column.formatEdit ? column.formatEdit(row) : String(previous ?? \"\");\n if (raw === currentText) {\n moveFrom(id, move);\n return;\n }\n\n const value = column.parse\n ? column.parse(raw, row)\n : column.editorType === \"number\"\n ? Number(raw)\n : raw.trim();\n\n const invalid = column.validate?.(value, row) ?? null;\n if (invalid) {\n setErrors((current) => ({ ...current, [id]: invalid }));\n return;\n }\n\n setErrors((current) => {\n const next = { ...current };\n delete next[id];\n return next;\n });\n setOverrides((current) => ({ ...current, [id]: value }));\n moveFrom(id, move);\n void persist(id, column, {\n row,\n key: column.key,\n value,\n previous,\n rowIndex: absoluteIndex(pageIndex),\n });\n },\n [displayed, moveFrom, persist, absoluteIndex],\n );\n\n const tableColumns = useMemo<TableColumn<T>[]>(\n () =>\n columns.map((column) => {\n const isSorted = sort?.key === column.key;\n const indicator = isSorted ? (sort?.direction === \"asc\" ? \" ▲\" : \" ▼\") : \"\";\n const header = column.sortable ? (\n <button\n type=\"button\"\n className={styles.sortButton}\n onClick={() => toggleSort(column.key)}\n aria-label={`Ordenar por ${headerText(column)}`}\n >\n {column.header}\n <span className={styles.sortIndicator} aria-hidden>\n {indicator}\n </span>\n </button>\n ) : (\n column.header\n );\n\n const plainCell = (row: T): ReactNode => {\n if (column.render) return column.render(row);\n return (row[column.key] as ReactNode) ?? null;\n };\n\n /**\n * Render an editable cell's content against the optimistic value.\n *\n * The row is shallow-patched rather than the value passed alongside it,\n * because a column with a custom `render` (a `<Money>`, a badge) reads\n * the row — handing it the stale row would show the old number under a\n * cell the user just changed.\n */\n const patchedCell = (row: T, value: unknown): ReactNode => {\n const patched = { ...row, [column.key]: value } as T;\n if (column.render) return column.render(patched);\n return (patched[column.key] as ReactNode) ?? null;\n };\n\n const editable = editingEnabled && column.editable === true;\n\n return {\n key: String(column.key),\n header,\n align: column.align,\n priority: column.priority,\n width: column.width,\n render: editable\n ? (row: T, index: number) => {\n const id = cellId(rowKey(row, absoluteIndex(index)), column.key);\n const value = displayed(row, column, id);\n const text = column.formatEdit\n ? column.formatEdit(row)\n : String(value ?? \"\");\n return (\n <EditableCell\n text={text}\n columnLabel={headerText(column)}\n rowNumber={index + 1}\n inputType={column.editorType ?? \"text\"}\n editing={editing === id}\n refocus={refocus === id}\n saving={saving[id] === true}\n error={errors[id] ?? null}\n errorId={`tempest-cell-error-${id.replace(/[^\\w-]/g, \"_\")}`}\n labels={labels}\n onOpen={() => {\n setEditing(id);\n setRefocus(null);\n }}\n onCommit={(raw, move) =>\n commit(row, column, id, index, raw, move)\n }\n onCancel={() => {\n setEditing(null);\n setRefocus(id);\n setErrors((current) => {\n const next = { ...current };\n delete next[id];\n return next;\n });\n }}\n >\n {patchedCell(row, value)}\n </EditableCell>\n );\n }\n : plainCell,\n };\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n columns,\n sort,\n editingEnabled,\n editing,\n refocus,\n saving,\n errors,\n labels,\n overrides,\n absoluteIndex,\n commit,\n ],\n );\n\n return (\n <div className={cn(styles.wrapper, className)} {...rest}>\n {searchable && (\n <SearchBar\n value={search}\n onChange={(value) => {\n setSearch(value);\n setPage(1);\n }}\n wrapperClassName={styles.search}\n />\n )}\n <Table\n columns={tableColumns}\n data={pageRows}\n rowKey={(row, index) => rowKey(row, absoluteIndex(index))}\n emptyMessage={emptyMessage}\n />\n {totalPages > 1 && (\n <Pagination\n page={safePage}\n totalPages={totalPages}\n onPageChange={setPage}\n totalItems={sorted.length}\n />\n )}\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;;;AA0GA,SAAS,EAAO,GAA8B,GAAgC;CAC1E,OAAO,GAAG,OAAO,CAAW,EAAE,IAAI,OAAO,CAAS;AACtD;AAEA,SAAS,EAAc,GAAoC;CACvD,OAAO,OAAO,EAAO,UAAW,WAAW,EAAO,SAAS,OAAO,EAAO,GAAG;AAChF;AA+BA,SAAgB,EAAa,EACzB,SACA,YACA,cAAW,IACX,gBAAa,IACb,eACA,iBACA,aAAU,GAAM,MAAU,GAC1B,kBACA,iBACA,eACA,cACA,GAAG,MACe;CAClB,IAAM,CAAC,GAAQ,MAAa,EAAiB,EAAE,GACzC,CAAC,GAAM,MAAW,EAAkC,MAAe,IAAI,GACvE,EAAE,SAAM,eAAY,EAAc,GAAG,CAAQ,GAC7C,IAAW,EAAY,GAEvB,CAAC,GAAS,KAAc,EAAwB,IAAI,GACpD,CAAC,GAAS,KAAc,EAAwB,IAAI,GACpD,CAAC,GAAW,KAAgB,EAAkC,CAAC,CAAC,GAChE,CAAC,GAAQ,KAAa,EAAiC,CAAC,CAAC,GACzD,CAAC,GAAQ,KAAa,EAAkC,CAAC,CAAC,GAE1D,IAAS,SACJ;EAAE,GAAG;EAAqB,GAAG;CAAW,IAC/C,CAAC,CAAU,CACf,GACM,IAAiB,MAAiB,KAAA,KAAa,EAAQ,MAAM,MAAW,EAAO,QAAQ,GAEvF,IAAsB,QACpB,KAAc,EAAW,SAAS,IAAU,IACzC,EACF,QAAQ,MAAW;EAChB,IAAM,IAAS,EAAK,MAAM,MAAQ,EAAI,EAAO,QAAQ,IAAI,GACnD,IAAQ,IAAS,EAAO,EAAO,OAAO,KAAA;EAC5C,OAAO,OAAO,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ACA;CACJ,CACJ;CAEA,OACI,kBAAC,OAAD;EAAK,WAAW,EAAG,EAAO,SAAS,CAAS;EAAG,GAAI;YAAnD;GACK,KACG,kBAAC,GAAD;IACI,OAAO;IACP,WAAW,MAAU;KAEjB,AADA,GAAU,CAAK,GACf,EAAQ,CAAC;IACb;IACA,kBAAkB,EAAO;GAC5B,CAAA;GAEL,kBAAC,GAAD;IACI,SAAS;IACT,MAAM;IACN,SAAS,GAAK,MAAU,EAAO,GAAK,EAAc,CAAK,CAAC;IAC1C;GACjB,CAAA;GACA,IAAa,KACV,kBAAC,GAAD;IACI,MAAM;IACM;IACZ,cAAc;IACd,YAAY,EAAO;GACtB,CAAA;EAEJ;;AAEb"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e=`tempest_wrapper_iB6ka`,t=`tempest_search_2y-yM`,n=`tempest_sortButton_9p6w4`,r=`tempest_sortIndicator_bZMlH`,i={wrapper:e,search:t,sortButton:n,sortIndicator:r};exports.
|
|
1
|
+
var e=`tempest_wrapper_iB6ka`,t=`tempest_search_2y-yM`,n=`tempest_sortButton_9p6w4`,r=`tempest_sortIndicator_bZMlH`,i=`tempest_cellWrap_8-ugE`,a=`tempest_cellButton_BgVe-`,o=`tempest_cellButtonInvalid_6MDdd`,s=`tempest_cellEditor_LfeJW`,c=`tempest_cellEditorInvalid_J7e2W`,l=`tempest_cellError_CRf3e`,u={wrapper:e,search:t,sortButton:n,sortIndicator:r,cellWrap:i,cellButton:a,cellButtonInvalid:o,cellEditor:s,cellEditorInvalid:c,cellError:l};exports.cellButton=a,exports.cellButtonInvalid=o,exports.cellEditor=s,exports.cellEditorInvalid=c,exports.cellError=l,exports.cellWrap=i,exports.default=u,exports.search=t,exports.sortButton=n,exports.sortIndicator=r,exports.wrapper=e;
|
|
2
2
|
//# sourceMappingURL=DataTable.module.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DataTable.module.cjs","names":[],"sources":["../../../src/components/DataTable/DataTable.module.css"],"sourcesContent":[".wrapper {\n display: flex;\n flex-direction: column;\n gap: var(--tempest-space-3, 0.75rem);\n}\n\n.search {\n max-width: 20rem;\n}\n\n.sortButton {\n display: inline-flex;\n align-items: center;\n gap: 0.25rem;\n padding: 0;\n border: none;\n background: none;\n font: inherit;\n color: inherit;\n cursor: pointer;\n user-select: none;\n}\n\n.sortIndicator {\n font-size: 0.75em;\n opacity: 0.7;\n}\n"],"mappings":""}
|
|
1
|
+
{"version":3,"file":"DataTable.module.cjs","names":[],"sources":["../../../src/components/DataTable/DataTable.module.css"],"sourcesContent":[".wrapper {\n display: flex;\n flex-direction: column;\n gap: var(--tempest-space-3, 0.75rem);\n}\n\n.search {\n max-width: 20rem;\n}\n\n.sortButton {\n display: inline-flex;\n align-items: center;\n gap: 0.25rem;\n padding: 0;\n border: none;\n background: none;\n font: inherit;\n color: inherit;\n cursor: pointer;\n user-select: none;\n}\n\n.sortIndicator {\n font-size: 0.75em;\n opacity: 0.7;\n}\n\n/* ── Inline editing ─────────────────────────────────────────────────────────── */\n\n.cellWrap {\n display: flex;\n flex-direction: column;\n gap: var(--tempest-space-1, 0.25rem);\n align-items: stretch;\n width: 100%;\n}\n\n.cellButton {\n position: relative;\n display: block;\n width: 100%;\n margin: calc(-1 * var(--tempest-space-1, 0.25rem)) calc(-1 * var(--tempest-space-2, 0.5rem));\n padding: var(--tempest-space-1, 0.25rem) var(--tempest-space-2, 0.5rem);\n border: 1px dashed transparent;\n border-radius: var(--tempest-radius-sm, 0.25rem);\n background: none;\n font: inherit;\n color: inherit;\n text-align: inherit;\n cursor: pointer;\n}\n\n/*\n * A resting affordance, not only a hover one: on a touch screen there is no hover,\n * so an editable cell that looks exactly like a read-only one is undiscoverable.\n * The dashed underline is the weakest mark that still says \"this is editable\"; hover\n * and focus then promote it to a full box.\n */\n.cellButton {\n border-bottom-color: var(--tempest-border-strong);\n}\n\n.cellButton:hover {\n border-color: var(--tempest-border-strong);\n background-color: var(--tempest-surface-2);\n}\n\n.cellButton:focus-visible {\n outline: none;\n border-color: transparent;\n box-shadow: 0 0 0 var(--tempest-focus-ring-width) var(--tempest-focus-ring-color);\n}\n\n.cellButtonInvalid {\n border-color: var(--tempest-danger-border);\n}\n\n/*\n * Touch: grow the hit area to the cell's own padding — exactly `--tempest-space-3`\n * vertically and `--tempest-space-4` horizontally in `Table.module.css` — so the\n * whole `<td>` is tappable and the target clears 44px without spilling into the\n * neighbouring row, which a symmetric slop would do in a dense table.\n */\n@media (pointer: coarse) {\n .cellButton::after {\n content: \"\";\n position: absolute;\n inset-block: calc(-1 * var(--tempest-space-3, 0.75rem));\n inset-inline: calc(-1 * var(--tempest-space-4, 1rem));\n }\n}\n\n.cellButton[aria-busy=\"true\"] {\n opacity: 0.6;\n}\n\n.cellEditor {\n width: 100%;\n min-width: 0;\n margin: calc(-1 * var(--tempest-space-1, 0.25rem)) calc(-1 * var(--tempest-space-2, 0.5rem));\n padding: var(--tempest-space-1, 0.25rem) var(--tempest-space-2, 0.5rem);\n border: 1px solid var(--tempest-border-strong);\n border-radius: var(--tempest-radius-sm, 0.25rem);\n background-color: var(--tempest-bg);\n font: inherit;\n color: var(--tempest-text);\n}\n\n.cellEditor:focus {\n outline: none;\n box-shadow: 0 0 0 var(--tempest-focus-ring-width) var(--tempest-focus-ring-color);\n}\n\n.cellEditorInvalid {\n border-color: var(--tempest-danger-border);\n}\n\n/*\n * The message sits on a tinted fill because `--tempest-danger-fg` over\n * `--tempest-danger-bg` is a pair `contrast.test.ts` verifies in both themes;\n * danger text straight onto the table background is not.\n */\n.cellError {\n padding: 0.125rem var(--tempest-space-2, 0.5rem);\n border-radius: var(--tempest-radius-sm, 0.25rem);\n background-color: var(--tempest-danger-bg);\n color: var(--tempest-danger-fg);\n font-size: var(--tempest-font-size-sm, 0.8125rem);\n line-height: 1.4;\n white-space: normal;\n}\n"],"mappings":""}
|
|
@@ -1,11 +1,17 @@
|
|
|
1
1
|
//#region src/components/DataTable/DataTable.module.css
|
|
2
|
-
var e = "tempest_wrapper_iB6ka", t = "tempest_search_2y-yM", n = "tempest_sortButton_9p6w4", r = "tempest_sortIndicator_bZMlH", i = {
|
|
2
|
+
var e = "tempest_wrapper_iB6ka", t = "tempest_search_2y-yM", n = "tempest_sortButton_9p6w4", r = "tempest_sortIndicator_bZMlH", i = "tempest_cellWrap_8-ugE", a = "tempest_cellButton_BgVe-", o = "tempest_cellButtonInvalid_6MDdd", s = "tempest_cellEditor_LfeJW", c = "tempest_cellEditorInvalid_J7e2W", l = "tempest_cellError_CRf3e", u = {
|
|
3
3
|
wrapper: e,
|
|
4
4
|
search: t,
|
|
5
5
|
sortButton: n,
|
|
6
|
-
sortIndicator: r
|
|
6
|
+
sortIndicator: r,
|
|
7
|
+
cellWrap: i,
|
|
8
|
+
cellButton: a,
|
|
9
|
+
cellButtonInvalid: o,
|
|
10
|
+
cellEditor: s,
|
|
11
|
+
cellEditorInvalid: c,
|
|
12
|
+
cellError: l
|
|
7
13
|
};
|
|
8
14
|
//#endregion
|
|
9
|
-
export { i as default, t as search, n as sortButton, r as sortIndicator, e as wrapper };
|
|
15
|
+
export { a as cellButton, o as cellButtonInvalid, s as cellEditor, c as cellEditorInvalid, l as cellError, i as cellWrap, u as default, t as search, n as sortButton, r as sortIndicator, e as wrapper };
|
|
10
16
|
|
|
11
17
|
//# sourceMappingURL=DataTable.module.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DataTable.module.js","names":[],"sources":["../../../src/components/DataTable/DataTable.module.css"],"sourcesContent":[".wrapper {\n display: flex;\n flex-direction: column;\n gap: var(--tempest-space-3, 0.75rem);\n}\n\n.search {\n max-width: 20rem;\n}\n\n.sortButton {\n display: inline-flex;\n align-items: center;\n gap: 0.25rem;\n padding: 0;\n border: none;\n background: none;\n font: inherit;\n color: inherit;\n cursor: pointer;\n user-select: none;\n}\n\n.sortIndicator {\n font-size: 0.75em;\n opacity: 0.7;\n}\n"],"mappings":""}
|
|
1
|
+
{"version":3,"file":"DataTable.module.js","names":[],"sources":["../../../src/components/DataTable/DataTable.module.css"],"sourcesContent":[".wrapper {\n display: flex;\n flex-direction: column;\n gap: var(--tempest-space-3, 0.75rem);\n}\n\n.search {\n max-width: 20rem;\n}\n\n.sortButton {\n display: inline-flex;\n align-items: center;\n gap: 0.25rem;\n padding: 0;\n border: none;\n background: none;\n font: inherit;\n color: inherit;\n cursor: pointer;\n user-select: none;\n}\n\n.sortIndicator {\n font-size: 0.75em;\n opacity: 0.7;\n}\n\n/* ── Inline editing ─────────────────────────────────────────────────────────── */\n\n.cellWrap {\n display: flex;\n flex-direction: column;\n gap: var(--tempest-space-1, 0.25rem);\n align-items: stretch;\n width: 100%;\n}\n\n.cellButton {\n position: relative;\n display: block;\n width: 100%;\n margin: calc(-1 * var(--tempest-space-1, 0.25rem)) calc(-1 * var(--tempest-space-2, 0.5rem));\n padding: var(--tempest-space-1, 0.25rem) var(--tempest-space-2, 0.5rem);\n border: 1px dashed transparent;\n border-radius: var(--tempest-radius-sm, 0.25rem);\n background: none;\n font: inherit;\n color: inherit;\n text-align: inherit;\n cursor: pointer;\n}\n\n/*\n * A resting affordance, not only a hover one: on a touch screen there is no hover,\n * so an editable cell that looks exactly like a read-only one is undiscoverable.\n * The dashed underline is the weakest mark that still says \"this is editable\"; hover\n * and focus then promote it to a full box.\n */\n.cellButton {\n border-bottom-color: var(--tempest-border-strong);\n}\n\n.cellButton:hover {\n border-color: var(--tempest-border-strong);\n background-color: var(--tempest-surface-2);\n}\n\n.cellButton:focus-visible {\n outline: none;\n border-color: transparent;\n box-shadow: 0 0 0 var(--tempest-focus-ring-width) var(--tempest-focus-ring-color);\n}\n\n.cellButtonInvalid {\n border-color: var(--tempest-danger-border);\n}\n\n/*\n * Touch: grow the hit area to the cell's own padding — exactly `--tempest-space-3`\n * vertically and `--tempest-space-4` horizontally in `Table.module.css` — so the\n * whole `<td>` is tappable and the target clears 44px without spilling into the\n * neighbouring row, which a symmetric slop would do in a dense table.\n */\n@media (pointer: coarse) {\n .cellButton::after {\n content: \"\";\n position: absolute;\n inset-block: calc(-1 * var(--tempest-space-3, 0.75rem));\n inset-inline: calc(-1 * var(--tempest-space-4, 1rem));\n }\n}\n\n.cellButton[aria-busy=\"true\"] {\n opacity: 0.6;\n}\n\n.cellEditor {\n width: 100%;\n min-width: 0;\n margin: calc(-1 * var(--tempest-space-1, 0.25rem)) calc(-1 * var(--tempest-space-2, 0.5rem));\n padding: var(--tempest-space-1, 0.25rem) var(--tempest-space-2, 0.5rem);\n border: 1px solid var(--tempest-border-strong);\n border-radius: var(--tempest-radius-sm, 0.25rem);\n background-color: var(--tempest-bg);\n font: inherit;\n color: var(--tempest-text);\n}\n\n.cellEditor:focus {\n outline: none;\n box-shadow: 0 0 0 var(--tempest-focus-ring-width) var(--tempest-focus-ring-color);\n}\n\n.cellEditorInvalid {\n border-color: var(--tempest-danger-border);\n}\n\n/*\n * The message sits on a tinted fill because `--tempest-danger-fg` over\n * `--tempest-danger-bg` is a pair `contrast.test.ts` verifies in both themes;\n * danger text straight onto the table background is not.\n */\n.cellError {\n padding: 0.125rem var(--tempest-space-2, 0.5rem);\n border-radius: var(--tempest-radius-sm, 0.25rem);\n background-color: var(--tempest-danger-bg);\n color: var(--tempest-danger-fg);\n font-size: var(--tempest-font-size-sm, 0.8125rem);\n line-height: 1.4;\n white-space: normal;\n}\n"],"mappings":""}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("../../utils/cn.cjs"),t=require("../VisuallyHidden/VisuallyHidden.cjs"),n=require("./DataTable.module.cjs");let r=require("react"),i=require("react/jsx-runtime");function a({initial:t,type:a,label:o,describedBy:s,invalid:c,onCommit:l,onCancel:u}){let[d,f]=(0,r.useState)(t),p=(0,r.useRef)(!1);function m(e){p.current=!0,l(d,e)}function h(e){if(e.key===`Enter`){e.preventDefault(),m(`none`);return}if(e.key===`Escape`){e.preventDefault(),p.current=!0,u();return}e.key===`Tab`&&(e.preventDefault(),m(e.shiftKey?`previous`:`next`))}return(0,i.jsx)(`input`,{autoFocus:!0,className:e.cn(n.default.cellEditor,c&&n.default.cellEditorInvalid),type:a,value:d,"aria-label":o,"aria-invalid":c||void 0,"aria-describedby":s,onChange:e=>{p.current=!1,f(e.target.value)},onKeyDown:h,onBlur:()=>{p.current||m(`none`)}})}function o({children:o,text:s,columnLabel:c,rowNumber:l,inputType:u,editing:d,refocus:f,saving:p,error:m,errorId:h,labels:g,onOpen:_,onCommit:v,onCancel:y}){let b=(0,r.useRef)(null),x=(0,r.useRef)(!1);return(0,r.useEffect)(()=>{!d&&x.current&&f&&b.current?.focus(),x.current=d},[d,f]),(0,i.jsxs)(`span`,{className:n.default.cellWrap,children:[d?(0,i.jsx)(a,{initial:s,type:u,label:g.editor(c,l),describedBy:m?h:void 0,invalid:m!==null,onCommit:v,onCancel:y}):(0,i.jsxs)(`button`,{ref:b,type:`button`,className:e.cn(n.default.cellButton,m&&n.default.cellButtonInvalid),"aria-describedby":m?h:void 0,"aria-busy":p||void 0,onClick:_,children:[(0,i.jsx)(t.VisuallyHidden,{children:g.editCell(c)}),` `,o]}),m&&(0,i.jsx)(`span`,{className:n.default.cellError,id:h,role:`alert`,children:m})]})}exports.EditableCell=o;
|
|
2
|
+
//# sourceMappingURL=EditableCell.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"EditableCell.cjs","names":[],"sources":["../../../src/components/DataTable/EditableCell.tsx"],"sourcesContent":["import { useEffect, useRef, useState } from \"react\";\nimport type { KeyboardEvent, ReactNode } from \"react\";\nimport { cn } from \"@/utils/cn\";\nimport { VisuallyHidden } from \"../VisuallyHidden\";\nimport type { CellCommitMove, DataTableEditLabels } from \"./edit-labels\";\nimport styles from \"./DataTable.module.css\";\n\ninterface CellEditorProps {\n /** Text the editor opens with. */\n initial: string;\n /** `<input type>` for the editor. */\n type: string;\n /** Accessible name. */\n label: string;\n /** Id of the message element, when there is one. */\n describedBy?: string;\n /** Whether the current draft was rejected by validation. */\n invalid: boolean;\n /** Commit the draft. The parent decides whether the editor closes. */\n onCommit: (raw: string, move: CellCommitMove) => void;\n /** Discard the draft. */\n onCancel: () => void;\n}\n\n/**\n * The `<input>` half of an editable cell.\n *\n * A separate component so it **mounts fresh** every time a cell opens: the draft\n * then starts from the current value through `useState`'s initialiser, with no\n * effect syncing props into state and no render where the draft is stale.\n *\n * `Tab` is intercepted rather than left to the browser. Default tab order would\n * walk into the next row's trigger button, which is one keystroke away from the\n * next *editor* — and in a table the reader is editing, moving cell to cell is the\n * expected behaviour. `Escape` discards; `Enter` commits and closes; blur commits,\n * because clicking away from a half-typed cell and losing the typing is a data-loss\n * bug users report as \"the table ate my edit\".\n *\n * `autoFocus` is safe here in a way it is not on page load: the editor only exists\n * because the user just clicked the cell or pressed `Tab` into it, so focus is\n * following the interaction rather than stealing it.\n *\n * The `settled` flag stops a keyboard commit from being repeated by the blur that\n * follows it. Typing clears the flag again, because after a commit the parent\n * rejected — the only case where the editor is still open and focused — the draft is\n * live once more, and dropping *that* edit on blur would be the same data loss the\n * blur-commits rule exists to prevent.\n */\nfunction CellEditor({\n initial,\n type,\n label,\n describedBy,\n invalid,\n onCommit,\n onCancel,\n}: CellEditorProps) {\n const [draft, setDraft] = useState<string>(initial);\n const settled = useRef(false);\n\n function finish(move: CellCommitMove): void {\n settled.current = true;\n onCommit(draft, move);\n }\n\n function handleKeyDown(event: KeyboardEvent<HTMLInputElement>): void {\n if (event.key === \"Enter\") {\n event.preventDefault();\n finish(\"none\");\n return;\n }\n if (event.key === \"Escape\") {\n event.preventDefault();\n settled.current = true;\n onCancel();\n return;\n }\n if (event.key === \"Tab\") {\n event.preventDefault();\n finish(event.shiftKey ? \"previous\" : \"next\");\n }\n }\n\n return (\n <input\n autoFocus\n className={cn(styles.cellEditor, invalid && styles.cellEditorInvalid)}\n type={type}\n value={draft}\n aria-label={label}\n aria-invalid={invalid || undefined}\n aria-describedby={describedBy}\n onChange={(event) => {\n settled.current = false;\n setDraft(event.target.value);\n }}\n onKeyDown={handleKeyDown}\n onBlur={() => {\n if (settled.current) return;\n finish(\"none\");\n }}\n />\n );\n}\n\nexport interface EditableCellProps {\n /** Rendered value, used when the cell is closed. */\n children: ReactNode;\n /** Plain-text value, for the editor's initial draft and the trigger's name. */\n text: string;\n /** Header text of this column, for accessible names. */\n columnLabel: string;\n /** 1-based row number on the current page. */\n rowNumber: number;\n /** `<input type>` for the editor. */\n inputType: string;\n /** Whether this cell owns the open editor. */\n editing: boolean;\n /** Return focus to the trigger when the editor closes (Enter/Escape, not Tab). */\n refocus: boolean;\n /** A save is in flight for this cell. */\n saving: boolean;\n /** Validation or save error to surface, or null. */\n error: string | null;\n /** Stable id used for `aria-describedby` on the input and the trigger. */\n errorId: string;\n /** Copy for the affordances. */\n labels: DataTableEditLabels;\n /** Open the editor. */\n onOpen: () => void;\n /** Commit a draft. */\n onCommit: (raw: string, move: CellCommitMove) => void;\n /** Close without committing. */\n onCancel: () => void;\n}\n\n/**\n * One cell of a {@link DataTable} column marked `editable`.\n *\n * Closed, it is a button carrying the value — a plain `<td>` with a click handler\n * would be invisible to a keyboard and unnamed to a screen reader, and a\n * `tabIndex`-only cell announces no role. Open, it is an `<input>`.\n *\n * The button's name comes from its **contents**: a visually hidden \"Editar {coluna}:\"\n * in front of whatever the column rendered. An `aria-label` built from the raw value\n * would read \"850000\" over a cell showing `R$ 8.500,00`, which fails WCAG 2.5.3 (Label\n * in Name) and leaves voice control unable to address the cell by what it says.\n *\n * The error message is a `role=\"alert\"` tied to the input (and to the trigger once\n * the editor closes) through `aria-describedby`, so a rejected save is announced and\n * then still reachable — an optimistic update that rolls back silently leaves the\n * user believing the edit stuck.\n */\nexport function EditableCell({\n children,\n text,\n columnLabel,\n rowNumber,\n inputType,\n editing,\n refocus,\n saving,\n error,\n errorId,\n labels,\n onOpen,\n onCommit,\n onCancel,\n}: EditableCellProps) {\n const trigger = useRef<HTMLButtonElement | null>(null);\n const wasEditing = useRef(false);\n\n useEffect(() => {\n if (!editing && wasEditing.current && refocus) trigger.current?.focus();\n wasEditing.current = editing;\n }, [editing, refocus]);\n\n return (\n <span className={styles.cellWrap}>\n {editing ? (\n <CellEditor\n initial={text}\n type={inputType}\n label={labels.editor(columnLabel, rowNumber)}\n describedBy={error ? errorId : undefined}\n invalid={error !== null}\n onCommit={onCommit}\n onCancel={onCancel}\n />\n ) : (\n <button\n ref={trigger}\n type=\"button\"\n className={cn(styles.cellButton, error && styles.cellButtonInvalid)}\n aria-describedby={error ? errorId : undefined}\n aria-busy={saving || undefined}\n onClick={onOpen}\n >\n <VisuallyHidden>{labels.editCell(columnLabel)}</VisuallyHidden> {children}\n </button>\n )}\n {error && (\n <span className={styles.cellError} id={errorId} role=\"alert\">\n {error}\n </span>\n )}\n </span>\n );\n}\n"],"mappings":"kLAgDA,SAAS,EAAW,CAChB,UACA,OACA,QACA,cACA,UACA,WACA,YACgB,CAChB,GAAM,CAAC,EAAO,IAAA,EAAA,EAAA,SAAA,CAA6B,CAAO,EAC5C,GAAA,EAAA,EAAA,OAAA,CAAiB,EAAK,EAE5B,SAAS,EAAO,EAA4B,CACxC,EAAQ,QAAU,GAClB,EAAS,EAAO,CAAI,CACxB,CAEA,SAAS,EAAc,EAA8C,CACjE,GAAI,EAAM,MAAQ,QAAS,CACvB,EAAM,eAAe,EACrB,EAAO,MAAM,EACb,MACJ,CACA,GAAI,EAAM,MAAQ,SAAU,CACxB,EAAM,eAAe,EACrB,EAAQ,QAAU,GAClB,EAAS,EACT,MACJ,CACI,EAAM,MAAQ,QACd,EAAM,eAAe,EACrB,EAAO,EAAM,SAAW,WAAa,MAAM,EAEnD,CAEA,OACI,EAAA,EAAA,IAAA,CAAC,QAAD,CACI,UAAA,GACA,UAAW,EAAA,GAAG,EAAA,QAAO,WAAY,GAAW,EAAA,QAAO,iBAAiB,EAC9D,OACN,MAAO,EACP,aAAY,EACZ,eAAc,GAAW,IAAA,GACzB,mBAAkB,EAClB,SAAW,GAAU,CACjB,EAAQ,QAAU,GACl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