@krak-stack/registry 0.11.6 → 0.11.9

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 (123) hide show
  1. package/CHANGELOG.md +80 -0
  2. package/README.md +39 -0
  3. package/dist/components/app-switcher/html.d.ts +2 -2
  4. package/dist/components/asset-input/html.d.ts +70 -0
  5. package/dist/components/asset-input/html.js +1549 -0
  6. package/dist/components/asset-input/index.d.ts +280 -0
  7. package/dist/components/asset-input/react.d.ts +32 -0
  8. package/dist/components/asset-input/react.js +2269 -0
  9. package/dist/components/asset-input/schema.d.ts +93 -0
  10. package/dist/components/asset-input/upload.d.ts +15 -0
  11. package/dist/components/asset-table/html.d.ts +110 -0
  12. package/dist/components/asset-table/html.js +4934 -0
  13. package/dist/components/asset-table/index.d.ts +225 -0
  14. package/dist/components/asset-table/react.d.ts +21 -0
  15. package/dist/components/asset-table/react.js +8241 -0
  16. package/dist/components/asset-table/schema.d.ts +73 -0
  17. package/dist/components/audit-log-table/classes.d.ts +1 -0
  18. package/dist/components/audit-log-table/html.d.ts +158 -0
  19. package/dist/components/audit-log-table/html.js +3294 -0
  20. package/dist/components/audit-log-table/index.d.ts +37 -0
  21. package/dist/components/audit-log-table/react.d.ts +3 -51
  22. package/dist/components/audit-log-table/react.js +130 -89
  23. package/dist/components/audit-log-table/schema.d.ts +122 -0
  24. package/dist/components/danger-confirmation/html.d.ts +2 -2
  25. package/dist/components/danger-confirmation/index.d.ts +2 -2
  26. package/dist/components/data-table/classes.d.ts +3 -0
  27. package/dist/components/data-table/html.d.ts +70 -12
  28. package/dist/components/data-table/html.js +56 -19
  29. package/dist/components/data-table/index.d.ts +51 -1
  30. package/dist/components/data-table/react.d.ts +1 -0
  31. package/dist/components/data-table/react.js +46 -16
  32. package/dist/components/data-table/schema.d.ts +93 -3
  33. package/dist/components/docs/html.js +22 -4
  34. package/dist/components/docs/react.js +33 -2
  35. package/dist/components/editable-text/html.d.ts +2 -2
  36. package/dist/components/editable-text/index.d.ts +4 -4
  37. package/dist/components/effect-form/react.js +343 -138
  38. package/dist/components/email-editor/legacy-editor.html.d.ts +6 -6
  39. package/dist/components/file-input/classes.d.ts +1 -1
  40. package/dist/components/file-input/file-type.d.ts +1 -0
  41. package/dist/components/file-input/html.d.ts +8 -1
  42. package/dist/components/file-input/html.js +170 -12
  43. package/dist/components/file-input/index.d.ts +1 -0
  44. package/dist/components/file-input/react.d.ts +9 -1
  45. package/dist/components/file-input/react.js +277 -127
  46. package/dist/components/file-input/schema.d.ts +1 -0
  47. package/dist/components/form/react.js +343 -138
  48. package/dist/components/icon-input/html.js +19 -5
  49. package/dist/components/icon-input/react.js +70 -13
  50. package/dist/components/map-menu/html.d.ts +6 -0
  51. package/dist/components/map-menu/html.js +13 -8
  52. package/dist/components/map-menu/index.d.ts +5 -4
  53. package/dist/components/map-menu/react.d.ts +28 -17
  54. package/dist/components/map-menu/react.js +84 -178
  55. package/dist/components/map-menu/schema.d.ts +6 -0
  56. package/dist/components/map-menu/shared.d.ts +4 -0
  57. package/dist/components/permissions-input/classes.d.ts +8 -0
  58. package/dist/components/permissions-input/html.d.ts +41 -0
  59. package/dist/components/permissions-input/html.js +130 -0
  60. package/dist/components/permissions-input/index.d.ts +80 -0
  61. package/dist/components/permissions-input/react.d.ts +7 -0
  62. package/dist/components/permissions-input/react.js +201 -0
  63. package/dist/components/permissions-input/schema.d.ts +33 -0
  64. package/dist/components/phone-number-input/html.js +48 -14
  65. package/dist/components/phone-number-input/react.js +67 -10
  66. package/dist/components/search-menu/html.d.ts +2 -2
  67. package/dist/components/select-with-custom-input/html.d.ts +2 -2
  68. package/dist/components/sidebar-layout/html.d.ts +3 -2
  69. package/dist/components/sidebar-layout/html.js +20 -2
  70. package/dist/components/sidebar-layout/index.d.ts +1 -0
  71. package/dist/components/sidebar-layout/react.js +33 -2
  72. package/dist/components/switch/react.d.ts +14 -0
  73. package/dist/components/switch/react.js +55 -0
  74. package/dist/components/theme-switcher/html.d.ts +2 -2
  75. package/dist/components/time-input/html.d.ts +2 -2
  76. package/dist/components/timezone-input/html.js +48 -14
  77. package/dist/components/timezone-input/react.js +67 -10
  78. package/dist/components/tracking-notice/classes.d.ts +6 -0
  79. package/dist/components/tracking-notice/html.d.ts +85 -0
  80. package/dist/components/tracking-notice/html.js +354 -0
  81. package/dist/components/tracking-notice/index.d.ts +95 -0
  82. package/dist/components/tracking-notice/react.d.ts +5 -27
  83. package/dist/components/tracking-notice/react.js +189 -59
  84. package/dist/components/tracking-notice/schema.d.ts +45 -0
  85. package/dist/components/upload-attachment/classes.d.ts +3 -2
  86. package/dist/components/upload-attachment/html.d.ts +5 -5
  87. package/dist/components/upload-attachment/html.js +7 -5
  88. package/dist/components/upload-attachment/react.d.ts +3 -1
  89. package/dist/components/upload-attachment/react.js +25 -17
  90. package/dist/components/virtualized-combobox/classes.d.ts +12 -0
  91. package/dist/components/virtualized-combobox/html.d.ts +42 -0
  92. package/dist/components/virtualized-combobox/html.js +48 -14
  93. package/dist/components/virtualized-combobox/index.d.ts +55 -4
  94. package/dist/components/virtualized-combobox/react.d.ts +6 -2
  95. package/dist/components/virtualized-combobox/react.js +67 -10
  96. package/dist/components/virtualized-combobox/schema.d.ts +60 -4
  97. package/dist/components/webhook-delivery-table/html.js +56 -19
  98. package/dist/components/webhook-delivery-table/react.js +46 -16
  99. package/dist/lib/access/index.d.ts +61 -0
  100. package/dist/lib/access/index.js +92 -0
  101. package/dist/lib/access/table/classes.d.ts +13 -0
  102. package/dist/lib/access/table/html.d.ts +39 -0
  103. package/dist/lib/access/table/html.js +157 -0
  104. package/dist/lib/access/table/index.d.ts +32 -0
  105. package/dist/lib/access/table/react.d.ts +3 -0
  106. package/dist/lib/access/table/react.js +195 -0
  107. package/dist/lib/access/table/schema.d.ts +43 -0
  108. package/dist/lib/docs.integrations.server.js +23 -1
  109. package/dist/lib/docs.js +33 -2
  110. package/dist/lib/docs.server.js +29 -2
  111. package/dist/lib/documentation-toolkit.js +23 -1
  112. package/dist/lib/effect-ui-adapter/use-model.d.ts +1 -1
  113. package/dist/lib/effect-ui-adapter/use-model.js +19 -11
  114. package/dist/lib/lucide-effect.d.ts +19 -19
  115. package/dist/lib/lucide-effect.js +38 -38
  116. package/dist/services/assets/library.d.ts +221 -0
  117. package/dist/services/assets/schema.d.ts +3 -0
  118. package/dist/services/assets/url.d.ts +12 -0
  119. package/dist/services/assets/use-library.d.ts +20 -0
  120. package/dist/services/events/browser.js +39 -26
  121. package/dist/services/events/index.js +23 -19
  122. package/dist/services/opentelemetry/web-vitals.js +27 -23
  123. package/package.json +21 -1
@@ -0,0 +1,3294 @@
1
+ // ../../src/components/audit-log-table/html.ts
2
+ import { Schema as Schema11 } from "effect";
3
+ import { Component as Component3, UiSchema as UiSchema4 } from "effect/ui";
4
+ import { Html as Html3 } from "effect/ui/html";
5
+
6
+ // ../../src/components/data-table/html.ts
7
+ import { Array as Arr, Schema as Schema6, Stream as Stream2 } from "effect";
8
+ import { Mount, UiSchema as UiSchema3 } from "effect/ui";
9
+ import { Html as Html2 } from "effect/ui/html";
10
+ import { Checkbox, Menu, Menubar, Select as Select2, VirtualList } from "effect/ui/kit";
11
+ import { Button as Button2, buttonVariants } from "@/components/effectcn/button";
12
+ import {
13
+ CheckboxIndicator,
14
+ CheckboxRoot
15
+ } from "@/components/effectcn/checkbox";
16
+ import { Input } from "@/components/effectcn/input";
17
+ import {
18
+ MenuCheckboxItem,
19
+ MenuEmpty,
20
+ MenuInput,
21
+ MenuItem,
22
+ MenuPopup,
23
+ MenuPositioner,
24
+ MenuRadioItem,
25
+ MenuSeparator,
26
+ MenuSubTrigger
27
+ } from "@/components/effectcn/menu";
28
+ import { MenubarRoot, MenubarTrigger } from "@/components/effectcn/menubar";
29
+ import {
30
+ SelectIcon as SelectIcon2,
31
+ SelectItem as SelectItem2,
32
+ SelectItemIndicator as SelectItemIndicator2,
33
+ SelectItemText as SelectItemText2,
34
+ SelectLabel as SelectLabel2,
35
+ SelectList as SelectList2,
36
+ SelectPopup as SelectPopup2,
37
+ SelectPositioner as SelectPositioner2,
38
+ SelectTrigger as SelectTrigger2,
39
+ SelectValue as SelectValue2
40
+ } from "@/components/effectcn/select";
41
+ import { krakstackLocaleRead as krakstackLocaleRead2 } from "@krak-stack/registry/krakstack-provider/html";
42
+
43
+ // ../../src/components/pagination/html.ts
44
+ import { Html } from "effect/ui/html";
45
+ import { Select } from "effect/ui/kit";
46
+ import { Button } from "@/components/effectcn/button";
47
+ import {
48
+ SelectIcon,
49
+ SelectItem,
50
+ SelectItemIndicator,
51
+ SelectItemText,
52
+ SelectLabel,
53
+ SelectList,
54
+ SelectPopup,
55
+ SelectPositioner,
56
+ SelectScrollDownArrow,
57
+ SelectScrollUpArrow,
58
+ SelectTrigger,
59
+ SelectValue
60
+ } from "@/components/effectcn/select";
61
+ import { krakstackLocaleRead } from "@krak-stack/registry/krakstack-provider/html";
62
+ import {
63
+ ChevronLeft,
64
+ ChevronRight,
65
+ ChevronsLeft,
66
+ ChevronsRight
67
+ } from "@krak-stack/registry/lucide-effect";
68
+
69
+ // ../../src/lib/utils.ts
70
+ import { cn } from "cn";
71
+
72
+ // ../../src/components/pagination/classes.ts
73
+ var paginationClasses = {
74
+ root: "flex flex-col gap-3 px-2 sm:flex-row sm:items-center sm:justify-between",
75
+ summary: "text-muted-foreground flex flex-wrap items-center gap-x-3 gap-y-1 text-sm",
76
+ controls: "flex items-center gap-4 sm:justify-end",
77
+ controlGroup: "flex items-center gap-2",
78
+ navigation: "flex items-center gap-1",
79
+ compactRoot: "gap-2 px-0 sm:flex-col sm:items-stretch",
80
+ compactControls: "flex-wrap justify-between gap-2 sm:justify-between"
81
+ };
82
+ var resolvePaginationClasses = (overrides) => ({
83
+ ...paginationClasses,
84
+ ...overrides
85
+ });
86
+
87
+ // ../../src/components/pagination/index.ts
88
+ import { Schema as Schema2 } from "effect";
89
+ import { Component, UiSchema } from "effect/ui";
90
+
91
+ // ../../src/components/pagination/schema.ts
92
+ import { Schema, Struct } from "effect";
93
+ var Labels = Schema.Struct({
94
+ pageSize: Schema.optional(Schema.String),
95
+ goToFirstPage: Schema.optional(Schema.String),
96
+ goToPreviousPage: Schema.optional(Schema.String),
97
+ goToNextPage: Schema.optional(Schema.String),
98
+ goToLastPage: Schema.optional(Schema.String)
99
+ }).annotate({ identifier: "PaginationLabelOverrides" });
100
+ var Translations = Schema.Record(Schema.String, Schema.UndefinedOr(Labels));
101
+ var PaginationClassesOverridesSchema = Schema.Record(Schema.Literals(Struct.keys(paginationClasses)), Schema.optionalKey(Schema.String)).annotate({ identifier: "PaginationClassesOverrides" });
102
+ var PaginationPropsSchema = Schema.Struct({
103
+ classes: Schema.optional(PaginationClassesOverridesSchema),
104
+ className: Schema.optional(Schema.String),
105
+ pageSizeContentClassName: Schema.optional(Schema.String),
106
+ compact: Schema.optional(Schema.Boolean),
107
+ locale: Schema.optional(Schema.String),
108
+ messages: Schema.optional(Translations),
109
+ page: Schema.Int,
110
+ pageCount: Schema.Int,
111
+ pageSize: Schema.Int,
112
+ pageSizes: Schema.optional(Schema.Array(Schema.Int)),
113
+ selectedRows: Schema.optional(Schema.Int),
114
+ showResults: Schema.optional(Schema.Boolean),
115
+ totalRows: Schema.Int
116
+ }).annotate({ identifier: "PaginationProps" });
117
+
118
+ // ../../src/components/pagination/index.ts
119
+ var PaginationMessage = UiSchema.TaggedEnum({
120
+ Opened: {},
121
+ Closed: {},
122
+ PageRequested: { page: Schema2.Int },
123
+ SizeRequested: { pageSize: Schema2.Int }
124
+ }).annotate({ identifier: "PaginationMessage" });
125
+ var PaginationEvents = UiSchema.TaggedEnum({
126
+ PageChanged: { page: Schema2.Int },
127
+ PageSizeChanged: { pageSize: Schema2.Int }
128
+ }).annotate({ identifier: "PaginationEvents" });
129
+ var paginationOptions = {
130
+ name: "Pagination",
131
+ props: PaginationPropsSchema,
132
+ model: Schema2.Boolean,
133
+ message: PaginationMessage,
134
+ events: PaginationEvents,
135
+ restore: false
136
+ };
137
+ var update = Component.define(paginationOptions).update({
138
+ Opened: () => true,
139
+ Closed: () => false,
140
+ PageRequested: ($, { page }) => $.set($.model).emit(PaginationEvents.PageChanged({ page })),
141
+ SizeRequested: ($, { pageSize }) => $.set(false).emit(PaginationEvents.PageSizeChanged({ pageSize }))
142
+ });
143
+ var paginationBehaviours = {
144
+ init: () => false,
145
+ update
146
+ };
147
+ var messages = {
148
+ en: {
149
+ pageSize: "Page size",
150
+ results: (count) => `${count} results`,
151
+ selectedOf: (selected, total) => `${selected} of ${total}`,
152
+ pageOf: (page, total) => `Page ${page} of ${total}`,
153
+ goToFirstPage: "Go to first page",
154
+ goToPreviousPage: "Go to previous page",
155
+ goToNextPage: "Go to next page",
156
+ goToLastPage: "Go to last page"
157
+ },
158
+ fr: {
159
+ pageSize: "Taille de la page",
160
+ results: (count) => `${count} résultats`,
161
+ selectedOf: (selected, total) => `${selected} sur ${total}`,
162
+ pageOf: (page, total) => `Page ${page} sur ${total}`,
163
+ goToFirstPage: "Aller à la première page",
164
+ goToPreviousPage: "Aller à la page précédente",
165
+ goToNextPage: "Aller à la page suivante",
166
+ goToLastPage: "Aller à la dernière page"
167
+ }
168
+ };
169
+ var paginationMessages = (locale = "en", translations) => ({
170
+ ...locale.startsWith("fr") ? messages.fr : messages.en,
171
+ ...translations?.[locale.split("-")[0] ?? locale],
172
+ ...translations?.[locale]
173
+ });
174
+ var defaultPageSizes = [20, 50, 100];
175
+ var paginationPageLabel = (page, pageCount, pageOf) => pageCount > 0 ? pageOf(page + 1, pageCount) : undefined;
176
+ var paginationNavigation = (page, pageCount) => ({
177
+ goToFirstPage: {
178
+ page: 0,
179
+ disabled: pageCount <= 0 || page <= 0,
180
+ edge: true
181
+ },
182
+ goToPreviousPage: {
183
+ page: page - 1,
184
+ disabled: pageCount <= 0 || page <= 0,
185
+ edge: false
186
+ },
187
+ goToNextPage: {
188
+ page: page + 1,
189
+ disabled: pageCount <= 0 || page + 1 >= pageCount,
190
+ edge: false
191
+ },
192
+ goToLastPage: {
193
+ page: pageCount - 1,
194
+ disabled: pageCount <= 0 || page + 1 >= pageCount,
195
+ edge: true
196
+ }
197
+ });
198
+
199
+ // ../../src/components/pagination/html.ts
200
+ var icons = {
201
+ goToFirstPage: ChevronsLeft,
202
+ goToPreviousPage: ChevronLeft,
203
+ goToNextPage: ChevronRight,
204
+ goToLastPage: ChevronsRight
205
+ };
206
+ var Pagination = Html.component({
207
+ ...paginationOptions,
208
+ reads: { localeConfig: krakstackLocaleRead }
209
+ }).make({
210
+ ...paginationBehaviours,
211
+ view: (h, open) => {
212
+ const paginationClasses = resolvePaginationClasses(h.props.classes);
213
+ const {
214
+ compact,
215
+ page,
216
+ pageCount,
217
+ pageSize,
218
+ pageSizes = defaultPageSizes,
219
+ selectedRows = 0,
220
+ showResults = true,
221
+ totalRows
222
+ } = h.props;
223
+ const labels = paginationMessages(h.props.locale ?? h.reads.localeConfig?.locale, h.props.messages);
224
+ const navigation = paginationNavigation(page, pageCount);
225
+ const pageLabel = paginationPageLabel(page, pageCount, labels.pageOf);
226
+ const items = pageSizes.map((size) => ({
227
+ value: String(size),
228
+ label: String(size)
229
+ }));
230
+ return h.div.attr("data-slot", "pagination").class(cn(paginationClasses.root, compact && paginationClasses.compactRoot, h.props.className)).children(showResults && h.div.class(paginationClasses.summary).children(h.span.children(labels.results(totalRows)), selectedRows > 0 && h.span.children(labels.selectedOf(selectedRows, totalRows))), h.div.class(cn(paginationClasses.controls, compact && paginationClasses.compactControls)).children(Select(h, {
231
+ props: {
232
+ open,
233
+ items,
234
+ value: items.some(({ value }) => value === String(pageSize)) ? String(pageSize) : null,
235
+ placeholder: String(pageSize),
236
+ side: "top",
237
+ alignItemWithTrigger: false
238
+ },
239
+ onEmit: {
240
+ RequestedOpen: () => PaginationMessage.Opened(),
241
+ RequestedClose: () => PaginationMessage.Closed(),
242
+ Picked: ({ value }) => {
243
+ const selected = pageSizes.find((size) => String(size) === value);
244
+ return selected === undefined ? undefined : PaginationMessage.SizeRequested({ pageSize: selected });
245
+ },
246
+ Settled: () => {
247
+ return;
248
+ }
249
+ },
250
+ view: (select) => h.div.class(paginationClasses.controlGroup).children(SelectLabel(h, select, {
251
+ class: cn("mb-0", !compact && "sr-only sm:not-sr-only")
252
+ }).children(labels.pageSize), SelectTrigger(h, select, {
253
+ size: "sm",
254
+ class: "min-w-0"
255
+ }).children(SelectValue(h, select), SelectIcon(h, select)), SelectPositioner(h, select).children(SelectPopup(h, select, {
256
+ size: "sm",
257
+ class: h.props.pageSizeContentClassName
258
+ }).children(SelectScrollUpArrow(h, select), SelectList(h, select).children(...items.map(({ value, label }) => SelectItem(h, select, { value }).children(SelectItemText(h, select).children(label), SelectItemIndicator(h, select, { value })))), SelectScrollDownArrow(h, select))))
259
+ }), h.div.class(paginationClasses.controlGroup).children(pageLabel !== undefined && h.div.class("text-sm font-medium").children(pageLabel), h.div.class(paginationClasses.navigation).children(...[
260
+ "goToFirstPage",
261
+ "goToPreviousPage",
262
+ "goToNextPage",
263
+ "goToLastPage"
264
+ ].map((key) => {
265
+ const Icon = icons[key];
266
+ const control = navigation[key];
267
+ return Button(h, {
268
+ size: "icon-sm",
269
+ class: control.edge ? compact ? "hidden" : "hidden lg:inline-flex" : undefined,
270
+ props: { type: "button", disabled: control.disabled },
271
+ onPress: PaginationMessage.PageRequested({ page: control.page })
272
+ }).key(key).attr("aria-label", labels[key]).children(Icon(h));
273
+ })))));
274
+ }
275
+ });
276
+
277
+ // ../../src/lib/query.ts
278
+ import {
279
+ DateTime,
280
+ Effect,
281
+ Option,
282
+ Schema as Schema3,
283
+ SchemaGetter,
284
+ SchemaIssue,
285
+ SchemaTransformation
286
+ } from "effect";
287
+ var parseSortParam = (sort) => {
288
+ const id = sort.startsWith("-") ? sort.slice(1) : sort;
289
+ if (!id || id.includes(",") || id.includes(":")) {
290
+ return null;
291
+ }
292
+ return { id, direction: sort.startsWith("-") ? "desc" : "asc" };
293
+ };
294
+ var SortDirection = Schema3.Union([
295
+ Schema3.Literal("asc"),
296
+ Schema3.Literal("desc")
297
+ ]).pipe(Schema3.annotate({
298
+ identifier: "SortDirection",
299
+ title: "Sort Direction",
300
+ description: "Sort direction for list query results.",
301
+ examples: ["asc", "desc"]
302
+ }));
303
+ var SortParam = Schema3.Struct({
304
+ id: Schema3.NonEmptyString,
305
+ direction: SortDirection
306
+ }).pipe(Schema3.annotate({
307
+ identifier: "SortParam",
308
+ title: "Sort Parameter",
309
+ description: "Decoded sort parameter with a field id and direction.",
310
+ examples: [{ id: "publicName", direction: "asc" }]
311
+ }));
312
+ var SortParamFromString = Schema3.String.pipe(Schema3.decodeTo(SortParam, SchemaTransformation.transformEffect({
313
+ decode: (sort) => {
314
+ const sortParam = parseSortParam(sort);
315
+ if (!sortParam) {
316
+ return Effect.fail(new SchemaIssue.InvalidValue({ message: 'Expected sort in the format "field" or "-field"' }, sort));
317
+ }
318
+ return Effect.succeed(sortParam);
319
+ },
320
+ encode: (sort) => Effect.succeed(sort.direction === "desc" ? `-${sort.id}` : sort.id)
321
+ })), Schema3.annotate({
322
+ identifier: "SortParamFromString",
323
+ title: "Sort Parameter From String",
324
+ description: 'URL encoded single sort parameter where descending fields are prefixed with "-".',
325
+ examples: [{ id: "publicName", direction: "asc" }]
326
+ }));
327
+ var SortParamsFromString = Schema3.String.pipe(Schema3.decodeTo(Schema3.Array(SortParam), SchemaTransformation.transformEffect({
328
+ decode: (sort) => {
329
+ if (sort === "")
330
+ return Effect.succeed([]);
331
+ const parts = sort.split(",");
332
+ const sortParams = [];
333
+ for (const part of parts) {
334
+ const sortParam = parseSortParam(part);
335
+ if (!sortParam) {
336
+ return Effect.fail(new SchemaIssue.InvalidValue({ message: 'Expected sort in the format "field,-otherField"' }, sort));
337
+ }
338
+ sortParams.push(sortParam);
339
+ }
340
+ return Effect.succeed(sortParams);
341
+ },
342
+ encode: (sort) => Effect.succeed(sort.map((part) => Schema3.encodeSync(SortParamFromString)(part)).join(","))
343
+ })), Schema3.annotate({
344
+ identifier: "SortParamsFromString",
345
+ title: "Sort Parameters From String",
346
+ description: 'URL encoded sort parameters where descending fields are prefixed with "-" and multiple fields are comma-separated.',
347
+ examples: [
348
+ [
349
+ { id: "name", direction: "desc" },
350
+ { id: "age", direction: "asc" }
351
+ ]
352
+ ]
353
+ }));
354
+ var SortParamsArray = Schema3.Array(SortParam);
355
+ var SortParams = Schema3.declare(Schema3.is(SortParamsArray), {
356
+ identifier: "SortParams",
357
+ toCodec: () => Schema3.link()(SortParamsArray, SchemaTransformation.passthrough()),
358
+ toCodecStringTree: () => Schema3.link()(SortParamsFromString, SchemaTransformation.passthrough())
359
+ });
360
+ var TextFilterOperator = Schema3.Literals([
361
+ "contains",
362
+ "equals",
363
+ "startsWith",
364
+ "endsWith"
365
+ ]).annotate({ identifier: "TextFilterOperator" });
366
+ var FilterCalendarDate = Schema3.String.check(Schema3.isPattern(/^\d{4}-\d{2}-\d{2}$/), Schema3.makeFilter((value) => Option.exists(DateTime.make(value), (date) => DateTime.formatIsoDateUtc(date) === value))).annotate({ identifier: "FilterCalendarDate" });
367
+ var ColumnFilter = Schema3.Union([
368
+ Schema3.Struct({
369
+ id: Schema3.NonEmptyString,
370
+ kind: Schema3.Literal("text"),
371
+ operator: TextFilterOperator,
372
+ value: Schema3.NonEmptyString
373
+ }),
374
+ Schema3.Struct({
375
+ id: Schema3.NonEmptyString,
376
+ kind: Schema3.Literal("number"),
377
+ min: Schema3.optional(Schema3.Finite),
378
+ max: Schema3.optional(Schema3.Finite)
379
+ }).check(Schema3.makeFilter((range) => (range.min !== undefined || range.max !== undefined) && (range.min === undefined || range.max === undefined || range.min <= range.max))),
380
+ Schema3.Struct({
381
+ id: Schema3.NonEmptyString,
382
+ kind: Schema3.Literal("date"),
383
+ from: Schema3.optional(FilterCalendarDate),
384
+ to: Schema3.optional(FilterCalendarDate)
385
+ }).check(Schema3.makeFilter((range) => (range.from !== undefined || range.to !== undefined) && (range.from === undefined || range.to === undefined || range.from <= range.to))),
386
+ Schema3.Struct({
387
+ id: Schema3.NonEmptyString,
388
+ kind: Schema3.Literal("boolean"),
389
+ value: Schema3.Boolean
390
+ }),
391
+ Schema3.Struct({
392
+ id: Schema3.NonEmptyString,
393
+ kind: Schema3.Literal("values"),
394
+ values: Schema3.NonEmptyArray(Schema3.String)
395
+ })
396
+ ]).annotate({ identifier: "ColumnFilter" });
397
+ var ColumnFiltersArray = Schema3.Array(ColumnFilter);
398
+ var ColumnFilters = Schema3.declare(Schema3.is(ColumnFiltersArray), {
399
+ identifier: "ColumnFilters",
400
+ toCodec: () => Schema3.link()(ColumnFiltersArray, SchemaTransformation.passthrough()),
401
+ toCodecStringTree: () => Schema3.link()(Schema3.fromJsonString(ColumnFiltersArray), SchemaTransformation.passthrough())
402
+ });
403
+ var DEFAULT_PAGE_SIZE = 100;
404
+ var Query = Schema3.Struct({
405
+ page: Schema3.optional(Schema3.Union([Schema3.Finite, Schema3.FiniteFromString]).check(Schema3.isInt(), Schema3.isGreaterThanOrEqualTo(0))).pipe(Schema3.decodeTo(Schema3.Int.check(Schema3.isGreaterThanOrEqualTo(0)), {
406
+ decode: SchemaGetter.withDefault(Effect.succeed(0)),
407
+ encode: SchemaGetter.transformOptional(Option.filter((page) => page !== 0))
408
+ })),
409
+ pageSize: Schema3.optional(Schema3.Union([Schema3.Finite, Schema3.FiniteFromString]).check(Schema3.isInt(), Schema3.isBetween({ minimum: 1, maximum: 100 }))).pipe(Schema3.decodeTo(Schema3.Int.check(Schema3.isBetween({ minimum: 1, maximum: 100 })), {
410
+ decode: SchemaGetter.withDefault(Effect.succeed(DEFAULT_PAGE_SIZE)),
411
+ encode: SchemaGetter.transformOptional(Option.filter((pageSize) => pageSize !== DEFAULT_PAGE_SIZE))
412
+ })),
413
+ globalFilter: Schema3.optional(Schema3.String),
414
+ sort: Schema3.optional(SortParams),
415
+ filters: Schema3.optional(ColumnFilters)
416
+ }).annotate({
417
+ identifier: "Query",
418
+ title: "Query",
419
+ description: "Zero-based page request parameters with optional filtering and sorting for list endpoints.",
420
+ examples: [
421
+ {
422
+ page: 0,
423
+ pageSize: DEFAULT_PAGE_SIZE,
424
+ globalFilter: "housing",
425
+ sort: [
426
+ { id: "publicName", direction: "desc" },
427
+ { id: "createdAt", direction: "asc" }
428
+ ]
429
+ }
430
+ ]
431
+ });
432
+ var QueryStandard = Schema3.toStandardSchemaV1(Query);
433
+ var PaginationMeta = Schema3.Struct({
434
+ page: Schema3.Int,
435
+ pageSize: Schema3.Int,
436
+ total: Schema3.Int,
437
+ pageCount: Schema3.Int
438
+ }).pipe(Schema3.annotate({
439
+ identifier: "PaginationMeta",
440
+ title: "Pagination Metadata",
441
+ description: "Pagination metadata returned with a paginated list response.",
442
+ examples: [{ page: 0, pageSize: 20, total: 125, pageCount: 7 }]
443
+ }));
444
+
445
+ // ../../src/components/data-table/html.ts
446
+ import {
447
+ ArrowDown,
448
+ ArrowUp,
449
+ ChevronDown,
450
+ ChevronRight as ChevronRight2,
451
+ ChevronsUpDown,
452
+ Download,
453
+ Ellipsis,
454
+ EyeOff,
455
+ FileJson,
456
+ FileText,
457
+ GripVertical,
458
+ LayoutGrid,
459
+ ListFilter,
460
+ RefreshCw,
461
+ Rows3,
462
+ Search,
463
+ Settings2,
464
+ X
465
+ } from "@krak-stack/registry/lucide-effect";
466
+
467
+ // ../../src/components/data-table/index.ts
468
+ import { DateTime as DateTime3, Effect as Effect2, Option as Option3, Redacted, Schema as Schema5, Stream } from "effect";
469
+ import { Csv } from "effect/encoding";
470
+ import { Command, Component as Component2, Subscription, UiSchema as UiSchema2 } from "effect/ui";
471
+
472
+ // ../../src/components/data-table/schema.ts
473
+ import { DateTime as DateTime2, Option as Option2, Predicate, Schema as Schema4, Struct as Struct2, Tuple } from "effect";
474
+
475
+ // ../../src/components/data-table/classes.ts
476
+ var booleanCellControl = "flex min-h-16 w-full items-center justify-start px-2 in-[[data-slot=table-cell]]:absolute in-[[data-slot=table-cell]]:inset-0 in-[[data-slot=table-cell]]:min-h-0 has-[:focus-visible]:outline-2 has-[:focus-visible]:-outline-offset-2 has-[:focus-visible]:outline-ring";
477
+ var cellTriggerFocus = "focus-visible:ring-0 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring";
478
+ var tableBadgeTones = {
479
+ success: "border-emerald-200 bg-emerald-100 text-emerald-900 dark:border-emerald-900/50 dark:bg-emerald-950/50 dark:text-emerald-200",
480
+ info: "border-blue-200 bg-blue-100 text-blue-900 dark:border-blue-900/50 dark:bg-blue-950/50 dark:text-blue-200",
481
+ muted: "border-muted bg-muted text-muted-foreground dark:bg-muted/50"
482
+ };
483
+ var tableClasses = {
484
+ selectionCell: "w-10 p-0 align-middle",
485
+ selectionCenter: "grid place-items-center",
486
+ count: "inline-flex min-w-5 shrink-0 items-center justify-center rounded-full bg-secondary px-1.5 py-0.5 text-xs font-medium tabular-nums text-secondary-foreground",
487
+ selectedTrigger: "bg-primary text-primary-foreground hover:bg-primary/90 hover:text-primary-foreground",
488
+ toolbar: "flex min-w-0 shrink-0 flex-wrap items-center gap-2",
489
+ toolbarSearch: "relative min-w-0 flex-[1_1_12rem]",
490
+ toolbarMenus: "w-max min-w-0 max-w-full",
491
+ menubar: "h-auto w-full flex-wrap justify-start border border-input bg-transparent",
492
+ cell: "overflow-hidden",
493
+ cellContent: "min-w-0 wrap-anywhere",
494
+ actionTrigger: `size-8 ${cellTriggerFocus}`,
495
+ actionsCell: "sticky right-0 z-20 w-10 min-w-10 cursor-default bg-background p-0 transition-colors group-hover/row:bg-[color-mix(in_oklab,var(--muted)_50%,var(--background))]",
496
+ actionsAlign: "flex min-h-12 items-center justify-end pe-1",
497
+ row: "h-16 [&:where(:not(:last-child))>td]:border-b",
498
+ header: "relative h-12 p-0",
499
+ stickyHeader: "sticky top-0 z-30 bg-background",
500
+ stickyHeaderRule: "after:border-border after:pointer-events-none after:absolute after:inset-x-0 after:bottom-0 after:border-b",
501
+ headerTrigger: `absolute inset-0 h-full w-full min-w-0 justify-start rounded-none px-2 pe-4 ${cellTriggerFocus}`,
502
+ resizeHandle: "absolute inset-y-0 right-0 z-10 w-2 cursor-col-resize touch-none outline-none after:absolute after:inset-y-3 after:right-0 after:w-px after:bg-border hover:after:w-0.5 hover:after:bg-primary/60 focus-visible:after:w-0.5 focus-visible:after:bg-ring",
503
+ relationshipCell: "grid min-h-16 in-[[data-slot=table-cell]]:absolute in-[[data-slot=table-cell]]:inset-0 in-[[data-slot=table-cell]]:min-h-0",
504
+ relationshipTrigger: `h-full w-full min-w-0 justify-between rounded-none px-2 text-start ${cellTriggerFocus}`,
505
+ reference: "flex min-w-0 items-center gap-2",
506
+ referenceAvatar: "relative grid size-8 shrink-0 place-items-center overflow-hidden bg-muted text-xs font-medium",
507
+ referenceText: "flex min-w-0 flex-col leading-tight",
508
+ group: "bg-muted/40 hover:bg-accent!",
509
+ groupContent: "flex min-w-0 items-center gap-2 py-2 pe-1 ps-2",
510
+ groupSticky: "sticky start-0 w-[100cqw] max-w-full",
511
+ groupTrigger: "flex min-w-0 flex-1 cursor-pointer items-center gap-2 text-start font-medium",
512
+ referenceName: "truncate font-medium",
513
+ referenceDescription: "text-muted-foreground truncate text-xs"
514
+ };
515
+ var tableResultsFooterClass = "bg-background text-muted-foreground sticky bottom-0 z-30 shrink-0 border-t px-2 py-2 text-sm";
516
+ var resolveTableClasses = (overrides) => ({
517
+ ...tableClasses,
518
+ ...overrides
519
+ });
520
+
521
+ // ../../src/components/data-table/schema.ts
522
+ var TableClassesOverridesSchema = Schema4.Record(Schema4.Literals(Struct2.keys(tableClasses)), Schema4.optionalKey(Schema4.String)).annotate({ identifier: "TableClassesOverrides" });
523
+ var DataTableCommonPropsSchema = Schema4.Struct({
524
+ classes: Schema4.optional(TableClassesOverridesSchema),
525
+ className: Schema4.optionalKey(Schema4.String),
526
+ locale: Schema4.optionalKey(Schema4.String)
527
+ }).annotate({ identifier: "DataTableCommonProps" });
528
+ var DataTableSortSchema = Schema4.Struct({
529
+ id: Schema4.NonEmptyString,
530
+ direction: Schema4.Literals(["asc", "desc"])
531
+ }).annotate({ identifier: "DataTableSort" });
532
+ var queryFields = {
533
+ page: Schema4.Int.check(Schema4.isGreaterThanOrEqualTo(0)),
534
+ pageSize: Schema4.Int.check(Schema4.isBetween({ minimum: 1, maximum: 100 })),
535
+ globalFilter: Schema4.optional(Schema4.String),
536
+ sort: Schema4.optional(Schema4.Array(DataTableSortSchema)),
537
+ filters: Schema4.optional(Schema4.Array(ColumnFilter))
538
+ };
539
+ var DataTableQuerySchema = Schema4.Struct(queryFields).annotate({
540
+ identifier: "DataTableQuery"
541
+ });
542
+ var PageSizes = Schema4.NonEmptyArray(Schema4.Int.check(Schema4.isBetween({ minimum: 1, maximum: 100 })));
543
+ var DataTableCommonFeaturesSchema = Schema4.Struct({
544
+ search: Schema4.optionalKey(Schema4.Boolean),
545
+ filtering: Schema4.optionalKey(Schema4.Boolean),
546
+ sorting: Schema4.optionalKey(Schema4.Boolean),
547
+ columnVisibility: Schema4.optionalKey(Schema4.Boolean)
548
+ });
549
+ var PaginationSchema = Schema4.Union([
550
+ Schema4.Struct({
551
+ mode: Schema4.optionalKey(Schema4.Literal("client")),
552
+ pageSizes: Schema4.optionalKey(PageSizes)
553
+ }).annotate({ identifier: "DataTableClientPagination" }),
554
+ Schema4.Struct({
555
+ mode: Schema4.Literal("server"),
556
+ rowCount: Schema4.Int.check(Schema4.isGreaterThanOrEqualTo(0)),
557
+ pageSizes: Schema4.optionalKey(PageSizes)
558
+ }).annotate({ identifier: "DataTableServerPagination" })
559
+ ]);
560
+ var DataTableItemSchema = Schema4.Struct({
561
+ value: Schema4.NonEmptyString,
562
+ label: Schema4.String
563
+ }).annotate({ identifier: "DataTableItem" });
564
+ var TableIconSchema = Schema4.declare((value) => Predicate.isFunction(value)).annotate({ identifier: "DataTableIcon" });
565
+ var DataTableReferenceSchema = Schema4.Struct({
566
+ label: Schema4.String,
567
+ description: Schema4.optionalKey(Schema4.String),
568
+ imageSrc: Schema4.optionalKey(Schema4.NullOr(Schema4.String))
569
+ }).annotate({ identifier: "DataTableReference" });
570
+ var CalendarDate = Schema4.String.check(Schema4.isPattern(/^\d{4}-\d{2}-\d{2}$/), Schema4.makeFilter((value) => Option2.exists(DateTime2.make(value), (date) => DateTime2.formatIsoDateUtc(date) === value))).annotate({ identifier: "DataTableCalendarDate" });
571
+ var isCalendarDate = Schema4.is(CalendarDate);
572
+ var InstantString = Schema4.String.check(Schema4.isPattern(/^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/), Schema4.makeFilter((value) => isCalendarDate(value.slice(0, 10)))).annotate({ identifier: "DataTableInstantString" });
573
+ var DataTableDateInputSchema = Schema4.Union([
574
+ Schema4.Date,
575
+ Schema4.Int,
576
+ CalendarDate,
577
+ InstantString
578
+ ]).annotate({ identifier: "DataTableDateInput" });
579
+ var DateStyle = Schema4.Literals(["full", "long", "medium", "short"]);
580
+ var DataTableDateFormatSchema = Schema4.Struct({
581
+ locale: Schema4.optionalKey(Schema4.String),
582
+ timeZone: Schema4.optionalKey(Schema4.String),
583
+ dateStyle: Schema4.optionalKey(DateStyle),
584
+ exportFormat: Schema4.optionalKey(Schema4.Literals(["iso", "formatted"]))
585
+ }).annotate({ identifier: "DataTableDateFormat" });
586
+ var DataTableDateTimeFormatSchema = Schema4.Struct({
587
+ ...DataTableDateFormatSchema.fields,
588
+ timeStyle: Schema4.optionalKey(DateStyle),
589
+ hour12: Schema4.optionalKey(Schema4.Boolean)
590
+ }).annotate({ identifier: "DataTableDateTimeFormat" });
591
+ var DataTableCellValueSchema = Schema4.NullOr(Schema4.Union([
592
+ Schema4.String,
593
+ Schema4.Boolean,
594
+ Schema4.Finite,
595
+ Schema4.Array(DataTableItemSchema),
596
+ DataTableReferenceSchema
597
+ ])).annotate({ identifier: "DataTableCellValue" });
598
+ var DataTableActionSchema = Schema4.Struct({
599
+ id: Schema4.NonEmptyString,
600
+ name: Schema4.String,
601
+ variant: Schema4.optionalKey(Schema4.Literals(["default", "destructive"])),
602
+ disabled: Schema4.optionalKey(Schema4.Boolean)
603
+ }).annotate({ identifier: "DataTableAction" });
604
+ var DataTableRowActionSchema = Schema4.Struct({
605
+ ...DataTableActionSchema.fields,
606
+ icon: Schema4.optionalKey(TableIconSchema)
607
+ }).annotate({ identifier: "DataTableRowAction" });
608
+ var DataTableRowSchema = Schema4.Struct({
609
+ id: Schema4.NonEmptyString,
610
+ label: Schema4.String,
611
+ cells: Schema4.Record(Schema4.String, DataTableCellValueSchema),
612
+ actions: Schema4.optionalKey(Schema4.Array(DataTableRowActionSchema)),
613
+ primaryActionId: Schema4.optionalKey(Schema4.String),
614
+ groups: Schema4.optionalKey(Schema4.Record(Schema4.String, Schema4.Array(Schema4.String))),
615
+ selectable: Schema4.optionalKey(Schema4.Boolean),
616
+ disabledColumnIds: Schema4.optionalKey(Schema4.Array(Schema4.String))
617
+ }).annotate({ identifier: "DataTableRow" });
618
+ var column = {
619
+ id: Schema4.NonEmptyString,
620
+ headerName: Schema4.String,
621
+ sortable: Schema4.optionalKey(Schema4.Boolean),
622
+ hideable: Schema4.optionalKey(Schema4.Boolean),
623
+ export: Schema4.optionalKey(Schema4.Boolean),
624
+ width: Schema4.optionalKey(Schema4.Number),
625
+ minWidth: Schema4.optionalKey(Schema4.Number),
626
+ maxWidth: Schema4.optionalKey(Schema4.Number),
627
+ resizable: Schema4.optionalKey(Schema4.Boolean),
628
+ truncate: Schema4.optionalKey(Schema4.Boolean),
629
+ searchable: Schema4.optionalKey(Schema4.Boolean),
630
+ filterable: Schema4.optionalKey(Schema4.Boolean),
631
+ emptyLabel: Schema4.optionalKey(Schema4.String),
632
+ nulls: Schema4.optionalKey(Schema4.Literals(["first", "last"]))
633
+ };
634
+ var DataTableBadgeOptionSchema = Schema4.Struct({
635
+ value: Schema4.NonEmptyString,
636
+ label: Schema4.optionalKey(Schema4.String),
637
+ variant: Schema4.optionalKey(Schema4.Literals([
638
+ "default",
639
+ "secondary",
640
+ "outline",
641
+ "destructive",
642
+ "success",
643
+ "info",
644
+ "muted"
645
+ ]))
646
+ }).annotate({ identifier: "DataTableBadgeOption" });
647
+ var DataTableBadgeOptionsSchema = Schema4.Struct({
648
+ options: Schema4.optionalKey(Schema4.Array(DataTableBadgeOptionSchema.mapFields((fields) => ({
649
+ ...fields,
650
+ icon: Schema4.optionalKey(TableIconSchema)
651
+ }))))
652
+ }).annotate({ identifier: "DataTableBadgeOptions" });
653
+ var DataTableFieldSchema = Schema4.Union([
654
+ Schema4.Struct({
655
+ ...column,
656
+ type: Schema4.Literal("text"),
657
+ display: Schema4.optionalKey(Schema4.Literal("badge")),
658
+ typeOptions: Schema4.optionalKey(DataTableBadgeOptionsSchema)
659
+ }),
660
+ Schema4.Struct({
661
+ ...column,
662
+ type: Schema4.Literal("number"),
663
+ typeOptions: Schema4.optionalKey(Schema4.Struct({
664
+ locale: Schema4.optionalKey(Schema4.String),
665
+ format: Schema4.optionalKey(Schema4.Literal("bytes")),
666
+ style: Schema4.optionalKey(Schema4.Literals(["decimal", "percent", "currency", "unit"])),
667
+ currency: Schema4.optionalKey(Schema4.String),
668
+ unit: Schema4.optionalKey(Schema4.String),
669
+ notation: Schema4.optionalKey(Schema4.Literals(["standard", "scientific", "engineering", "compact"])),
670
+ minimumFractionDigits: Schema4.optionalKey(Schema4.Int.check(Schema4.isBetween({ minimum: 0, maximum: 20 }))),
671
+ maximumFractionDigits: Schema4.optionalKey(Schema4.Int.check(Schema4.isBetween({ minimum: 0, maximum: 20 }))),
672
+ exportFormat: Schema4.optionalKey(Schema4.Literals(["raw", "formatted"]))
673
+ }).annotate({ identifier: "DataTableNumberFormat" }))
674
+ }),
675
+ Schema4.Struct({
676
+ ...column,
677
+ type: Schema4.Literal("reference"),
678
+ typeOptions: Schema4.optionalKey(Schema4.Struct({
679
+ imageVariant: Schema4.optionalKey(Schema4.Literals(["circle", "square"])),
680
+ fallbackIcons: Schema4.optionalKey(Schema4.Record(Schema4.String, TableIconSchema))
681
+ }).annotate({ identifier: "DataTableReferenceOptions" }))
682
+ }),
683
+ Schema4.Struct({
684
+ ...column,
685
+ type: Schema4.Literal("date"),
686
+ typeOptions: Schema4.optionalKey(DataTableDateFormatSchema)
687
+ }),
688
+ Schema4.Struct({
689
+ ...column,
690
+ type: Schema4.Literal("dateTime"),
691
+ typeOptions: Schema4.optionalKey(DataTableDateTimeFormatSchema)
692
+ }),
693
+ Schema4.Struct({
694
+ ...column,
695
+ type: Schema4.Literal("boolean"),
696
+ editable: Schema4.optionalKey(Schema4.Boolean),
697
+ typeOptions: Schema4.optionalKey(Schema4.Struct({
698
+ trueLabel: Schema4.optionalKey(Schema4.String),
699
+ falseLabel: Schema4.optionalKey(Schema4.String),
700
+ exportFormat: Schema4.optionalKey(Schema4.Literals(["raw", "formatted"]))
701
+ }).annotate({ identifier: "DataTableBooleanFormat" }))
702
+ }),
703
+ Schema4.Struct({
704
+ ...column,
705
+ type: Schema4.Literal("list"),
706
+ filterOptions: Schema4.optionalKey(Schema4.Array(DataTableItemSchema)),
707
+ options: Schema4.optionalKey(Schema4.Array(DataTableItemSchema)),
708
+ allowRemove: Schema4.optionalKey(Schema4.Boolean),
709
+ itemActions: Schema4.optionalKey(Schema4.Array(DataTableActionSchema)),
710
+ display: Schema4.optionalKey(Schema4.Literals(["list", "icon", "badge"])),
711
+ visibleCount: Schema4.optionalKey(Schema4.Int.check(Schema4.isGreaterThanOrEqualTo(0))),
712
+ actionsLabel: Schema4.optionalKey(Schema4.String),
713
+ manageLabel: Schema4.optionalKey(Schema4.String)
714
+ })
715
+ ]).annotate({ identifier: "DataTableField" });
716
+ var DataTableColumnSchema = DataTableFieldSchema.mapMembers(Tuple.map(Schema4.fieldsAssign({
717
+ fields: Schema4.optionalKey(Schema4.Array(DataTableFieldSchema))
718
+ }))).annotate({ identifier: "DataTableColumn" });
719
+ var DataTableLabelsSchema = Schema4.Struct({
720
+ actions: Schema4.optionalKey(Schema4.String),
721
+ addItem: Schema4.optionalKey(Schema4.String),
722
+ listDetails: Schema4.optionalKey(Schema4.String),
723
+ empty: Schema4.optionalKey(Schema4.String),
724
+ filters: Schema4.optionalKey(Schema4.String),
725
+ filtersClear: Schema4.optionalKey(Schema4.String),
726
+ filterColumn: Schema4.optionalKey(Schema4.String),
727
+ filterClear: Schema4.optionalKey(Schema4.String),
728
+ filterApply: Schema4.optionalKey(Schema4.String),
729
+ filterValue: Schema4.optionalKey(Schema4.String),
730
+ filterOperator: Schema4.optionalKey(Schema4.String),
731
+ filterContains: Schema4.optionalKey(Schema4.String),
732
+ filterEquals: Schema4.optionalKey(Schema4.String),
733
+ filterStartsWith: Schema4.optionalKey(Schema4.String),
734
+ filterEndsWith: Schema4.optionalKey(Schema4.String),
735
+ filterMin: Schema4.optionalKey(Schema4.String),
736
+ filterMax: Schema4.optionalKey(Schema4.String),
737
+ filterFrom: Schema4.optionalKey(Schema4.String),
738
+ filterTo: Schema4.optionalKey(Schema4.String),
739
+ filterTrue: Schema4.optionalKey(Schema4.String),
740
+ filterFalse: Schema4.optionalKey(Schema4.String),
741
+ filterInvalid: Schema4.optionalKey(Schema4.String),
742
+ columns: Schema4.optionalKey(Schema4.String),
743
+ sortBy: Schema4.optionalKey(Schema4.String),
744
+ hideColumn: Schema4.optionalKey(Schema4.String),
745
+ loading: Schema4.optionalKey(Schema4.String),
746
+ removeItem: Schema4.optionalKey(Schema4.String),
747
+ search: Schema4.optionalKey(Schema4.String),
748
+ selectAllRows: Schema4.optionalKey(Schema4.String),
749
+ selectRow: Schema4.optionalKey(Schema4.String),
750
+ selected: Schema4.optionalKey(Schema4.String),
751
+ sortAsc: Schema4.optionalKey(Schema4.String),
752
+ sortDesc: Schema4.optionalKey(Schema4.String),
753
+ sortClear: Schema4.optionalKey(Schema4.String),
754
+ view: Schema4.optionalKey(Schema4.String),
755
+ tableView: Schema4.optionalKey(Schema4.String),
756
+ galleryView: Schema4.optionalKey(Schema4.String),
757
+ groupBy: Schema4.optionalKey(Schema4.String),
758
+ export: Schema4.optionalKey(Schema4.String),
759
+ exportFailed: Schema4.optionalKey(Schema4.String),
760
+ moveUp: Schema4.optionalKey(Schema4.String),
761
+ moveDown: Schema4.optionalKey(Schema4.String),
762
+ reorder: Schema4.optionalKey(Schema4.String),
763
+ refresh: Schema4.optionalKey(Schema4.String),
764
+ resize: Schema4.optionalKey(Schema4.String)
765
+ }).annotate({ identifier: "DataTableLabels" });
766
+ var DataTableViewSchema = Schema4.Literals(["table", "gallery"]);
767
+ var DataTablePreferencesSchema = Schema4.Struct({
768
+ columnVisibility: Schema4.Record(Schema4.String, Schema4.Boolean),
769
+ columnSizing: Schema4.Record(Schema4.String, Schema4.Finite),
770
+ grouping: Schema4.optionalKey(Schema4.Array(Schema4.String)),
771
+ view: DataTableViewSchema
772
+ }).annotate({ identifier: "DataTablePersistedUiState" });
773
+ var GroupField = Schema4.Struct({
774
+ id: Schema4.NonEmptyString,
775
+ label: Schema4.String,
776
+ actionsLabel: Schema4.optionalKey(Schema4.String),
777
+ groups: Schema4.optionalKey(Schema4.Array(Schema4.Struct({
778
+ id: Schema4.String,
779
+ label: Schema4.String,
780
+ empty: Schema4.optionalKey(Schema4.String)
781
+ }).annotate({ identifier: "DataTableGroupLabel" }))),
782
+ actions: Schema4.optionalKey(Schema4.Array(DataTableActionSchema)),
783
+ movable: Schema4.optionalKey(Schema4.Boolean)
784
+ }).annotate({ identifier: "DataTableGroupField" });
785
+ var DataTablePropsSchema = Schema4.Struct({
786
+ ...DataTableCommonPropsSchema.fields,
787
+ label: Schema4.String,
788
+ rowData: Schema4.Array(DataTableRowSchema),
789
+ rowActivation: Schema4.optionalKey(Schema4.Boolean),
790
+ columnDefs: Schema4.Array(DataTableColumnSchema),
791
+ status: Schema4.optionalKey(Schema4.Struct({
792
+ loading: Schema4.optionalKey(Schema4.Boolean),
793
+ empty: Schema4.optionalKey(Schema4.String),
794
+ error: Schema4.optionalKey(Schema4.String)
795
+ })),
796
+ sort: Schema4.optionalKey(Schema4.Array(DataTableSortSchema)),
797
+ sortMode: Schema4.optionalKey(Schema4.Literals(["client", "server"])),
798
+ search: Schema4.optionalKey(Schema4.Boolean),
799
+ columnFilters: Schema4.optionalKey(Schema4.Boolean),
800
+ state: Schema4.optionalKey(DataTableQuerySchema),
801
+ features: Schema4.optionalKey(Schema4.Struct({
802
+ ...DataTableCommonFeaturesSchema.fields,
803
+ pagination: Schema4.optionalKey(Schema4.Union([Schema4.Literal(false), PaginationSchema])),
804
+ grouping: Schema4.optionalKey(Schema4.Struct({
805
+ initial: Schema4.optionalKey(Schema4.Array(Schema4.String)),
806
+ fields: Schema4.Array(GroupField)
807
+ }).annotate({ identifier: "DataTableGrouping" })),
808
+ gallery: Schema4.optionalKey(Schema4.Struct({
809
+ name: Schema4.String,
810
+ description: Schema4.optionalKey(Schema4.String),
811
+ image: Schema4.optionalKey(Schema4.String),
812
+ tags: Schema4.optionalKey(Schema4.Array(Schema4.String))
813
+ }).annotate({ identifier: "DataTableGallery" })),
814
+ reordering: Schema4.optionalKey(Schema4.Boolean),
815
+ export: Schema4.optionalKey(Schema4.Struct({
816
+ baseName: Schema4.String,
817
+ scope: Schema4.optionalKey(Schema4.Literals(["filteredRows", "currentPage"])),
818
+ builtIn: Schema4.optionalKey(Schema4.Boolean),
819
+ actions: Schema4.optionalKey(Schema4.Array(DataTableActionSchema)),
820
+ pending: Schema4.optionalKey(Schema4.Boolean),
821
+ failed: Schema4.optionalKey(Schema4.Boolean)
822
+ }).annotate({ identifier: "DataTableExport" })),
823
+ refresh: Schema4.optionalKey(Schema4.Boolean),
824
+ virtualization: Schema4.optionalKey(Schema4.Union([
825
+ Schema4.Boolean,
826
+ Schema4.Struct({
827
+ scroll: Schema4.optionalKey(Schema4.Literals(["table", "internal", "page"])),
828
+ height: Schema4.optionalKey(Schema4.Int.check(Schema4.isGreaterThan(0))),
829
+ estimateRowHeight: Schema4.optionalKey(Schema4.Int.check(Schema4.isGreaterThan(0))),
830
+ overscan: Schema4.optionalKey(Schema4.Int.check(Schema4.isGreaterThanOrEqualTo(0)))
831
+ }).annotate({ identifier: "DataTableVirtualization" })
832
+ ]))
833
+ }).annotate({ identifier: "DataTableHtmlFeatures" })),
834
+ initialState: Schema4.optionalKey(Schema4.Struct({
835
+ ...queryFields,
836
+ page: Schema4.optional(queryFields.page),
837
+ pageSize: Schema4.optional(queryFields.pageSize),
838
+ columnVisibility: Schema4.optionalKey(Schema4.Record(Schema4.String, Schema4.Boolean)),
839
+ view: Schema4.optionalKey(DataTableViewSchema)
840
+ }).annotate({ identifier: "DataTableInitialQuery" })),
841
+ pagination: Schema4.optionalKey(PaginationSchema),
842
+ selection: Schema4.optionalKey(Schema4.Struct({
843
+ selectedRowIds: Schema4.optionalKey(Schema4.Array(Schema4.String)),
844
+ bulkActionsLabel: Schema4.optionalKey(Schema4.String),
845
+ bulkActions: Schema4.optionalKey(Schema4.Array(DataTableActionSchema))
846
+ })),
847
+ messages: Schema4.optionalKey(Schema4.Record(Schema4.String, DataTableLabelsSchema))
848
+ }).annotate({ identifier: "DataTableProps" });
849
+ var DataTableFilterDraftSchema = Schema4.Struct({
850
+ id: Schema4.String,
851
+ primary: Schema4.String,
852
+ secondary: Schema4.String,
853
+ operator: TextFilterOperator,
854
+ values: Schema4.Array(Schema4.String)
855
+ }).annotate({ identifier: "DataTableFilterDraft" });
856
+
857
+ // ../../src/components/data-table/index.ts
858
+ var defaultMessages = {
859
+ en: {
860
+ actions: "Actions",
861
+ addItem: "Add item...",
862
+ listDetails: "View all items",
863
+ empty: "No results.",
864
+ filters: "Filters",
865
+ filtersClear: "Clear all filters",
866
+ filterColumn: "Column",
867
+ filterClear: "Clear filter",
868
+ filterApply: "Apply filter",
869
+ filterValue: "Value",
870
+ filterOperator: "Operator",
871
+ filterContains: "Contains",
872
+ filterEquals: "Equals",
873
+ filterStartsWith: "Starts with",
874
+ filterEndsWith: "Ends with",
875
+ filterMin: "Minimum",
876
+ filterMax: "Maximum",
877
+ filterFrom: "From (UTC)",
878
+ filterTo: "To (UTC)",
879
+ filterTrue: "True",
880
+ filterFalse: "False",
881
+ filterInvalid: "Enter a valid filter. Ranges must be in ascending order.",
882
+ columns: "Columns",
883
+ sortBy: "Sort by",
884
+ hideColumn: "Hide column",
885
+ loading: "Loading...",
886
+ removeItem: "Remove",
887
+ search: "Search",
888
+ selectAllRows: "Select all rows on this page",
889
+ selectRow: "Select row",
890
+ selected: "Selected",
891
+ sortAsc: "Ascending",
892
+ sortDesc: "Descending",
893
+ sortClear: "Clear sorting",
894
+ view: "View",
895
+ tableView: "Table",
896
+ galleryView: "Gallery",
897
+ groupBy: "Group by",
898
+ export: "Export",
899
+ exportFailed: "Export failed. Please try again.",
900
+ refresh: "Refresh",
901
+ moveUp: "Move up",
902
+ moveDown: "Move down",
903
+ reorder: "Drag to reorder",
904
+ resize: "Resize column"
905
+ },
906
+ fr: {
907
+ actions: "Actions",
908
+ addItem: "Ajouter un élément...",
909
+ listDetails: "Afficher tous les éléments",
910
+ empty: "Aucun résultat.",
911
+ filters: "Filtres",
912
+ filtersClear: "Effacer tous les filtres",
913
+ filterColumn: "Colonne",
914
+ filterClear: "Effacer le filtre",
915
+ filterApply: "Appliquer le filtre",
916
+ filterValue: "Valeur",
917
+ filterOperator: "Opérateur",
918
+ filterContains: "Contient",
919
+ filterEquals: "Égal à",
920
+ filterStartsWith: "Commence par",
921
+ filterEndsWith: "Se termine par",
922
+ filterMin: "Minimum",
923
+ filterMax: "Maximum",
924
+ filterFrom: "Du (UTC)",
925
+ filterTo: "Au (UTC)",
926
+ filterTrue: "Vrai",
927
+ filterFalse: "Faux",
928
+ filterInvalid: "Saisissez un filtre valide. Les bornes doivent être dans l’ordre croissant.",
929
+ columns: "Colonnes",
930
+ sortBy: "Trier par",
931
+ hideColumn: "Masquer la colonne",
932
+ loading: "Chargement...",
933
+ removeItem: "Retirer",
934
+ search: "Rechercher",
935
+ selectAllRows: "Sélectionner toutes les lignes de cette page",
936
+ selectRow: "Sélectionner la ligne",
937
+ selected: "Sélectionnés",
938
+ sortAsc: "Croissant",
939
+ sortDesc: "Décroissant",
940
+ sortClear: "Effacer le tri",
941
+ view: "Affichage",
942
+ tableView: "Tableau",
943
+ galleryView: "Galerie",
944
+ groupBy: "Grouper par",
945
+ export: "Exporter",
946
+ exportFailed: "L’exportation a échoué. Veuillez réessayer.",
947
+ refresh: "Rafraîchir",
948
+ moveUp: "Déplacer vers le haut",
949
+ moveDown: "Déplacer vers le bas",
950
+ reorder: "Glisser pour réorganiser",
951
+ resize: "Redimensionner la colonne"
952
+ }
953
+ };
954
+ var htmlDataTableMessages = (locale, messages) => {
955
+ const base = locale.split("-")[0] ?? "en";
956
+ return {
957
+ ...defaultMessages[base === "fr" ? "fr" : "en"],
958
+ ...messages?.[base],
959
+ ...messages?.[locale]
960
+ };
961
+ };
962
+ var compareTableText = (left, right, locale) => left.localeCompare(right, locale, { numeric: true, sensitivity: "base" });
963
+ var isTableText = Schema5.is(Schema5.String);
964
+ var isTableNumber = Schema5.is(Schema5.Finite);
965
+ var isTableBoolean = Schema5.is(Schema5.Boolean);
966
+ var isTableReference = Schema5.is(DataTableReferenceSchema);
967
+ var isTableList = Schema5.is(Schema5.Array(DataTableItemSchema));
968
+ var tableInitials = (label) => label.trim().split(/\s+/).slice(0, 2).map((word) => word.slice(0, 1)).join("").toLocaleUpperCase();
969
+ var formatBytes = (bytes, locale) => {
970
+ const [unit, scale] = bytes >= 1024 ** 2 ? ["megabyte", 1024 ** 2] : bytes >= 1024 ? ["kilobyte", 1024] : ["byte", 1];
971
+ return new Intl.NumberFormat(locale, {
972
+ style: "unit",
973
+ unit,
974
+ maximumFractionDigits: 1
975
+ }).format(bytes / scale);
976
+ };
977
+ var formatNumberValue = (value, options, defaultLocale = "en") => {
978
+ const { locale, format, ...intlOptions } = options ?? {};
979
+ return format === "bytes" ? formatBytes(value, locale ?? defaultLocale) : new Intl.NumberFormat(locale ?? defaultLocale, intlOptions).format(value);
980
+ };
981
+ var tableBooleanLabel = (value, options) => (value ? options?.trueLabel : options?.falseLabel) ?? String(value);
982
+ var decodeDateInput = Schema5.decodeUnknownOption(DataTableDateInputSchema);
983
+ var resolveDate = (value, type) => Option3.getOrUndefined(Option3.flatMap(decodeDateInput(value), (input) => {
984
+ const calendarOnly = isCalendarDate(input);
985
+ if (calendarOnly && type === "dateTime")
986
+ return Option3.none();
987
+ return Option3.map(DateTime3.make(input), (instant) => ({
988
+ instant,
989
+ calendarOnly
990
+ }));
991
+ }));
992
+ var formatDateValue = (date, column, locale = "en") => DateTime3.format(date.instant, {
993
+ locale: column.typeOptions?.locale ?? locale,
994
+ timeZone: date.calendarOnly ? "UTC" : column.typeOptions?.timeZone ?? "UTC",
995
+ dateStyle: column.typeOptions?.dateStyle ?? "medium",
996
+ timeStyle: column.type === "dateTime" ? column.typeOptions?.timeStyle ?? "short" : undefined,
997
+ hour12: column.type === "dateTime" ? column.typeOptions?.hour12 : undefined
998
+ });
999
+ var dateIsoValue = (date) => date.calendarOnly ? DateTime3.formatIsoDateUtc(date.instant) : DateTime3.formatIso(date.instant);
1000
+ var matchesDateFilter = (date, filter) => {
1001
+ if (!date)
1002
+ return false;
1003
+ const day = DateTime3.formatIsoDateUtc(date.instant);
1004
+ return (filter.from === undefined || day >= filter.from) && (filter.to === undefined || day <= filter.to);
1005
+ };
1006
+ var matchesFilterText = (value, filter) => {
1007
+ const text = value.toLocaleLowerCase();
1008
+ const query = filter.value.toLocaleLowerCase();
1009
+ switch (filter.operator) {
1010
+ case "contains":
1011
+ return text.includes(query);
1012
+ case "equals":
1013
+ return text === query;
1014
+ case "startsWith":
1015
+ return text.startsWith(query);
1016
+ case "endsWith":
1017
+ return text.endsWith(query);
1018
+ }
1019
+ };
1020
+ var tableFilterKind = (column, hasOptions = false) => hasOptions || column.type === "list" || column.display === "badge" ? "values" : column.type === "reference" ? "text" : column.type === "dateTime" ? "date" : column.type ?? "text";
1021
+ var tableBadgeValue = (value) => isTableText(value) && value !== "" ? value : null;
1022
+ var tableBadge = (input, config) => {
1023
+ const value = tableBadgeValue(input);
1024
+ if (value === null)
1025
+ return null;
1026
+ const option = config?.options?.find((option) => option.value === value);
1027
+ return {
1028
+ value,
1029
+ label: option?.label ?? value,
1030
+ variant: option?.variant ?? "secondary",
1031
+ option
1032
+ };
1033
+ };
1034
+ var tableBadgeFilterOptions = (values, config) => {
1035
+ const options = new Map(config?.options?.map(({ value, label }) => [value, label ?? value]));
1036
+ for (const input of values) {
1037
+ const value = tableBadgeValue(input);
1038
+ if (value !== null && !options.has(value))
1039
+ options.set(value, value);
1040
+ }
1041
+ return [...options].map(([value, label]) => ({ value, label }));
1042
+ };
1043
+ var tableBadgeSearchText = (value, config) => {
1044
+ const badge = tableBadge(value, config);
1045
+ return badge ? `${badge.label} ${badge.value}` : "";
1046
+ };
1047
+ var matchesTableFilter = (filter, value, type, text, values) => {
1048
+ switch (filter.kind) {
1049
+ case "text":
1050
+ return matchesFilterText(text(), filter);
1051
+ case "number":
1052
+ return isTableNumber(value) && (filter.min === undefined || value >= filter.min) && (filter.max === undefined || value <= filter.max);
1053
+ case "boolean":
1054
+ return value === filter.value;
1055
+ case "values":
1056
+ return values().some((value) => filter.values.includes(value));
1057
+ case "date":
1058
+ return matchesDateFilter(resolveDate(value, type === "dateTime" ? "dateTime" : "date"), filter);
1059
+ }
1060
+ };
1061
+ var tableDataColumns = (columns) => columns.flatMap((column) => column.fields?.length ? column.fields.map((field) => ({
1062
+ ...field,
1063
+ id: `${column.id}.${field.id}`,
1064
+ headerName: `${column.headerName} / ${field.headerName}`,
1065
+ sortable: column.sortable === false ? false : field.sortable,
1066
+ searchable: column.searchable === false ? false : field.searchable,
1067
+ filterable: column.filterable === false ? false : field.filterable,
1068
+ export: column.export === false ? false : field.export
1069
+ })) : [column]);
1070
+ var tableFilterOptions = (rows, columnId, locale) => {
1071
+ const options = new Map;
1072
+ for (const row of rows) {
1073
+ const items = row.cells[columnId];
1074
+ if (isTableList(items)) {
1075
+ for (const item of items)
1076
+ options.set(item.value, item);
1077
+ }
1078
+ }
1079
+ return [...options.values()].sort((a, b) => compareTableText(a.label, b.label, locale));
1080
+ };
1081
+ var filterTableColumns = (rows, columns, filters) => {
1082
+ const byId = new Map(columns.filter(({ filterable }) => filterable !== false).map((column) => [column.id, column]));
1083
+ const active = filters.filter((filter) => {
1084
+ const column = byId.get(filter.id);
1085
+ return column && tableFilterKind(column) === filter.kind;
1086
+ });
1087
+ if (!active.length)
1088
+ return rows;
1089
+ return rows.filter((row) => active.every((filter) => {
1090
+ const value = row.cells[filter.id];
1091
+ const column = byId.get(filter.id);
1092
+ return matchesTableFilter(filter, value, column?.type, () => isTableText(value) ? value : isTableReference(value) ? `${value.label} ${value.description ?? ""}`.trim() : "", () => {
1093
+ if (column?.type === "text" && column.display === "badge") {
1094
+ const key = tableBadgeValue(value);
1095
+ return key === null ? [] : [key];
1096
+ }
1097
+ return isTableList(value) ? value.map(({ value }) => value) : [];
1098
+ });
1099
+ }));
1100
+ };
1101
+ var columnValue = (column, value) => {
1102
+ switch (column.type) {
1103
+ case "text":
1104
+ return column.display === "badge" ? tableBadgeValue(value) : isTableText(value) ? value : null;
1105
+ case "number":
1106
+ case "boolean":
1107
+ case "date":
1108
+ case "dateTime":
1109
+ return tableSortScalar(column.type, value);
1110
+ case "reference":
1111
+ return isTableReference(value) ? value.label : null;
1112
+ case "list":
1113
+ return isTableList(value) ? value.map(({ label }) => label).join(", ") : null;
1114
+ }
1115
+ };
1116
+ var tableSortScalar = (type, value) => {
1117
+ if (type === "number")
1118
+ return isTableNumber(value) ? value : null;
1119
+ if (type === "boolean")
1120
+ return isTableBoolean(value) ? Number(value) : null;
1121
+ const date = resolveDate(value, type);
1122
+ return date ? DateTime3.toEpochMillis(date.instant) : null;
1123
+ };
1124
+ var compareTableSortValues = (left, right, direction, nulls, locale) => {
1125
+ if (left === right)
1126
+ return 0;
1127
+ const nullOrder = nulls === "first" ? -1 : 1;
1128
+ if (left === null)
1129
+ return nullOrder;
1130
+ if (right === null)
1131
+ return -nullOrder;
1132
+ const comparison = isTableNumber(left) && isTableNumber(right) ? left - right : compareTableText(String(left), String(right), locale);
1133
+ return direction === "asc" ? comparison : -comparison;
1134
+ };
1135
+ var sortTableRows = (rows, columns, sort, locale) => {
1136
+ const byId = new Map(columns.map((column) => [column.id, column]));
1137
+ return rows.slice().sort((leftRow, rightRow) => {
1138
+ for (const { id, direction } of sort) {
1139
+ const column = byId.get(id);
1140
+ if (!column || column.sortable === false)
1141
+ continue;
1142
+ const left = columnValue(column, leftRow.cells[id]);
1143
+ const right = columnValue(column, rightRow.cells[id]);
1144
+ const comparison = compareTableSortValues(left, right, direction, column.nulls, locale);
1145
+ if (comparison !== 0)
1146
+ return comparison;
1147
+ }
1148
+ return 0;
1149
+ });
1150
+ };
1151
+ var filterTableRows = (rows, columns, search, locale) => {
1152
+ const query = search.trim().toLocaleLowerCase(locale);
1153
+ if (!query)
1154
+ return rows;
1155
+ const searchable = columns.filter(({ searchable }) => searchable !== false);
1156
+ return rows.filter((row) => searchable.some((column) => {
1157
+ const value = row.cells[column.id];
1158
+ if (column.type === "text" && column.display === "badge")
1159
+ return tableBadgeSearchText(value, column.typeOptions).toLocaleLowerCase(locale).includes(query);
1160
+ if (column.type === "date" || column.type === "dateTime") {
1161
+ const date = resolveDate(value, column.type);
1162
+ return !!date && `${formatDateValue(date, column, locale)} ${dateIsoValue(date)}`.toLocaleLowerCase(locale).includes(query);
1163
+ }
1164
+ const text = column.type === "reference" && isTableReference(value) ? `${value.label} ${value.description ?? ""}` : column.type === "number" && isTableNumber(value) ? `${formatNumberValue(value, column.typeOptions, locale)} ${value}` : column.type === "boolean" && isTableBoolean(value) ? `${tableBooleanLabel(value, column.typeOptions)} ${value}` : String(columnValue(column, value) ?? "");
1165
+ return text.toLocaleLowerCase(locale).includes(query);
1166
+ }));
1167
+ };
1168
+ var updateSelectedRows = (selected, targets, checked) => {
1169
+ const next = new Set(selected);
1170
+ for (const id of targets) {
1171
+ if (checked)
1172
+ next.add(id);
1173
+ else
1174
+ next.delete(id);
1175
+ }
1176
+ return Array.from(next);
1177
+ };
1178
+ var resolveTablePage = (rowCount, query) => {
1179
+ const pageSize = Math.max(1, query.pageSize);
1180
+ const pageCount = Math.max(1, Math.ceil(rowCount / pageSize));
1181
+ const page = Math.min(pageCount - 1, Math.max(0, query.page));
1182
+ const start = page * pageSize;
1183
+ return { page, pageCount, start, end: start + pageSize };
1184
+ };
1185
+ var edit = UiSchema2.TaggedEnum({
1186
+ SetBoolean: { value: Schema5.Boolean },
1187
+ AddItem: { itemId: Schema5.String },
1188
+ RemoveItem: { itemId: Schema5.String }
1189
+ }).annotate({ identifier: "DataTableEdit" });
1190
+ var DataTableEdit = edit;
1191
+ var eventFields = {
1192
+ RowActivated: { rowId: Schema5.String },
1193
+ ItemActionRequested: {
1194
+ rowId: Schema5.String,
1195
+ columnId: Schema5.String,
1196
+ itemId: Schema5.String,
1197
+ actionId: Schema5.String
1198
+ },
1199
+ RefreshRequested: {},
1200
+ ExportRequested: { actionId: Schema5.String },
1201
+ GroupActionRequested: {
1202
+ fieldId: Schema5.String,
1203
+ groupId: Schema5.String,
1204
+ actionId: Schema5.String
1205
+ },
1206
+ GroupMoveRequested: {
1207
+ rowId: Schema5.String,
1208
+ fieldId: Schema5.String,
1209
+ groupId: Schema5.String
1210
+ },
1211
+ RowsReordered: { rowIds: Schema5.Array(Schema5.String) },
1212
+ StateChanged: { state: DataTableQuerySchema },
1213
+ SortChanged: { sort: Schema5.Array(DataTableSortSchema) },
1214
+ SelectionChanged: { selectedRowIds: Schema5.Array(Schema5.String) },
1215
+ CellEditRequested: { rowId: Schema5.String, columnId: Schema5.String, edit },
1216
+ RowActionRequested: { rowId: Schema5.String, actionId: Schema5.String },
1217
+ BulkActionRequested: {
1218
+ rowIds: Schema5.Array(Schema5.String),
1219
+ actionId: Schema5.String
1220
+ }
1221
+ };
1222
+ var DataTableEvents = UiSchema2.TaggedEnum(eventFields).annotate({
1223
+ identifier: "DataTableEvents"
1224
+ });
1225
+ var DataTableMessage = UiSchema2.TaggedEnum({
1226
+ ReferenceImageFailed: { src: Schema5.String },
1227
+ RowActivated: eventFields.RowActivated,
1228
+ PreferencesLoaded: { preferences: Schema5.NullOr(DataTablePreferencesSchema) },
1229
+ ItemActionRequested: eventFields.ItemActionRequested,
1230
+ BuiltInExportRequested: {
1231
+ format: Schema5.Literals(["csv", "json"]),
1232
+ locale: Schema5.optionalKey(Schema5.String)
1233
+ },
1234
+ ExportStarted: {},
1235
+ ExportFinished: { failed: Schema5.Boolean },
1236
+ RefreshRequested: {},
1237
+ ExportRequested: eventFields.ExportRequested,
1238
+ GroupActionRequested: eventFields.GroupActionRequested,
1239
+ GroupMoveRequested: eventFields.GroupMoveRequested,
1240
+ ReorderRequested: {
1241
+ rowId: Schema5.String,
1242
+ targetId: Schema5.String,
1243
+ after: Schema5.Boolean
1244
+ },
1245
+ DragStarted: { rowId: Schema5.String },
1246
+ DragEnded: {},
1247
+ DragDropped: { targetId: Schema5.String },
1248
+ GroupDropped: { fieldId: Schema5.String, groupId: Schema5.String },
1249
+ ViewPicked: { view: DataTableViewSchema },
1250
+ GroupingToggled: { fieldId: Schema5.String },
1251
+ GroupToggled: { key: Schema5.String },
1252
+ ColumnResized: { id: Schema5.String, delta: Schema5.Finite },
1253
+ ColumnResizeReset: { id: Schema5.String },
1254
+ ResizeStarted: { id: Schema5.String, x: Schema5.Finite, pointerId: Schema5.Int },
1255
+ ResizeMoved: { x: Schema5.Finite, pointerId: Schema5.Int },
1256
+ ResizeEnded: { pointerId: Schema5.Int },
1257
+ ColumnFiltersCleared: { id: Schema5.String },
1258
+ ColumnSortCleared: { id: Schema5.String },
1259
+ CellEditRequested: eventFields.CellEditRequested,
1260
+ RowActionRequested: eventFields.RowActionRequested,
1261
+ MenuOpened: { key: Schema5.String },
1262
+ MenuClosed: { key: Schema5.String },
1263
+ MenuQueryChanged: { key: Schema5.String, query: Schema5.String },
1264
+ SubmenuOpened: {
1265
+ key: Schema5.String,
1266
+ filterColumnId: Schema5.optionalKey(Schema5.String)
1267
+ },
1268
+ SubmenuClosed: { key: Schema5.String },
1269
+ SearchChanged: { value: Schema5.String },
1270
+ FilterInputChanged: {
1271
+ field: Schema5.Literals(["primary", "secondary"]),
1272
+ value: Schema5.String
1273
+ },
1274
+ FilterOperatorChanged: { operator: TextFilterOperator },
1275
+ FilterValueToggled: { value: Schema5.String, checked: Schema5.Boolean },
1276
+ FilterApplied: {},
1277
+ ColumnFilterChanged: {
1278
+ id: Schema5.String,
1279
+ filter: Schema5.NullOr(ColumnFilter)
1280
+ },
1281
+ FilterCleared: {},
1282
+ FiltersCleared: {},
1283
+ PageRequested: { page: Schema5.Int },
1284
+ ServerPageInvalidated: {},
1285
+ PageSizeRequested: { pageSize: Schema5.Int },
1286
+ SortRequested: {
1287
+ columnId: Schema5.String,
1288
+ direction: Schema5.NullOr(DataTableSortSchema.fields.direction)
1289
+ },
1290
+ ColumnVisibilityChanged: { id: Schema5.String, visible: Schema5.Boolean },
1291
+ SelectionRequested: {
1292
+ rowIds: Schema5.Array(Schema5.String),
1293
+ checked: Schema5.Boolean
1294
+ },
1295
+ BulkActionRequested: { actionId: Schema5.String }
1296
+ }).annotate({ identifier: "DataTableMessage" });
1297
+ var dataTableOptions = {
1298
+ name: "DataTable",
1299
+ props: DataTablePropsSchema,
1300
+ model: Schema5.Struct({
1301
+ menu: Schema5.NullOr(Schema5.String),
1302
+ submenu: Schema5.NullOr(Schema5.String),
1303
+ menuQuery: Schema5.String,
1304
+ failedImages: Schema5.Array(Schema5.String),
1305
+ selectedRowIds: Schema5.Array(Schema5.String),
1306
+ query: DataTableQuerySchema,
1307
+ preferencesLoaded: Schema5.Boolean,
1308
+ columnVisibility: Schema5.Record(Schema5.String, Schema5.Boolean),
1309
+ columnSizing: Schema5.Record(Schema5.String, Schema5.Finite),
1310
+ view: DataTableViewSchema,
1311
+ grouping: Schema5.Array(Schema5.String),
1312
+ collapsedGroups: Schema5.Record(Schema5.String, Schema5.Boolean),
1313
+ dragging: Schema5.NullOr(Schema5.String),
1314
+ exporting: Schema5.Boolean,
1315
+ exportFailed: Schema5.Boolean,
1316
+ resizing: Schema5.NullOr(Schema5.Struct({
1317
+ id: Schema5.String,
1318
+ x: Schema5.Finite,
1319
+ width: Schema5.Finite,
1320
+ pointerId: Schema5.Int
1321
+ }).annotate({ identifier: "DataTableResizeSession" })),
1322
+ filterDraft: Schema5.NullOr(DataTableFilterDraftSchema),
1323
+ invalidFilter: Schema5.Boolean
1324
+ }).annotate({ identifier: "DataTableModel" }),
1325
+ message: DataTableMessage,
1326
+ events: DataTableEvents,
1327
+ restore: false
1328
+ };
1329
+ var available = (props) => props.status?.error === undefined && (!props.status?.loading || props.rowData.length > 0);
1330
+ var tableQuery = (props, model) => props.state ?? { ...model.query, sort: props.sort ?? model.query.sort };
1331
+ var tableFeatures = (props) => ({
1332
+ ...props.features,
1333
+ search: props.features?.search ?? props.search ?? true,
1334
+ filtering: props.features?.filtering ?? props.columnFilters ?? true,
1335
+ sorting: props.features?.sorting ?? true,
1336
+ columnVisibility: props.features?.columnVisibility ?? true,
1337
+ pagination: props.features?.pagination ?? props.pagination
1338
+ });
1339
+ var tableSelectedRowIds = (props, model) => {
1340
+ const supplied = new Set(props.rowData.map(({ id }) => id));
1341
+ return [
1342
+ ...new Set(props.selection?.selectedRowIds ?? model.selectedRowIds)
1343
+ ].filter((id) => supplied.has(id));
1344
+ };
1345
+ var serverPageCorrection = (props, model) => {
1346
+ const pagination = tableFeatures(props).pagination;
1347
+ if (!pagination || pagination.mode !== "server")
1348
+ return;
1349
+ const query = tableQuery(props, model);
1350
+ const { page } = resolveTablePage(pagination.rowCount, query);
1351
+ if (query.page !== page)
1352
+ return { requested: query.page, page, size: query.pageSize };
1353
+ };
1354
+ var tablePreferencesKey = (pathname, columns, gallery) => `data-table:${pathname}:${columns.join(",")}:${gallery ? "gallery" : "table"}:ui`;
1355
+ var preferencesJson = Schema5.fromJsonString(DataTablePreferencesSchema);
1356
+ var decodePreferences = Schema5.decodeUnknownOption(preferencesJson);
1357
+ var encodePreferences = Schema5.encodeSync(preferencesJson);
1358
+ var readTablePreferences = (key, host = globalThis.window) => {
1359
+ try {
1360
+ return Option3.getOrNull(decodePreferences(host?.localStorage.getItem(key)));
1361
+ } catch {
1362
+ return null;
1363
+ }
1364
+ };
1365
+ var writeTablePreferences = (key, preferences, host = globalThis.window) => {
1366
+ try {
1367
+ host?.localStorage.setItem(key, encodePreferences(preferences));
1368
+ } catch {}
1369
+ };
1370
+ var tablePreferences = (model) => model.preferencesLoaded ? {
1371
+ columnVisibility: model.columnVisibility,
1372
+ columnSizing: model.columnSizing,
1373
+ grouping: model.grouping,
1374
+ view: model.view
1375
+ } : null;
1376
+ var tableVirtualization = (count, options, flat) => {
1377
+ if (!flat || (options === undefined ? count < 100 : !options))
1378
+ return;
1379
+ const config = typeof options === "object" ? options : undefined;
1380
+ const height = config?.height ?? 480;
1381
+ const itemSize = config?.estimateRowHeight ?? 64;
1382
+ const overscan = config?.overscan ?? 5;
1383
+ return {
1384
+ height,
1385
+ itemSize,
1386
+ overscan,
1387
+ initialCount: Math.min(count, Math.ceil(height / itemSize) + overscan),
1388
+ scroll: config?.scroll ?? "table"
1389
+ };
1390
+ };
1391
+ var tableRowActions = (row, siblings, reorder, labels) => {
1392
+ const index = siblings.findIndex(({ id }) => id === row.id);
1393
+ const actions = (row.actions ?? []).map((action) => ({
1394
+ ...action,
1395
+ message: DataTableMessage.RowActionRequested({
1396
+ rowId: row.id,
1397
+ actionId: action.id
1398
+ })
1399
+ }));
1400
+ const moves = reorder && index >= 0 ? [
1401
+ { target: siblings[index - 1], after: false, name: labels.moveUp },
1402
+ { target: siblings[index + 1], after: true, name: labels.moveDown }
1403
+ ].flatMap(({ target, after, name }) => target ? [
1404
+ {
1405
+ id: JSON.stringify(["move", after]),
1406
+ name,
1407
+ message: DataTableMessage.ReorderRequested({
1408
+ rowId: row.id,
1409
+ targetId: target.id,
1410
+ after
1411
+ })
1412
+ }
1413
+ ] : []) : [];
1414
+ return [...moves, ...actions];
1415
+ };
1416
+ var tableColumnLimits = (column) => {
1417
+ const min = column.minWidth ?? 96;
1418
+ return { min, max: Math.max(min, column.maxWidth ?? 640) };
1419
+ };
1420
+ var clampTableWidth = (column, width = column.width ?? 208) => {
1421
+ const { min, max } = tableColumnLimits(column);
1422
+ return Math.min(max, Math.max(min, width));
1423
+ };
1424
+ var tableColumnWidth = (column, sizing) => clampTableWidth(column, sizing[column.id]);
1425
+ var tableLayoutWidth = (widths, utilityColumns) => widths.reduce((total, width) => total + width, utilityColumns * 40);
1426
+ var tableResizeStep = (key) => key === "ArrowLeft" ? -8 : key === "ArrowRight" ? 8 : 0;
1427
+ var activeTableGroups = (grouping, fields) => grouping.flatMap((id) => fields.find((field) => field.id === id) ?? []);
1428
+ var tableGrouping = (props, model) => activeTableGroups(model.grouping, props.features?.grouping?.fields ?? []);
1429
+ var canReorderTableRows = (props, model) => !!props.features?.reordering && !tableGrouping(props, model).length && !tableQuery(props, model).sort?.length;
1430
+ var partitionTableGroups = (rows, known, memberships) => {
1431
+ const groups = new Map(known.map((id) => [id, []]));
1432
+ for (const row of rows) {
1433
+ for (const id of new Set(memberships(row))) {
1434
+ const group = groups.get(id);
1435
+ if (group)
1436
+ group.push(row);
1437
+ else
1438
+ groups.set(id, [row]);
1439
+ }
1440
+ }
1441
+ return groups;
1442
+ };
1443
+ var tableGroupKey = (parent, fieldId, groupId) => `${parent ? `${parent}/` : ""}${encodeURIComponent(fieldId)}:${encodeURIComponent(groupId)}`;
1444
+ var reorderRows = ($, rowId, targetId, after) => {
1445
+ const rowIds = $.props.rowData.map(({ id }) => id);
1446
+ const next = $.evolve({ dragging: null });
1447
+ if (!available($.props) || !canReorderTableRows($.props, $.model) || rowId === targetId || !rowIds.includes(rowId) || !rowIds.includes(targetId))
1448
+ return next;
1449
+ const reordered = rowIds.filter((id) => id !== rowId);
1450
+ reordered.splice(reordered.indexOf(targetId) + Number(after), 0, rowId);
1451
+ return next.emit(DataTableEvents.RowsReordered({ rowIds: reordered }));
1452
+ };
1453
+ var moveGroup = ($, rowId, fieldId, groupId) => {
1454
+ const field = tableGrouping($.props, $.model).find(({ id }) => id === fieldId);
1455
+ const row = $.props.rowData.find(({ id }) => id === rowId);
1456
+ const next = $.evolve({ dragging: null });
1457
+ if (!available($.props) || !field?.movable || !row || row.groups?.[fieldId]?.includes(groupId))
1458
+ return next;
1459
+ if (!field.groups?.some(({ id }) => id === groupId) && !$.props.rowData.some((row) => row.groups?.[fieldId]?.includes(groupId)))
1460
+ return next;
1461
+ return next.emit(DataTableEvents.GroupMoveRequested({ rowId, fieldId, groupId }));
1462
+ };
1463
+ var changeQuery = ($, patch, ui = {}, legacy) => {
1464
+ const current = tableQuery($.props, $.model);
1465
+ const state = { ...current, ...patch };
1466
+ if (state.page === current.page && state.pageSize === current.pageSize && state.globalFilter === current.globalFilter && state.filters === current.filters && state.sort === current.sort)
1467
+ return $.evolve(ui);
1468
+ const step = $.evolve({
1469
+ ...ui,
1470
+ query: $.props.state ? $.model.query : { ...state, sort: $.props.sort ? $.model.query.sort : state.sort }
1471
+ }).emit(DataTableEvents.StateChanged({ state }));
1472
+ return legacy ? step.emit(legacy) : step;
1473
+ };
1474
+ var tableFilterDraft = (id, current) => ({
1475
+ id,
1476
+ primary: current?.kind === "text" || current?.kind === "boolean" ? String(current.value) : current?.kind === "number" ? String(current.min ?? "") : current?.kind === "date" ? current.from ?? "" : "",
1477
+ secondary: current?.kind === "number" ? String(current.max ?? "") : current?.kind === "date" ? current.to ?? "" : "",
1478
+ operator: current?.kind === "text" ? current.operator : "contains",
1479
+ values: current?.kind === "values" ? current.values : []
1480
+ });
1481
+ var decodeFilter = Schema5.decodeUnknownOption(ColumnFilter);
1482
+ var decodeBound = Schema5.decodeOption(Schema5.FiniteFromString);
1483
+ var parseTableFilterDraft = (kind, {
1484
+ id,
1485
+ primary,
1486
+ secondary,
1487
+ operator,
1488
+ values
1489
+ }) => {
1490
+ switch (kind) {
1491
+ case "number": {
1492
+ const min = primary.trim() ? decodeBound(primary) : Option3.some(undefined);
1493
+ const max = secondary.trim() ? decodeBound(secondary) : Option3.some(undefined);
1494
+ return Option3.isNone(min) || Option3.isNone(max) ? Option3.none() : decodeFilter({ id, kind, min: min.value, max: max.value });
1495
+ }
1496
+ case "boolean":
1497
+ return decodeFilter({
1498
+ id,
1499
+ kind,
1500
+ value: primary === "true" ? true : primary === "false" ? false : undefined
1501
+ });
1502
+ case "values":
1503
+ return decodeFilter({ id, kind, values });
1504
+ case "date":
1505
+ return decodeFilter({
1506
+ id,
1507
+ kind,
1508
+ from: primary || undefined,
1509
+ to: secondary || undefined
1510
+ });
1511
+ case "text":
1512
+ return decodeFilter({ id, kind, operator, value: primary.trim() });
1513
+ }
1514
+ };
1515
+ var changeColumnFilter = ($, id, filter, ui) => {
1516
+ const filters = (tableQuery($.props, $.model).filters ?? []).filter((current) => current.id !== id);
1517
+ if (filter)
1518
+ filters.push(filter);
1519
+ return changeQuery($, { filters: filters.length ? filters : undefined, page: 0 }, ui);
1520
+ };
1521
+ var projectDataTableRows = (source, query, {
1522
+ pagination,
1523
+ grouped,
1524
+ sortMode,
1525
+ search,
1526
+ filter,
1527
+ sort
1528
+ }) => {
1529
+ const server = pagination && pagination.mode === "server";
1530
+ const filtered = server ? source : filter(search(source, query.globalFilter ?? ""), query.filters ?? []);
1531
+ const ordered = !server && sortMode !== "server" && query.sort?.length ? sort(filtered, query.sort) : filtered;
1532
+ const { pageSize } = query;
1533
+ const totalRows = server ? pagination.rowCount : ordered.length;
1534
+ const { page, pageCount, start, end } = resolveTablePage(totalRows, query);
1535
+ const paginationVisible = !!pagination && (server || !grouped);
1536
+ const rows = paginationVisible && !server ? ordered.slice(start, end) : ordered;
1537
+ return {
1538
+ rows,
1539
+ filtered,
1540
+ ordered,
1541
+ pageSize,
1542
+ totalRows,
1543
+ pageCount,
1544
+ page,
1545
+ paginationVisible
1546
+ };
1547
+ };
1548
+ var dataTablePage = (props, model, locale) => {
1549
+ const pagination = tableFeatures(props).pagination;
1550
+ const columns = tableDataColumns(props.columnDefs);
1551
+ return {
1552
+ ...projectDataTableRows(props.rowData, tableQuery(props, model), {
1553
+ pagination,
1554
+ grouped: tableGrouping(props, model).length > 0,
1555
+ sortMode: props.sortMode,
1556
+ search: (rows, value) => filterTableRows(rows, columns, value, locale),
1557
+ filter: (rows, filters) => filterTableColumns(rows, columns, filters),
1558
+ sort: (rows, sorting) => sortTableRows(rows, columns, sorting, locale)
1559
+ }),
1560
+ pageSizes: pagination && pagination.pageSizes || defaultPageSizes
1561
+ };
1562
+ };
1563
+ var encodeTableCsv = (headers, data) => Effect2.runSync(Stream.fromIterable([headers, ...data]).pipe(Stream.map((row) => row.map((value) => value == null ? "" : String(value))), Stream.pipeThroughChannel(Csv.encodeString({ newline: `
1564
+ ` })), Stream.runCollect, Effect2.map((parts) => parts.join("").slice(0, -1))));
1565
+ var tableExportFilename = (name, extension) => name.includes(".") ? name.replace(/\.[^/.]+$/, `.${extension}`) : `${name}.${extension}`;
1566
+ var downloadTableBlob = (content, type, filename) => {
1567
+ const url = window.URL.createObjectURL(new Blob([content], { type }));
1568
+ const link = document.createElement("a");
1569
+ link.href = url;
1570
+ link.download = filename;
1571
+ document.body.appendChild(link);
1572
+ try {
1573
+ link.click();
1574
+ } finally {
1575
+ link.remove();
1576
+ requestAnimationFrame(() => window.URL.revokeObjectURL(url));
1577
+ }
1578
+ };
1579
+ var tableExportValue = (column, row, locale) => {
1580
+ const value = row.cells[column.id];
1581
+ switch (column.type) {
1582
+ case "date":
1583
+ case "dateTime": {
1584
+ const date = resolveDate(value, column.type);
1585
+ return !date ? null : column.typeOptions?.exportFormat === "formatted" ? formatDateValue(date, column, locale) : dateIsoValue(date);
1586
+ }
1587
+ case "reference":
1588
+ return isTableReference(value) ? [value.label, value.description].filter(Boolean).join(" — ") : "";
1589
+ case "list":
1590
+ return isTableList(value) ? value.map(({ label }) => label).join(", ") : "";
1591
+ case "boolean":
1592
+ return !isTableBoolean(value) ? null : column.typeOptions?.exportFormat === "formatted" ? tableBooleanLabel(value, column.typeOptions) : value;
1593
+ case "number":
1594
+ return !isTableNumber(value) ? null : column.typeOptions?.exportFormat === "formatted" ? formatNumberValue(value, column.typeOptions, locale) : value;
1595
+ default:
1596
+ return columnValue(column, value);
1597
+ }
1598
+ };
1599
+ var DownloadTable = Command.make("DataTable/Download", {
1600
+ args: {
1601
+ filename: Schema5.String,
1602
+ content: Schema5.Redacted(Schema5.String, { disallowJsonEncode: true }),
1603
+ type: Schema5.String
1604
+ }
1605
+ }, ({ filename, content, type }) => Effect2.try(() => downloadTableBlob(Redacted.value(content), type, filename)).pipe(Effect2.match({
1606
+ onSuccess: () => DataTableMessage.ExportFinished({ failed: false }),
1607
+ onFailure: () => DataTableMessage.ExportFinished({ failed: true })
1608
+ })));
1609
+ var update2 = Component2.define(dataTableOptions).update({
1610
+ ReferenceImageFailed: ($, { src }) => $.model.failedImages.includes(src) ? $.model : $.evolve({ failedImages: [...$.model.failedImages, src] }),
1611
+ RowActivated: ($, { rowId }) => $.props.rowActivation && available($.props) && $.props.rowData.some(({ id }) => id === rowId) ? $.emit(DataTableEvents.RowActivated({ rowId })) : $.model,
1612
+ PreferencesLoaded: ($, { preferences }) => $.model.preferencesLoaded ? $.model : $.evolve({
1613
+ preferencesLoaded: true,
1614
+ columnVisibility: {
1615
+ ...$.model.columnVisibility,
1616
+ ...preferences?.columnVisibility
1617
+ },
1618
+ columnSizing: preferences?.columnSizing ?? $.model.columnSizing,
1619
+ grouping: preferences?.grouping ?? $.model.grouping,
1620
+ view: $.props.features?.gallery ? preferences?.view ?? $.model.view : "table"
1621
+ }),
1622
+ ItemActionRequested: ($, request) => {
1623
+ const row = $.props.rowData.find(({ id }) => id === request.rowId);
1624
+ const column = $.props.columnDefs.find(({ id }) => id === request.columnId);
1625
+ const items = row?.cells[request.columnId];
1626
+ return available($.props) && column?.type === "list" && isTableList(items) && items.some(({ value }) => value === request.itemId) && column.itemActions?.some(({ id, disabled }) => id === request.actionId && !disabled) ? $.emit(DataTableEvents.ItemActionRequested(request)) : $.model;
1627
+ },
1628
+ ExportStarted: ($) => $.evolve({ exporting: true, exportFailed: false }),
1629
+ ExportFinished: ($, { failed }) => $.evolve({ exporting: false, exportFailed: failed }),
1630
+ BuiltInExportRequested: ($, { format, locale = $.props.locale ?? "en" }) => {
1631
+ const feature = $.props.features?.export;
1632
+ if (!feature || feature.pending || $.model.exporting || feature.builtIn === false || !available($.props))
1633
+ return $.model;
1634
+ const projection = dataTablePage($.props, $.model, locale);
1635
+ const rows = feature.scope === "currentPage" ? projection.rows : projection.ordered;
1636
+ if (!rows.length)
1637
+ return $.model;
1638
+ const columns = tableDataColumns($.props.columnDefs.filter(({ id, export: enabled }) => enabled !== false && $.model.columnVisibility[id] !== false)).filter(({ export: enabled }) => enabled !== false);
1639
+ const content = format === "csv" ? encodeTableCsv(columns.map(({ headerName }) => headerName), rows.map((row) => columns.map((column) => tableExportValue(column, row, locale)))) : JSON.stringify(rows.map((row) => Object.fromEntries(columns.map((column) => [
1640
+ column.id,
1641
+ tableExportValue(column, row, locale)
1642
+ ]))), null, 2);
1643
+ return $.evolve({ menu: null, exporting: true, exportFailed: false }).run(DownloadTable.make({
1644
+ content: Redacted.make(content),
1645
+ filename: tableExportFilename(feature.baseName, format),
1646
+ type: format === "csv" ? "text/csv;charset=utf-8" : "application/json;charset=utf-8"
1647
+ }));
1648
+ },
1649
+ RefreshRequested: ($) => $.props.features?.refresh ? $.emit(DataTableEvents.RefreshRequested()) : $.model,
1650
+ ExportRequested: ($, { actionId }) => !$.props.features?.export?.pending && $.props.features?.export?.actions?.some(({ id, disabled }) => id === actionId && !disabled) ? $.emit(DataTableEvents.ExportRequested({ actionId })) : $.model,
1651
+ GroupActionRequested: ($, request) => available($.props) && $.props.features?.grouping?.fields.some(({ id, actions }) => id === request.fieldId && actions?.some(({ id, disabled }) => id === request.actionId && !disabled)) ? $.emit(DataTableEvents.GroupActionRequested(request)) : $.model,
1652
+ GroupMoveRequested: ($, { rowId, fieldId, groupId }) => moveGroup($, rowId, fieldId, groupId),
1653
+ ReorderRequested: ($, { rowId, targetId, after }) => reorderRows($, rowId, targetId, after),
1654
+ DragStarted: ($, { rowId }) => $.evolve({ dragging: rowId }),
1655
+ DragEnded: ($) => $.evolve({ dragging: null }),
1656
+ DragDropped: ($, { targetId }) => $.model.dragging === null ? $.model : reorderRows($, $.model.dragging, targetId, $.props.rowData.findIndex(({ id }) => id === $.model.dragging) < $.props.rowData.findIndex(({ id }) => id === targetId)),
1657
+ GroupDropped: ($, { fieldId, groupId }) => $.model.dragging === null ? $.model : moveGroup($, $.model.dragging, fieldId, groupId),
1658
+ ViewPicked: ($, { view }) => view === "table" || $.props.features?.gallery ? $.evolve({ view, menu: null }) : $.model,
1659
+ GroupingToggled: ($, { fieldId }) => $.props.features?.grouping?.fields.some(({ id }) => id === fieldId) ? $.evolve({
1660
+ grouping: updateSelectedRows($.model.grouping, [fieldId], !$.model.grouping.includes(fieldId))
1661
+ }) : $.model,
1662
+ GroupToggled: ($, { key }) => $.evolve({
1663
+ collapsedGroups: {
1664
+ ...$.model.collapsedGroups,
1665
+ [key]: !$.model.collapsedGroups[key]
1666
+ }
1667
+ }),
1668
+ ColumnResized: ($, { id, delta }) => {
1669
+ const column = $.props.columnDefs.find((column) => column.id === id);
1670
+ if (!column || column.resizable === false)
1671
+ return $.model;
1672
+ const sizing = {
1673
+ ...$.model.columnSizing,
1674
+ [id]: tableColumnWidth(column, $.model.columnSizing) + delta
1675
+ };
1676
+ return $.evolve({
1677
+ columnSizing: { ...sizing, [id]: tableColumnWidth(column, sizing) }
1678
+ });
1679
+ },
1680
+ ColumnResizeReset: ($, { id }) => {
1681
+ const column = $.props.columnDefs.find((column) => column.id === id);
1682
+ if (!column || column.resizable === false)
1683
+ return $.model;
1684
+ return $.evolve({
1685
+ columnSizing: {
1686
+ ...$.model.columnSizing,
1687
+ [id]: clampTableWidth(column)
1688
+ }
1689
+ });
1690
+ },
1691
+ ResizeStarted: ($, { id, x, pointerId }) => {
1692
+ const column = $.props.columnDefs.find((column) => column.id === id);
1693
+ return column && column.resizable !== false ? $.evolve({
1694
+ resizing: {
1695
+ id,
1696
+ x,
1697
+ pointerId,
1698
+ width: tableColumnWidth(column, $.model.columnSizing)
1699
+ }
1700
+ }) : $.model;
1701
+ },
1702
+ ResizeMoved: ($, { x, pointerId }) => {
1703
+ const resize = $.model.resizing;
1704
+ const column = resize && $.props.columnDefs.find(({ id }) => id === resize.id);
1705
+ if (!resize || resize.pointerId !== pointerId || !column || column.resizable === false)
1706
+ return $.model;
1707
+ return $.evolve({
1708
+ columnSizing: {
1709
+ ...$.model.columnSizing,
1710
+ [resize.id]: tableColumnWidth(column, {
1711
+ [resize.id]: resize.width + x - resize.x
1712
+ })
1713
+ }
1714
+ });
1715
+ },
1716
+ ResizeEnded: ($, { pointerId }) => $.model.resizing?.pointerId === pointerId ? $.evolve({ resizing: null }) : $.model,
1717
+ ColumnFiltersCleared: ($, { id }) => {
1718
+ const column = $.props.columnDefs.find((column) => column.id === id);
1719
+ if (!column || !tableFeatures($.props).filtering)
1720
+ return $.model;
1721
+ const owned = new Set([
1722
+ id,
1723
+ ...tableDataColumns([column]).map(({ id }) => id)
1724
+ ]);
1725
+ const filters = tableQuery($.props, $.model).filters?.filter(({ id }) => !owned.has(id));
1726
+ return changeQuery($, { filters: filters?.length ? filters : undefined, page: 0 }, { filterDraft: null, invalidFilter: false });
1727
+ },
1728
+ ColumnSortCleared: ($, { id }) => {
1729
+ const column = $.props.columnDefs.find((column) => column.id === id);
1730
+ if (!column || !tableFeatures($.props).sorting)
1731
+ return $.model;
1732
+ const owned = new Set([
1733
+ id,
1734
+ ...tableDataColumns([column]).map(({ id }) => id)
1735
+ ]);
1736
+ const sort = (tableQuery($.props, $.model).sort ?? []).filter(({ id }) => !owned.has(id));
1737
+ return changeQuery($, { sort }, {}, DataTableEvents.SortChanged({ sort }));
1738
+ },
1739
+ MenuOpened: ($, { key }) => $.evolve({ menu: key, submenu: null, menuQuery: "" }),
1740
+ MenuQueryChanged: ($, { key, query }) => $.model.menu === key ? $.evolve({ menuQuery: query }) : $.model,
1741
+ MenuClosed: ($, { key }) => $.model.menu === key ? $.evolve({ menu: null, submenu: null }) : $.model,
1742
+ SubmenuOpened: ($, { key, filterColumnId }) => $.evolve({
1743
+ submenu: key,
1744
+ menuQuery: "",
1745
+ ...filterColumnId === undefined ? {} : {
1746
+ filterDraft: tableFilterDraft(filterColumnId, tableQuery($.props, $.model).filters?.find(({ id }) => id === filterColumnId)),
1747
+ invalidFilter: false
1748
+ }
1749
+ }),
1750
+ SubmenuClosed: ($, { key }) => $.model.submenu === key ? $.evolve({ submenu: null }) : $.model,
1751
+ SearchChanged: ($, { value }) => tableFeatures($.props).search ? changeQuery($, { globalFilter: value || undefined, page: 0 }, { menu: null }) : $.model,
1752
+ FilterInputChanged: ($, { field, value }) => {
1753
+ const draft = $.model.filterDraft;
1754
+ return draft ? $.evolve({
1755
+ filterDraft: { ...draft, [field]: value },
1756
+ invalidFilter: false
1757
+ }) : $.model;
1758
+ },
1759
+ FilterOperatorChanged: ($, { operator }) => {
1760
+ const draft = $.model.filterDraft;
1761
+ return draft ? $.evolve({
1762
+ filterDraft: { ...draft, operator },
1763
+ invalidFilter: false
1764
+ }) : $.model;
1765
+ },
1766
+ FilterValueToggled: ($, { value, checked }) => {
1767
+ const draft = $.model.filterDraft;
1768
+ return draft ? $.evolve({
1769
+ filterDraft: {
1770
+ ...draft,
1771
+ values: updateSelectedRows(draft.values, [value], checked)
1772
+ },
1773
+ invalidFilter: false
1774
+ }) : $.model;
1775
+ },
1776
+ FilterApplied: ($) => {
1777
+ const draft = $.model.filterDraft;
1778
+ if (!tableFeatures($.props).filtering || !draft)
1779
+ return $.model;
1780
+ const column = tableDataColumns($.props.columnDefs).find(({ id, filterable }) => id === draft.id && filterable !== false);
1781
+ if (!column)
1782
+ return $.model;
1783
+ const decoded = parseTableFilterDraft(tableFilterKind(column), draft);
1784
+ return Option3.isNone(decoded) ? $.evolve({ invalidFilter: true }) : changeColumnFilter($, draft.id, decoded.value, {
1785
+ invalidFilter: false
1786
+ });
1787
+ },
1788
+ FilterCleared: ($) => {
1789
+ const draft = $.model.filterDraft;
1790
+ if (!draft)
1791
+ return $.model;
1792
+ return changeColumnFilter($, draft.id, null, {
1793
+ filterDraft: tableFilterDraft(draft.id),
1794
+ invalidFilter: false
1795
+ });
1796
+ },
1797
+ ColumnFilterChanged: ($, { id, filter }) => {
1798
+ if (!tableFeatures($.props).filtering || !tableDataColumns($.props.columnDefs).some((column) => column.id === id && column.filterable !== false) || filter && filter.id !== id)
1799
+ return $.model;
1800
+ return changeColumnFilter($, id, filter);
1801
+ },
1802
+ FiltersCleared: ($) => changeQuery($, { filters: undefined, page: 0 }, {
1803
+ filterDraft: null,
1804
+ invalidFilter: false
1805
+ }),
1806
+ PageRequested: ($, { page }) => tableFeatures($.props).pagination && page >= 0 ? changeQuery($, { page }, { menu: null }) : $.model,
1807
+ ServerPageInvalidated: ($) => {
1808
+ const correction = serverPageCorrection($.props, $.model);
1809
+ return correction ? changeQuery($, { page: correction.page }) : $.model;
1810
+ },
1811
+ PageSizeRequested: ($, { pageSize }) => {
1812
+ const pagination = tableFeatures($.props).pagination;
1813
+ return pagination && (pagination.pageSizes ?? defaultPageSizes).includes(pageSize) ? changeQuery($, { pageSize, page: 0 }, { menu: null }) : $.model;
1814
+ },
1815
+ SortRequested: ($, { columnId, direction }) => {
1816
+ if (!tableFeatures($.props).sorting || !tableDataColumns($.props.columnDefs).some(({ id, sortable }) => id === columnId && sortable !== false))
1817
+ return $.model;
1818
+ const sort = direction === null ? (tableQuery($.props, $.model).sort ?? []).filter(({ id }) => id !== columnId) : [{ id: columnId, direction }];
1819
+ return changeQuery($, { sort: sort.length ? sort : undefined, page: 0 }, {}, DataTableEvents.SortChanged({ sort }));
1820
+ },
1821
+ ColumnVisibilityChanged: ($, { id, visible }) => tableFeatures($.props).columnVisibility && $.props.columnDefs.some((column) => column.id === id && column.hideable !== false) ? $.evolve({
1822
+ columnVisibility: { ...$.model.columnVisibility, [id]: visible }
1823
+ }) : $.model,
1824
+ SelectionRequested: ($, { rowIds, checked }) => {
1825
+ if (!available($.props) || !$.props.selection)
1826
+ return $.model;
1827
+ const requested = new Set(rowIds);
1828
+ const targets = $.props.rowData.filter((row) => row.selectable !== false && requested.has(row.id)).map(({ id }) => id);
1829
+ if (targets.length === 0)
1830
+ return $.model;
1831
+ const controlled = $.props.selection.selectedRowIds;
1832
+ const selectedRowIds = updateSelectedRows(controlled ?? $.model.selectedRowIds, targets, checked);
1833
+ return $.evolve(controlled ? {} : { selectedRowIds }).emit(DataTableEvents.SelectionChanged({ selectedRowIds }));
1834
+ },
1835
+ CellEditRequested: ($, { rowId, columnId, edit }) => {
1836
+ if (!available($.props))
1837
+ return $.model;
1838
+ const row = $.props.rowData.find(({ id }) => id === rowId);
1839
+ const column = $.props.columnDefs.find(({ id }) => id === columnId);
1840
+ if (!row || !column || row.disabledColumnIds?.includes(columnId))
1841
+ return $.model;
1842
+ const value = row.cells[columnId];
1843
+ if (edit._tag === "SetBoolean") {
1844
+ if (column.type !== "boolean" || !column.editable || !isTableBoolean(value) || edit.value === value)
1845
+ return $.model;
1846
+ } else {
1847
+ if (column.type !== "list")
1848
+ return $.model;
1849
+ const items = isTableList(value) ? value : [];
1850
+ const contains = items.some(({ value }) => value === edit.itemId);
1851
+ if (edit._tag === "AddItem") {
1852
+ if (contains || !column.options?.some(({ value }) => value === edit.itemId))
1853
+ return $.model;
1854
+ } else if (!contains || !column.allowRemove)
1855
+ return $.model;
1856
+ }
1857
+ return $.emit(DataTableEvents.CellEditRequested({ rowId, columnId, edit }));
1858
+ },
1859
+ RowActionRequested: ($, { rowId, actionId }) => {
1860
+ const row = $.props.rowData.find(({ id }) => id === rowId);
1861
+ if (!available($.props) || !row?.actions?.some(({ id, disabled }) => id === actionId && !disabled))
1862
+ return $.model;
1863
+ return $.emit(DataTableEvents.RowActionRequested({ rowId, actionId }));
1864
+ },
1865
+ BulkActionRequested: ($, { actionId }) => {
1866
+ const selection = $.props.selection;
1867
+ if (!available($.props) || !selection?.bulkActions?.some(({ id, disabled }) => id === actionId && !disabled))
1868
+ return $.model;
1869
+ const rowIds = tableSelectedRowIds($.props, $.model);
1870
+ return rowIds.length > 0 ? $.emit(DataTableEvents.BulkActionRequested({ actionId, rowIds })) : $.model;
1871
+ }
1872
+ });
1873
+ var dataTableBehaviours = {
1874
+ subscriptions: ({
1875
+ props,
1876
+ model
1877
+ }) => {
1878
+ const correction = serverPageCorrection(props, model);
1879
+ return correction ? [
1880
+ Subscription.make("reconcile-server-page", [correction.requested, correction.page, correction.size], () => Stream.make(DataTableMessage.ServerPageInvalidated()))
1881
+ ] : [];
1882
+ },
1883
+ init: ({ props }) => ({
1884
+ menu: null,
1885
+ submenu: null,
1886
+ menuQuery: "",
1887
+ failedImages: [],
1888
+ selectedRowIds: [],
1889
+ query: {
1890
+ globalFilter: props.initialState?.globalFilter,
1891
+ filters: props.initialState?.filters,
1892
+ sort: props.initialState?.sort,
1893
+ page: props.initialState?.page ?? 0,
1894
+ pageSize: props.initialState?.pageSize ?? (props.pagination?.mode === undefined ? props.pagination?.pageSizes?.[0] : undefined) ?? DEFAULT_PAGE_SIZE
1895
+ },
1896
+ columnVisibility: props.initialState?.columnVisibility ?? {},
1897
+ preferencesLoaded: false,
1898
+ columnSizing: {},
1899
+ view: props.initialState?.view ?? "table",
1900
+ grouping: props.features?.grouping?.initial ?? [],
1901
+ collapsedGroups: {},
1902
+ dragging: null,
1903
+ exporting: false,
1904
+ exportFailed: false,
1905
+ resizing: null,
1906
+ filterDraft: null,
1907
+ invalidFilter: false
1908
+ }),
1909
+ update: update2
1910
+ };
1911
+
1912
+ // ../../src/components/data-table/html.ts
1913
+ var keyOf = (...parts) => JSON.stringify(parts);
1914
+ var cellClass = "px-3 py-2 align-middle";
1915
+ var badgeVariants = {
1916
+ ...tableBadgeTones,
1917
+ default: "bg-primary text-primary-foreground",
1918
+ secondary: "bg-secondary text-secondary-foreground",
1919
+ outline: "border-border text-foreground",
1920
+ destructive: "bg-destructive/10 text-destructive dark:bg-destructive/20"
1921
+ };
1922
+ var badgeClass = "inline-flex items-center gap-1 rounded-full border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap";
1923
+ var isTextFilterOperator = Schema6.is(TextFilterOperator);
1924
+ var RowDrag = "application/x-krakstack-table-row";
1925
+ var PersistPreferences = Mount.makeStream("DataTable/PersistPreferences", {
1926
+ args: {
1927
+ columns: Schema6.Array(Schema6.String),
1928
+ gallery: Schema6.Boolean,
1929
+ preferences: Schema6.NullOr(DataTablePreferencesSchema)
1930
+ }
1931
+ }, (element, initial, changes) => Stream2.make(initial).pipe(Stream2.concat(changes), Stream2.map(({ columns, gallery, preferences }) => {
1932
+ const host = element.ownerDocument.defaultView;
1933
+ const storageKey = tablePreferencesKey(host?.location.pathname ?? "/", columns, gallery);
1934
+ if (preferences) {
1935
+ writeTablePreferences(storageKey, preferences, host);
1936
+ return;
1937
+ }
1938
+ return DataTableMessage.PreferencesLoaded({
1939
+ preferences: readTablePreferences(storageKey, host)
1940
+ });
1941
+ }), Stream2.filter((message) => message !== undefined)));
1942
+ var FilterSelectMessage = UiSchema3.TaggedEnum({
1943
+ OpenChanged: { open: Schema6.Boolean },
1944
+ Picked: { value: Schema6.String }
1945
+ });
1946
+ var FilterSelectEvent = UiSchema3.TaggedEnum({
1947
+ Changed: { value: Schema6.String }
1948
+ });
1949
+ var FilterSelect = Html2.component({
1950
+ name: "DataTableFilterSelect",
1951
+ props: Schema6.Struct({
1952
+ label: Schema6.String,
1953
+ value: Schema6.String,
1954
+ items: Schema6.Array(Schema6.Struct({ value: Schema6.String, label: Schema6.String }))
1955
+ }),
1956
+ model: Schema6.Boolean,
1957
+ message: FilterSelectMessage,
1958
+ events: FilterSelectEvent,
1959
+ restore: false
1960
+ }).make({
1961
+ init: () => false,
1962
+ update: {
1963
+ OpenChanged: ($, { open }) => $.set(open),
1964
+ Picked: ($, { value }) => $.set(false).emit(FilterSelectEvent.Changed({ value }))
1965
+ },
1966
+ view: (h, open) => Select2(h, {
1967
+ props: {
1968
+ open,
1969
+ items: h.props.items,
1970
+ value: h.props.value || null,
1971
+ placeholder: "—",
1972
+ alignItemWithTrigger: false
1973
+ },
1974
+ onEmit: {
1975
+ RequestedOpen: () => FilterSelectMessage.OpenChanged({ open: true }),
1976
+ RequestedClose: () => FilterSelectMessage.OpenChanged({ open: false }),
1977
+ Picked: ({ value }) => {
1978
+ const item = h.props.items.find((item) => item.value === value);
1979
+ return item && FilterSelectMessage.Picked({ value: item.value });
1980
+ },
1981
+ Settled: () => {
1982
+ return;
1983
+ }
1984
+ },
1985
+ view: (select) => h.div.class("grid gap-1").children(SelectLabel2(h, select, { class: "mb-0" }).children(h.props.label), SelectTrigger2(h, select, {
1986
+ size: "sm",
1987
+ class: "w-full min-w-0"
1988
+ }).children(SelectValue2(h, select), SelectIcon2(h, select)), SelectPositioner2(h, select).children(SelectPopup2(h, select, { size: "sm" }).children(SelectList2(h, select).children(h.props.items.map(({ value, label }) => SelectItem2(h, select, { value }).children(SelectItemText2(h, select).children(label), SelectItemIndicator2(h, select, { value })))))))
1989
+ })
1990
+ });
1991
+ var DataTable = Html2.component({
1992
+ ...dataTableOptions,
1993
+ reads: { localeConfig: krakstackLocaleRead2 }
1994
+ }).make({
1995
+ ...dataTableBehaviours,
1996
+ view: (h, model) => {
1997
+ const tableClasses = resolveTableClasses(h.props.classes);
1998
+ const props = h.props;
1999
+ const locale = props.locale ?? h.reads.localeConfig?.locale ?? "en";
2000
+ const copy = htmlDataTableMessages(locale, props.messages);
2001
+ const query = tableQuery(props, model);
2002
+ const features = tableFeatures(props);
2003
+ const columns = props.columnDefs.filter(({ id }) => model.columnVisibility[id] !== false);
2004
+ const dataColumns = tableDataColumns(props.columnDefs);
2005
+ const sortableColumns = dataColumns.filter(({ sortable }) => sortable !== false);
2006
+ const hideableColumns = props.columnDefs.filter(({ hideable }) => hideable !== false);
2007
+ const sort = query.sort ?? [];
2008
+ const selection = props.selection;
2009
+ const selected = new Set(tableSelectedRowIds(props, model));
2010
+ const selectedCount = selected.size;
2011
+ const {
2012
+ rows,
2013
+ page,
2014
+ pageSize,
2015
+ pageSizes,
2016
+ pageCount,
2017
+ totalRows,
2018
+ paginationVisible
2019
+ } = dataTablePage(props, model, locale);
2020
+ const grouping = tableGrouping(props, model);
2021
+ const gallery = model.view === "gallery" && features.gallery;
2022
+ const reorder = canReorderTableRows(props, model);
2023
+ const draggable = reorder || grouping.some(({ movable }) => movable);
2024
+ const dropOnRow = (rowId, group) => group ? DataTableMessage.GroupDropped(group) : reorder ? DataTableMessage.DragDropped({ targetId: rowId }) : undefined;
2025
+ const rowActions = reorder || props.rowData.some(({ actions }) => actions?.length);
2026
+ const span = Math.max(1, columns.length + Number(!!selection) + Number(rowActions) + Number(draggable));
2027
+ const virtualization = features.virtualization;
2028
+ const fillHeight = virtualization && virtualization !== true && virtualization.scroll === "internal";
2029
+ const virtual = tableVirtualization(rows.length, virtualization, !grouping.length && !gallery && !features.reordering && props.status?.error === undefined && rows.length > 0);
2030
+ const ids = rows.filter(({ selectable }) => selectable !== false).map(({ id }) => id);
2031
+ const selectedHere = ids.filter((id) => selected.has(id)).length;
2032
+ const status = props.status;
2033
+ const blocked = status?.error !== undefined || status?.loading === true && rows.length === 0;
2034
+ const widths = columns.map((column) => tableColumnWidth(column, model.columnSizing));
2035
+ const layoutWidth = tableLayoutWidth(widths, Number(!!selection) + Number(rowActions) + Number(draggable));
2036
+ const icons = {
2037
+ asc: ArrowUp,
2038
+ desc: ArrowDown,
2039
+ clear: X,
2040
+ filter: ListFilter,
2041
+ hide: EyeOff,
2042
+ sort: ChevronsUpDown,
2043
+ columns: Settings2,
2044
+ refresh: RefreshCw,
2045
+ table: Rows3,
2046
+ gallery: LayoutGrid,
2047
+ export: Download,
2048
+ csv: FileText,
2049
+ json: FileJson
2050
+ };
2051
+ const indicator = (icon) => icon ? icons[icon](h, { size: 16, className: "shrink-0" }) : undefined;
2052
+ const menu = (key, label, accessibleLabel, items, inBar = false, searchLabel, pending = false, presentation) => Menu(h, {
2053
+ key,
2054
+ props: {
2055
+ disabled: pending,
2056
+ open: model.menu === key,
2057
+ query: searchLabel ? model.menu === key ? model.menuQuery : "" : undefined,
2058
+ filter: searchLabel ? "contains" : undefined,
2059
+ items: items.map(({ id, name, disabled, checked }) => ({
2060
+ value: id,
2061
+ label: name,
2062
+ disabled,
2063
+ checked
2064
+ })),
2065
+ modal: false,
2066
+ align: presentation === "actions" || presentation && "selectedCount" in presentation ? "end" : "start",
2067
+ sideOffset: 4,
2068
+ locale
2069
+ },
2070
+ onEmit: {
2071
+ RequestedOpen: () => DataTableMessage.MenuOpened({ key }),
2072
+ RequestedClose: () => DataTableMessage.MenuClosed({ key }),
2073
+ Picked: ({ value }) => items.find(({ id, disabled }) => id === value && !disabled)?.message,
2074
+ Highlighted: () => {
2075
+ return;
2076
+ },
2077
+ RequestedQuery: ({ query }) => searchLabel ? DataTableMessage.MenuQueryChanged({ key, query }) : undefined,
2078
+ Settled: () => {
2079
+ return;
2080
+ }
2081
+ },
2082
+ view: (menu) => {
2083
+ const relationship = presentation && presentation !== "actions" && "relationship" in presentation;
2084
+ const showTitle = relationship || presentation === "actions" || presentation && "selectedCount" in presentation;
2085
+ return h.div.attr("data-slot", relationship ? "data-table-list-cell" : undefined).class(relationship ? tableClasses.relationshipCell : "").children((inBar ? MenubarTrigger(h, menu, accessibleLabel, presentation && presentation !== "actions" && "selectedCount" in presentation ? cn(tableClasses.selectedTrigger, "data-[popup-open]:bg-primary/90 data-[popup-open]:text-primary-foreground") : undefined) : menu.trigger({
2086
+ element: h.button.class(cn(buttonVariants({
2087
+ variant: "ghost",
2088
+ size: presentation === "actions" ? "icon" : "sm"
2089
+ }), presentation === "actions" && tableClasses.actionTrigger, presentation && presentation !== "actions" && "filtered" in presentation && tableClasses.headerTrigger, presentation && presentation !== "actions" && "relationship" in presentation && tableClasses.relationshipTrigger)).attr("aria-label", accessibleLabel)
2090
+ })).attr("aria-busy", pending ? "true" : undefined).attr("aria-description", presentation && presentation !== "actions" && "toolbarIcon" in presentation && presentation.filterCount ? `${copy.filters}: ${presentation.filterCount}` : presentation && presentation !== "actions" && ("filtered" in presentation) && presentation.filtered ? `${copy.filters}: ${presentation.filtered}` : undefined).children(presentation === "actions" ? Ellipsis(h, { size: 16 }) : presentation && ("selectedCount" in presentation) ? [
2091
+ copy.selected,
2092
+ h.span.class(tableClasses.count).children(String(presentation.selectedCount)),
2093
+ ChevronDown(h, { size: 16 })
2094
+ ] : presentation && ("relationship" in presentation) ? [
2095
+ presentation.relationship,
2096
+ ChevronDown(h, { size: 16, className: "shrink-0" })
2097
+ ] : presentation && ("toolbarIcon" in presentation) ? [
2098
+ indicator(presentation.toolbarIcon),
2099
+ label,
2100
+ !!presentation.filterCount && h.span.attr("data-slot", "badge").class(tableClasses.count).children(String(presentation.filterCount))
2101
+ ] : presentation ? [
2102
+ h.span.class("truncate").children(label),
2103
+ presentation.filtered > 0 && indicator("filter"),
2104
+ indicator(presentation.sort)
2105
+ ] : label), MenuPositioner(h, menu).children(MenuPopup(h, menu, {
2106
+ class: presentation === "actions" || presentation && "selectedCount" in presentation ? "w-max min-w-36" : presentation && ("filtered" in presentation) ? "w-48 min-w-0" : undefined
2107
+ }).children(showTitle && h.div.class("px-2 py-1.5 text-xs font-medium text-muted-foreground").children(label), showTitle && MenuSeparator(h, menu), searchLabel && MenuInput(h, menu, { placeholder: searchLabel }), searchLabel && MenuEmpty(h, menu)?.children(copy.empty), menu.list(h.div.class("outline-none")).children(items.map(({
2108
+ id,
2109
+ name,
2110
+ variant,
2111
+ checked,
2112
+ radio,
2113
+ children,
2114
+ filterEditor,
2115
+ filterColumnId,
2116
+ childSearch,
2117
+ icon,
2118
+ rowIcon,
2119
+ separatorBefore
2120
+ }) => {
2121
+ if (children || filterEditor) {
2122
+ const subitems = children ?? [];
2123
+ const subkey = keyOf(key, id);
2124
+ return Menu(h, {
2125
+ key: subkey,
2126
+ props: {
2127
+ parentItem: id,
2128
+ query: childSearch ? model.menuQuery : undefined,
2129
+ filter: childSearch ? "contains" : undefined,
2130
+ open: model.menu === key && model.submenu === subkey,
2131
+ items: subitems.map(({ id, name, disabled, checked }) => ({
2132
+ value: id,
2133
+ label: name,
2134
+ disabled,
2135
+ checked
2136
+ })),
2137
+ locale
2138
+ },
2139
+ onEmit: {
2140
+ RequestedOpen: () => DataTableMessage.SubmenuOpened({
2141
+ key: subkey,
2142
+ ...filterEditor ? { filterColumnId: filterColumnId ?? id } : {}
2143
+ }),
2144
+ RequestedClose: () => DataTableMessage.SubmenuClosed({ key: subkey }),
2145
+ Picked: ({ value }) => subitems.find(({ id, disabled }) => id === value && !disabled)?.message,
2146
+ Highlighted: () => {
2147
+ return;
2148
+ },
2149
+ RequestedQuery: ({ query }) => childSearch ? DataTableMessage.MenuQueryChanged({ key, query }) : undefined,
2150
+ Settled: () => {
2151
+ return;
2152
+ }
2153
+ },
2154
+ view: (submenu) => h.div.children(separatorBefore && MenuSeparator(h, menu), MenuSubTrigger(h, menu, submenu, {
2155
+ value: id
2156
+ }).children(indicator(icon), name), MenuPositioner(h, submenu).children(MenuPopup(h, submenu).children(childSearch && MenuInput(h, submenu, {
2157
+ placeholder: copy.addItem
2158
+ }), childSearch && MenuEmpty(h, submenu)?.children(copy.empty), filterEditor && model.submenu === subkey && filterEditor(), submenu.list(h.div).children(subitems.map(({
2159
+ id,
2160
+ name,
2161
+ variant,
2162
+ keepOpen,
2163
+ icon,
2164
+ checked,
2165
+ radio,
2166
+ separatorBefore
2167
+ }) => {
2168
+ const options = {
2169
+ value: id,
2170
+ closeOnClick: keepOpen ? false : undefined
2171
+ };
2172
+ const part = radio ? MenuRadioItem(h, submenu, options) : checked !== undefined ? MenuCheckboxItem(h, submenu, options) : MenuItem(h, submenu, {
2173
+ ...options,
2174
+ variant
2175
+ });
2176
+ const content = part.children(indicator(icon), name);
2177
+ return separatorBefore ? h.div.children(MenuSeparator(h, submenu), content) : content;
2178
+ })))))
2179
+ });
2180
+ }
2181
+ const element = h.div.class(cn("data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground relative flex min-h-[30px] cursor-default items-center gap-2 rounded-sm px-2 whitespace-nowrap outline-none select-none data-[disabled]:opacity-45", variant === "destructive" && "text-destructive data-[highlighted]:bg-destructive/10 data-[highlighted]:text-destructive"));
2182
+ const part = radio ? menu.radioItem({ element, value: id }) : checked !== undefined ? menu.checkboxItem({
2183
+ element,
2184
+ value: id,
2185
+ closeOnClick: false
2186
+ }) : menu.item({
2187
+ element,
2188
+ value: id,
2189
+ closeOnClick: !searchLabel
2190
+ });
2191
+ const content = part.children(rowIcon?.(h, { size: 16, className: "shrink-0" }), checked !== undefined && h.span.attr("aria-hidden", "true").class("w-3").children(checked ? "✓" : ""), indicator(icon), name);
2192
+ return separatorBefore ? h.div.children(MenuSeparator(h, menu), content) : content;
2193
+ })))));
2194
+ }
2195
+ });
2196
+ const check = (key, label, checked, onToggle, options, inCell = false) => Checkbox(h, {
2197
+ key,
2198
+ props: { checked, ...options },
2199
+ onEmit: { Toggled: ({ checked }) => onToggle(checked) },
2200
+ view: (checkbox) => h.span.class("grid size-4 shrink-0 place-items-center").children(CheckboxRoot(h, checkbox, {
2201
+ class: inCell ? "focus-visible:outline-none" : undefined
2202
+ }).attr("aria-label", label).children(CheckboxIndicator(h, checkbox, {
2203
+ class: "pointer-events-none"
2204
+ })))
2205
+ });
2206
+ const filterColumns = dataColumns.filter(({ filterable }) => filterable !== false);
2207
+ const draft = model.filterDraft;
2208
+ const filterColumn = draft && filterColumns.find(({ id }) => id === draft.id);
2209
+ const filterKind = filterColumn && tableFilterKind(filterColumn);
2210
+ const activeFilters = (query.filters ?? []).filter((filter) => filterColumns.some((column) => column.id === filter.id && tableFilterKind(column) === filter.kind));
2211
+ const selectFilter = (label, value, options, change) => FilterSelect(h, {
2212
+ props: { label, value, items: options },
2213
+ onEmit: { Changed: ({ value }) => change(value) }
2214
+ });
2215
+ const filterInput = (label, field, value, type = "text") => h.label.class("grid gap-1 text-sm").children(label, Input(h, {
2216
+ element: type === "number" ? h.input.attrs({ type: "number", step: "any" }) : h.input.attr("type", type),
2217
+ props: { value },
2218
+ onUpdate: ({ value }) => DataTableMessage.FilterInputChanged({ field, value })
2219
+ }));
2220
+ const filterPanel = () => h.div.class("grid w-64 max-w-[80vw] gap-2 p-2").children(draft && filterColumn && h.div.key(filterColumn.id).class("grid gap-2").children(filterKind === "text" && [
2221
+ selectFilter(copy.filterOperator, draft.operator, [
2222
+ { value: "contains", label: copy.filterContains },
2223
+ { value: "equals", label: copy.filterEquals },
2224
+ { value: "startsWith", label: copy.filterStartsWith },
2225
+ { value: "endsWith", label: copy.filterEndsWith }
2226
+ ], (operator) => isTextFilterOperator(operator) ? DataTableMessage.FilterOperatorChanged({ operator }) : undefined),
2227
+ filterInput(copy.filterValue, "primary", draft.primary)
2228
+ ], filterKind === "number" && [
2229
+ filterInput(copy.filterMin, "primary", draft.primary, "number"),
2230
+ filterInput(copy.filterMax, "secondary", draft.secondary, "number")
2231
+ ], filterKind === "date" && [
2232
+ filterInput(copy.filterFrom, "primary", draft.primary, "date"),
2233
+ filterInput(copy.filterTo, "secondary", draft.secondary, "date")
2234
+ ], model.invalidFilter && h.p.attr("role", "alert").class("text-destructive text-sm").children(copy.filterInvalid), h.div.class("flex flex-wrap gap-2").children(Button2(h, {
2235
+ size: "sm",
2236
+ onPress: DataTableMessage.FilterApplied()
2237
+ }).children(copy.filterApply), Button2(h, {
2238
+ size: "sm",
2239
+ variant: "outline",
2240
+ onPress: DataTableMessage.FilterCleared()
2241
+ }).children(copy.filterClear))));
2242
+ const filterSubmenu = (column) => {
2243
+ const { id } = column;
2244
+ const current = activeFilters.find((filter) => filter.id === id);
2245
+ let children;
2246
+ if (column.type === "boolean") {
2247
+ children = [true, false].map((value) => ({
2248
+ id: String(value),
2249
+ name: value ? column.typeOptions?.trueLabel ?? copy.filterTrue : column.typeOptions?.falseLabel ?? copy.filterFalse,
2250
+ radio: true,
2251
+ checked: current?.kind === "boolean" && current.value === value,
2252
+ keepOpen: true,
2253
+ message: DataTableMessage.ColumnFilterChanged({
2254
+ id,
2255
+ filter: { id, kind: "boolean", value }
2256
+ })
2257
+ }));
2258
+ } else if (column.type === "list" || column.type === "text" && column.display === "badge") {
2259
+ const selected = current?.kind === "values" ? current.values : [];
2260
+ const options = column.type === "text" ? tableBadgeFilterOptions(props.rowData.map((row) => row.cells[id]), column.typeOptions) : column.filterOptions ?? tableFilterOptions(props.rowData, id, locale);
2261
+ children = options.map(({ value, label }) => {
2262
+ const checked = selected.includes(value);
2263
+ const values = updateSelectedRows(selected, [value], !checked);
2264
+ return {
2265
+ id: keyOf("option", value),
2266
+ name: label,
2267
+ checked,
2268
+ keepOpen: true,
2269
+ message: DataTableMessage.ColumnFilterChanged({
2270
+ id,
2271
+ filter: Arr.isArrayNonEmpty(values) ? { id, kind: "values", values } : null
2272
+ })
2273
+ };
2274
+ });
2275
+ } else {
2276
+ return { filterColumnId: id, filterEditor: filterPanel };
2277
+ }
2278
+ children.push({
2279
+ id: "clear",
2280
+ name: copy.filterClear,
2281
+ keepOpen: true,
2282
+ separatorBefore: children.length > 0,
2283
+ message: DataTableMessage.ColumnFilterChanged({ id, filter: null })
2284
+ });
2285
+ return { children };
2286
+ };
2287
+ const cell = (column, row) => {
2288
+ const value = row.cells[column.id];
2289
+ const empty = column.emptyLabel ?? "—";
2290
+ const disabled = row.disabledColumnIds?.includes(column.id);
2291
+ const edit = (edit) => DataTableMessage.CellEditRequested({ rowId: row.id, columnId: column.id, edit });
2292
+ switch (column.type) {
2293
+ case "text": {
2294
+ if (column.display !== "badge")
2295
+ return isTableText(value) ? value : empty;
2296
+ const badge = tableBadge(value, column.typeOptions);
2297
+ return badge ? h.span.class(cn(badgeClass, badgeVariants[badge.variant])).children(badge.option?.icon && h.span.attr("aria-hidden", "true").class("inline-flex shrink-0").children(badge.option.icon(h, { size: 12 })), badge.label) : empty;
2298
+ }
2299
+ case "number":
2300
+ return isTableNumber(value) ? formatNumberValue(value, column.typeOptions, locale) : empty;
2301
+ case "date":
2302
+ case "dateTime": {
2303
+ const date = resolveDate(value, column.type);
2304
+ return date ? h.time.attr("datetime", dateIsoValue(date)).children(formatDateValue(date, column, locale)) : empty;
2305
+ }
2306
+ case "boolean":
2307
+ return isTableBoolean(value) ? h.label.attr("data-slot", "data-table-boolean-cell").class(cn(booleanCellControl, column.editable && !disabled && "hover:bg-muted/50 cursor-pointer")).children(check(keyOf("edit", row.id, column.id), `${column.headerName}: ${row.label}`, value, (value) => edit(DataTableEdit.SetBoolean({ value })), { readOnly: !column.editable || disabled }, true)) : empty;
2308
+ case "reference": {
2309
+ if (!isTableReference(value))
2310
+ return empty;
2311
+ const image = value.imageSrc && !model.failedImages.includes(value.imageSrc) ? value.imageSrc : undefined;
2312
+ const fallbackIcons = column.typeOptions?.fallbackIcons;
2313
+ const fallbackIcon = fallbackIcons && Object.hasOwn(fallbackIcons, row.id) ? fallbackIcons[row.id] : undefined;
2314
+ return h.div.class(tableClasses.reference).children(h.span.class(cn(tableClasses.referenceAvatar, column.typeOptions?.imageVariant === "square" ? "rounded-md" : "rounded-full")).children((!image || !fallbackIcon) && h.span.attr("aria-hidden", "true").children(fallbackIcon?.(h, { size: 16 }) ?? tableInitials(value.label)), image && h.img.attrs({
2315
+ src: image,
2316
+ alt: "",
2317
+ loading: "lazy"
2318
+ }).class("absolute inset-0 size-full object-cover").on("error", DataTableMessage.ReferenceImageFailed({ src: image }))), h.div.class(tableClasses.referenceText).children(h.span.class(tableClasses.referenceName).attr("title", value.label).children(value.label), value.description && h.span.class(tableClasses.referenceDescription).children(value.description)));
2319
+ }
2320
+ case "list": {
2321
+ const current = isTableList(value) ? value : [];
2322
+ const visible = current.slice(0, column.visibleCount ?? 3);
2323
+ const overflow = current.length - visible.length;
2324
+ const badgeSummary = () => h.span.class("inline-flex min-w-0 flex-wrap items-center gap-1").children(visible.map(({ value, label }) => h.span.key(value).class(cn(badgeClass, badgeVariants.secondary)).children(label)), overflow > 0 && h.span.class(cn(badgeClass, badgeVariants.secondary)).children(`+${overflow}`));
2325
+ if (column.manageLabel && !disabled && (column.options || column.allowRemove)) {
2326
+ const used = new Set(current.map(({ value }) => value));
2327
+ const available = (column.options ?? []).filter(({ value }) => !used.has(value));
2328
+ const items = current.map(({ value, label }) => ({
2329
+ id: keyOf("member", value),
2330
+ name: label,
2331
+ disabled: !column.allowRemove,
2332
+ ...column.allowRemove ? {
2333
+ children: [
2334
+ {
2335
+ id: "remove",
2336
+ name: copy.removeItem,
2337
+ keepOpen: true,
2338
+ message: edit(DataTableEdit.RemoveItem({ itemId: value }))
2339
+ }
2340
+ ]
2341
+ } : {}
2342
+ }));
2343
+ return h.div.class("min-w-0").children(menu(keyOf("manage", row.id, column.id), column.manageLabel, `${column.manageLabel}: ${row.label}`, [
2344
+ ...items,
2345
+ ...available.length ? [
2346
+ {
2347
+ id: "add",
2348
+ name: copy.addItem,
2349
+ childSearch: true,
2350
+ separatorBefore: items.length > 0,
2351
+ children: available.map(({ value, label }) => ({
2352
+ id: value,
2353
+ name: label,
2354
+ keepOpen: true,
2355
+ message: edit(DataTableEdit.AddItem({ itemId: value }))
2356
+ }))
2357
+ }
2358
+ ] : []
2359
+ ], false, undefined, false, {
2360
+ relationship: column.display === "badge" && current.length ? badgeSummary() : h.span.class("min-w-0 truncate").children(current.length ? `${current.slice(0, column.visibleCount ?? 3).map(({ label }) => label).join(", ")}${current.length > (column.visibleCount ?? 3) ? ` +${current.length - (column.visibleCount ?? 3)}` : ""}` : empty)
2361
+ }));
2362
+ }
2363
+ if (column.display && !column.options && !column.allowRemove) {
2364
+ const label = column.actionsLabel ?? (column.itemActions?.length ? copy.actions : copy.listDetails);
2365
+ const summary = column.display === "icon" ? h.span.class("flex min-w-0 items-center gap-1 overflow-hidden").children(visible.map(({ value, label }) => h.span.key(value).attr("title", label).class("inline-grid size-7 place-items-center rounded-full bg-muted text-xs").children(tableInitials(label))), overflow > 0 && `+${overflow}`) : column.display === "badge" ? badgeSummary() : h.span.class("min-w-0 truncate").children(`${visible.map(({ label }) => label).join(", ")}${overflow > 0 ? ` +${overflow}` : ""}`);
2366
+ return !current.length ? empty : h.div.class("min-w-0").children(menu(keyOf("items", row.id, column.id), label, `${label}: ${row.label}`, current.map(({ value, label }) => ({
2367
+ id: value,
2368
+ name: label,
2369
+ ...column.itemActions?.length ? {
2370
+ children: column.itemActions.map((action) => ({
2371
+ ...action,
2372
+ message: DataTableMessage.ItemActionRequested({
2373
+ rowId: row.id,
2374
+ columnId: column.id,
2375
+ itemId: value,
2376
+ actionId: action.id
2377
+ })
2378
+ }))
2379
+ } : { disabled: true }
2380
+ })), false, undefined, false, { relationship: summary }));
2381
+ }
2382
+ const used = new Set(current.map(({ value }) => value));
2383
+ const add = (column.options ?? []).filter(({ value }) => !used.has(value));
2384
+ return h.div.class("grid gap-1").children(current.length > 0 ? h.ul.class("flex flex-wrap gap-1").children(current.map(({ value, label }) => h.li.key(value).class(column.display === "badge" ? cn(badgeClass, badgeVariants.secondary) : "bg-muted rounded-sm ps-2 inline-flex items-center gap-1").children(label, !!column.itemActions?.length && menu(keyOf("item", row.id, column.id, value), copy.actions, `${copy.actions}: ${label} — ${row.label}`, column.itemActions.map((action) => ({
2385
+ ...action,
2386
+ message: DataTableMessage.ItemActionRequested({
2387
+ rowId: row.id,
2388
+ columnId: column.id,
2389
+ itemId: value,
2390
+ actionId: action.id
2391
+ })
2392
+ }))), column.allowRemove && !disabled && Button2(h, {
2393
+ variant: "ghost",
2394
+ size: "sm",
2395
+ onPress: edit(DataTableEdit.RemoveItem({ itemId: value }))
2396
+ }).attr("aria-label", `${copy.removeItem}: ${label} — ${row.label}`).children("×")))) : empty, !disabled && add.length > 0 && menu(keyOf("add", row.id, column.id), copy.addItem, `${copy.addItem} ${column.headerName}: ${row.label}`, add.map(({ value, label }) => ({
2397
+ id: value,
2398
+ name: label,
2399
+ message: edit(DataTableEdit.AddItem({ itemId: value }))
2400
+ })), false, copy.addItem));
2401
+ }
2402
+ }
2403
+ };
2404
+ const dragHandle = (row) => draggable && h.span.attr("aria-hidden", "true").class("inline-flex size-8 cursor-grab items-center justify-center text-muted-foreground").draggable({ [RowDrag]: row.id }, { effectAllowed: "move" }).on("dragstart", DataTableMessage.DragStarted({ rowId: row.id })).on("dragend", DataTableMessage.DragEnded()).children(GripVertical(h, { size: 16 }));
2405
+ const rowControls = (row, siblings, key) => {
2406
+ const items = tableRowActions(row, siblings, reorder, copy).map((item) => {
2407
+ if ("icon" in item) {
2408
+ const { icon, ...action } = item;
2409
+ return { ...action, rowIcon: icon };
2410
+ }
2411
+ return { ...item, icon: undefined };
2412
+ });
2413
+ return items.length > 0 && menu(keyOf("row", key, row.id), copy.actions, `${copy.actions}: ${row.label}`, items, false, undefined, false, "actions");
2414
+ };
2415
+ const renderRow = (row, siblings, key, group) => {
2416
+ const primary = row.actions?.find(({ id, disabled }) => id === row.primaryActionId && !disabled);
2417
+ const activate = props.rowActivation ? DataTableMessage.RowActivated({ rowId: row.id }) : primary && DataTableMessage.RowActionRequested({ rowId: row.id, actionId: primary.id });
2418
+ const tr = h.tr.key(keyOf(key, row.id)).class(cn("group/row hover:bg-muted/50 data-[selected]:bg-muted/40", tableClasses.row, props.rowActivation && "cursor-pointer")).attr("data-selected", selected.has(row.id) ? "" : undefined);
2419
+ const rowElement = props.rowActivation && activate ? tr.attr("tabindex", "0").on("click", activate).on("keydown", (event) => !event.repeat && !event.composing && (event.key === "Enter" || event.key === " ") ? activate : undefined, { preventDefault: true }) : tr;
2420
+ const ignoreActivation = () => {
2421
+ return;
2422
+ };
2423
+ const drop = dropOnRow(row.id, group);
2424
+ return (drop ? rowElement.dropTarget({ accepts: [RowDrag], dropEffect: "move" }).on("drop", drop) : rowElement).children(selection && h.td.class(tableClasses.selectionCell).on("click", ignoreActivation).on("keydown", ignoreActivation).children(h.div.class(tableClasses.selectionCenter).children(check(keyOf("select", key, row.id), `${copy.selectRow}: ${row.label}`, selected.has(row.id), (checked) => DataTableMessage.SelectionRequested({ rowIds: [row.id], checked }), { disabled: row.selectable === false }))), draggable && h.td.class("w-10 ps-1").on("click", ignoreActivation).on("keydown", ignoreActivation).children(dragHandle(row)), columns.map((column) => {
2425
+ const td = h.td.key(column.id).attr("data-slot", "table-cell").attr("data-column-id", column.id).class(cn(cellClass, tableClasses.cell, column.truncate ? "whitespace-nowrap" : "whitespace-normal", column.type === "list" && "p-0", column.type === "boolean" && "min-w-24 has-[[data-slot=data-table-boolean-cell]]:relative has-[[data-slot=data-table-boolean-cell]]:p-0", "has-[[data-slot=data-table-list-cell]]:relative has-[[data-slot=data-table-list-cell]]:h-16"));
2426
+ const content = () => h.div.class(cn(tableClasses.cellContent, column.truncate && "truncate")).children(cell(column, row));
2427
+ if (column.type === "list" || column.type === "boolean" && isTableBoolean(row.cells[column.id])) {
2428
+ return td.on("click", ignoreActivation).on("keydown", ignoreActivation).children(content());
2429
+ }
2430
+ return (!props.rowActivation && activate && column.type !== "boolean" ? td.class("cursor-pointer").on("click", activate) : td).children(content());
2431
+ }), rowActions && h.td.on("click", ignoreActivation).on("keydown", ignoreActivation).class(cn(tableClasses.actionsCell, "group-data-[selected]/row:bg-muted")).children(h.div.class(tableClasses.actionsAlign).children(primary && activate && Button2(h, {
2432
+ variant: primary.variant === "destructive" ? "destructive" : "ghost",
2433
+ size: "sm",
2434
+ onPress: activate
2435
+ }).attr("aria-label", `${primary.name}: ${row.label}`).children(primary.name), rowControls(row, siblings, key))));
2436
+ };
2437
+ const galleryValue = (id, row) => {
2438
+ const column = props.columnDefs.find((column) => column.id === id);
2439
+ return column ? cell(column, row) : "";
2440
+ };
2441
+ const renderCard = (row, siblings, key, group) => {
2442
+ if (!gallery)
2443
+ return h.div;
2444
+ const image = gallery.image && row.cells[gallery.image];
2445
+ const primary = row.actions?.find(({ id, disabled }) => row.primaryActionId === id && !disabled);
2446
+ const name = galleryValue(gallery.name, row) || row.label;
2447
+ const activate = props.rowActivation ? DataTableMessage.RowActivated({ rowId: row.id }) : primary && DataTableMessage.RowActionRequested({ rowId: row.id, actionId: primary.id });
2448
+ const card = h.article.key(keyOf(key, row.id)).class("grid content-start gap-2 rounded-lg border p-3");
2449
+ const drop = dropOnRow(row.id, group);
2450
+ return (drop ? card.dropTarget({ accepts: [RowDrag], dropEffect: "move" }).on("drop", drop) : card).children(isTableText(image) && h.img.attrs({ src: image, alt: "", loading: "lazy" }).class("aspect-video w-full rounded object-cover"), h.h3.class("font-medium").children(activate ? Button2(h, {
2451
+ variant: "ghost",
2452
+ onPress: activate
2453
+ }).children(name) : name), gallery.description && h.div.class("text-muted-foreground text-sm").children(galleryValue(gallery.description, row)), h.div.class("flex flex-wrap gap-2").children(gallery.tags?.map((id) => {
2454
+ const column = props.columnDefs.find((column) => column.id === id);
2455
+ if ((column?.type === "text" || column?.type === "list") && column.display === "badge")
2456
+ return h.div.key(id).children(cell(column, row));
2457
+ return h.span.key(id).class("bg-muted rounded px-2 py-1 text-xs").children(galleryValue(id, row));
2458
+ })), selection && check(keyOf("select", key, row.id), `${copy.selectRow}: ${row.label}`, selected.has(row.id), (checked) => DataTableMessage.SelectionRequested({ rowIds: [row.id], checked }), { disabled: row.selectable === false }), h.div.class("flex items-center justify-end gap-1").children(dragHandle(row), rowControls(row, siblings, key)));
2459
+ };
2460
+ const renderGroups = (members, depth, parent, parentTarget) => {
2461
+ const field = grouping[depth];
2462
+ if (!field)
2463
+ return members.map((row) => gallery ? renderCard(row, members, parent, parentTarget) : renderRow(row, members, parent, parentTarget));
2464
+ const groups = partitionTableGroups(members, field.groups?.map(({ id }) => id) ?? [], (row) => row.groups?.[field.id] ?? []);
2465
+ return [...groups].flatMap(([groupId, children]) => {
2466
+ const key = tableGroupKey(parent, field.id, groupId);
2467
+ const definition = field.groups?.find(({ id }) => id === groupId);
2468
+ const label = definition?.label ?? groupId;
2469
+ const open = !model.collapsedGroups[key];
2470
+ const title = h.div.class(cn(tableClasses.groupContent, !gallery && tableClasses.groupSticky)).children(h.button.attr("type", "button").class(tableClasses.groupTrigger).style({ paddingInlineStart: `${depth * 20}px` }).on("click", DataTableMessage.GroupToggled({ key })).attr("aria-expanded", open ? "true" : "false").attr("aria-label", label).children((open ? ChevronDown : ChevronRight2)(h, {
2471
+ size: 16,
2472
+ className: "shrink-0"
2473
+ }), h.span.class("min-w-0 flex-1 truncate").children(label), h.span.class(tableClasses.count).children(String(children.length))), !!field.actions?.length && menu(keyOf("group", key), field.actionsLabel ?? copy.actions, `${field.actionsLabel ?? copy.actions}: ${label}`, field.actions.map((action) => ({
2474
+ ...action,
2475
+ message: DataTableMessage.GroupActionRequested({
2476
+ fieldId: field.id,
2477
+ groupId,
2478
+ actionId: action.id
2479
+ })
2480
+ })), false, undefined, false, "actions"));
2481
+ const header = gallery ? h.div.key(key).class(cn("col-span-full rounded-md border", tableClasses.group)).children(title) : h.tr.key(key).class(tableClasses.group).children(h.td.class("p-0").attr("colspan", String(span)).children(title));
2482
+ const groupTarget = field.movable ? { fieldId: field.id, groupId } : parentTarget;
2483
+ const target = groupTarget ? header.dropTarget({ accepts: [RowDrag], dropEffect: "move" }).on("drop", DataTableMessage.GroupDropped(groupTarget)) : header;
2484
+ const empty = definition?.empty ?? copy.empty;
2485
+ return [
2486
+ target,
2487
+ ...open ? children.length ? renderGroups(children, depth + 1, key, groupTarget) : [
2488
+ gallery ? h.p.key(keyOf(key, "empty")).class("col-span-full text-sm").children(empty) : h.tr.key(keyOf(key, "empty")).children(h.td.attr("colspan", String(span)).class("p-3").children(empty))
2489
+ ] : []
2490
+ ];
2491
+ });
2492
+ };
2493
+ return h.section.class(cn("min-w-0 gap-2", fillHeight ? "flex min-h-0 flex-1 flex-col" : "grid", props.className)).onMount(PersistPreferences({
2494
+ columns: props.columnDefs.map(({ id }) => id),
2495
+ gallery: !!features.gallery,
2496
+ preferences: tablePreferences(model)
2497
+ })).children(h.div.class(tableClasses.toolbar).children(features.search && h.div.class(tableClasses.toolbarSearch).children(Search(h, {
2498
+ size: 16,
2499
+ className: "text-muted-foreground pointer-events-none absolute top-1/2 start-3 -translate-y-1/2"
2500
+ }), Input(h, {
2501
+ class: cn("ps-9", query.globalFilter && "pe-10"),
2502
+ element: h.input.attrs({
2503
+ type: "search",
2504
+ placeholder: copy.search
2505
+ }),
2506
+ props: { value: query.globalFilter ?? "" },
2507
+ onUpdate: ({ value }) => DataTableMessage.SearchChanged({ value })
2508
+ }).attr("aria-label", copy.search), !!query.globalFilter && Button2(h, {
2509
+ class: "absolute end-1 top-1/2 -translate-y-1/2",
2510
+ size: "icon-sm",
2511
+ variant: "ghost",
2512
+ onPress: DataTableMessage.SearchChanged({ value: "" })
2513
+ }).attr("aria-label", copy.search).children(X(h, { size: 16 }))), (features.filtering && filterColumns.length > 0 || features.sorting && sortableColumns.length > 0 || features.columnVisibility && hideableColumns.length > 0 || !blocked && selectedCount > 0 && !!selection?.bulkActions?.length || features.refresh || !!features.grouping?.fields.length || !!features.gallery || !!features.export) && Menubar(h, {
2514
+ props: { modal: false },
2515
+ view: (bar) => h.div.class(tableClasses.toolbarMenus).children(MenubarRoot(h, bar, tableClasses.menubar).children(!blocked && selectedCount > 0 && selection && selection.bulkActions && selection.bulkActions.length > 0 && menu(keyOf("bulk"), selection.bulkActionsLabel ?? copy.actions, `${copy.selected} ${selectedCount}`, selection.bulkActions.map((action) => ({
2516
+ ...action,
2517
+ message: DataTableMessage.BulkActionRequested({
2518
+ actionId: action.id
2519
+ })
2520
+ })), true, undefined, false, { selectedCount }), features.filtering && filterColumns.length > 0 && menu(keyOf("filters"), copy.filters, copy.filters, [
2521
+ ...filterColumns.map((column) => ({
2522
+ id: column.id,
2523
+ name: column.headerName,
2524
+ ...filterSubmenu(column)
2525
+ })),
2526
+ ...activeFilters.length > 0 ? [
2527
+ {
2528
+ id: keyOf("clear-filters"),
2529
+ name: copy.filtersClear,
2530
+ icon: "clear",
2531
+ message: DataTableMessage.FiltersCleared()
2532
+ }
2533
+ ] : []
2534
+ ], true, undefined, false, {
2535
+ toolbarIcon: "filter",
2536
+ filterCount: activeFilters.length
2537
+ }), features.sorting && sortableColumns.length > 0 && menu(keyOf("sort-toolbar"), copy.sortBy, copy.sortBy, sortableColumns.map((column) => ({
2538
+ id: column.id,
2539
+ name: column.headerName,
2540
+ children: ["asc", "desc", null].filter((direction) => direction !== null || sort.some(({ id }) => id === column.id)).map((direction) => ({
2541
+ id: keyOf(column.id, direction ?? "clear"),
2542
+ name: direction === "asc" ? copy.sortAsc : direction === "desc" ? copy.sortDesc : copy.sortClear,
2543
+ icon: direction ?? "clear",
2544
+ message: DataTableMessage.SortRequested({
2545
+ columnId: column.id,
2546
+ direction
2547
+ })
2548
+ }))
2549
+ })), true, undefined, false, { toolbarIcon: sort[0]?.direction ?? "sort" }), features.columnVisibility && hideableColumns.length > 0 && menu(keyOf("columns"), copy.columns, copy.columns, hideableColumns.map(({ id, headerName }) => ({
2550
+ id,
2551
+ name: headerName,
2552
+ checked: model.columnVisibility[id] !== false,
2553
+ message: DataTableMessage.ColumnVisibilityChanged({
2554
+ id,
2555
+ visible: model.columnVisibility[id] === false
2556
+ })
2557
+ })), true, undefined, false, { toolbarIcon: "columns" }), features.refresh && menu(keyOf("refresh"), copy.refresh, copy.refresh, [
2558
+ {
2559
+ id: "refresh",
2560
+ name: copy.refresh,
2561
+ icon: "refresh",
2562
+ message: DataTableMessage.RefreshRequested()
2563
+ }
2564
+ ], true, undefined, false, { toolbarIcon: "refresh" }), features.grouping && features.grouping.fields.length > 0 && menu(keyOf("group-by"), copy.groupBy, copy.groupBy, features.grouping.fields.map(({ id, label }) => ({
2565
+ id,
2566
+ name: label,
2567
+ checked: model.grouping.includes(id),
2568
+ message: DataTableMessage.GroupingToggled({ fieldId: id })
2569
+ })), true, undefined, false, { toolbarIcon: "table" }), features.gallery && menu(keyOf("view"), copy.view, copy.view, [
2570
+ {
2571
+ id: "table",
2572
+ name: copy.tableView,
2573
+ icon: "table",
2574
+ checked: !gallery,
2575
+ radio: true,
2576
+ message: DataTableMessage.ViewPicked({ view: "table" })
2577
+ },
2578
+ {
2579
+ id: "gallery",
2580
+ name: copy.galleryView,
2581
+ icon: "gallery",
2582
+ checked: !!gallery,
2583
+ radio: true,
2584
+ message: DataTableMessage.ViewPicked({ view: "gallery" })
2585
+ }
2586
+ ], true, undefined, false, { toolbarIcon: gallery ? "gallery" : "table" }), features.export && menu(keyOf("export"), copy.export, copy.export, [
2587
+ ...features.export.builtIn === false ? [] : ["csv", "json"].map((format) => ({
2588
+ id: keyOf("built-in", format),
2589
+ name: format.toUpperCase(),
2590
+ icon: format,
2591
+ disabled: blocked || !rows.length,
2592
+ message: DataTableMessage.BuiltInExportRequested({
2593
+ format,
2594
+ locale
2595
+ })
2596
+ })),
2597
+ ...(features.export.actions ?? []).map((action) => ({
2598
+ ...action,
2599
+ id: keyOf("custom", action.id),
2600
+ message: DataTableMessage.ExportRequested({
2601
+ actionId: action.id
2602
+ })
2603
+ }))
2604
+ ], true, undefined, features.export.pending || model.exporting, { toolbarIcon: "export" })))
2605
+ })), (model.exportFailed || features.export?.failed) && h.p.attr("role", "alert").class("text-destructive text-sm").children(copy.exportFailed), gallery ? h.div.class("grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-3").children(blocked ? h.p.attr("role", status?.error !== undefined ? "alert" : "status").children(status?.error ?? copy.loading) : !rows.length && !grouping.length ? h.p.attr("role", "status").children(status?.empty ?? copy.empty) : renderGroups(rows, 0, "")) : (() => {
2606
+ const renderTable = (list) => {
2607
+ const table = h.table.class("table-fixed border-separate border-spacing-0 text-start text-sm").style({ width: "100%", minWidth: `${layoutWidth}px` }).attr("aria-busy", status?.loading ? "true" : undefined);
2608
+ return (list ? list.table(table) : table).children(h.caption.class("sr-only").children(props.label), h.thead.class(list ? cn(tableClasses.stickyHeader, tableClasses.stickyHeaderRule) : "[&_th]:border-b").children(h.tr.children(selection && h.th.attr("scope", "col").class(tableClasses.selectionCell).children(h.div.class(tableClasses.selectionCenter).children(check(keyOf("select-all"), copy.selectAllRows, selectedHere > 0 && selectedHere === ids.length, (checked) => DataTableMessage.SelectionRequested({
2609
+ rowIds: ids,
2610
+ checked
2611
+ }), {
2612
+ disabled: blocked || ids.length === 0,
2613
+ indeterminate: selectedHere > 0 && selectedHere < ids.length
2614
+ }))), draggable && h.th.attr("scope", "col").class("w-10"), columns.map((column, index) => {
2615
+ const fields = tableDataColumns([column]);
2616
+ const owns = (id) => id === column.id || fields.some((field) => field.id === id);
2617
+ const active = sort.find(({ id }) => owns(id))?.direction;
2618
+ const filtered = activeFilters.filter(({ id }) => owns(id)).length;
2619
+ const sorting = features.sorting && fields.some(({ sortable }) => sortable !== false);
2620
+ const filtering = features.filtering && fields.some(({ filterable }) => filterable !== false);
2621
+ const hiding = features.columnVisibility && column.hideable !== false;
2622
+ const width = widths[index] ?? tableColumnWidth(column, model.columnSizing);
2623
+ const { min, max } = tableColumnLimits(column);
2624
+ return h.th.key(column.id).class(cn(tableClasses.header, "text-start font-medium")).style({
2625
+ width: `${width}px`
2626
+ }).attrs({
2627
+ scope: "col",
2628
+ "aria-label": column.headerName,
2629
+ "aria-sort": active === "asc" ? "ascending" : active === "desc" ? "descending" : undefined
2630
+ }).children(!sorting && !filtering && !hiding ? h.div.class("truncate px-2 pe-4").children(column.headerName) : menu(keyOf("sort", column.id), column.headerName, column.headerName, [
2631
+ ...sorting && column.fields?.length ? tableDataColumns([column]).filter(({ sortable }) => sortable !== false).map((field) => ({
2632
+ id: keyOf("sort", field.id),
2633
+ name: field.headerName,
2634
+ children: ["asc", "desc"].map((direction) => ({
2635
+ id: direction,
2636
+ name: direction === "asc" ? copy.sortAsc : direction === "desc" ? copy.sortDesc : copy.sortDesc,
2637
+ message: DataTableMessage.SortRequested({
2638
+ columnId: field.id,
2639
+ direction
2640
+ })
2641
+ }))
2642
+ })) : sorting ? [
2643
+ {
2644
+ id: "asc",
2645
+ name: copy.sortAsc,
2646
+ icon: "asc",
2647
+ message: DataTableMessage.SortRequested({
2648
+ columnId: column.id,
2649
+ direction: "asc"
2650
+ })
2651
+ },
2652
+ {
2653
+ id: "desc",
2654
+ name: copy.sortDesc,
2655
+ icon: "desc",
2656
+ message: DataTableMessage.SortRequested({
2657
+ columnId: column.id,
2658
+ direction: "desc"
2659
+ })
2660
+ }
2661
+ ] : [],
2662
+ ...sorting && active ? [
2663
+ {
2664
+ id: "clear-sort",
2665
+ name: copy.sortClear,
2666
+ icon: "clear",
2667
+ message: DataTableMessage.ColumnSortCleared({
2668
+ id: column.id
2669
+ })
2670
+ }
2671
+ ] : [],
2672
+ ...filtering ? tableDataColumns([column]).filter(({ filterable }) => filterable !== false).map((field, index) => ({
2673
+ id: keyOf("filter", field.id),
2674
+ name: column.fields?.length ? `${copy.filters}: ${field.headerName}` : copy.filters,
2675
+ ...filterSubmenu(field),
2676
+ icon: "filter",
2677
+ separatorBefore: sorting && index === 0
2678
+ })) : [],
2679
+ ...filtering && filtered ? [
2680
+ {
2681
+ id: "clear-filter",
2682
+ name: copy.filterClear,
2683
+ icon: "clear",
2684
+ message: DataTableMessage.ColumnFiltersCleared({
2685
+ id: column.id
2686
+ })
2687
+ }
2688
+ ] : [],
2689
+ ...hiding ? [
2690
+ {
2691
+ id: "hide",
2692
+ name: copy.hideColumn,
2693
+ icon: "hide",
2694
+ separatorBefore: sorting || filtering,
2695
+ message: DataTableMessage.ColumnVisibilityChanged({
2696
+ id: column.id,
2697
+ visible: false
2698
+ })
2699
+ }
2700
+ ] : []
2701
+ ], false, undefined, false, { filtered, sort: active }), column.resizable !== false && h.button.attr("type", "button").attr("role", "separator").attr("aria-orientation", "vertical").attr("aria-valuemin", String(min)).attr("aria-valuemax", String(max)).attr("aria-valuenow", String(width)).attr("aria-label", `${copy.resize}: ${column.headerName}`).class(tableClasses.resizeHandle).on("pointerdown", ({ x, button, pointerId }) => button === 0 ? DataTableMessage.ResizeStarted({
2702
+ id: column.id,
2703
+ x,
2704
+ pointerId
2705
+ }) : undefined, {
2706
+ capturePointer: true,
2707
+ preventDefault: true
2708
+ }).on("pointermove", ({ x, pointerId }) => model.resizing?.id === column.id ? DataTableMessage.ResizeMoved({ x, pointerId }) : undefined).on("pointerup", ({ pointerId }) => DataTableMessage.ResizeEnded({ pointerId })).on("pointercancel", ({ pointerId }) => DataTableMessage.ResizeEnded({ pointerId })).on("dblclick", DataTableMessage.ColumnResizeReset({
2709
+ id: column.id
2710
+ })).on("keydown", ({ key }) => {
2711
+ const delta = tableResizeStep(key);
2712
+ return delta ? DataTableMessage.ColumnResized({
2713
+ id: column.id,
2714
+ delta
2715
+ }) : undefined;
2716
+ }, { preventDefault: true }));
2717
+ }), rowActions && h.th.attr("scope", "col").class("w-10").attr("aria-label", copy.actions))), (list ? list.list(h.tbody) : h.tbody).children(blocked || rows.length === 0 && grouping.length === 0 ? h.tr.children(h.td.attr("colspan", String(span)).class("py-8 text-center").children(status?.error !== undefined ? h.p.attr("role", "alert").class("text-destructive").children(status.error) : h.p.attr("role", "status").children(status?.loading ? copy.loading : status?.empty ?? copy.empty))) : list ? list.items.flatMap((index) => {
2718
+ const row = rows[index];
2719
+ return row ? [
2720
+ list.item({
2721
+ element: renderRow(row, rows, ""),
2722
+ index
2723
+ })
2724
+ ] : [];
2725
+ }) : renderGroups(rows, 0, "")));
2726
+ };
2727
+ const viewport = () => h.div.class(cn("@container overflow-auto", fillHeight && "min-h-0 flex-1"));
2728
+ if (!virtual)
2729
+ return viewport().children(renderTable());
2730
+ return VirtualList(h, {
2731
+ props: {
2732
+ keys: rows.map(({ id }) => id),
2733
+ count: rows.length,
2734
+ itemSize: virtual.itemSize,
2735
+ measure: true,
2736
+ overscan: virtual.overscan,
2737
+ initialCount: virtual.initialCount
2738
+ },
2739
+ view: (list) => virtual.scroll === "page" ? h.div.children(renderTable(list)) : list.viewport(fillHeight ? viewport() : viewport().style({
2740
+ maxHeight: `${virtual.height}px`
2741
+ })).children(renderTable(list))
2742
+ });
2743
+ })(), paginationVisible ? Pagination(h, {
2744
+ props: {
2745
+ locale,
2746
+ page,
2747
+ pageSize,
2748
+ pageSizes,
2749
+ pageCount,
2750
+ totalRows,
2751
+ selectedRows: selectedCount
2752
+ },
2753
+ onEmit: {
2754
+ PageChanged: ({ page }) => DataTableMessage.PageRequested({ page }),
2755
+ PageSizeChanged: ({ pageSize }) => DataTableMessage.PageSizeRequested({ pageSize })
2756
+ }
2757
+ }) : h.div.attr("role", "status").class(tableResultsFooterClass).children(paginationMessages(locale).results(totalRows)));
2758
+ }
2759
+ });
2760
+
2761
+ // ../../src/components/audit-log-table/html.ts
2762
+ import { krakstackLocaleRead as krakstackLocaleRead3 } from "@krak-stack/registry/krakstack-provider/html";
2763
+
2764
+ // ../../src/services/events/schema.ts
2765
+ import { Effect as Effect3, Option as Option4, Schema as Schema8 } from "effect";
2766
+
2767
+ // ../../src/services/opentelemetry/schema.ts
2768
+ import { Schema as Schema7 } from "effect";
2769
+ var BrowserAnalyticsPreference = Schema7.Struct({
2770
+ version: Schema7.String,
2771
+ choice: Schema7.Literals(["accepted", "declined"]),
2772
+ revision: Schema7.String,
2773
+ issuedAt: Schema7.Finite,
2774
+ expiresAt: Schema7.Finite
2775
+ }).annotate({ identifier: "BrowserAnalyticsPreference" });
2776
+ var BrowserPrivacySignals = Schema7.Struct({
2777
+ globalPrivacyControl: Schema7.optional(Schema7.Boolean)
2778
+ }).annotate({ identifier: "BrowserPrivacySignals" });
2779
+ var BrowserWebVital = Schema7.Struct({
2780
+ name: Schema7.Literals(["LCP", "INP", "CLS", "FCP", "TTFB"]),
2781
+ id: Schema7.NonEmptyString.check(Schema7.isMaxLength(64)),
2782
+ value: Schema7.Finite.check(Schema7.isGreaterThanOrEqualTo(0)),
2783
+ delta: Schema7.Finite,
2784
+ rating: Schema7.Literals(["good", "needs-improvement", "poor"]),
2785
+ navigationType: Schema7.Literals([
2786
+ "navigate",
2787
+ "reload",
2788
+ "back-forward",
2789
+ "back-forward-cache",
2790
+ "prerender",
2791
+ "restore"
2792
+ ])
2793
+ }).annotate({ identifier: "BrowserWebVital" });
2794
+ var EventAttributeValue = Schema7.Union([
2795
+ Schema7.String,
2796
+ Schema7.Finite,
2797
+ Schema7.Boolean,
2798
+ Schema7.Array(Schema7.String),
2799
+ Schema7.Array(Schema7.Finite),
2800
+ Schema7.Array(Schema7.Boolean)
2801
+ ]);
2802
+ var EventAttributesSchema = Schema7.Record(Schema7.String, EventAttributeValue).annotate({ identifier: "EventAttributes" });
2803
+ var EventPropertiesSchema = Schema7.Record(Schema7.String, Schema7.Json).annotate({ identifier: "EventProperties" });
2804
+ var EventOptionsSchema = Schema7.Struct({
2805
+ userId: Schema7.optional(Schema7.NonEmptyString),
2806
+ anonymousId: Schema7.optional(Schema7.NonEmptyString),
2807
+ sessionId: Schema7.optional(Schema7.NonEmptyString),
2808
+ messageId: Schema7.optional(Schema7.NonEmptyString),
2809
+ timestamp: Schema7.optional(Schema7.DateTimeUtc),
2810
+ context: Schema7.optional(EventAttributesSchema)
2811
+ }).annotate({ identifier: "EventOptions" });
2812
+ var TelemetryEvent = Schema7.Struct({
2813
+ name: Schema7.NonEmptyString,
2814
+ properties: Schema7.optional(EventPropertiesSchema),
2815
+ options: Schema7.optional(EventOptionsSchema)
2816
+ }).annotate({ identifier: "TelemetryEvent" });
2817
+
2818
+ // ../../src/services/events/schema.ts
2819
+ var EventUuid = Schema8.String.check(Schema8.isUUID());
2820
+ var EventId = Schema8.NonEmptyString.check(Schema8.isMaxLength(100));
2821
+ var BrowserEventPath = Schema8.String.check(Schema8.isMaxLength(2048), Schema8.isPattern(/^\/(?!\/)[^?#]*$/));
2822
+ var EventIdentity = Schema8.Struct({
2823
+ userId: Schema8.optional(Schema8.NonEmptyString),
2824
+ organizationId: Schema8.optional(Schema8.NonEmptyString)
2825
+ }).annotate({ identifier: "EventIdentity" });
2826
+ var EventIpAddress = Schema8.String.check(Schema8.makeFilter((value) => Option4.isSome(Schema8.decodeOption(Schema8.IpAddressFromString)(value)) || "Invalid IP address")).annotate({ identifier: "EventIpAddress" });
2827
+ var EventCountry = Schema8.String.check(Schema8.isPattern(/^[A-Z]{2}$/), Schema8.makeFilter((value) => !["XX", "T1"].includes(value) || "Unknown country")).annotate({ identifier: "EventCountry" });
2828
+ var EventRegion = Schema8.String.check(Schema8.isPattern(/^[A-Z0-9]{1,3}$/)).annotate({ identifier: "EventRegion" });
2829
+ var EventCity = Schema8.NonEmptyString.check(Schema8.isMaxLength(128)).annotate({ identifier: "EventCity" });
2830
+ var EventGeolocation = Schema8.Struct({
2831
+ ip: Schema8.optional(EventIpAddress),
2832
+ country: Schema8.optional(EventCountry),
2833
+ region: Schema8.optional(EventRegion),
2834
+ city: Schema8.optional(EventCity)
2835
+ }).annotate({ identifier: "EventGeolocation" });
2836
+
2837
+ class EventGeolocationError extends Schema8.TaggedError()("EventGeolocationError", {}) {
2838
+ }
2839
+ var BrowserEventOptions = Schema8.Struct({
2840
+ messageId: Schema8.optional(EventId),
2841
+ timestamp: Schema8.optional(Schema8.DateTimeUtc),
2842
+ context: Schema8.optional(EventAttributesSchema)
2843
+ }).annotate({ identifier: "BrowserEventOptions" });
2844
+ var BrowserPage = Schema8.Struct({
2845
+ name: Schema8.optional(Schema8.NonEmptyString),
2846
+ category: Schema8.optional(Schema8.NonEmptyString),
2847
+ path: Schema8.optional(Schema8.NonEmptyString),
2848
+ properties: Schema8.optional(EventAttributesSchema),
2849
+ options: Schema8.optional(BrowserEventOptions)
2850
+ }).annotate({ identifier: "BrowserPage" });
2851
+ var AuditTarget = Schema8.Struct({
2852
+ id: Schema8.NonEmptyString.check(Schema8.isMaxLength(256)),
2853
+ name: Schema8.NonEmptyString.check(Schema8.isMaxLength(2048)),
2854
+ type: Schema8.NonEmptyString.check(Schema8.isMaxLength(128))
2855
+ }).annotate({ identifier: "AuditTarget" });
2856
+ var trackEventFields = {
2857
+ eventId: Schema8.optional(EventId),
2858
+ name: Schema8.NonEmptyString.check(Schema8.isMaxLength(128)),
2859
+ properties: Schema8.optional(EventPropertiesSchema),
2860
+ identity: Schema8.optional(EventIdentity),
2861
+ timestamp: Schema8.optional(Schema8.DateTimeUtc)
2862
+ };
2863
+ var TrackEvent = Schema8.Union([
2864
+ Schema8.Struct({
2865
+ ...trackEventFields,
2866
+ category: Schema8.optional(Schema8.Literal("analytics"))
2867
+ }),
2868
+ Schema8.Struct({
2869
+ ...trackEventFields,
2870
+ category: Schema8.Literal("audit"),
2871
+ target: AuditTarget
2872
+ })
2873
+ ]).annotate({ identifier: "TrackEvent" });
2874
+ var EventInputProperties = Schema8.Record(Schema8.String, Schema8.Unknown).annotate({ identifier: "EventInputProperties" });
2875
+ var TrackEventInput = Schema8.Union([
2876
+ Schema8.Struct({
2877
+ ...TrackEvent.members[0].fields,
2878
+ properties: Schema8.optional(EventInputProperties)
2879
+ }),
2880
+ Schema8.Struct({
2881
+ ...TrackEvent.members[1].fields,
2882
+ properties: Schema8.optional(EventInputProperties)
2883
+ })
2884
+ ]).annotate({ identifier: "TrackEventInput" });
2885
+ var EventSubscription = Schema8.Struct({
2886
+ name: Schema8.NonEmptyString.check(Schema8.isMaxLength(128)),
2887
+ events: Schema8.NonEmptyArray(trackEventFields.name)
2888
+ }).annotate({ identifier: "EventSubscription" });
2889
+
2890
+ class EventSubscriberError extends Schema8.TaggedError()("EventSubscriberError", { subscription: Schema8.String }) {
2891
+ }
2892
+ var EventActionFilter = Schema8.Struct({
2893
+ id: Schema8.Literal("eventName"),
2894
+ kind: Schema8.Literal("values"),
2895
+ values: Schema8.NonEmptyArray(trackEventFields.name)
2896
+ }).annotate({ identifier: "EventActionFilter" });
2897
+ var EventColumnFilter = ColumnFilter.check(Schema8.makeFilter((filter) => filter.id === "eventName" ? Schema8.is(EventActionFilter)(filter) : filter.id === "time" ? filter.kind === "date" : filter.id === "actor" || filter.id === "record" ? filter.kind === "text" : filter.id === "method" ? filter.kind === "values" && filter.values.every((value) => ["session", "api_key", "unknown"].includes(value)) : false)).annotate({ identifier: "EventColumnFilter" });
2898
+ var EventColumnFilters = ColumnFilters.check(Schema8.makeFilter((filters) => filters.every(Schema8.is(EventColumnFilter)))).annotate({ identifier: "EventColumnFilters" });
2899
+ var EventQuery = Schema8.Struct({
2900
+ ...Query.fields,
2901
+ filters: Schema8.optional(EventColumnFilters),
2902
+ eventName: Schema8.optional(trackEventFields.name)
2903
+ }).annotate({ identifier: "EventQuery" });
2904
+ var EventQueryStandard = Schema8.toStandardSchemaV1(EventQuery);
2905
+ var ListEvents = Schema8.Struct({
2906
+ organizationId: Schema8.NonEmptyString,
2907
+ category: Schema8.Literals(["audit", "analytics"]),
2908
+ ...EventQuery.fields
2909
+ }).annotate({ identifier: "ListEvents" });
2910
+ var AuditSortId = Schema8.Literals([
2911
+ "time",
2912
+ "eventName",
2913
+ "recordType",
2914
+ "record",
2915
+ "actorType",
2916
+ "actorId"
2917
+ ]).annotate({ identifier: "AuditSortId" });
2918
+ var AuditCount = Schema8.Struct({ total: Schema8.Int }).annotate({
2919
+ identifier: "AuditCount"
2920
+ });
2921
+ var AuditAttribution = Schema8.Struct({
2922
+ "app.actor.type": Schema8.NonEmptyString,
2923
+ "app.actor.id": Schema8.NonEmptyString
2924
+ }).annotate({ identifier: "AuditAttribution" });
2925
+ var RequestActorAttribution = Schema8.Struct({
2926
+ ...AuditAttribution.fields,
2927
+ "app.auth.method": Schema8.optional(Schema8.NonEmptyString),
2928
+ "app.auth.credential.id": Schema8.optional(Schema8.NonEmptyString),
2929
+ "app.auth.impersonator.id": Schema8.optional(Schema8.NonEmptyString),
2930
+ "user.roles": Schema8.optional(Schema8.Array(Schema8.String))
2931
+ }).annotate({ identifier: "RequestActorAttribution" });
2932
+
2933
+ class EventsPersistenceError extends Schema8.TaggedError()("EventsPersistenceError", { operation: Schema8.String }) {
2934
+ }
2935
+
2936
+ class EventConflictError extends Schema8.TaggedError()("EventConflictError", { eventId: EventId }) {
2937
+ }
2938
+ var EventSource = Schema8.Literals(["browser", "server"]).annotate({
2939
+ identifier: "EventSource"
2940
+ });
2941
+ var ExistingEventRequest = Schema8.Struct({
2942
+ eventId: EventId,
2943
+ source: EventSource
2944
+ }).annotate({ identifier: "ExistingEventRequest" });
2945
+ var StoredEventRequest = Schema8.Struct({
2946
+ source: EventSource,
2947
+ event_id: EventId,
2948
+ event_name: Schema8.NonEmptyString,
2949
+ event_type: Schema8.Literals(["page", "track"]),
2950
+ occurred_at: Schema8.Finite,
2951
+ received_at: Schema8.Finite,
2952
+ organization_id: Schema8.NullOr(Schema8.NonEmptyString),
2953
+ user_id: Schema8.NullOr(Schema8.NonEmptyString),
2954
+ session_id: Schema8.NullOr(Schema8.NonEmptyString),
2955
+ anonymous_id: Schema8.NullOr(Schema8.NonEmptyString),
2956
+ payload_json: Schema8.String
2957
+ }).annotate({ identifier: "StoredEventRequest" });
2958
+ var StoredEventId = Schema8.Struct({
2959
+ event_id: EventId
2960
+ }).annotate({ identifier: "StoredEventId" });
2961
+ var PrimitiveValue = Schema8.Union([
2962
+ Schema8.Struct({ stringValue: Schema8.String.check(Schema8.isMaxLength(2048)) }),
2963
+ Schema8.Struct({
2964
+ intValue: Schema8.Union([
2965
+ Schema8.String.check(Schema8.isPattern(/^-?\d{1,20}$/)),
2966
+ Schema8.Int
2967
+ ])
2968
+ }),
2969
+ Schema8.Struct({ doubleValue: Schema8.Finite }),
2970
+ Schema8.Struct({ boolValue: Schema8.Boolean })
2971
+ ]);
2972
+ var AttributeValue = Schema8.Union([
2973
+ PrimitiveValue,
2974
+ Schema8.Struct({
2975
+ arrayValue: Schema8.Struct({
2976
+ values: Schema8.Array(PrimitiveValue).check(Schema8.isMaxLength(32))
2977
+ })
2978
+ })
2979
+ ]);
2980
+ var EventAttribute = Schema8.Struct({
2981
+ key: Schema8.NonEmptyString.check(Schema8.isMaxLength(128)),
2982
+ value: Schema8.StructWithRest(Schema8.Struct({ stringValue: Schema8.optional(Schema8.String) }), [Schema8.Record(Schema8.String, Schema8.Json)])
2983
+ }).annotate({ identifier: "EventAttribute" });
2984
+ var EventLogRecord = Schema8.Struct({
2985
+ eventName: Schema8.NonEmptyString.check(Schema8.isMaxLength(128), Schema8.isPattern(/^[^\r\n]+$/)),
2986
+ timeUnixNano: Schema8.String.check(Schema8.isPattern(/^\d{1,20}$/)),
2987
+ observedTimeUnixNano: Schema8.optional(Schema8.String.check(Schema8.isPattern(/^\d{1,20}$/))),
2988
+ severityNumber: Schema8.optional(Schema8.Int),
2989
+ traceId: Schema8.optional(Schema8.String.check(Schema8.isPattern(/^[a-f0-9]{32}$/))),
2990
+ spanId: Schema8.optional(Schema8.String.check(Schema8.isPattern(/^[a-f0-9]{16}$/))),
2991
+ attributes: Schema8.Array(EventAttribute).check(Schema8.isMaxLength(64), Schema8.makeFilter((values) => new Set(values.map(({ key }) => key)).size === values.length || "Duplicate attribute keys"))
2992
+ }).annotate({ identifier: "EventLogRecord" });
2993
+ var BrowserEventLogRecord = Schema8.Struct({
2994
+ ...EventLogRecord.fields,
2995
+ attributes: Schema8.Array(Schema8.Struct({
2996
+ key: EventAttribute.fields.key,
2997
+ value: AttributeValue
2998
+ })).check(Schema8.isMaxLength(64), Schema8.makeFilter((values) => new Set(values.map(({ key }) => key)).size === values.length || "Duplicate attribute keys"))
2999
+ }).annotate({ identifier: "BrowserEventLogRecord" });
3000
+ var extensions = Schema8.Record(Schema8.String, Schema8.Unknown);
3001
+ var OtlpLogs = Schema8.StructWithRest(Schema8.Struct({
3002
+ resourceLogs: Schema8.Array(Schema8.StructWithRest(Schema8.Struct({
3003
+ scopeLogs: Schema8.Array(Schema8.StructWithRest(Schema8.Struct({
3004
+ scope: Schema8.optional(Schema8.StructWithRest(Schema8.Struct({ name: Schema8.optional(Schema8.String) }), [extensions])),
3005
+ logRecords: Schema8.Array(Schema8.Unknown).pipe(Schema8.withDecodingDefaultKey(Effect3.succeed([])))
3006
+ }), [extensions])).pipe(Schema8.withDecodingDefaultKey(Effect3.succeed([])))
3007
+ }), [extensions])).pipe(Schema8.withDecodingDefaultKey(Effect3.succeed([])))
3008
+ }), [extensions]).annotate({ identifier: "EventsOtlpLogs" });
3009
+ var StoredEventPayload = Schema8.Struct({
3010
+ payload_json: Schema8.Union([OtlpLogs, Schema8.fromJsonString(OtlpLogs)])
3011
+ }).annotate({ identifier: "StoredEventPayload" });
3012
+ var VisitorEventsRequest = Schema8.Struct({
3013
+ visitorId: Schema8.NonEmptyString
3014
+ }).annotate({ identifier: "VisitorEventsRequest" });
3015
+ var VisitorEventSession = Schema8.Struct({
3016
+ event_id: EventId,
3017
+ session_id: Schema8.NullOr(Schema8.NonEmptyString),
3018
+ received_at: Schema8.Finite
3019
+ }).annotate({ identifier: "VisitorEventSession" });
3020
+
3021
+ // ../../src/components/audit-log-table/classes.ts
3022
+ var auditTableLayout = "flex min-h-0 flex-1 flex-col";
3023
+
3024
+ // ../../src/services/events/record.ts
3025
+ import { Option as Option5, Schema as Schema9 } from "effect";
3026
+ var TextValue = Schema9.Struct({ stringValue: Schema9.String }).annotate({
3027
+ identifier: "EventTextValue"
3028
+ });
3029
+ var TextArrayValue = Schema9.Struct({
3030
+ arrayValue: Schema9.Struct({ values: Schema9.Array(TextValue) })
3031
+ }).annotate({ identifier: "EventTextArrayValue" });
3032
+ var eventTextAttribute = (record, key) => Schema9.decodeUnknownOption(TextValue)(record.attributes.find((attribute) => attribute.key === key)?.value).pipe(Option5.map((value) => value.stringValue), Option5.getOrNull);
3033
+
3034
+ // ../../src/components/audit-log-table/index.ts
3035
+ var defaultMessages2 = {
3036
+ en: {
3037
+ title: "Activity history",
3038
+ event: "Action",
3039
+ allEvents: "All actions",
3040
+ time: "Time",
3041
+ action: "Action",
3042
+ target: "Target",
3043
+ actor: "Actor",
3044
+ method: "Method",
3045
+ actorMember: "Member",
3046
+ impersonatedBy: "Impersonated by",
3047
+ actorOrganization: "Organization",
3048
+ methodApiKey: "API Key",
3049
+ methodSession: "User session",
3050
+ methodUnknown: "Unknown"
3051
+ },
3052
+ fr: {
3053
+ title: "Historique d’activité",
3054
+ event: "Action",
3055
+ allEvents: "Toutes les actions",
3056
+ time: "Date",
3057
+ action: "Action",
3058
+ target: "Cible",
3059
+ actor: "Acteur",
3060
+ method: "Méthode",
3061
+ actorMember: "Membre",
3062
+ impersonatedBy: "Identité empruntée par",
3063
+ actorOrganization: "Organisation",
3064
+ methodApiKey: "Clé API",
3065
+ methodSession: "Session utilisateur",
3066
+ methodUnknown: "Inconnue"
3067
+ }
3068
+ };
3069
+ var auditLogMessages = (locale, messages) => {
3070
+ const base = locale.split("-")[0];
3071
+ return {
3072
+ ...base === "fr" ? defaultMessages2.fr : defaultMessages2.en,
3073
+ ...messages?.[base],
3074
+ ...messages?.[locale]
3075
+ };
3076
+ };
3077
+ var auditTableState = (state) => state?.eventName && !state.filters?.some(({ id }) => id === "eventName") ? {
3078
+ ...state,
3079
+ filters: [
3080
+ ...state.filters ?? [],
3081
+ { id: "eventName", kind: "values", values: [state.eventName] }
3082
+ ]
3083
+ } : state;
3084
+ var auditRowId = (entry) => eventTextAttribute(entry, "log.record.uid") ?? `${entry.timeUnixNano}:${entry.eventName}`;
3085
+ var auditRowTime = (entry) => Number(BigInt(entry.timeUnixNano) / 1000000n);
3086
+ var auditActionLabel = (entry, events) => events.find(({ value }) => value === entry.eventName)?.label ?? entry.eventName;
3087
+ var auditActor = (entry, labels) => {
3088
+ const type = eventTextAttribute(entry, "app.actor.type");
3089
+ const userId = eventTextAttribute(entry, "user.id");
3090
+ const id = eventTextAttribute(entry, "app.actor.id") ?? userId;
3091
+ if (type === "organization")
3092
+ return { label: labels.actorOrganization, description: id ?? undefined };
3093
+ if (type === "user" || userId !== null) {
3094
+ const name = eventTextAttribute(entry, "user.full_name") || eventTextAttribute(entry, "user.name");
3095
+ const email = eventTextAttribute(entry, "user.email");
3096
+ return {
3097
+ label: name || email || labels.actorMember,
3098
+ description: (name ? email || id : id) ?? undefined
3099
+ };
3100
+ }
3101
+ return { label: type ?? labels.actor, description: id ?? undefined };
3102
+ };
3103
+ var auditTarget = (entry, labels) => {
3104
+ const id = eventTextAttribute(entry, "app.audit.target.id");
3105
+ const name = eventTextAttribute(entry, "app.audit.target.name");
3106
+ const type = eventTextAttribute(entry, "app.audit.target.type");
3107
+ return id === null ? null : {
3108
+ label: name && name !== id ? name : type || labels.target,
3109
+ description: name && name !== id && type ? `${type} · ${id}` : id
3110
+ };
3111
+ };
3112
+ var auditImpersonation = (entry, labels) => {
3113
+ const id = eventTextAttribute(entry, "app.auth.impersonator.id");
3114
+ return id === null ? undefined : `${labels.impersonatedBy}: ${id}`;
3115
+ };
3116
+ var auditMethod = (entry) => {
3117
+ const method = eventTextAttribute(entry, "app.auth.method");
3118
+ return method === "session" || method === "api_key" ? method : "unknown";
3119
+ };
3120
+ var auditMethods = (labels) => ({
3121
+ session: labels.methodSession,
3122
+ api_key: labels.methodApiKey,
3123
+ unknown: labels.methodUnknown
3124
+ });
3125
+
3126
+ // ../../src/components/audit-log-table/schema.ts
3127
+ import { Schema as Schema10 } from "effect";
3128
+ var AuditLogMessagesSchema = Schema10.Struct({
3129
+ title: Schema10.String,
3130
+ event: Schema10.String,
3131
+ allEvents: Schema10.String,
3132
+ time: Schema10.String,
3133
+ action: Schema10.String,
3134
+ target: Schema10.String,
3135
+ actor: Schema10.String,
3136
+ method: Schema10.String,
3137
+ actorMember: Schema10.String,
3138
+ impersonatedBy: Schema10.String,
3139
+ actorOrganization: Schema10.String,
3140
+ methodApiKey: Schema10.String,
3141
+ methodSession: Schema10.String,
3142
+ methodUnknown: Schema10.String
3143
+ }).annotate({ identifier: "AuditLogMessages" });
3144
+ var AuditLogTablePropsSchema = Schema10.Struct({
3145
+ entries: Schema10.Array(EventLogRecord),
3146
+ rowCount: Schema10.Int.check(Schema10.isGreaterThanOrEqualTo(0)),
3147
+ events: Schema10.optionalKey(Schema10.Array(Schema10.Struct({ value: Schema10.String, label: Schema10.String }))),
3148
+ state: Schema10.optionalKey(EventQuery),
3149
+ timeZone: Schema10.optionalKey(Schema10.String),
3150
+ locale: Schema10.optionalKey(Schema10.String),
3151
+ messages: Schema10.optionalKey(Schema10.Record(Schema10.String, AuditLogMessagesSchema.mapFields((fields) => ({
3152
+ title: Schema10.optional(fields.title),
3153
+ event: Schema10.optional(fields.event),
3154
+ allEvents: Schema10.optional(fields.allEvents),
3155
+ time: Schema10.optional(fields.time),
3156
+ action: Schema10.optional(fields.action),
3157
+ target: Schema10.optional(fields.target),
3158
+ actor: Schema10.optional(fields.actor),
3159
+ method: Schema10.optional(fields.method),
3160
+ actorMember: Schema10.optional(fields.actorMember),
3161
+ impersonatedBy: Schema10.optional(fields.impersonatedBy),
3162
+ actorOrganization: Schema10.optional(fields.actorOrganization),
3163
+ methodApiKey: Schema10.optional(fields.methodApiKey),
3164
+ methodSession: Schema10.optional(fields.methodSession),
3165
+ methodUnknown: Schema10.optional(fields.methodUnknown)
3166
+ })))),
3167
+ loading: Schema10.optionalKey(Schema10.Boolean),
3168
+ error: Schema10.optionalKey(Schema10.String),
3169
+ empty: Schema10.optionalKey(Schema10.String)
3170
+ }).annotate({ identifier: "AuditLogTableProps" });
3171
+
3172
+ // ../../src/components/audit-log-table/html.ts
3173
+ var StateChanged = UiSchema4.TaggedEnum({
3174
+ StateChanged: { state: EventQuery }
3175
+ });
3176
+ var options = {
3177
+ name: "AuditLogTable",
3178
+ props: AuditLogTablePropsSchema,
3179
+ model: Schema11.Null,
3180
+ message: StateChanged,
3181
+ events: StateChanged,
3182
+ restore: false
3183
+ };
3184
+ var update3 = Component3.define(options).update({
3185
+ StateChanged: ($, { state: { eventName: _legacy, ...state } }) => $.emit(StateChanged.StateChanged({ state }))
3186
+ });
3187
+ var AuditLogTable = Html3.component({
3188
+ ...options,
3189
+ reads: { locale: krakstackLocaleRead3 }
3190
+ }).make({
3191
+ init: () => null,
3192
+ update: update3,
3193
+ view: (h) => {
3194
+ const {
3195
+ entries,
3196
+ events = [],
3197
+ rowCount,
3198
+ timeZone = "America/New_York",
3199
+ state,
3200
+ loading,
3201
+ empty,
3202
+ error
3203
+ } = h.props;
3204
+ const locale = h.props.locale ?? h.reads.locale?.locale ?? "en";
3205
+ const labels = auditLogMessages(locale, h.props.messages);
3206
+ const methods = auditMethods(labels);
3207
+ const tableState = auditTableState(state);
3208
+ const actionOptions = new Map(events.map(({ value, label }) => [value, label]));
3209
+ const actionFilter = tableState?.filters?.find(({ id }) => id === "eventName");
3210
+ if (actionFilter?.kind === "values") {
3211
+ for (const value of actionFilter.values) {
3212
+ if (!actionOptions.has(value))
3213
+ actionOptions.set(value, value);
3214
+ }
3215
+ }
3216
+ const columns = [
3217
+ {
3218
+ id: "time",
3219
+ headerName: labels.time,
3220
+ type: "dateTime",
3221
+ typeOptions: { timeZone }
3222
+ },
3223
+ {
3224
+ id: "eventName",
3225
+ headerName: labels.action,
3226
+ type: "list",
3227
+ filterOptions: Array.from(actionOptions, ([value, label]) => ({
3228
+ value,
3229
+ label
3230
+ })),
3231
+ filterable: actionOptions.size > 0
3232
+ },
3233
+ { id: "record", headerName: labels.target, type: "reference" },
3234
+ {
3235
+ id: "actor",
3236
+ headerName: labels.actor,
3237
+ type: "reference",
3238
+ sortable: false
3239
+ },
3240
+ {
3241
+ id: "method",
3242
+ headerName: labels.method,
3243
+ type: "list",
3244
+ sortable: false,
3245
+ filterOptions: Object.entries(methods).map(([value, label]) => ({
3246
+ value,
3247
+ label
3248
+ }))
3249
+ }
3250
+ ];
3251
+ return h.section.class(auditTableLayout).attr("aria-label", labels.title).children(DataTable(h, {
3252
+ props: {
3253
+ label: labels.title,
3254
+ locale,
3255
+ columnDefs: columns,
3256
+ state: tableState,
3257
+ status: { loading, error, empty },
3258
+ features: {
3259
+ filtering: state !== undefined,
3260
+ pagination: { mode: "server", rowCount },
3261
+ virtualization: { scroll: "internal" }
3262
+ },
3263
+ rowData: entries.map((entry) => {
3264
+ const actor = auditActor(entry, labels);
3265
+ const impersonation = auditImpersonation(entry, labels);
3266
+ const description = [actor.description, impersonation].filter(Boolean).join(" · ");
3267
+ const method = auditMethod(entry);
3268
+ const action = auditActionLabel(entry, events);
3269
+ return {
3270
+ id: auditRowId(entry),
3271
+ label: action,
3272
+ cells: {
3273
+ time: auditRowTime(entry),
3274
+ eventName: [
3275
+ {
3276
+ value: entry.eventName,
3277
+ label: action
3278
+ }
3279
+ ],
3280
+ record: auditTarget(entry, labels),
3281
+ actor: description ? { label: actor.label, description } : { label: actor.label },
3282
+ method: [{ value: method, label: methods[method] }]
3283
+ }
3284
+ };
3285
+ })
3286
+ },
3287
+ onEmit: (event) => event._tag === "StateChanged" ? StateChanged.StateChanged({ state: event.state }) : undefined
3288
+ }));
3289
+ }
3290
+ });
3291
+ export {
3292
+ EventQuery as AuditLogQuerySchema,
3293
+ AuditLogTable
3294
+ };