torch-glare 2.4.4 → 2.5.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.
Files changed (147) hide show
  1. package/apps/lib/components/DataViews/{badgeAdapter.ts → badge.ts} +2 -2
  2. package/apps/lib/components/DataViews/cell.tsx +324 -0
  3. package/apps/lib/components/DataViews/context.ts +144 -0
  4. package/apps/lib/components/DataViews/data-views.tsx +383 -0
  5. package/apps/lib/components/DataViews/filters/children.tsx +98 -0
  6. package/apps/lib/components/DataViews/filters/custom.tsx +34 -0
  7. package/apps/lib/components/DataViews/filters/filters.tsx +163 -0
  8. package/apps/lib/components/DataViews/filters/index.ts +4 -0
  9. package/apps/lib/components/DataViews/filters/labelled.tsx +20 -0
  10. package/apps/lib/components/DataViews/filters/presets.tsx +65 -0
  11. package/apps/lib/components/DataViews/filters/summary.tsx +65 -0
  12. package/apps/lib/components/DataViews/filters/sync.tsx +35 -0
  13. package/apps/lib/components/DataViews/filters/values.ts +173 -0
  14. package/apps/lib/components/DataViews/header.tsx +217 -0
  15. package/apps/lib/components/DataViews/hooks/index.ts +5 -0
  16. package/apps/lib/components/DataViews/hooks/useActiveRow.ts +22 -0
  17. package/apps/lib/components/DataViews/hooks/useControllable.ts +52 -0
  18. package/apps/lib/components/DataViews/index.ts +74 -26
  19. package/apps/lib/components/DataViews/panel/columns.tsx +153 -0
  20. package/apps/lib/components/DataViews/panel/controls.tsx +106 -0
  21. package/apps/lib/components/DataViews/panel/index.ts +3 -0
  22. package/apps/lib/components/DataViews/panel/panel.tsx +164 -0
  23. package/apps/lib/components/DataViews/panel/saved-views.tsx +67 -0
  24. package/apps/lib/components/DataViews/panel/section.tsx +79 -0
  25. package/apps/lib/components/DataViews/panel/sort.tsx +42 -0
  26. package/apps/lib/components/DataViews/panel/tab.tsx +31 -0
  27. package/apps/lib/components/DataViews/slots.ts +63 -0
  28. package/apps/lib/components/DataViews/states.tsx +38 -0
  29. package/apps/lib/components/DataViews/types.ts +485 -178
  30. package/apps/lib/components/DataViews/views/board-view.tsx +379 -0
  31. package/apps/lib/components/DataViews/views/card-rows.tsx +36 -0
  32. package/apps/lib/components/DataViews/views/inbox-view.tsx +257 -0
  33. package/apps/lib/components/DataViews/views/pane-views.tsx +192 -0
  34. package/apps/lib/components/DataViews/views/table-view.tsx +426 -0
  35. package/apps/lib/components/DataViews/views/tree-view.tsx +365 -0
  36. package/apps/lib/components/FormBuilder/context.ts +20 -6
  37. package/apps/lib/components/FormBuilder/field-kind.ts +28 -0
  38. package/apps/lib/components/FormBuilder/fields/DateField.tsx +3 -3
  39. package/apps/lib/components/FormBuilder/fields/FieldShell.tsx +7 -6
  40. package/apps/lib/components/FormBuilder/fields/PhoneField.tsx +30 -4
  41. package/apps/lib/components/FormBuilder/fields/SelectField.tsx +7 -7
  42. package/apps/lib/components/FormBuilder/fields/TableField.tsx +80 -52
  43. package/apps/lib/components/FormBuilder/fields/TextField.tsx +9 -9
  44. package/apps/lib/components/FormBuilder/form-builder.tsx +66 -6
  45. package/apps/lib/components/FormBuilder/index.ts +3 -1
  46. package/apps/lib/components/FormBuilder/types.ts +40 -0
  47. package/apps/lib/components/Input.tsx +3 -0
  48. package/apps/lib/components/SearchableTable.tsx +5 -4
  49. package/apps/lib/components/SectionBlock.tsx +58 -11
  50. package/apps/lib/components/Select.tsx +3 -1
  51. package/apps/lib/components/TabSwitch.tsx +16 -4
  52. package/apps/lib/components/Table.tsx +265 -67
  53. package/apps/lib/components/TreeFolder/TreeFolder.tsx +6 -3
  54. package/apps/lib/components/TreeFolder/TreeFolderRow.tsx +16 -14
  55. package/apps/lib/components/TreeFolder/index.ts +1 -1
  56. package/apps/lib/components/TreeFolder/useTreeFolderDnD.ts +70 -207
  57. package/apps/lib/hooks/useDragDrop.tsx +365 -0
  58. package/apps/lib/hooks/useInfiniteScroll.ts +108 -0
  59. package/apps/lib/registry.json +159 -4
  60. package/apps/lib/tsconfig.tsbuildinfo +1 -1
  61. package/apps/lib/utils/dataViews/path.ts +67 -0
  62. package/apps/lib/utils/dataViews/query.ts +73 -0
  63. package/apps/lib/utils/dataViews/types.ts +187 -0
  64. package/docs/components/breadcrumb.md +1 -1
  65. package/docs/components/button-group.md +1 -1
  66. package/docs/components/button.md +1 -1
  67. package/docs/components/card.md +1 -1
  68. package/docs/components/checkbox.md +1 -1
  69. package/docs/components/data-views/backend-response.md +324 -0
  70. package/docs/components/data-views/examples/a11y-rtl.md +250 -0
  71. package/docs/components/data-views/examples/api-orders-route.md +130 -0
  72. package/docs/components/data-views/examples/fields.md +362 -0
  73. package/docs/components/data-views/examples/filters.md +308 -0
  74. package/docs/components/data-views/examples/inbox-routing.md +218 -0
  75. package/docs/components/data-views/examples/index.md +29 -0
  76. package/docs/components/data-views/examples/overview.md +244 -0
  77. package/docs/components/data-views/examples/panel.md +212 -0
  78. package/docs/components/data-views/examples/scale.md +231 -0
  79. package/docs/components/data-views/examples/server-side.md +210 -0
  80. package/docs/components/data-views/examples/state.md +250 -0
  81. package/docs/components/data-views/examples/tree-custom.md +388 -0
  82. package/docs/components/data-views/examples/view-registry.md +313 -0
  83. package/docs/components/data-views/examples/views.md +534 -0
  84. package/docs/components/data-views/guide.md +405 -0
  85. package/docs/components/data-views/index.md +1504 -0
  86. package/docs/components/data-views/migration.md +79 -0
  87. package/docs/components/date-picker.md +0 -1
  88. package/docs/components/form-builder.md +19 -8
  89. package/docs/components/form-renderer.md +2 -1
  90. package/docs/components/form.md +1 -1
  91. package/docs/components/input-field.md +1 -1
  92. package/docs/components/input-otp.md +1 -1
  93. package/docs/components/input.md +1 -1
  94. package/docs/components/labeled-check-box.md +1 -1
  95. package/docs/components/labeled-radio.md +1 -1
  96. package/docs/components/radio-card.md +1 -1
  97. package/docs/components/radio.md +1 -1
  98. package/docs/components/search-field.md +1 -1
  99. package/docs/components/section-block.md +79 -3
  100. package/docs/components/select.md +1 -1
  101. package/docs/components/simple-select.md +1 -1
  102. package/docs/components/switch.md +1 -1
  103. package/docs/components/tab-switch.md +1 -1
  104. package/docs/components/table.md +45 -8
  105. package/docs/components/text-editor.md +1 -1
  106. package/docs/components/textarea.md +1 -1
  107. package/docs/components/toggle-button.md +1 -1
  108. package/docs/components/toggle.md +1 -1
  109. package/docs/components/tree-folder.md +110 -0
  110. package/docs/how-to/forms-with-form-builder.md +6 -4
  111. package/docs/reference/components.md +16 -6
  112. package/docs/tutorials/component-composition.md +11 -13
  113. package/package.json +3 -2
  114. package/apps/lib/components/DataViews/DataViewRadio.tsx +0 -49
  115. package/apps/lib/components/DataViews/DataViewsConfigPanel.tsx +0 -393
  116. package/apps/lib/components/DataViews/DataViewsHeader.tsx +0 -207
  117. package/apps/lib/components/DataViews/DataViewsLayout.tsx +0 -332
  118. package/apps/lib/components/DataViews/FilterPanel.tsx +0 -493
  119. package/apps/lib/components/DataViews/HeaderSearch.tsx +0 -93
  120. package/apps/lib/components/DataViews/InboxView.tsx +0 -463
  121. package/apps/lib/components/DataViews/InboxViewCard.tsx +0 -127
  122. package/apps/lib/components/DataViews/KanbanView.tsx +0 -336
  123. package/apps/lib/components/DataViews/PanelControls.tsx +0 -39
  124. package/apps/lib/components/DataViews/SettingsPanel.tsx +0 -279
  125. package/apps/lib/components/DataViews/TableView.tsx +0 -212
  126. package/apps/lib/components/DataViews/TreeView.tsx +0 -364
  127. package/apps/lib/components/DataViews/fieldRenderers.tsx +0 -299
  128. package/apps/lib/components/DataViews/filters/DatePickerRangeFilter.tsx +0 -87
  129. package/apps/lib/components/DataViews/filters/DateRangePopover.tsx +0 -120
  130. package/apps/lib/components/DataViews/filters/PresetChips.tsx +0 -45
  131. package/apps/lib/components/DataViews/filters/RangeSliderWithInputs.tsx +0 -165
  132. package/apps/lib/components/DataViews/tree/TreeDrawer.tsx +0 -50
  133. package/apps/lib/components/DataViews/tree/TreeSidebar.tsx +0 -74
  134. package/apps/lib/hooks/useDataViewsState.ts +0 -175
  135. package/apps/lib/utils/dataViews/columnUtils.ts +0 -132
  136. package/apps/lib/utils/dataViews/fieldUtils.ts +0 -197
  137. package/apps/lib/utils/dataViews/nestedDataUtils.tsx +0 -371
  138. package/apps/lib/utils/dataViews/pathUtils.ts +0 -139
  139. package/apps/lib/utils/dataViews/rangeUtils.ts +0 -234
  140. package/apps/lib/utils/dataViews/treeUtils.ts +0 -396
  141. package/docs/components/data-views-config-panel.md +0 -208
  142. package/docs/components/data-views-layout.md +0 -291
  143. package/docs/components/inbox-view.md +0 -170
  144. package/docs/components/kanban-view.md +0 -135
  145. package/docs/components/table-view.md +0 -141
  146. package/docs/components/tree-view.md +0 -147
  147. package/docs/how-to/data-views-from-backend-response.md +0 -194
@@ -0,0 +1,362 @@
1
+ ---
2
+ title: DataViews example — Fields
3
+ description: The field types, painted.
4
+ group: examples
5
+ component: DataViews
6
+ keywords: [data-views, example, examples, fields]
7
+ ---
8
+
9
+ # DataViews example — Fields
10
+
11
+ The field types, painted.
12
+
13
+ Complete and runnable — this is the page itself, not an excerpt. In the monorepo it lives at `apps/app/data-views/fields/page.tsx`.
14
+
15
+ See the [component reference](../index.md) for what each prop does, or the [guide](../guide.md) for the same ground as scenarios.
16
+
17
+ ```tsx
18
+ "use client";
19
+
20
+ import { useMemo, useState } from "react";
21
+ import { useInfiniteQuery } from "@tanstack/react-query";
22
+ import { Filter, Settings } from "lucide-react";
23
+ import { Badge } from "@/components/Badge";
24
+ import { Button } from "@/components/Button";
25
+ import { Cell, DataViews, emptyQuery, queryToParams, type SavedView } from "@/components/DataViews";
26
+ import { FormBuilder } from "@/components/FormBuilder";
27
+ import type {
28
+ DataViewsQuery,
29
+ FieldConfig,
30
+ Row,
31
+ } from "@/utils/dataViews/types";
32
+
33
+ // ─── Case 1 · every field type ────────────────────────────────────────────────
34
+
35
+ /**
36
+ * One row shape carrying every `FieldType`.
37
+ *
38
+ * Deliberately includes a broken avatar URL and a broken image src — a 404 is the normal case for
39
+ * user-supplied image data, and the fallback path is worth being able to see.
40
+ */
41
+ /**
42
+ * All seventeen types, each with the config it actually reads. The `label`s name the option being
43
+ * demonstrated rather than the data, because that is what this case is about. Two entries share
44
+ * `price` and two share `iconText` — a path may appear more than once, which is why the views key
45
+ * columns by position rather than by path.
46
+ */
47
+ const SHOWCASE_FIELDS: FieldConfig[] = [
48
+ { path: "text", label: "text", type: "text" },
49
+ { path: "number", label: "number", type: "number" },
50
+ { path: "date", label: "date", type: "date" },
51
+ { path: "dateFormatted", label: "date-format · tokens", type: "date-format", dateFormat: "DD/MM/YYYY HH:mm" },
52
+ {
53
+ path: "bool",
54
+ label: "boolean · badges",
55
+ type: "boolean",
56
+ trueLabel: "Paid",
57
+ falseLabel: "Unpaid",
58
+ trueVariant: "green",
59
+ falseVariant: "redLight",
60
+ },
61
+ { path: "hidden", label: "hidden", type: "hidden" },
62
+ { path: "status", label: "enum-badge", type: "enum-badge", variants: { Pending: "yellow", Shipped: "blue", Delivered: "green" } },
63
+ {
64
+ path: "tags",
65
+ label: "badge-array · limit 3",
66
+ type: "badge-array",
67
+ limit: 3,
68
+ variants: { urgent: "redOrange", hardware: "blue", licence: "purple" },
69
+ defaultVariant: "gray",
70
+ },
71
+ { path: "price", label: "currency · code", type: "currency", currency: "EUR" },
72
+ { path: "price", label: "currency · options", type: "currency", currency: { code: "USD", locale: "en-US", decimals: 0 } },
73
+ { path: "compact", label: "number-format", type: "number-format", format: { notation: "compact", maximumFractionDigits: 1 } },
74
+ { path: "progress", label: "progress-bar · thresholds", type: "progress-bar", max: 100, thresholds: [30, 80] },
75
+ { path: "rating", label: "star-rating · max 5", type: "star-rating", max: 5 },
76
+ { path: "iconText", label: "icon-text · before", type: "icon-text", icon: "ri-map-pin-line" },
77
+ { path: "iconText", label: "icon-text · after", type: "icon-text", icon: "ri-arrow-right-up-line", iconPosition: "after" },
78
+ { path: "title", label: "two-line", type: "two-line", secondaryPath: "subtitle" },
79
+ { path: "avatar", label: "avatar", type: "avatar", fallbackPath: "avatarName" },
80
+ { path: "email", label: "link · mailto", type: "link", linkType: "mailto" },
81
+ { path: "phone", label: "link · tel", type: "link", linkType: "tel" },
82
+ { path: "url", label: "link · url", type: "link", linkType: "url" },
83
+ { path: "image", label: "image", type: "image" },
84
+ ];
85
+
86
+ const TITLE_OPTIONS = ["Acme Inc.", "Globex Corp.", "Initech", "Umbrella"].map((v) => ({ label: v, value: v }));
87
+ const TAG_OPTIONS = ["urgent", "hardware", "emea", "q3", "approved"].map((v) => ({ label: v, value: v }));
88
+
89
+ const STATUS_OPTIONS = [
90
+ { label: "Pending", value: "Pending" },
91
+ { label: "Shipped", value: "Shipped" },
92
+ { label: "Delivered", value: "Delivered" },
93
+ ];
94
+
95
+ // ─── Case 2 · blank values, every type × every blank ──────────────────────────
96
+
97
+ const TYPES_UNDER_TEST = [
98
+ { type: "text" as const, extra: {} },
99
+ { type: "number" as const, extra: {} },
100
+ { type: "date" as const, extra: {} },
101
+ { type: "date-format" as const, extra: { dateFormat: "YYYY-MM-DD" } },
102
+ { type: "boolean" as const, extra: { trueLabel: "Yes", falseLabel: "No" } },
103
+ { type: "enum-badge" as const, extra: { defaultVariant: "gray" as const } },
104
+ { type: "badge-array" as const, extra: { defaultVariant: "gray" as const } },
105
+ { type: "currency" as const, extra: { currency: "USD" } },
106
+ { type: "number-format" as const, extra: {} },
107
+ { type: "progress-bar" as const, extra: { max: 100 } },
108
+ { type: "star-rating" as const, extra: { max: 5 } },
109
+ { type: "icon-text" as const, extra: { icon: "ri-hashtag" } },
110
+ { type: "two-line" as const, extra: { secondaryPath: "secondary" } },
111
+ { type: "avatar" as const, extra: { fallbackPath: "avatarName" } },
112
+ { type: "link" as const, extra: { linkType: "url" as const } },
113
+ { type: "image" as const, extra: {} },
114
+ ];
115
+
116
+
117
+ /**
118
+ * Generated rather than hand-written: 16 types × 7 blank values is 112 cells, and a hand-authored
119
+ * table of that size drifts the moment a type is added.
120
+ *
121
+ * One row per blank value, one column per type. The `undefined` case has to *omit* the key rather
122
+ * than set it, so an absent path is genuinely absent — and `[]` is the one that used to slip
123
+ * through, because `String([])` is `""` and an `image` field happily rendered `<img src="">`.
124
+ */
125
+ const BLANK_FIELDS: FieldConfig[] = [
126
+ { path: "case", label: "Value", type: "text" },
127
+ ...TYPES_UNDER_TEST.map(({ type, extra }) => ({
128
+ path: type.replace(/-/g, "_"),
129
+ label: type,
130
+ type,
131
+ ...extra,
132
+ })),
133
+ ];
134
+
135
+
136
+ // ─── Case 3 · custom cells ────────────────────────────────────────────────────
137
+
138
+ interface Order extends Row {
139
+ id: number;
140
+ customer: { name: string };
141
+ status: "Pending" | "Shipped" | "Delivered";
142
+ priority: "High" | "Medium" | "Low";
143
+ total: number;
144
+ items: number;
145
+ createdAt: string;
146
+ }
147
+
148
+ /** `render` wins over `type`: it gets the raw value and the whole row, and paints what it likes. */
149
+ const CUSTOM_FIELDS: FieldConfig[] = [
150
+ { path: "id", label: "Order #", type: "number" },
151
+ { path: "customer.name", label: "Customer", type: "text" },
152
+ {
153
+ path: "total",
154
+ label: "Total vs. average",
155
+ render: (value, row) => (
156
+ <span className="flex items-center gap-2">
157
+ <span className="tabular-nums">${Number(value).toLocaleString("en-US")}</span>
158
+ <span className="typography-body-small-regular text-content-presentation-global-secondary">
159
+ ${(Number(value) / Math.max(1, Number((row as Order).items))).toFixed(0)}/item
160
+ </span>
161
+ </span>
162
+ ),
163
+ },
164
+ {
165
+ path: "status",
166
+ label: "Two fields, one cell",
167
+ render: (value, row) => (
168
+ <span className="flex items-center gap-1">
169
+ <Badge label={String(value)} color="blue" badgeStyle="subtle" showIcon={false} />
170
+ <Badge
171
+ label={String((row as Order).priority)}
172
+ color={(row as Order).priority === "High" ? "red" : "gray"}
173
+ badgeStyle="subtle"
174
+ showIcon={false}
175
+ />
176
+ </span>
177
+ ),
178
+ },
179
+ {
180
+ // `Cell` is exported and needs no context — reuse the field vocabulary anywhere, including
181
+ // inside another field's `render`.
182
+ path: "priority",
183
+ label: "Cell, reused",
184
+ render: (_value, row) => (
185
+ <Cell
186
+ field={{ path: "priority", type: "enum-badge", variants: { High: "redOrange", Medium: "purple", Low: "gray" } }}
187
+ row={row}
188
+ />
189
+ ),
190
+ },
191
+ {
192
+ path: "missing",
193
+ label: "render beats blank",
194
+ render: (value) => (
195
+ <span className="typography-body-small-regular text-content-presentation-global-secondary">
196
+ {value === undefined ? "nothing at this path, and render still ran" : String(value)}
197
+ </span>
198
+ ),
199
+ },
200
+ {
201
+ path: "createdAt",
202
+ label: "render beats hidden",
203
+ type: "hidden",
204
+ render: (value) => <code>{String(value)}</code>,
205
+ },
206
+ ];
207
+
208
+ // ─── Case 4 · nested paths ────────────────────────────────────────────────────
209
+
210
+ const NESTED_FIELDS: FieldConfig[] = [
211
+ { path: "id", label: "#", type: "number" },
212
+ // Two paths sharing a last segment: label them yourself, or both columns read "name".
213
+ { path: "customer.name", label: "Customer", type: "text" },
214
+ { path: "vendor.name", label: "Vendor", type: "text" },
215
+ { path: "customer.contact.email", label: "Billing email", type: "link", linkType: "mailto" },
216
+ // Array indices are just another segment — and index 7 does not exist, so the cell goes blank
217
+ // rather than throwing.
218
+ { path: "lines.0.sku", label: "First SKU", type: "text" },
219
+ { path: "lines.7.sku", label: "Eighth SKU", type: "text" },
220
+ { path: "status", label: "Status", type: "enum-badge", variants: { Open: "yellow", Paid: "green" } },
221
+ ];
222
+
223
+
224
+
225
+ // ─── Query ────────────────────────────────────────────────────────────────────
226
+
227
+ /** One query for all four cases — they differ only in which path is searched and which are text. */
228
+ /**
229
+ * Stands in for the endpoint. Every case goes through it, so switching case is a request rather
230
+ * than an array swap.
231
+ */
232
+ /**
233
+ * The request this page makes. Three of the four cases come from `app/api/showcase/route.ts`;
234
+ * `custom` paints ordinary orders, so it reads the orders endpoint instead — a page is free to
235
+ * ask more than one thing for the same table.
236
+ */
237
+ async function fetchCase(q: DataViewsQuery & {
238
+ kase: Case;
239
+ }): Promise<{ rows: Row[]; total: number }> {
240
+ const params = queryToParams(q);
241
+ const url =
242
+ q.kase === "custom" ? `/api/orders?${params}` : `/api/showcase?case=${q.kase}&${params}`;
243
+ const res = await fetch(url);
244
+ if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
245
+ return res.json();
246
+ }
247
+
248
+ const CASES = [
249
+ { id: "types", label: "Types" },
250
+ { id: "blanks", label: "Blanks" },
251
+ { id: "custom", label: "Custom" },
252
+ { id: "nested", label: "Nested" },
253
+ ] as const;
254
+
255
+ type Case = (typeof CASES)[number]["id"];
256
+
257
+ // ─── Page ─────────────────────────────────────────────────────────────────────
258
+
259
+ export default function FieldsExample() {
260
+ const [kase, setCase] = useState<Case>("types");
261
+
262
+ const [query, setQuery] = useState(emptyQuery());
263
+ const [saved, setSaved] = useState<SavedView[]>([]);
264
+
265
+
266
+ // Only the columns are the page's business — the rows for each case come from the endpoint.
267
+ // `custom` paints orders, so it reads the orders endpoint rather than the showcase one.
268
+ const fields = { types: SHOWCASE_FIELDS, blanks: BLANK_FIELDS, custom: CUSTOM_FIELDS, nested: NESTED_FIELDS }[kase];
269
+
270
+ const { data, isPending, fetchNextPage, isFetchingNextPage } = useInfiniteQuery({
271
+ // `kase` is part of the question — each case is a different dataset behind the endpoints.
272
+ queryKey: ["fields", { ...query, page: undefined, kase }],
273
+ queryFn: ({ pageParam }) => fetchCase({ ...query, page: pageParam, kase }),
274
+ initialPageParam: 1,
275
+ // Undefined means "no more" — which is what the component's `hasMore` resolves to.
276
+ getNextPageParam: (last, pages) => {
277
+ const loaded = pages.reduce((n, page) => n + page.rows.length, 0);
278
+ return loaded < last.total ? pages.length + 1 : undefined;
279
+ },
280
+ });
281
+
282
+ const rows = useMemo(() => data?.pages.flatMap((page) => page.rows) ?? [], [data]);
283
+ const total = data?.pages[0]?.total ?? 0;
284
+
285
+ return (
286
+ <div className="flex h-full min-h-0 flex-col p-4">
287
+ <DataViews
288
+ // Remount per case so columns and filters do not leak between datasets.
289
+ key={kase}
290
+ rows={rows}
291
+ fields={fields}
292
+ total={total}
293
+ loading={isPending}
294
+ onLoadMore={fetchNextPage}
295
+ loadingMore={isFetchingNextPage}
296
+ onQueryChange={setQuery}
297
+ className="h-full"
298
+ >
299
+ <DataViews.Header title="Fields">
300
+ <DataViews.ViewSwitch />
301
+ <DataViews.Search />
302
+ <DataViews.Actions>
303
+ {CASES.map((c) => (
304
+ <Button variant="BluColStyle"
305
+ size="M"
306
+ key={c.id}
307
+ onClick={() => {
308
+ // A different dataset is a different question — the old filters and sort mean
309
+ // nothing against it. Columns reset with the remount below.
310
+ setCase(c.id);
311
+ setQuery(emptyQuery());
312
+ }}
313
+ >
314
+ {c.label}
315
+ </Button>
316
+ ))}
317
+ </DataViews.Actions>
318
+ <DataViews.PanelToggle />
319
+ </DataViews.Header>
320
+
321
+ <DataViews.Table />
322
+
323
+ <DataViews.Panel>
324
+ <DataViews.Panel.Tab value="config" label="Config." icon={<Settings />}>
325
+ {/* Saving is the app's job — a view outlives the component. Restoring is not:
326
+ hand the snapshot back and selecting it puts everything back internally. */}
327
+ {/* Saving is the app's job — a view outlives the component. Restoring is not:
328
+ hand the snapshot back and selecting it puts everything back internally. */}
329
+ <DataViews.Panel.SavedViews
330
+ views={saved}
331
+ onSave={(snapshot) =>
332
+ setSaved((prev) => [
333
+ ...prev,
334
+ { id: `view-${prev.length + 1}`, label: `View ${prev.length + 1}`, snapshot },
335
+ ])
336
+ }
337
+ />
338
+ <DataViews.Panel.Columns />
339
+ <DataViews.Panel.Sort />
340
+ </DataViews.Panel.Tab>
341
+
342
+ <DataViews.Panel.Tab value="filters" label="Filters" icon={<Filter />}>
343
+ {/* Each case filters its own dataset, so each offers its own controls. */}
344
+ <DataViews.Filters
345
+ title={null}
346
+ className="border-b-0 p-0"
347
+ >
348
+ {/* This page's data has one enum and a tags array, so it exercises the checkbox
349
+ list, the searchable single, the BadgeField multi, the range and the date. */}
350
+ <FormBuilder.CheckboxGroup name="status" label="Status" options={STATUS_OPTIONS} />
351
+ <FormBuilder.SearchableSelect name="title" label="Title" options={TITLE_OPTIONS} />
352
+ <FormBuilder.MultiSelect name="tags" label="Tags" options={TAG_OPTIONS} />
353
+ <FormBuilder.Slider name="price" label="Price" range min={0} max={2000} step={50} />
354
+ <FormBuilder.DateRange name="date" label="Date" />
355
+ </DataViews.Filters>
356
+ </DataViews.Panel.Tab>
357
+ </DataViews.Panel>
358
+ </DataViews>
359
+ </div>
360
+ );
361
+ }
362
+ ```
@@ -0,0 +1,308 @@
1
+ ---
2
+ title: DataViews example — Filters
3
+ description: Every filter control, presets, custom filters and the summary.
4
+ group: examples
5
+ component: DataViews
6
+ keywords: [data-views, example, examples, filters]
7
+ ---
8
+
9
+ # DataViews example — Filters
10
+
11
+ Every filter control, presets, custom filters and the summary.
12
+
13
+ Complete and runnable — this is the page itself, not an excerpt. In the monorepo it lives at `apps/app/data-views/filters/page.tsx`.
14
+
15
+ See the [component reference](../index.md) for what each prop does, or the [guide](../guide.md) for the same ground as scenarios.
16
+
17
+ ```tsx
18
+ "use client";
19
+
20
+ import { useMemo, useState } from "react";
21
+ import { useInfiniteQuery } from "@tanstack/react-query";
22
+ import { Filter, Settings } from "lucide-react";
23
+ import { Button } from "@/components/Button";
24
+ import { DataViews, emptyQuery, queryToParams, type SavedView } from "@/components/DataViews";
25
+ import { FormBuilder } from "@/components/FormBuilder";
26
+ import type {
27
+ DataViewsQuery,
28
+ FieldConfig,
29
+ FilterState,
30
+ FilterValue,
31
+ Row,
32
+ } from "@/utils/dataViews/types";
33
+
34
+ // ─── Data ─────────────────────────────────────────────────────────────────────
35
+
36
+ interface Order extends Row {
37
+ id: number;
38
+ customer: { name: string };
39
+ status: "Pending" | "Shipped" | "Delivered";
40
+ priority: "High" | "Medium" | "Low";
41
+ total: number;
42
+ items: number;
43
+ createdAt: string;
44
+ }
45
+
46
+ const FIELDS: FieldConfig[] = [
47
+ { path: "id", label: "Order #", type: "number" },
48
+ { path: "customer.name", label: "Customer", type: "text" },
49
+ { path: "brand.name", label: "Brand", type: "text" },
50
+ { path: "status", label: "Status", type: "enum-badge", variants: { Pending: "yellow", Shipped: "blue", Delivered: "green" } },
51
+ { path: "priority", label: "Priority", type: "enum-badge", variants: { High: "redOrange", Medium: "purple", Low: "gray" } },
52
+ { path: "items", label: "Items", type: "number" },
53
+ { path: "total", label: "Total", type: "currency", currency: "USD" },
54
+ { path: "createdAt", label: "Created", type: "date-format", dateFormat: "YYYY-MM-DD" },
55
+ ];
56
+
57
+ /**
58
+ * The options each control offers. Supplied — DataViews never scans the dataset to find them, and
59
+ * in a real app they come from the same endpoint that does the filtering.
60
+ */
61
+ /** Dynamic sets — in a real app these come from the endpoint that also does the filtering. */
62
+ const CUSTOMER_OPTIONS = [
63
+ "Acme Inc.", "Globex Corp.", "Initech", "Umbrella",
64
+ "Hooli", "Stark Industries", "Wayne Enterprises", "Cyberdyne",
65
+ ].map((v) => ({ label: v, value: v }));
66
+
67
+ const BRAND_OPTIONS = ["Bosch", "Makita", "DeWalt", "Hilti"].map((v) => ({ label: v, value: v }));
68
+
69
+ const STATUS_OPTIONS = [
70
+ { label: "Pending", value: "Pending" },
71
+ { label: "Shipped", value: "Shipped" },
72
+ { label: "Delivered", value: "Delivered" },
73
+ ];
74
+
75
+ const PRIORITY_OPTIONS = [
76
+ { label: "High", value: "High" },
77
+ { label: "Medium", value: "Medium" },
78
+ { label: "Low", value: "Low" },
79
+ ];
80
+
81
+ /** Buckets for the custom control below — DataViews has no built-in for this. */
82
+ /**
83
+ * The request this page makes. The querying itself happens in `app/api/orders/route.ts` —
84
+ * nothing on this page filters, sorts or pages anything, which is the split DataViews is built
85
+ * around.
86
+ */
87
+ async function fetchOrders(q: DataViewsQuery): Promise<{ rows: Order[]; total: number }> {
88
+ const params = queryToParams(q);
89
+ const res = await fetch(`/api/orders?${params}`);
90
+ if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
91
+ return res.json();
92
+ }
93
+
94
+ /**
95
+ * The buckets this picker offers. What each one *means* — which item counts fall in it — is the
96
+ * endpoint's business, in `app/api/orders/route.ts`. The page sends the label; the server decides.
97
+ */
98
+ const BUCKETS = ["1–3", "4–10", "10+"];
99
+
100
+ /** `Filters.Custom` renders whatever you like against this path's slot in `FilterState`. */
101
+ function ItemsPicker({
102
+ value,
103
+ setValue,
104
+ }: {
105
+ value: FilterValue | undefined;
106
+ setValue: (v: FilterValue | undefined) => void;
107
+ }) {
108
+ const selected = Array.isArray(value) ? value : [];
109
+ return (
110
+ <div className="flex gap-1">
111
+ {BUCKETS.map((bucket) => (
112
+ <button
113
+ key={bucket}
114
+ type="button"
115
+ onClick={() => {
116
+ const next = selected.includes(bucket)
117
+ ? selected.filter((b) => b !== bucket)
118
+ : [...selected, bucket];
119
+ setValue(next.length ? next : undefined);
120
+ }}
121
+ className={[
122
+ "typography-body-small-regular rounded-[6px] border px-2 py-1 transition-colors",
123
+ selected.includes(bucket)
124
+ ? "border-transparent bg-background-presentation-action-selected text-content-presentation-global-primary"
125
+ : "border-border-presentation-global-primary text-content-presentation-global-secondary",
126
+ ].join(" ")}
127
+ >
128
+ {bucket}
129
+ </button>
130
+ ))}
131
+ </div>
132
+ );
133
+ }
134
+
135
+ // ─── Page ─────────────────────────────────────────────────────────────────────
136
+
137
+ /**
138
+ * The controls are real FormBuilder fields — `Select`, `MultiSelect`, `Slider`, `DateRange` — in
139
+ * `CellContext`'s `"bare"` mode: no label row, no table borders. One set of inputs across the
140
+ * design system.
141
+ *
142
+ * Three behaviours worth knowing:
143
+ *
144
+ * - **A slider at its bounds emits nothing.** Drag *Total* away from 0–15,000 and a `total` key
145
+ * appears; drag it back and the key vanishes, because "the whole range" and "no constraint" are
146
+ * the same query. The cost is that a filter genuinely meaning "0 to 15,000" is inexpressible —
147
+ * use `Filters.Custom` if you need that distinction.
148
+ * - **Dates are local, not UTC.** You get the day you clicked; `toISOString()` would hand back the
149
+ * previous day for anyone east of Greenwich.
150
+ * - **A parent may rewrite what it is handed.** Turn on *Normalising*: every emitted array comes
151
+ * back sorted. Because `Filters` debounces and compares before emitting, the rewritten value
152
+ * settles instead of ping-ponging — a control that echoed immediately would loop and eat every
153
+ * keystroke.
154
+ *
155
+ * The custom `items` key is owned by no declared control, and survives anyway: the built-in
156
+ * controls merge over the paths in `fields` and leave everything else alone.
157
+ */
158
+ export default function FiltersExample() {
159
+ // Controlled, because this page starts with a filter no control owns and then rewrites what it
160
+ // is handed. Everywhere else `onQueryChange` alone is enough.
161
+ const [query, setQuery] = useState<DataViewsQuery>({
162
+ ...emptyQuery(),
163
+ filters: { items: ["10+"] },
164
+ });
165
+ const [saved, setSaved] = useState<SavedView[]>([]);
166
+ const [normalise, setNormalise] = useState(false);
167
+
168
+ /**
169
+ * A parent may rewrite what it is handed. With normalising on, every emitted list comes back
170
+ * sorted — and it settles rather than ping-ponging, because `Filters` debounces and compares
171
+ * before emitting again. A control that echoed immediately would loop and eat every keystroke.
172
+ */
173
+ const onQueryChange = (next: DataViewsQuery) => {
174
+ if (!normalise) return setQuery(next);
175
+ const filters: FilterState = {};
176
+ for (const [path, value] of Object.entries(next.filters)) {
177
+ filters[path] = Array.isArray(value) ? [...value].sort() : value;
178
+ }
179
+ setQuery({ ...next, filters });
180
+ };
181
+
182
+ const { data, isPending, fetchNextPage, isFetchingNextPage } = useInfiniteQuery({
183
+ // The key *is* the query: touch any part of it and TanStack refetches, and a response that
184
+ // has been superseded is discarded rather than landing on top of a newer one.
185
+ queryKey: ["filters-orders", { ...query, page: undefined }],
186
+ queryFn: ({ pageParam }) => fetchOrders({ ...query, page: pageParam }),
187
+ initialPageParam: 1,
188
+ // Undefined means "no more" — which is what the component's `hasMore` resolves to.
189
+ getNextPageParam: (last, pages) => {
190
+ const loaded = pages.reduce((n, page) => n + page.rows.length, 0);
191
+ return loaded < last.total ? pages.length + 1 : undefined;
192
+ },
193
+ });
194
+
195
+ const rows = useMemo(() => data?.pages.flatMap((page) => page.rows) ?? [], [data]);
196
+ const total = data?.pages[0]?.total ?? 0;
197
+
198
+ return (
199
+ <div className="flex h-full min-h-0 flex-col p-4">
200
+ <DataViews
201
+ rows={rows}
202
+ fields={FIELDS}
203
+ total={total}
204
+ loading={isPending}
205
+ onLoadMore={fetchNextPage}
206
+ loadingMore={isFetchingNextPage}
207
+ query={query}
208
+ onQueryChange={onQueryChange}
209
+ className="h-full"
210
+ >
211
+ <DataViews.Header title="Orders">
212
+ <DataViews.ViewSwitch />
213
+ <DataViews.Search />
214
+ <DataViews.Actions>
215
+ <Button variant="BluColStyle"
216
+ size="M"
217
+ onClick={() => setNormalise((v) => !v)}
218
+ >
219
+ {normalise ? "Normalising on" : "Normalising off"}
220
+ </Button>
221
+ <Button
222
+ variant="BluColStyle"
223
+ size="M"
224
+ onClick={() => setQuery({ ...emptyQuery(), filters: { items: ["10+"] } })}
225
+ >
226
+ Reset
227
+ </Button>
228
+ </DataViews.Actions>
229
+ <DataViews.PanelToggle />
230
+ </DataViews.Header>
231
+
232
+ {/* The active query, as removable chips — including the search term. */}
233
+ <div className="border-border-presentation-global-primary border-b px-4 py-2 empty:hidden">
234
+ <DataViews.Filters.Summary />
235
+ </div>
236
+
237
+ <DataViews.Table />
238
+ <DataViews.Panel>
239
+ <DataViews.Panel.Tab value="config" label="Config." icon={<Settings />}>
240
+ {/* Saving is the app's job — a view outlives the component. Restoring is not:
241
+ hand the snapshot back and selecting it puts everything back internally. */}
242
+ <DataViews.Panel.SavedViews
243
+ views={saved}
244
+ onSave={(snapshot) =>
245
+ setSaved((prev) => [
246
+ ...prev,
247
+ { id: `view-${prev.length + 1}`, label: `View ${prev.length + 1}`, snapshot },
248
+ ])
249
+ }
250
+ />
251
+ <DataViews.Panel.Columns />
252
+ <DataViews.Panel.Sort />
253
+ </DataViews.Panel.Tab>
254
+
255
+ <DataViews.Panel.Tab value="filters" label="Filters" icon={<Filter />}>
256
+ {/* Every kind of control, written as the FormBuilder fields they are. The
257
+ <FormBuilder> itself lives inside Filters — you supply its fields and nothing
258
+ else, and Filters reads each one's name, label and bounds to learn what it is. */}
259
+ <DataViews.Filters
260
+ title={null}
261
+ className="border-b-0 p-0"
262
+ >
263
+ {/* ① FIXED set, multi-pick → a checkbox list. The four statuses are fixed by the
264
+ model; an org cannot add a fifth without a release. */}
265
+ <FormBuilder.CheckboxGroup name="status" label="Status" options={STATUS_OPTIONS} />
266
+
267
+ {/* ② FIXED set, single-pick → radios. High/Medium/Low are mutually exclusive, so
268
+ picking two would be meaningless. Writes a one-element array. */}
269
+ <FormBuilder.RadioList name="priority" label="Priority" options={PRIORITY_OPTIONS} />
270
+
271
+ {/* ③ DYNAMIC set, single-pick → a searchable combobox. Customers are data-fed, so
272
+ the list grows; one record has one customer, so one at a time is the natural pick. */}
273
+ <FormBuilder.SearchableSelect
274
+ name="customer.name"
275
+ label="Customer"
276
+ options={CUSTOMER_OPTIONS}
277
+ />
278
+
279
+ {/* ④ DYNAMIC set, multi-pick → BadgeField: search *and* several values, as chips.
280
+ This is the control the enhancement request asked for; `MultiSelect` and `Tags`
281
+ are the same field and both render it. */}
282
+ <FormBuilder.MultiSelect name="brand.name" label="Brand" options={BRAND_OPTIONS} />
283
+ <FormBuilder.Slider name="total" label="Total" range min={0} max={15000} step={100} />
284
+ <DataViews.Filters.Presets
285
+ for="total"
286
+ items={[
287
+ { label: "Under $500", max: 500 },
288
+ { label: "$5k+", min: 5000 },
289
+ ]}
290
+ />
291
+ <FormBuilder.DateRange name="createdAt" label="Created" />
292
+ <DataViews.Filters.Presets
293
+ for="createdAt"
294
+ items={[{ label: "September", from: "2025-09-01", to: "2025-09-30" }]}
295
+ />
296
+ <DataViews.Filters.Custom
297
+ path="items"
298
+ label="Item count"
299
+ render={({ value, setValue }) => <ItemsPicker value={value} setValue={setValue} />}
300
+ />
301
+ </DataViews.Filters>
302
+ </DataViews.Panel.Tab>
303
+ </DataViews.Panel>
304
+ </DataViews>
305
+ </div>
306
+ );
307
+ }
308
+ ```