@middag-io/react 0.45.0 → 0.45.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.
Files changed (321) hide show
  1. package/README.md +4 -3
  2. package/docs/public/schemas/ai-contract-manifest.json +1820 -0
  3. package/docs/public/schemas/blocks.json +445 -0
  4. package/docs/public/schemas/components.json +166 -0
  5. package/docs/public/schemas/connectors.json +97 -0
  6. package/docs/public/schemas/fragment.json +2329 -0
  7. package/docs/public/schemas/manifest.json +119 -0
  8. package/docs/public/schemas/navigation.json +72 -0
  9. package/docs/public/schemas/page-contract.json +2329 -0
  10. package/docs/public/schemas/shared-props.json +118 -0
  11. package/docs/public/schemas/theme-defaults.json +253 -0
  12. package/docs/public/schemas/theme.json +401 -0
  13. package/package.json +109 -3
  14. package/src/assets/lottie/calendar/schedule-1.json +1 -0
  15. package/src/assets/lottie/calendar/schedule-2.json +1 -0
  16. package/src/assets/lottie/celebration/confetti-1.json +1 -0
  17. package/src/assets/lottie/celebration/confetti-2.json +1 -0
  18. package/src/assets/lottie/celebration/confetti-3.json +1 -0
  19. package/src/assets/lottie/cloud/cloud-1.json +1 -0
  20. package/src/assets/lottie/cloud/cloud-2.json +1 -0
  21. package/src/assets/lottie/connection/network-1.json +1 -0
  22. package/src/assets/lottie/connection/network-2.json +1 -0
  23. package/src/assets/lottie/connection/network-3.json +1 -0
  24. package/src/assets/lottie/dashboard/analytics-1.json +1 -0
  25. package/src/assets/lottie/dashboard/analytics-2.json +1 -0
  26. package/src/assets/lottie/dashboard/analytics-3.json +1 -0
  27. package/src/assets/lottie/email/mail-1.json +1 -0
  28. package/src/assets/lottie/email/mail-2.json +1 -0
  29. package/src/assets/lottie/email/mail-3.json +1 -0
  30. package/src/assets/lottie/empty-state/empty-1.json +1 -0
  31. package/src/assets/lottie/empty-state/empty-2.json +1 -0
  32. package/src/assets/lottie/empty-state/empty-3.json +1 -0
  33. package/src/assets/lottie/error/warning-1.json +1 -0
  34. package/src/assets/lottie/error/warning-2.json +1 -0
  35. package/src/assets/lottie/error/warning-3.json +1 -0
  36. package/src/assets/lottie/index.ts +49 -0
  37. package/src/assets/lottie/loading/spinner-1.json +1 -0
  38. package/src/assets/lottie/loading/spinner-2.json +1 -0
  39. package/src/assets/lottie/loading/spinner-3.json +1 -0
  40. package/src/assets/lottie/maintenance/construction-1.json +1 -0
  41. package/src/assets/lottie/maintenance/construction-2.json +1 -0
  42. package/src/assets/lottie/maintenance/construction-3.json +1 -0
  43. package/src/assets/lottie/not-found/404-1.json +1 -0
  44. package/src/assets/lottie/not-found/404-2.json +1 -0
  45. package/src/assets/lottie/not-found/404-3.json +1 -0
  46. package/src/assets/lottie/notification/bell-1.json +1 -0
  47. package/src/assets/lottie/notification/bell-2.json +1 -0
  48. package/src/assets/lottie/notification/bell-3.json +1 -0
  49. package/src/assets/lottie/onboarding/welcome-1.json +1 -0
  50. package/src/assets/lottie/onboarding/welcome-2.json +1 -0
  51. package/src/assets/lottie/onboarding/welcome-3.json +1 -0
  52. package/src/assets/lottie/payment/wallet-1.json +1 -0
  53. package/src/assets/lottie/payment/wallet-2.json +1 -0
  54. package/src/assets/lottie/payment/wallet-3.json +1 -0
  55. package/src/assets/lottie/search/search-1.json +1 -0
  56. package/src/assets/lottie/search/search-2.json +1 -0
  57. package/src/assets/lottie/search/search-3.json +1 -0
  58. package/src/assets/lottie/security/lock-1.json +1 -0
  59. package/src/assets/lottie/security/lock-2.json +1 -0
  60. package/src/assets/lottie/security/lock-3.json +1 -0
  61. package/src/assets/lottie/settings/gear-1.json +1 -0
  62. package/src/assets/lottie/settings/gear-2.json +1 -0
  63. package/src/assets/lottie/settings/gear-3.json +1 -0
  64. package/src/assets/lottie/success/check-1.json +1 -0
  65. package/src/assets/lottie/success/check-2.json +1 -0
  66. package/src/assets/lottie/success/check-3.json +1 -0
  67. package/src/assets/lottie/upload/upload-1.json +1 -0
  68. package/src/assets/lottie/upload/upload-2.json +1 -0
  69. package/src/assets/lottie/upload/upload-3.json +1 -0
  70. package/src/assets/lottie/user/profile-1.json +1 -0
  71. package/src/assets/lottie/user/profile-2.json +1 -0
  72. package/src/assets/lottie/user/profile-3.json +1 -0
  73. package/src/base/blocks/ActionGridBlock.tsx +151 -0
  74. package/src/base/blocks/ActivityTimelineBlock.tsx +180 -0
  75. package/src/base/blocks/CardGridBlock.tsx +384 -0
  76. package/src/base/blocks/ChartBlock.tsx +81 -0
  77. package/src/base/blocks/DenseTableBlock.tsx +403 -0
  78. package/src/base/blocks/DetailPanelBlock.tsx +189 -0
  79. package/src/base/blocks/EmptyStateBlock.tsx +46 -0
  80. package/src/base/blocks/FormPanelBlock.lazy.tsx +38 -0
  81. package/src/base/blocks/FormPanelBlock.tsx +480 -0
  82. package/src/base/blocks/LinkListBlock.tsx +94 -0
  83. package/src/base/blocks/MarkdownPanelBlock.tsx +60 -0
  84. package/src/base/blocks/MetricCardBlock.tsx +128 -0
  85. package/src/base/blocks/StatusStripBlock.tsx +43 -0
  86. package/src/base/blocks/TabsBlock.tsx +94 -0
  87. package/src/base/form/FormField.tsx +607 -0
  88. package/src/base/form/fields/CheckboxField.tsx +56 -0
  89. package/src/base/form/fields/ColorField.tsx +76 -0
  90. package/src/base/form/fields/CurrencyField.tsx +126 -0
  91. package/src/base/form/fields/DateField.tsx +168 -0
  92. package/src/base/form/fields/DateRangeField.tsx +66 -0
  93. package/src/base/form/fields/DocumentField.tsx +222 -0
  94. package/src/base/form/fields/EntityPickerField.tsx +244 -0
  95. package/src/base/form/fields/FileUploadField.tsx +253 -0
  96. package/src/base/form/fields/MultiSelectField.tsx +286 -0
  97. package/src/base/form/fields/NativeSelectField.tsx +67 -0
  98. package/src/base/form/fields/NumberField.tsx +67 -0
  99. package/src/base/form/fields/OtpField.tsx +88 -0
  100. package/src/base/form/fields/PasswordField.tsx +69 -0
  101. package/src/base/form/fields/PhoneField.tsx +64 -0
  102. package/src/base/form/fields/RadioField.tsx +66 -0
  103. package/src/base/form/fields/RatingField.tsx +52 -0
  104. package/src/base/form/fields/SelectField.tsx +76 -0
  105. package/src/base/form/fields/SliderField.tsx +77 -0
  106. package/src/base/form/fields/SlugField.tsx +114 -0
  107. package/src/base/form/fields/StaticField.tsx +25 -0
  108. package/src/base/form/fields/SwitchField.tsx +56 -0
  109. package/src/base/form/fields/TagsField.tsx +128 -0
  110. package/src/base/form/fields/TextField.tsx +55 -0
  111. package/src/base/form/fields/TextareaField.tsx +55 -0
  112. package/src/base/form/fields/document-validation.ts +126 -0
  113. package/src/base/form/fields/field-registry.ts +53 -0
  114. package/src/base/form/fields/register-default-fields.ts +86 -0
  115. package/src/base/form/form-schema-builder.ts +192 -0
  116. package/src/base/form/form-utils.ts +71 -0
  117. package/src/base/hooks/useIsDark.ts +50 -0
  118. package/src/base/hooks/useLazyTabs.ts +98 -0
  119. package/src/base/hooks/usePolling.ts +43 -0
  120. package/src/base/hooks/useRemember.ts +58 -0
  121. package/src/base/hooks/useToast.ts +27 -0
  122. package/src/base/layout/BlockRegion.tsx +39 -0
  123. package/src/base/layout/DashboardLayout.tsx +110 -0
  124. package/src/base/layout/SidebarLayout.tsx +38 -0
  125. package/src/base/layout/StackLayout.tsx +32 -0
  126. package/src/base/layout/WizardLayout.tsx +49 -0
  127. package/src/base/partials/ActionBar/index.tsx +115 -0
  128. package/src/base/partials/ConfirmationDialog/index.tsx +128 -0
  129. package/src/base/partials/DataTable/cell-registry.ts +50 -0
  130. package/src/base/partials/DataTable/cell-renderers.tsx +372 -0
  131. package/src/base/partials/DataTable/index.tsx +1282 -0
  132. package/src/base/partials/DataTable/register-default-cells.ts +37 -0
  133. package/src/base/partials/DataTable/sanitize-html.ts +45 -0
  134. package/src/base/partials/DataTable/types.ts +229 -0
  135. package/src/base/partials/DetailSection/index.tsx +316 -0
  136. package/src/base/partials/EmptyPlaceholder/index.tsx +162 -0
  137. package/src/base/partials/EntityItem/index.tsx +154 -0
  138. package/src/base/partials/FilterBar/index.tsx +256 -0
  139. package/src/base/partials/FormSection/index.tsx +87 -0
  140. package/src/base/partials/LogViewer/JsonBlock.tsx +39 -0
  141. package/src/base/partials/LogViewer/LogEntry.tsx +68 -0
  142. package/src/base/partials/LogViewer/LogViewerToolbar.tsx +71 -0
  143. package/src/base/partials/LogViewer/index.tsx +110 -0
  144. package/src/base/partials/LogViewer/types.ts +28 -0
  145. package/src/base/partials/MarkdownContent/index.tsx +307 -0
  146. package/src/base/partials/MenuBar/index.tsx +80 -0
  147. package/src/base/partials/QuickRecordSheet/index.tsx +59 -0
  148. package/src/base/partials/ResizableSidebar/index.tsx +70 -0
  149. package/src/base/partials/StatRow/index.tsx +28 -0
  150. package/src/base/partials/StatusBar/index.tsx +126 -0
  151. package/src/base/partials/StatusIndicator/index.tsx +61 -0
  152. package/src/base/partials/StepIndicator/index.tsx +63 -0
  153. package/src/base/partials/TableOfContents/index.tsx +78 -0
  154. package/src/base/partials/TimelineList/index.tsx +273 -0
  155. package/src/base/partials/ToggleGroupControl/index.tsx +100 -0
  156. package/src/base/partials/TreeView/index.tsx +75 -0
  157. package/src/base/partials/index.ts +23 -0
  158. package/src/base/shell/AuthShell.tsx +54 -0
  159. package/src/base/shell/BasicShell.tsx +286 -0
  160. package/src/base/shell/ImmersiveShell.tsx +85 -0
  161. package/src/base/shell/partials/EditablePanelContext.tsx +82 -0
  162. package/src/base/shell/partials/EditablePanelProvider.tsx +122 -0
  163. package/src/base/shell/partials/InlineEditablePanel.tsx +239 -0
  164. package/src/base/shell/partials/InspectorContext.tsx +173 -0
  165. package/src/base/shell/partials/InspectorPanel.tsx +65 -0
  166. package/src/base/shell/partials/NavErrorBoundary.tsx +82 -0
  167. package/src/base/shell/partials/OverlayScreen.tsx +67 -0
  168. package/src/base/shell/partials/PageActionButton.tsx +203 -0
  169. package/src/base/theme/appearance.ts +133 -0
  170. package/src/base/theme/host-layout-detector.ts +119 -0
  171. package/src/base/theme/host-theme-detector.ts +146 -0
  172. package/src/base/theme/sidebar-safelist.txt +20 -0
  173. package/src/base/theme/tailwind-theme.css +136 -0
  174. package/src/base/theme/theme-bridge.css +164 -0
  175. package/src/base/theme/theme-context.tsx +142 -0
  176. package/src/base/theme/themes/classic.css +174 -0
  177. package/src/base/theme/tokens.css +290 -0
  178. package/src/base/theme/useHostTheme.ts +95 -0
  179. package/src/base/utils/clipboard.ts +39 -0
  180. package/src/base/utils/conditions.ts +27 -0
  181. package/src/base/utils/icon-registry.ts +78 -0
  182. package/src/base/utils/icons.ts +31 -0
  183. package/src/base/utils/interpolate.ts +9 -0
  184. package/src/base/utils/register-default-icons.ts +163 -0
  185. package/src/base/utils/storage.ts +65 -0
  186. package/src/base/utils/time.ts +139 -0
  187. package/src/contracts/block-data/actions.ts +73 -0
  188. package/src/contracts/block-data/data-display.ts +343 -0
  189. package/src/contracts/block-data/form.ts +164 -0
  190. package/src/contracts/block-data/index.ts +15 -0
  191. package/src/contracts/block-data/interactive.ts +34 -0
  192. package/src/contracts/block-data/shared.ts +44 -0
  193. package/src/contracts/connectors.ts +60 -0
  194. package/src/contracts/generated/contract-schema.ts +1237 -0
  195. package/src/contracts/generated/contract-types.ts +675 -0
  196. package/src/contracts/generated/index.ts +15 -0
  197. package/src/contracts/navigation.ts +59 -0
  198. package/src/contracts/page-contract-schema.ts +40 -0
  199. package/src/contracts/page-contract.ts +79 -0
  200. package/src/contracts/shared-props.ts +92 -0
  201. package/src/engine/ContractPage.tsx +178 -0
  202. package/src/engine/EntityRoutes.tsx +72 -0
  203. package/src/engine/HostSlot.tsx +126 -0
  204. package/src/engine/LazyBlock.tsx +92 -0
  205. package/src/engine/bootstrap.tsx +20 -0
  206. package/src/engine/providers/auth.tsx +87 -0
  207. package/src/engine/providers/error-reporter.tsx +89 -0
  208. package/src/engine/providers/flash.tsx +44 -0
  209. package/src/engine/providers/index.ts +18 -0
  210. package/src/engine/providers/inertia-error-reporter.tsx +61 -0
  211. package/src/engine/providers/progress.tsx +56 -0
  212. package/src/engine/providers/scope.tsx +51 -0
  213. package/src/engine/register-defaults.ts +88 -0
  214. package/src/engine/registries.ts +96 -0
  215. package/src/i18n/I18nProvider.tsx +53 -0
  216. package/src/i18n/MANIFEST.md +101 -0
  217. package/src/i18n/host-resolver.ts +18 -0
  218. package/src/i18n/instance.ts +69 -0
  219. package/src/i18n/locales/en/ui.json +277 -0
  220. package/src/i18n/locales/en/validators.json +13 -0
  221. package/src/i18n/locales/pt-BR/ui.json +277 -0
  222. package/src/i18n/locales/pt-BR/validators.json +13 -0
  223. package/src/i18n/register-strings.ts +10 -0
  224. package/src/i18n/render-label.ts +33 -0
  225. package/src/i18n/resolve-field-error.ts +29 -0
  226. package/src/i18n/useHostString.ts +50 -0
  227. package/src/i18n/useTranslation.ts +83 -0
  228. package/src/lib/actions/resolve-action-target.ts +151 -0
  229. package/src/lib/hooks/use-copy-to-clipboard.ts +37 -0
  230. package/src/lib/hooks/use-file-upload.ts +406 -0
  231. package/src/lib/hooks/use-mobile.ts +21 -0
  232. package/src/lib/host-pending.ts +76 -0
  233. package/src/lib/portal-container.ts +16 -0
  234. package/src/lib/test-ids.ts +40 -0
  235. package/src/lib/utils.ts +6 -0
  236. package/src/primitives/reui/MANIFEST.md +97 -0
  237. package/src/primitives/reui/accordion.tsx +64 -0
  238. package/src/primitives/reui/alert-dialog.tsx +196 -0
  239. package/src/primitives/reui/alert.tsx +92 -0
  240. package/src/primitives/reui/aspect-ratio.tsx +9 -0
  241. package/src/primitives/reui/autocomplete.tsx +343 -0
  242. package/src/primitives/reui/avatar.tsx +109 -0
  243. package/src/primitives/reui/badge.tsx +94 -0
  244. package/src/primitives/reui/breadcrumb.tsx +109 -0
  245. package/src/primitives/reui/button-group.tsx +83 -0
  246. package/src/primitives/reui/button.tsx +64 -0
  247. package/src/primitives/reui/calendar.tsx +220 -0
  248. package/src/primitives/reui/card.tsx +92 -0
  249. package/src/primitives/reui/carousel.tsx +239 -0
  250. package/src/primitives/reui/chart.tsx +388 -0
  251. package/src/primitives/reui/checkbox.tsx +30 -0
  252. package/src/primitives/reui/collapsible.tsx +31 -0
  253. package/src/primitives/reui/combobox.tsx +308 -0
  254. package/src/primitives/reui/command.tsx +182 -0
  255. package/src/primitives/reui/context-menu.tsx +250 -0
  256. package/src/primitives/reui/data-grid/data-grid-column-filter.tsx +172 -0
  257. package/src/primitives/reui/data-grid/data-grid-column-header.tsx +420 -0
  258. package/src/primitives/reui/data-grid/data-grid-column-visibility.tsx +51 -0
  259. package/src/primitives/reui/data-grid/data-grid-pagination.tsx +235 -0
  260. package/src/primitives/reui/data-grid/data-grid-scroll-area.tsx +427 -0
  261. package/src/primitives/reui/data-grid/data-grid-table-dnd-rows.tsx +308 -0
  262. package/src/primitives/reui/data-grid/data-grid-table-dnd.tsx +318 -0
  263. package/src/primitives/reui/data-grid/data-grid-table-virtual.tsx +491 -0
  264. package/src/primitives/reui/data-grid/data-grid-table.tsx +1430 -0
  265. package/src/primitives/reui/data-grid/data-grid.tsx +269 -0
  266. package/src/primitives/reui/data-grid-pagination.tsx +235 -0
  267. package/src/primitives/reui/date-selector.tsx +1353 -0
  268. package/src/primitives/reui/dialog.tsx +158 -0
  269. package/src/primitives/reui/drawer.tsx +133 -0
  270. package/src/primitives/reui/dropdown-menu.tsx +257 -0
  271. package/src/primitives/reui/empty.tsx +104 -0
  272. package/src/primitives/reui/field.tsx +246 -0
  273. package/src/primitives/reui/filters.tsx +1891 -0
  274. package/src/primitives/reui/frame.tsx +170 -0
  275. package/src/primitives/reui/hover-card.tsx +42 -0
  276. package/src/primitives/reui/icon-placeholder.tsx +39 -0
  277. package/src/primitives/reui/index.ts +98 -0
  278. package/src/primitives/reui/input-group.tsx +170 -0
  279. package/src/primitives/reui/input-otp.tsx +75 -0
  280. package/src/primitives/reui/input.tsx +21 -0
  281. package/src/primitives/reui/item.tsx +193 -0
  282. package/src/primitives/reui/kanban.tsx +743 -0
  283. package/src/primitives/reui/kbd.tsx +28 -0
  284. package/src/primitives/reui/label.tsx +22 -0
  285. package/src/primitives/reui/menubar.tsx +274 -0
  286. package/src/primitives/reui/native-select.tsx +62 -0
  287. package/src/primitives/reui/navigation-menu.tsx +168 -0
  288. package/src/primitives/reui/number-field.tsx +250 -0
  289. package/src/primitives/reui/pagination.tsx +127 -0
  290. package/src/primitives/reui/phone-input.tsx +231 -0
  291. package/src/primitives/reui/popover.tsx +87 -0
  292. package/src/primitives/reui/progress.tsx +31 -0
  293. package/src/primitives/reui/radio-group.tsx +43 -0
  294. package/src/primitives/reui/rating.tsx +177 -0
  295. package/src/primitives/reui/resizable.tsx +51 -0
  296. package/src/primitives/reui/scroll-area.tsx +58 -0
  297. package/src/primitives/reui/scrollspy.tsx +240 -0
  298. package/src/primitives/reui/select.tsx +188 -0
  299. package/src/primitives/reui/separator.tsx +28 -0
  300. package/src/primitives/reui/sheet.tsx +141 -0
  301. package/src/primitives/reui/sidebar.tsx +732 -0
  302. package/src/primitives/reui/skeleton.tsx +13 -0
  303. package/src/primitives/reui/slider.tsx +61 -0
  304. package/src/primitives/reui/sonner.tsx +47 -0
  305. package/src/primitives/reui/sortable.tsx +414 -0
  306. package/src/primitives/reui/spinner.tsx +16 -0
  307. package/src/primitives/reui/stepper.tsx +484 -0
  308. package/src/primitives/reui/svgs/claudeAiIcon.tsx +12 -0
  309. package/src/primitives/reui/svgs/gemini.tsx +171 -0
  310. package/src/primitives/reui/svgs/openai.tsx +9 -0
  311. package/src/primitives/reui/svgs/openaiDark.tsx +12 -0
  312. package/src/primitives/reui/switch.tsx +33 -0
  313. package/src/primitives/reui/table.tsx +114 -0
  314. package/src/primitives/reui/tabs.tsx +91 -0
  315. package/src/primitives/reui/textarea.tsx +18 -0
  316. package/src/primitives/reui/timeline.tsx +219 -0
  317. package/src/primitives/reui/toggle-group.tsx +83 -0
  318. package/src/primitives/reui/toggle.tsx +45 -0
  319. package/src/primitives/reui/tooltip.tsx +55 -0
  320. package/src/primitives/reui/tree.tsx +247 -0
  321. package/src/theme.css +71 -0
@@ -0,0 +1,1282 @@
1
+ /**
2
+ * DataTable — high-level table partial wrapping ReUI DataGrid.
3
+ *
4
+ * Features: search, filters, column visibility, sorting, row selection,
5
+ * bulk actions, row actions, skeleton loading, empty state, mobile card layout.
6
+ *
7
+ * @see NV-05-ux-blocks.md
8
+ */
9
+
10
+ import {
11
+ useCallback,
12
+ useEffect,
13
+ useMemo,
14
+ useRef,
15
+ useState,
16
+ type ReactElement,
17
+ type ReactNode,
18
+ } from "react";
19
+ import { MoreHorizontalIcon, SlidersHorizontalIcon } from "@hugeicons/core-free-icons";
20
+ import { HugeiconsIcon, type IconSvgElement } from "@hugeicons/react";
21
+ import {
22
+ flexRender,
23
+ getCoreRowModel,
24
+ getFilteredRowModel,
25
+ getPaginationRowModel,
26
+ getSortedRowModel,
27
+ useReactTable,
28
+ type ColumnDef,
29
+ type RowSelectionState,
30
+ type SortingState,
31
+ type VisibilityState,
32
+ } from "@tanstack/react-table";
33
+
34
+ import { useRemember } from "@/base/hooks/useRemember";
35
+ import { EmptyPlaceholder } from "@/base/partials/EmptyPlaceholder";
36
+ import { FilterBar } from "@/base/partials/FilterBar";
37
+ import { getIcon } from "@/base/utils/icons";
38
+ import { renderLabel } from "@/i18n/render-label";
39
+ import { useTranslation } from "@/i18n/useTranslation";
40
+ import { rowActionTestId, rowTestId, TEST_IDS } from "@/lib/test-ids";
41
+ import { cn } from "@/lib/utils";
42
+ import { Button } from "@/primitives/reui/button";
43
+ import { Checkbox } from "@/primitives/reui/checkbox";
44
+ import {
45
+ DropdownMenu,
46
+ DropdownMenuCheckboxItem,
47
+ DropdownMenuContent,
48
+ DropdownMenuItem,
49
+ DropdownMenuLabel,
50
+ DropdownMenuSeparator,
51
+ DropdownMenuTrigger,
52
+ } from "@/primitives/reui/dropdown-menu";
53
+ import { Skeleton } from "@/primitives/reui/skeleton";
54
+
55
+ import { resolveCellRenderer } from "./cell-registry";
56
+ import type {
57
+ DataTableColumn,
58
+ DataTableParamChange,
59
+ DataTableProps,
60
+ DataTableRowAction,
61
+ } from "./types";
62
+
63
+ // ---------------------------------------------------------------------------
64
+ // Null-safe text fallback (used when no cell renderer is registered)
65
+ // ---------------------------------------------------------------------------
66
+
67
+ function NullSafe({ children }: { children: unknown }): ReactElement {
68
+ if (children == null || children === "") {
69
+ return <span className="text-muted-foreground">&mdash;</span>;
70
+ }
71
+ return <>{String(children)}</>;
72
+ }
73
+
74
+ // ---------------------------------------------------------------------------
75
+ // Row action overlay
76
+ // ---------------------------------------------------------------------------
77
+
78
+ function RowActionButtons<TData>({
79
+ row,
80
+ actions,
81
+ }: {
82
+ row: TData;
83
+ actions: DataTableRowAction<TData>[];
84
+ }): ReactElement {
85
+ const { t } = useTranslation();
86
+ const visible = actions.filter((a) => !a.hidden?.(row));
87
+ if (visible.length === 0) return <></>;
88
+
89
+ const inline = visible.slice(0, 2);
90
+ const overflow = visible.slice(2);
91
+
92
+ return (
93
+ <div className="flex items-center justify-end gap-1">
94
+ {inline.map((action) => {
95
+ const isDisabled = action.disabled?.(row) ?? false;
96
+ const isLoading = action.loading?.(row) ?? false;
97
+ const reason = action.disabledReason?.(row);
98
+ const isButton = action.variant === "button";
99
+
100
+ return (
101
+ <Button
102
+ key={action.id}
103
+ data-testid={rowActionTestId(action.id)}
104
+ variant={isButton ? (action.intent === "danger" ? "destructive" : "outline") : "ghost"}
105
+ size={isButton ? "xs" : "icon-xs"}
106
+ onClick={(e) => {
107
+ e.stopPropagation();
108
+ if (!isDisabled && !isLoading) action.onAction(row);
109
+ }}
110
+ title={isDisabled && reason ? reason : action.label}
111
+ disabled={isDisabled || isLoading}
112
+ className={cn(
113
+ !isButton && action.intent === "danger" && "text-destructive hover:text-destructive",
114
+ )}
115
+ >
116
+ {isLoading ? (
117
+ <svg
118
+ className="size-3.5 animate-spin"
119
+ xmlns="http://www.w3.org/2000/svg"
120
+ fill="none"
121
+ viewBox="0 0 24 24"
122
+ >
123
+ <circle
124
+ className="opacity-25"
125
+ cx="12"
126
+ cy="12"
127
+ r="10"
128
+ stroke="currentColor"
129
+ strokeWidth="4"
130
+ />
131
+ <path
132
+ className="opacity-75"
133
+ fill="currentColor"
134
+ d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
135
+ />
136
+ </svg>
137
+ ) : action.icon ? (
138
+ <HugeiconsIcon
139
+ icon={getIcon(action.icon) as unknown as IconSvgElement}
140
+ className="size-3.5"
141
+ />
142
+ ) : null}
143
+ {isButton && <span className="text-xs">{action.label}</span>}
144
+ </Button>
145
+ );
146
+ })}
147
+ {overflow.length > 0 && (
148
+ <DropdownMenu>
149
+ <DropdownMenuTrigger asChild>
150
+ <Button
151
+ variant="ghost"
152
+ size="icon-xs"
153
+ data-testid={TEST_IDS.rowActionsMenu}
154
+ aria-label={t("middag.ui.table.row_actions")}
155
+ onClick={(e) => e.stopPropagation()}
156
+ >
157
+ <HugeiconsIcon icon={MoreHorizontalIcon} className="size-3.5" />
158
+ </Button>
159
+ </DropdownMenuTrigger>
160
+ <DropdownMenuContent align="end">
161
+ {overflow.map((action) => {
162
+ const isDisabled = action.disabled?.(row) ?? false;
163
+ const isLoading = action.loading?.(row) ?? false;
164
+
165
+ return (
166
+ <DropdownMenuItem
167
+ key={action.id}
168
+ data-testid={rowActionTestId(action.id)}
169
+ onClick={() => {
170
+ if (!isDisabled && !isLoading) action.onAction(row);
171
+ }}
172
+ disabled={isDisabled || isLoading}
173
+ className={cn(action.intent === "danger" && "text-destructive")}
174
+ >
175
+ {action.icon && (
176
+ <HugeiconsIcon
177
+ icon={getIcon(action.icon) as unknown as IconSvgElement}
178
+ className="mr-2 size-3.5"
179
+ />
180
+ )}
181
+ {action.label}
182
+ </DropdownMenuItem>
183
+ );
184
+ })}
185
+ </DropdownMenuContent>
186
+ </DropdownMenu>
187
+ )}
188
+ </div>
189
+ );
190
+ }
191
+
192
+ // ---------------------------------------------------------------------------
193
+ // Skeleton width classes for column meta
194
+ // ---------------------------------------------------------------------------
195
+
196
+ const SKELETON_WIDTHS = ["w-3/4", "w-1/2", "w-2/3", "w-5/6", "w-1/3"];
197
+
198
+ // ---------------------------------------------------------------------------
199
+ // Mobile card layout
200
+ // ---------------------------------------------------------------------------
201
+
202
+ function MobileCardView<TData>({
203
+ rows,
204
+ columns,
205
+ rowKey,
206
+ rowActions,
207
+ rowSelection,
208
+ onToggleRow,
209
+ hasBulkActions,
210
+ onRowClick,
211
+ t,
212
+ }: {
213
+ rows: TData[];
214
+ columns: DataTableColumn<TData>[];
215
+ rowKey: (row: TData) => string;
216
+ rowActions?: DataTableRowAction<TData>[];
217
+ rowSelection: RowSelectionState;
218
+ onToggleRow: (key: string) => void;
219
+ hasBulkActions: boolean;
220
+ onRowClick?: (row: TData) => void;
221
+ t: (key: string) => string;
222
+ }): ReactElement {
223
+ return (
224
+ <div className="flex flex-col gap-3 p-3">
225
+ {rows.map((row) => {
226
+ const key = rowKey(row);
227
+ const isSelected = !!rowSelection[key];
228
+ const clickable = !!onRowClick;
229
+
230
+ return (
231
+ <div
232
+ key={key}
233
+ data-testid={rowTestId(key)}
234
+ className={cn(
235
+ "space-y-2 rounded-lg border p-4 transition-colors",
236
+ clickable && "hover:border-primary/50 cursor-pointer",
237
+ isSelected && "bg-muted/50 border-primary/30",
238
+ )}
239
+ role={clickable ? "button" : undefined}
240
+ tabIndex={clickable ? 0 : undefined}
241
+ onClick={clickable ? () => onRowClick(row) : undefined}
242
+ onKeyDown={
243
+ clickable
244
+ ? (e) => {
245
+ if (e.key === "Enter" || e.key === " ") {
246
+ e.preventDefault();
247
+ onRowClick(row);
248
+ }
249
+ }
250
+ : undefined
251
+ }
252
+ >
253
+ <div className="flex items-start justify-between gap-2">
254
+ <div className="flex items-center gap-2">
255
+ {hasBulkActions && (
256
+ <Checkbox
257
+ checked={isSelected}
258
+ onCheckedChange={() => onToggleRow(key)}
259
+ onClick={(e) => e.stopPropagation()}
260
+ aria-label={t("middag.ui.table.select_row")}
261
+ />
262
+ )}
263
+ <span className="text-sm font-medium">
264
+ {columns[0] && renderCellValue(columns[0], row)}
265
+ </span>
266
+ </div>
267
+ {rowActions && rowActions.length > 0 && (
268
+ <RowActionButtons row={row} actions={rowActions} />
269
+ )}
270
+ </div>
271
+ <dl className="grid grid-cols-2 gap-x-4 gap-y-1.5 text-sm">
272
+ {columns.slice(1).map((col) => (
273
+ <div key={col.key}>
274
+ <dt className="text-muted-foreground text-xs">{col.label}</dt>
275
+ <dd>{renderCellValue(col, row)}</dd>
276
+ </div>
277
+ ))}
278
+ </dl>
279
+ </div>
280
+ );
281
+ })}
282
+ </div>
283
+ );
284
+ }
285
+
286
+ // ---------------------------------------------------------------------------
287
+ // Helpers
288
+ // ---------------------------------------------------------------------------
289
+
290
+ function getRowValue<TData>(row: TData, key: string): unknown {
291
+ return (row as Record<string, unknown>)[key];
292
+ }
293
+
294
+ function renderCellValue<TData>(col: DataTableColumn<TData>, row: TData): ReactNode {
295
+ const value = getRowValue(row, col.key);
296
+
297
+ if (col.render) return col.render(value, row);
298
+
299
+ if (col.type && col.type !== "text" && col.type !== "custom") {
300
+ const Renderer = resolveCellRenderer(col.type);
301
+ if (Renderer) {
302
+ return (
303
+ <Renderer
304
+ value={value}
305
+ row={row as unknown as Record<string, unknown>}
306
+ column={{
307
+ key: col.key,
308
+ href: col.href,
309
+ entityType: col.entityType,
310
+ entityIdField: col.entityIdField,
311
+ statusMap: col.statusMap,
312
+ timestampFormat: col.timestampFormat,
313
+ }}
314
+ />
315
+ );
316
+ }
317
+ }
318
+
319
+ return <NullSafe>{value}</NullSafe>;
320
+ }
321
+
322
+ function makeRowKey<TData>(rowKeyProp: DataTableProps<TData>["rowKey"]): (row: TData) => string {
323
+ if (typeof rowKeyProp === "function") return rowKeyProp;
324
+ return (row: TData) => String((row as Record<string, unknown>)[rowKeyProp as string]);
325
+ }
326
+
327
+ // ---------------------------------------------------------------------------
328
+ // useDebounce
329
+ // ---------------------------------------------------------------------------
330
+
331
+ function useDebounce(value: string, delay: number): string {
332
+ const [debounced, setDebounced] = useState(value);
333
+ useEffect(() => {
334
+ const id = setTimeout(() => setDebounced(value), delay);
335
+ return () => clearTimeout(id);
336
+ }, [value, delay]);
337
+ return debounced;
338
+ }
339
+
340
+ // ---------------------------------------------------------------------------
341
+ // Density toggle (compact / comfortable / spacious)
342
+ // ---------------------------------------------------------------------------
343
+
344
+ type DensityLevel = "compact" | "comfortable" | "spacious";
345
+ const DENSITY_HEIGHTS: Record<DensityLevel, string> = {
346
+ compact: "32px",
347
+ comfortable: "40px",
348
+ spacious: "48px",
349
+ };
350
+
351
+ /** Density icon SVGs — distinct line spacing per level */
352
+ const DENSITY_ICONS: Record<DensityLevel, ReactElement> = {
353
+ compact: (
354
+ <svg
355
+ viewBox="0 0 24 24"
356
+ fill="none"
357
+ stroke="currentColor"
358
+ strokeWidth={2}
359
+ className="h-3.5 w-3.5"
360
+ >
361
+ <line x1="4" y1="7" x2="20" y2="7" />
362
+ <line x1="4" y1="11" x2="20" y2="11" />
363
+ <line x1="4" y1="15" x2="20" y2="15" />
364
+ <line x1="4" y1="19" x2="20" y2="19" />
365
+ </svg>
366
+ ),
367
+ comfortable: (
368
+ <svg
369
+ viewBox="0 0 24 24"
370
+ fill="none"
371
+ stroke="currentColor"
372
+ strokeWidth={2}
373
+ className="h-3.5 w-3.5"
374
+ >
375
+ <line x1="4" y1="7" x2="20" y2="7" />
376
+ <line x1="4" y1="12" x2="20" y2="12" />
377
+ <line x1="4" y1="17" x2="20" y2="17" />
378
+ </svg>
379
+ ),
380
+ spacious: (
381
+ <svg
382
+ viewBox="0 0 24 24"
383
+ fill="none"
384
+ stroke="currentColor"
385
+ strokeWidth={2}
386
+ className="h-3.5 w-3.5"
387
+ >
388
+ <line x1="4" y1="8" x2="20" y2="8" />
389
+ <line x1="4" y1="16" x2="20" y2="16" />
390
+ </svg>
391
+ ),
392
+ };
393
+
394
+ function DensityToggle({
395
+ value,
396
+ onChange,
397
+ }: {
398
+ value: DensityLevel;
399
+ onChange: (d: DensityLevel) => void;
400
+ }): ReactElement {
401
+ const { t } = useTranslation();
402
+ const levels: DensityLevel[] = ["compact", "comfortable", "spacious"];
403
+ return (
404
+ <div
405
+ role="group"
406
+ aria-label={t("middag.ui.table.density")}
407
+ className="border-border/60 flex h-[30px] items-center gap-0 rounded-[5px] border p-0.5"
408
+ >
409
+ {levels.map((level) => {
410
+ const label = t(`middag.ui.table.density_${level}`);
411
+ return (
412
+ <button
413
+ key={level}
414
+ type="button"
415
+ onClick={() => onChange(level)}
416
+ aria-label={label}
417
+ aria-pressed={value === level}
418
+ title={label}
419
+ className={cn(
420
+ "flex items-center justify-center rounded px-1.5 py-1 transition-all",
421
+ value === level
422
+ ? "bg-accent text-primary"
423
+ : "text-muted-foreground hover:text-foreground",
424
+ )}
425
+ >
426
+ {DENSITY_ICONS[level]}
427
+ </button>
428
+ );
429
+ })}
430
+ </div>
431
+ );
432
+ }
433
+
434
+ // ---------------------------------------------------------------------------
435
+ // Minimal table column header (preview 03 style)
436
+ // ---------------------------------------------------------------------------
437
+
438
+ function MinimalColumnHeader<TData, TValue>({
439
+ column,
440
+ title,
441
+ }: {
442
+ column: import("@tanstack/react-table").Column<TData, TValue>;
443
+ title: string;
444
+ }): ReactElement {
445
+ const isSorted = column.getIsSorted();
446
+ const canSort = column.getCanSort();
447
+
448
+ const handleClick = () => {
449
+ if (!canSort) return;
450
+ if (isSorted === "asc") column.toggleSorting(true);
451
+ else if (isSorted === "desc") column.clearSorting();
452
+ else column.toggleSorting(false);
453
+ };
454
+
455
+ if (canSort) {
456
+ return (
457
+ <button
458
+ type="button"
459
+ onClick={handleClick}
460
+ className="text-muted-foreground hover:text-secondary-foreground flex h-full cursor-pointer items-center text-[11px] font-semibold tracking-[0.04em] whitespace-nowrap uppercase select-none"
461
+ >
462
+ {title}
463
+ <span
464
+ className={cn("ml-1 text-[9px]", isSorted ? "text-primary opacity-100" : "opacity-30")}
465
+ >
466
+ {isSorted === "desc" ? "\u25BC" : "\u25B2"}
467
+ </span>
468
+ </button>
469
+ );
470
+ }
471
+
472
+ return (
473
+ <div className="text-muted-foreground flex h-full items-center text-[11px] font-semibold tracking-[0.04em] whitespace-nowrap uppercase select-none">
474
+ {title}
475
+ </div>
476
+ );
477
+ }
478
+
479
+ // ---------------------------------------------------------------------------
480
+ // DataTable component
481
+ // ---------------------------------------------------------------------------
482
+
483
+ export function DataTable<TData extends object>({
484
+ columns,
485
+ rows,
486
+ rowKey: rowKeyProp,
487
+ pagination,
488
+ sort,
489
+ filters,
490
+ appliedFilters = {},
491
+ rowActions,
492
+ actionsAlwaysVisible = false,
493
+ bulkActions,
494
+ isLoading = false,
495
+ searchPlaceholder: _searchPlaceholder,
496
+ searchValue: controlledSearch = "",
497
+ emptyStateIcon,
498
+ emptyStateTitle: _emptyStateTitle,
499
+ emptyStateDescription,
500
+ emptyStateCTA,
501
+ onParamChange,
502
+ onBulkAction,
503
+ onSaveView,
504
+ savedView = false,
505
+ saveViewLabel,
506
+ onRowClick,
507
+ selectedRowKey,
508
+ remember = false,
509
+ rememberKey,
510
+ clientSide = false,
511
+ }: DataTableProps<TData> & { clientSide?: boolean }): ReactElement {
512
+ const { t } = useTranslation();
513
+ const emptyStateTitle = _emptyStateTitle ?? t("middag.ui.table.empty_title");
514
+ const getKey = useMemo(() => makeRowKey(rowKeyProp), [rowKeyProp]);
515
+
516
+ // -----------------------------------------------------------------------
517
+ // Local state
518
+ // -----------------------------------------------------------------------
519
+ const [searchInput, setSearchInput] = useState(controlledSearch);
520
+ const debouncedSearch = useDebounce(searchInput, 300);
521
+ const prevDebouncedRef = useRef(debouncedSearch);
522
+
523
+ // Client-side pagination state (only used when clientSide=true)
524
+ const [clientPagination, setClientPagination] = useState({
525
+ pageIndex: 0,
526
+ pageSize: pagination?.perPage ?? 10,
527
+ });
528
+
529
+ const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
530
+ // Column visibility + density are client-only view prefs (never sent to the
531
+ // server). useRemember persists them across history nav when the block opts
532
+ // in via `remember`; otherwise it is a plain useState (default).
533
+ const rememberScope = rememberKey ?? "datatable";
534
+ const [columnVisibility, setColumnVisibility] = useRemember<VisibilityState>(
535
+ () => {
536
+ const vis: VisibilityState = {};
537
+ for (const col of columns) {
538
+ if (col.visible === false) vis[col.key] = false;
539
+ }
540
+ return vis;
541
+ },
542
+ `${rememberScope}:columns`,
543
+ remember,
544
+ );
545
+ const [isMobile, setIsMobile] = useState(false);
546
+ const [density, setDensity] = useRemember<DensityLevel>(
547
+ "comfortable",
548
+ `${rememberScope}:density`,
549
+ remember,
550
+ );
551
+
552
+ // Sync controlled search prop
553
+ useEffect(() => {
554
+ setSearchInput(controlledSearch);
555
+ }, [controlledSearch]);
556
+
557
+ // Detect mobile breakpoint
558
+ useEffect(() => {
559
+ const mql = window.matchMedia("(max-width: 767px)");
560
+ const handler = (e: MediaQueryListEvent | MediaQueryList) => setIsMobile(e.matches);
561
+ handler(mql);
562
+ mql.addEventListener("change", handler as (e: MediaQueryListEvent) => void);
563
+ return () => mql.removeEventListener("change", handler as (e: MediaQueryListEvent) => void);
564
+ }, []);
565
+
566
+ // Emit search changes
567
+ useEffect(() => {
568
+ if (debouncedSearch !== prevDebouncedRef.current) {
569
+ prevDebouncedRef.current = debouncedSearch;
570
+ onParamChange?.({ search: debouncedSearch, page: 0 });
571
+ }
572
+ }, [debouncedSearch, onParamChange]);
573
+
574
+ // -----------------------------------------------------------------------
575
+ // Sorting bridge: DataTable sort <-> TanStack SortingState
576
+ // -----------------------------------------------------------------------
577
+ const initialSorting: SortingState = useMemo(
578
+ () => (sort ? [{ id: sort.key, desc: sort.direction === "desc" }] : []),
579
+ [sort],
580
+ );
581
+ const [clientSorting, setClientSorting] = useState<SortingState>(initialSorting);
582
+ const sortingState = clientSide ? clientSorting : initialSorting;
583
+
584
+ const handleSortingChange = useCallback(
585
+ (updater: SortingState | ((old: SortingState) => SortingState)) => {
586
+ const next = typeof updater === "function" ? updater(sortingState) : updater;
587
+ if (clientSide) {
588
+ setClientSorting(next);
589
+ return;
590
+ }
591
+ if (next.length === 0) {
592
+ onParamChange?.({ sort: null });
593
+ } else {
594
+ const s = next[0];
595
+ onParamChange?.({
596
+ sort: { key: s.id, direction: s.desc ? "desc" : "asc" },
597
+ });
598
+ }
599
+ },
600
+ [sortingState, onParamChange, clientSide],
601
+ );
602
+
603
+ // -----------------------------------------------------------------------
604
+ // Build TanStack column defs
605
+ // -----------------------------------------------------------------------
606
+ const hasBulkActions = bulkActions && bulkActions.length > 0;
607
+
608
+ // Sync inspector selectedRowKey into TanStack row selection for visual highlight
609
+ useEffect(() => {
610
+ if (selectedRowKey) {
611
+ setRowSelection({ [selectedRowKey]: true });
612
+ } else if (!hasBulkActions) {
613
+ setRowSelection({});
614
+ }
615
+ }, [selectedRowKey, hasBulkActions]);
616
+
617
+ const tanstackColumns = useMemo<ColumnDef<TData, unknown>[]>(() => {
618
+ const defs: ColumnDef<TData, unknown>[] = [];
619
+
620
+ // Selection column
621
+ if (hasBulkActions) {
622
+ defs.push({
623
+ id: "_select",
624
+ header: ({ table: tbl }) => (
625
+ <Checkbox
626
+ checked={
627
+ tbl.getIsAllPageRowsSelected() || (tbl.getIsSomePageRowsSelected() && "indeterminate")
628
+ }
629
+ onCheckedChange={(v) => tbl.toggleAllPageRowsSelected(!!v)}
630
+ aria-label={t("middag.ui.table.select_all")}
631
+ />
632
+ ),
633
+ cell: ({ row }) => (
634
+ <Checkbox
635
+ checked={row.getIsSelected()}
636
+ onCheckedChange={(v) => row.toggleSelected(!!v)}
637
+ onClick={(e) => e.stopPropagation()}
638
+ aria-label={t("middag.ui.table.select_row")}
639
+ />
640
+ ),
641
+ size: 40,
642
+ enableSorting: false,
643
+ enableHiding: false,
644
+ });
645
+ }
646
+
647
+ // Data columns
648
+ for (let colIdx = 0; colIdx < columns.length; colIdx++) {
649
+ const col = columns[colIdx];
650
+ const isFirstDataCol = colIdx === 0;
651
+ const isNumeric =
652
+ (col.type as string) === "number" ||
653
+ col.key === "acessos" ||
654
+ col.key === "records" ||
655
+ col.key === "seats_total" ||
656
+ col.key === "seats_usados";
657
+ defs.push({
658
+ id: col.key,
659
+ accessorFn: (row: TData) => getRowValue(row, col.key),
660
+ header: ({ column }) => <MinimalColumnHeader column={column} title={col.label} />,
661
+ cell: ({ row }) => {
662
+ // Capped columns clip to one line; uncapped ones keep wrapping, which
663
+ // is what every column did before the cap existed. The untouched value
664
+ // rides along as `title` so hovering still reveals it in full — the
665
+ // point of clipping in CSS rather than shortening the data.
666
+ const raw = col.maxWidth ? getRowValue(row.original, col.key) : undefined;
667
+ const full = typeof raw === "string" || typeof raw === "number" ? String(raw) : undefined;
668
+ return (
669
+ <span
670
+ className={cn(
671
+ "block text-[13px]",
672
+ col.maxWidth ? "w-full truncate" : "break-words",
673
+ isFirstDataCol && "font-medium",
674
+ isNumeric && "text-right tabular-nums",
675
+ )}
676
+ title={full}
677
+ >
678
+ {renderCellValue(col, row.original)}
679
+ </span>
680
+ );
681
+ },
682
+ size: col.width,
683
+ minSize: col.minWidth ?? 80,
684
+ maxSize: col.maxWidth ?? Number.MAX_SAFE_INTEGER,
685
+ enableSorting: col.sortable ?? false,
686
+ enableHiding: col.hideable !== false,
687
+ meta: {
688
+ headerTitle: col.label,
689
+ headerClassName: isNumeric ? "text-right" : undefined,
690
+ skeleton: (
691
+ <Skeleton
692
+ className={cn("h-4", SKELETON_WIDTHS[columns.indexOf(col) % SKELETON_WIDTHS.length])}
693
+ />
694
+ ),
695
+ },
696
+ });
697
+ }
698
+
699
+ // Row actions column
700
+ if (rowActions && rowActions.length > 0) {
701
+ defs.push({
702
+ id: "_actions",
703
+ header: () => null,
704
+ cell: ({ row }) => (
705
+ <div
706
+ className={
707
+ actionsAlwaysVisible ? "" : "opacity-0 transition-opacity group-hover/row:opacity-100"
708
+ }
709
+ >
710
+ <RowActionButtons row={row.original} actions={rowActions} />
711
+ </div>
712
+ ),
713
+ size: rowActions.some((a) => a.variant === "button")
714
+ ? Math.max(200, rowActions.filter((a) => a.variant === "button").length * 110)
715
+ : rowActions.length > 2
716
+ ? 120
717
+ : 80,
718
+ enableSorting: false,
719
+ enableHiding: false,
720
+ });
721
+ }
722
+
723
+ return defs;
724
+ }, [columns, hasBulkActions, rowActions, actionsAlwaysVisible, t]);
725
+
726
+ // -----------------------------------------------------------------------
727
+ // Row id map for TanStack row selection
728
+ // -----------------------------------------------------------------------
729
+ const getRowId = useCallback((row: TData) => getKey(row), [getKey]);
730
+
731
+ // -----------------------------------------------------------------------
732
+ // TanStack table instance
733
+ // -----------------------------------------------------------------------
734
+ // eslint-disable-next-line react-hooks/incompatible-library -- TanStack Table vs React Compiler known limitation
735
+ const table = useReactTable({
736
+ data: rows,
737
+ columns: tanstackColumns,
738
+ state: {
739
+ sorting: sortingState,
740
+ rowSelection,
741
+ columnVisibility,
742
+ ...(clientSide
743
+ ? { pagination: clientPagination, globalFilter: debouncedSearch }
744
+ : {
745
+ pagination: pagination
746
+ ? { pageIndex: pagination.page, pageSize: pagination.perPage }
747
+ : undefined,
748
+ }),
749
+ },
750
+ ...(clientSide
751
+ ? {}
752
+ : {
753
+ pageCount: pagination ? Math.ceil(pagination.total / pagination.perPage) : undefined,
754
+ }),
755
+ manualPagination: clientSide ? false : !!pagination,
756
+ manualSorting: clientSide ? false : true,
757
+ enableRowSelection: !!hasBulkActions || !!selectedRowKey,
758
+ enableGlobalFilter: clientSide,
759
+ // Match nested values (not just scalar cells) so object/array cells like the
760
+ // tag-chip column [{label, href}] are searchable by their label — the built-in
761
+ // includesString stringifies the whole cell ("[object Object]") and misses them.
762
+ // Collect VALUES only (never keys, to avoid every row matching a field name)
763
+ // and skip href/url to avoid link-text false positives.
764
+ globalFilterFn: (row, _columnId, filterValue) => {
765
+ if (filterValue == null || filterValue === "") return true;
766
+ const needle = String(filterValue).toLowerCase();
767
+ const collect = (v: unknown): string => {
768
+ if (v == null) return "";
769
+ if (Array.isArray(v)) return v.map(collect).join(" ");
770
+ if (typeof v === "object") {
771
+ return Object.entries(v as Record<string, unknown>)
772
+ .filter(([k]) => k !== "href" && k !== "url")
773
+ .map(([, val]) => collect(val))
774
+ .join(" ");
775
+ }
776
+ return String(v);
777
+ };
778
+ return collect(row.original).toLowerCase().includes(needle);
779
+ },
780
+ onSortingChange: handleSortingChange,
781
+ onRowSelectionChange: setRowSelection,
782
+ onColumnVisibilityChange: setColumnVisibility,
783
+ onPaginationChange: clientSide
784
+ ? setClientPagination
785
+ : (updater) => {
786
+ if (!pagination) return;
787
+ const current = {
788
+ pageIndex: pagination.page,
789
+ pageSize: pagination.perPage,
790
+ };
791
+ const next = typeof updater === "function" ? updater(current) : updater;
792
+ const changes: DataTableParamChange = {};
793
+ if (next.pageIndex !== current.pageIndex) changes.page = next.pageIndex;
794
+ if (next.pageSize !== current.pageSize) {
795
+ changes.perPage = next.pageSize;
796
+ changes.page = 0;
797
+ }
798
+ onParamChange?.(changes);
799
+ },
800
+ getCoreRowModel: getCoreRowModel(),
801
+ ...(clientSide
802
+ ? {
803
+ getSortedRowModel: getSortedRowModel(),
804
+ getFilteredRowModel: getFilteredRowModel(),
805
+ getPaginationRowModel: getPaginationRowModel(),
806
+ }
807
+ : {}),
808
+ getRowId,
809
+ });
810
+
811
+ // -----------------------------------------------------------------------
812
+ // Selected keys for bulk actions
813
+ // -----------------------------------------------------------------------
814
+ const selectedKeys = useMemo(
815
+ () => Object.keys(rowSelection).filter((k) => rowSelection[k]),
816
+ [rowSelection],
817
+ );
818
+ // Width cap per column, by id. Both the `<th>` and the `<td>` apply it, and
819
+ // the cell fills whatever width the column has.
820
+ const columnMaxWidth = useCallback(
821
+ (id: string) => columns.find((c) => c.key === id)?.maxWidth,
822
+ [columns],
823
+ );
824
+
825
+ const hasSelection = selectedKeys.length > 0;
826
+
827
+ const handleBulkAction = useCallback(
828
+ (actionId: string) => {
829
+ onBulkAction?.(actionId, selectedKeys);
830
+ },
831
+ [onBulkAction, selectedKeys],
832
+ );
833
+
834
+ // -----------------------------------------------------------------------
835
+ // Filter handlers (client-side uses local state + TanStack column filters)
836
+ // -----------------------------------------------------------------------
837
+ const [clientFilters, setClientFilters] = useState<Record<string, string | string[]>>({});
838
+ const activeFilters = clientSide ? clientFilters : appliedFilters;
839
+
840
+ const handleFilterApply = useCallback(
841
+ (key: string, value: string | string[]) => {
842
+ if (clientSide) {
843
+ setClientFilters((prev) => ({ ...prev, [key]: value }));
844
+ table.getColumn(key)?.setFilterValue(value);
845
+ table.setPageIndex(0);
846
+ return;
847
+ }
848
+ onParamChange?.({
849
+ filters: { ...appliedFilters, [key]: value },
850
+ page: 0,
851
+ });
852
+ },
853
+ [appliedFilters, onParamChange, clientSide, table],
854
+ );
855
+
856
+ const handleFilterRemove = useCallback(
857
+ (key: string) => {
858
+ if (clientSide) {
859
+ setClientFilters((prev) => {
860
+ const next = { ...prev };
861
+ delete next[key];
862
+ return next;
863
+ });
864
+ table.getColumn(key)?.setFilterValue(undefined);
865
+ table.setPageIndex(0);
866
+ return;
867
+ }
868
+ const next = { ...appliedFilters };
869
+ delete next[key];
870
+ onParamChange?.({ filters: next, page: 0 });
871
+ },
872
+ [appliedFilters, onParamChange, clientSide, table],
873
+ );
874
+
875
+ const handleFilterClearAll = useCallback(() => {
876
+ if (clientSide) {
877
+ setClientFilters({});
878
+ table.resetColumnFilters();
879
+ table.setPageIndex(0);
880
+ return;
881
+ }
882
+ onParamChange?.({ filters: {}, page: 0 });
883
+ }, [onParamChange, clientSide, table]);
884
+
885
+ // -----------------------------------------------------------------------
886
+ // Column count for visibility toggle threshold
887
+ // -----------------------------------------------------------------------
888
+ const recordCount = clientSide
889
+ ? table.getFilteredRowModel().rows.length
890
+ : (pagination?.total ?? rows.length);
891
+ const isEmpty = !isLoading && rows.length === 0;
892
+
893
+ // -----------------------------------------------------------------------
894
+ // Skeleton rows for loading state
895
+ // -----------------------------------------------------------------------
896
+ const skeletonRowCount = pagination?.perPage ?? 10;
897
+
898
+ // -----------------------------------------------------------------------
899
+ // Pagination helpers
900
+ // -----------------------------------------------------------------------
901
+ const pageIndex = clientSide ? table.getState().pagination.pageIndex : (pagination?.page ?? 0);
902
+ const pageSize = clientSide
903
+ ? table.getState().pagination.pageSize
904
+ : (pagination?.perPage ?? rows.length);
905
+ const pageCount = clientSide
906
+ ? table.getPageCount()
907
+ : pagination
908
+ ? Math.ceil(pagination.total / pagination.perPage)
909
+ : 1;
910
+ const pageSizes = pagination?.pageSizes ?? [10, 25, 50, 100];
911
+ const showPagination = clientSide ? rows.length > pageSize : !!pagination;
912
+ const paginationFrom = pageIndex * pageSize + 1;
913
+ const paginationTo = Math.min(
914
+ (pageIndex + 1) * pageSize,
915
+ clientSide ? recordCount : (pagination?.total ?? rows.length),
916
+ );
917
+
918
+ // -----------------------------------------------------------------------
919
+ // Render
920
+ // -----------------------------------------------------------------------
921
+ return (
922
+ <div>
923
+ {/* Bulk Action Bar (preview 03 style) */}
924
+ {hasSelection && bulkActions && bulkActions.length > 0 && (
925
+ <div className="bg-primary text-primary-foreground flex items-center gap-2.5 px-4 py-1.5 text-xs font-medium">
926
+ <span>{t("middag.ui.table.selected", { count: selectedKeys.length })}</span>
927
+ {bulkActions.map((action) => (
928
+ <button
929
+ key={action.id}
930
+ onClick={() => handleBulkAction(action.id)}
931
+ className="rounded px-2.5 py-1 text-[11px] font-medium transition-colors focus-visible:ring-2 focus-visible:ring-white/70 focus-visible:outline-none"
932
+ style={{ background: "oklch(1 0 0 / 0.12)" }}
933
+ onMouseEnter={(e) => (e.currentTarget.style.background = "oklch(1 0 0 / 0.22)")}
934
+ onMouseLeave={(e) => (e.currentTarget.style.background = "oklch(1 0 0 / 0.12)")}
935
+ onFocus={(e) => (e.currentTarget.style.background = "oklch(1 0 0 / 0.22)")}
936
+ onBlur={(e) => (e.currentTarget.style.background = "oklch(1 0 0 / 0.12)")}
937
+ >
938
+ {renderLabel(action.label, t)}
939
+ </button>
940
+ ))}
941
+ <button
942
+ onClick={() => {
943
+ setRowSelection({});
944
+ table.toggleAllPageRowsSelected(false);
945
+ }}
946
+ className="ml-auto rounded px-2.5 py-1 text-[11px] font-medium transition-colors focus-visible:ring-2 focus-visible:ring-white/70 focus-visible:outline-none"
947
+ style={{ background: "oklch(1 0 0 / 0.12)" }}
948
+ onMouseEnter={(e) => (e.currentTarget.style.background = "oklch(1 0 0 / 0.22)")}
949
+ onMouseLeave={(e) => (e.currentTarget.style.background = "oklch(1 0 0 / 0.12)")}
950
+ onFocus={(e) => (e.currentTarget.style.background = "oklch(1 0 0 / 0.22)")}
951
+ onBlur={(e) => (e.currentTarget.style.background = "oklch(1 0 0 / 0.12)")}
952
+ >
953
+ {t("middag.ui.table.clear_selection")}
954
+ </button>
955
+ </div>
956
+ )}
957
+
958
+ {/* Toolbar (Jira-like enterprise style) */}
959
+ <div className="border-border/50 flex flex-wrap items-center gap-2 border-b px-4 py-2">
960
+ {/* Search input */}
961
+ <div className="relative w-[220px]">
962
+ <svg
963
+ className="text-muted-foreground pointer-events-none absolute top-1/2 left-2.5 h-3.5 w-3.5 -translate-y-1/2"
964
+ viewBox="0 0 24 24"
965
+ fill="none"
966
+ stroke="currentColor"
967
+ strokeWidth={2}
968
+ >
969
+ <circle cx="11" cy="11" r="8" />
970
+ <path d="m21 21-4.35-4.35" />
971
+ </svg>
972
+ <input
973
+ type="text"
974
+ value={searchInput}
975
+ onChange={(e) => setSearchInput(e.target.value)}
976
+ placeholder={_searchPlaceholder ?? t("middag.ui.table.search_placeholder")}
977
+ className="border-border bg-popover text-foreground placeholder:text-muted-foreground focus:border-primary focus:ring-primary/20 h-[30px] w-full rounded-[5px] border pr-2.5 pl-8 text-xs transition-[border-color,box-shadow] outline-none focus:ring-2"
978
+ />
979
+ </div>
980
+
981
+ {/* Applied filter chips (enterprise label:value style) */}
982
+ {Object.entries(activeFilters).map(([key, value]) => {
983
+ const filter = filters?.find((f) => f.key === key);
984
+ const displayValue = Array.isArray(value) ? value.join(", ") : value;
985
+ const optionLabel =
986
+ filter?.options?.find((o) => o.value === displayValue)?.label ?? displayValue;
987
+ return (
988
+ <span
989
+ key={key}
990
+ className="border-border bg-popover inline-flex h-[30px] items-center gap-1 rounded-[5px] border py-0.5 pr-1.5 pl-2.5 text-xs font-medium transition-colors"
991
+ >
992
+ <span className="text-muted-foreground">{filter?.label ?? key}:</span>
993
+ <span className="text-foreground font-semibold">{optionLabel}</span>
994
+ <button
995
+ type="button"
996
+ onClick={() => handleFilterRemove(key)}
997
+ aria-label={t("middag.ui.table.remove_filter", { label: filter?.label ?? key })}
998
+ className="text-muted-foreground hover:text-foreground ml-0.5 cursor-pointer text-sm leading-none opacity-60 hover:opacity-100"
999
+ >
1000
+ {"\u00D7"}
1001
+ </button>
1002
+ </span>
1003
+ );
1004
+ })}
1005
+
1006
+ {/* Filter trigger (dashed add button) */}
1007
+ {filters && filters.length > 0 && (
1008
+ <FilterBar
1009
+ filters={filters}
1010
+ applied={appliedFilters}
1011
+ onApply={handleFilterApply}
1012
+ onRemove={handleFilterRemove}
1013
+ onClearAll={handleFilterClearAll}
1014
+ hideChips
1015
+ />
1016
+ )}
1017
+
1018
+ <div className="flex-1" />
1019
+
1020
+ {/* Results count */}
1021
+ <span className="text-muted-foreground text-[11px] font-medium tabular-nums">
1022
+ {t("middag.ui.table.record", { count: recordCount })}
1023
+ </span>
1024
+
1025
+ {/* Density toggle */}
1026
+ <DensityToggle value={density} onChange={setDensity} />
1027
+
1028
+ {/* Column visibility */}
1029
+ {(() => {
1030
+ const hideableColumns = table.getAllColumns().filter((c) => c.getCanHide());
1031
+ if (hideableColumns.length === 0) return null;
1032
+ return (
1033
+ <DropdownMenu>
1034
+ <DropdownMenuTrigger asChild>
1035
+ <button
1036
+ type="button"
1037
+ className="border-border text-muted-foreground hover:text-foreground hover:border-muted-foreground inline-flex h-[30px] w-[30px] items-center justify-center rounded-[5px] border transition-colors"
1038
+ title={t("middag.ui.table.columns")}
1039
+ aria-label={t("middag.ui.table.columns")}
1040
+ >
1041
+ <HugeiconsIcon
1042
+ icon={SlidersHorizontalIcon}
1043
+ strokeWidth={2}
1044
+ className="h-3.5 w-3.5"
1045
+ />
1046
+ </button>
1047
+ </DropdownMenuTrigger>
1048
+ <DropdownMenuContent align="end" className="w-48">
1049
+ <DropdownMenuLabel>{t("middag.ui.table.columns")}</DropdownMenuLabel>
1050
+ <DropdownMenuSeparator />
1051
+ {hideableColumns.map((c) => (
1052
+ <DropdownMenuCheckboxItem
1053
+ key={c.id}
1054
+ checked={c.getIsVisible()}
1055
+ onSelect={(e) => e.preventDefault()}
1056
+ onCheckedChange={(value) => c.toggleVisibility(!!value)}
1057
+ >
1058
+ {(c.columnDef.meta as { headerTitle?: string } | undefined)?.headerTitle ??
1059
+ c.id}
1060
+ </DropdownMenuCheckboxItem>
1061
+ ))}
1062
+ </DropdownMenuContent>
1063
+ </DropdownMenu>
1064
+ );
1065
+ })()}
1066
+
1067
+ {/*
1068
+ Save as view — rendered only when the consumer wired a handler. It used
1069
+ to render unconditionally with no `onClick` at all: a button carrying a
1070
+ title and an aria-label, promising an action it never performed.
1071
+
1072
+ `savedView` fills the star so the control reports state instead of only
1073
+ accepting a click, and `aria-pressed` says the same thing to a screen
1074
+ reader.
1075
+ */}
1076
+ {onSaveView && (
1077
+ <button
1078
+ type="button"
1079
+ onClick={onSaveView}
1080
+ aria-pressed={savedView}
1081
+ className={cn(
1082
+ "inline-flex h-[30px] w-[30px] items-center justify-center rounded-[5px] border transition-colors",
1083
+ savedView
1084
+ ? "border-primary text-primary"
1085
+ : "border-border text-muted-foreground hover:text-foreground hover:border-muted-foreground",
1086
+ )}
1087
+ title={saveViewLabel ?? t("middag.ui.table.save_view")}
1088
+ aria-label={saveViewLabel ?? t("middag.ui.table.save_view")}
1089
+ >
1090
+ <svg
1091
+ viewBox="0 0 24 24"
1092
+ fill={savedView ? "currentColor" : "none"}
1093
+ stroke="currentColor"
1094
+ strokeWidth={2}
1095
+ className="h-3.5 w-3.5"
1096
+ >
1097
+ <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" />
1098
+ </svg>
1099
+ </button>
1100
+ )}
1101
+ </div>
1102
+
1103
+ {/* Table or Empty State */}
1104
+ {isEmpty ? (
1105
+ <EmptyPlaceholder
1106
+ variant="no-results"
1107
+ icon={emptyStateIcon}
1108
+ title={emptyStateTitle}
1109
+ description={emptyStateDescription}
1110
+ cta={emptyStateCTA}
1111
+ />
1112
+ ) : isMobile ? (
1113
+ <MobileCardView
1114
+ rows={rows}
1115
+ columns={columns}
1116
+ rowKey={getKey}
1117
+ rowActions={rowActions}
1118
+ rowSelection={rowSelection}
1119
+ onToggleRow={(key) => {
1120
+ setRowSelection((prev) => ({
1121
+ ...prev,
1122
+ [key]: !prev[key],
1123
+ }));
1124
+ }}
1125
+ hasBulkActions={!!hasBulkActions}
1126
+ onRowClick={onRowClick}
1127
+ t={t}
1128
+ />
1129
+ ) : (
1130
+ <div
1131
+ className="overflow-auto"
1132
+ role="region"
1133
+ aria-label={t("middag.ui.table.scroll_region")}
1134
+ tabIndex={0}
1135
+ >
1136
+ <table className="w-full border-collapse" role="grid">
1137
+ <thead>
1138
+ {table.getHeaderGroups().map((headerGroup) => (
1139
+ <tr key={headerGroup.id}>
1140
+ {headerGroup.headers.map((header) => (
1141
+ <th
1142
+ key={header.id}
1143
+ scope="col"
1144
+ className="text-muted-foreground h-8 px-4 text-left text-[11px] font-semibold tracking-[0.04em] uppercase"
1145
+ style={{
1146
+ ...(header.getSize() !== 150 ? { width: header.getSize() } : {}),
1147
+ maxWidth: columnMaxWidth(header.column.id),
1148
+ }}
1149
+ aria-sort={
1150
+ header.column.getCanSort()
1151
+ ? header.column.getIsSorted() === "asc"
1152
+ ? "ascending"
1153
+ : header.column.getIsSorted() === "desc"
1154
+ ? "descending"
1155
+ : "none"
1156
+ : undefined
1157
+ }
1158
+ >
1159
+ {header.isPlaceholder
1160
+ ? null
1161
+ : flexRender(header.column.columnDef.header, header.getContext())}
1162
+ </th>
1163
+ ))}
1164
+ </tr>
1165
+ ))}
1166
+ </thead>
1167
+ <tbody>
1168
+ {isLoading
1169
+ ? Array.from({ length: skeletonRowCount }, (_, i) => (
1170
+ <tr key={`skeleton-${i}`}>
1171
+ {table.getAllColumns().map((col) => (
1172
+ <td
1173
+ key={col.id}
1174
+ className="border-border/50 border-b px-4"
1175
+ style={{ height: DENSITY_HEIGHTS[density] }}
1176
+ >
1177
+ <Skeleton
1178
+ className={cn(
1179
+ "h-4",
1180
+ SKELETON_WIDTHS[
1181
+ table.getAllColumns().indexOf(col) % SKELETON_WIDTHS.length
1182
+ ],
1183
+ )}
1184
+ />
1185
+ </td>
1186
+ ))}
1187
+ </tr>
1188
+ ))
1189
+ : table.getRowModel().rows.map((row) => (
1190
+ <tr
1191
+ key={row.id}
1192
+ data-testid={rowTestId(row.id)}
1193
+ className={cn(
1194
+ "group/row cursor-pointer transition-[background] duration-75",
1195
+ "hover:bg-sidebar-hover",
1196
+ row.getIsSelected() && "bg-info-subtle",
1197
+ )}
1198
+ data-state={row.getIsSelected() ? "selected" : undefined}
1199
+ onClick={() => onRowClick?.(row.original)}
1200
+ >
1201
+ {row.getVisibleCells().map((cell) => (
1202
+ <td
1203
+ key={cell.id}
1204
+ className="border-border/50 truncate overflow-hidden border-b px-4 align-middle text-[13px] whitespace-nowrap"
1205
+ style={{
1206
+ height: DENSITY_HEIGHTS[density],
1207
+ // The cap belongs to the column, not to the text. Held on
1208
+ // the cell, it bounds how wide the column can grow; held on
1209
+ // the text, the column still took its share of any surplus
1210
+ // width and the clipped value sat short of the next column
1211
+ // — 170px of dead space at 1920.
1212
+ maxWidth: columnMaxWidth(cell.column.id),
1213
+ }}
1214
+ >
1215
+ {flexRender(cell.column.columnDef.cell, cell.getContext())}
1216
+ </td>
1217
+ ))}
1218
+ </tr>
1219
+ ))}
1220
+ </tbody>
1221
+ </table>
1222
+ </div>
1223
+ )}
1224
+
1225
+ {/* Pagination */}
1226
+ {showPagination && !isEmpty && (
1227
+ <div className="border-border flex items-center justify-between border-t px-4 py-2">
1228
+ <span className="text-muted-foreground text-xs tabular-nums">
1229
+ {paginationFrom} - {paginationTo} {t("middag.ui.table.pagination_of")} {recordCount}
1230
+ </span>
1231
+ <div className="flex items-center gap-2">
1232
+ <select
1233
+ value={pageSize}
1234
+ aria-label={t("middag.ui.table.pagination_rows_per_page")}
1235
+ onChange={(e) => {
1236
+ if (clientSide) {
1237
+ table.setPageSize(Number(e.target.value));
1238
+ } else {
1239
+ onParamChange?.({ perPage: Number(e.target.value), page: 0 });
1240
+ }
1241
+ }}
1242
+ className="border-border text-muted-foreground h-7 rounded border bg-transparent px-1.5 text-xs"
1243
+ >
1244
+ {pageSizes.map((size) => (
1245
+ <option key={size} value={size}>
1246
+ {size} {t("middag.ui.table.pagination_per_page")}
1247
+ </option>
1248
+ ))}
1249
+ </select>
1250
+ <div className="flex gap-1">
1251
+ <Button
1252
+ variant="outline"
1253
+ size="icon-xs"
1254
+ disabled={pageIndex === 0}
1255
+ onClick={() =>
1256
+ clientSide ? table.previousPage() : onParamChange?.({ page: pageIndex - 1 })
1257
+ }
1258
+ aria-label={t("middag.ui.table.previous_page")}
1259
+ >
1260
+ &lsaquo;
1261
+ </Button>
1262
+ <span className="text-muted-foreground flex items-center px-1.5 text-xs tabular-nums">
1263
+ {pageIndex + 1} / {pageCount}
1264
+ </span>
1265
+ <Button
1266
+ variant="outline"
1267
+ size="icon-xs"
1268
+ disabled={pageIndex >= pageCount - 1}
1269
+ onClick={() =>
1270
+ clientSide ? table.nextPage() : onParamChange?.({ page: pageIndex + 1 })
1271
+ }
1272
+ aria-label={t("middag.ui.table.next_page")}
1273
+ >
1274
+ &rsaquo;
1275
+ </Button>
1276
+ </div>
1277
+ </div>
1278
+ </div>
1279
+ )}
1280
+ </div>
1281
+ );
1282
+ }