@nubitio/devextreme 0.6.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,1104 @@
1
+ import { forwardRef, useCallback, useEffect, useId, useImperativeHandle, useMemo, useRef, useState } from "react";
2
+ import { BETWEEN_VALUE_SEPARATOR, CrudViewProvider, FORM_ERRORS_EVENT, FORM_EVENTS, FieldType, FileUploadField, HydraAdapter, buildEmptyRow, canEditFieldInline, getFieldTypeModule, getIdField, loadDetailRows, mapApiViolations, normalizeFormData, resolveInlineEditToolbar, serializeFormFields, useFormState, useFormSubmit, useFormValidation, useResourceStoreFactory } from "@nubitio/crud";
3
+ import CustomStore from "devextreme/data/custom_store";
4
+ import DataGrid, { Column, Editing, FilterRow, HeaderFilter, Item, LoadPanel, MasterDetail, Pager, Paging, RemoteOperations, Selection, Sorting, Toolbar } from "devextreme-react/data-grid";
5
+ import { useCoreHttpClient, useCoreTranslation, useEvents } from "@nubitio/core";
6
+ import { ConfirmDialog } from "@nubitio/ui";
7
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
8
+ import Form, { SimpleItem } from "devextreme-react/form";
9
+ //#region packages/devextreme/convertDxFilterToNubit.ts
10
+ function isDxFilterTriplet(value) {
11
+ return Array.isArray(value) && value.length === 3 && typeof value[0] === "string" && typeof value[1] === "string";
12
+ }
13
+ function isLogicalOperator(value) {
14
+ return value === "and" || value === "or" || value === "!";
15
+ }
16
+ /**
17
+ * Flattens a DevExtreme filter expression into leaf triplets.
18
+ * Compound `and` groups are fully expanded. `or` groups are also flattened
19
+ * (API Platform treats multiple filter[] params as conjunction).
20
+ */
21
+ function flattenDxFilter(filter) {
22
+ if (filter == null || filter === "") return [];
23
+ if (isDxFilterTriplet(filter)) return [filter];
24
+ if (!Array.isArray(filter)) return [];
25
+ if (filter.length === 3 && typeof filter[0] === "string" && !isLogicalOperator(filter[1])) return [filter];
26
+ const leaves = [];
27
+ for (const item of filter) {
28
+ if (isLogicalOperator(item)) continue;
29
+ leaves.push(...flattenDxFilter(item));
30
+ }
31
+ return leaves;
32
+ }
33
+ function normalizeFilterValue(field, operator, value) {
34
+ if (operator === "between" && Array.isArray(value)) {
35
+ const [start = "", end = ""] = value.map((part) => String(part ?? ""));
36
+ return `${start}${BETWEEN_VALUE_SEPARATOR}${end}`;
37
+ }
38
+ if (field?.type === FieldType.CHECKBOX || field?.type === FieldType.SWITCH) {
39
+ if (value === true || value === "true" || value === 1) return "true";
40
+ if (value === false || value === "false" || value === 0) return "false";
41
+ }
42
+ if (value instanceof Date) {
43
+ if (field?.type === FieldType.DATETIME) return value.toISOString();
44
+ return value.toISOString().slice(0, 10);
45
+ }
46
+ return String(value ?? "");
47
+ }
48
+ const DX_TO_NUBIT_OPERATOR = {
49
+ "=": "=",
50
+ "<>": "<>",
51
+ ">": ">",
52
+ ">=": ">=",
53
+ "<": "<",
54
+ "<=": "<=",
55
+ contains: "contains",
56
+ notcontains: "notcontains",
57
+ startswith: "startswith",
58
+ endswith: "endswith",
59
+ between: "between"
60
+ };
61
+ function mapDxOperator(operator) {
62
+ return DX_TO_NUBIT_OPERATOR[operator] ?? operator;
63
+ }
64
+ /**
65
+ * Converts a DevExtreme filter expression into Nubit/Hydra filter tuples,
66
+ * applying per-field `buildFilterTerms` expansion (e.g. date `between`).
67
+ */
68
+ function convertDxFilterToNubit(filter, fields) {
69
+ return flattenDxFilter(filter).flatMap(([fieldName, operator, rawValue]) => {
70
+ const field = fields.find((candidate) => candidate.name === fieldName);
71
+ const mappedOperator = mapDxOperator(operator);
72
+ const value = normalizeFilterValue(field, mappedOperator, rawValue);
73
+ if (value.trim() === "" && mappedOperator !== "=") return [];
74
+ if (!field) return [[
75
+ fieldName,
76
+ mappedOperator,
77
+ value
78
+ ]];
79
+ return getFieldTypeModule(field.type).buildFilterTerms(field, mappedOperator, value);
80
+ });
81
+ }
82
+ function mergeGridFilters(routingFilters, dxFilter, fields) {
83
+ const routingTerms = routingFilters?.flatMap((rule) => {
84
+ const field = fields.find((candidate) => candidate.name === rule.field);
85
+ const value = String(rule.value ?? "");
86
+ if (!field) return [[
87
+ rule.field,
88
+ rule.operator,
89
+ value
90
+ ]];
91
+ return getFieldTypeModule(field.type).buildFilterTerms(field, rule.operator, value);
92
+ }) ?? [];
93
+ const dxTerms = convertDxFilterToNubit(dxFilter, fields);
94
+ return [...routingTerms, ...dxTerms];
95
+ }
96
+ //#endregion
97
+ //#region packages/devextreme/mapFieldsToDxColumns.ts
98
+ function resolveDataType(field) {
99
+ switch (field.type) {
100
+ case FieldType.NUMBER:
101
+ case FieldType.CURRENCY: return "number";
102
+ case FieldType.DATE: return "date";
103
+ case FieldType.DATETIME: return "datetime";
104
+ case FieldType.CHECKBOX:
105
+ case FieldType.SWITCH: return "boolean";
106
+ default: return field.valueType === "number" ? "number" : field.valueType === "date" ? "date" : field.valueType === "datetime" ? "datetime" : field.valueType === "boolean" ? "boolean" : "string";
107
+ }
108
+ }
109
+ function mapFieldsToDxColumns(fields, visibleColumns) {
110
+ return fields.filter((field) => field.visible && !field.hidden).filter((field) => visibleColumns == null || visibleColumns.includes(field.name)).sort((left, right) => (left.order ?? Number.MAX_SAFE_INTEGER) - (right.order ?? Number.MAX_SAFE_INTEGER)).map((field) => ({
111
+ dataField: field.name,
112
+ caption: field.label || field.name,
113
+ dataType: resolveDataType(field),
114
+ allowSorting: field.sortable,
115
+ allowFiltering: field.filterable,
116
+ width: field.width,
117
+ format: field.format || void 0
118
+ }));
119
+ }
120
+ //#endregion
121
+ //#region packages/devextreme/DevExtremeDetailGridSection.tsx
122
+ /**
123
+ * Expanded-row detail grid for DevExtreme DataGrid master-detail.
124
+ * Loads related rows through ResourceStore and renders a read-only nested grid.
125
+ */
126
+ function DevExtremeDetailGridSection({ fields, url }) {
127
+ const { t } = useCoreTranslation();
128
+ const resourceStoreFactory = useResourceStoreFactory();
129
+ const [rows, setRows] = useState([]);
130
+ const [loading, setLoading] = useState(true);
131
+ const idField = useMemo(() => getIdField(fields), [fields]);
132
+ const columns = useMemo(() => mapFieldsToDxColumns(fields), [fields]);
133
+ useEffect(() => {
134
+ const source = resourceStoreFactory({
135
+ url,
136
+ idField
137
+ });
138
+ setLoading(true);
139
+ source.load({}).then((result) => setRows(result.data)).finally(() => setLoading(false));
140
+ }, [
141
+ fields,
142
+ idField,
143
+ resourceStoreFactory,
144
+ url
145
+ ]);
146
+ if (loading) return /* @__PURE__ */ jsx("div", {
147
+ className: "nb-dx-detail-grid__loading",
148
+ children: t("grid.loading")
149
+ });
150
+ if (rows.length === 0) return /* @__PURE__ */ jsx("div", {
151
+ className: "nb-dx-detail-grid__empty",
152
+ children: t("grid.noRecords")
153
+ });
154
+ return /* @__PURE__ */ jsx("div", {
155
+ className: "nb-dx-detail-grid",
156
+ children: /* @__PURE__ */ jsxs(DataGrid, {
157
+ dataSource: rows,
158
+ keyExpr: idField,
159
+ showBorders: true,
160
+ columnAutoWidth: true,
161
+ height: Math.min(360, 56 + rows.length * 36),
162
+ children: [/* @__PURE__ */ jsx(LoadPanel, { enabled: false }), columns.map((column) => /* @__PURE__ */ jsx(Column, {
163
+ ...column,
164
+ allowEditing: false
165
+ }, column.dataField))]
166
+ })
167
+ });
168
+ }
169
+ //#endregion
170
+ //#region packages/devextreme/DevExtremeDataGridView.tsx
171
+ function resolveDxEditMode(editMode) {
172
+ if (!editMode || editMode === "popup") return null;
173
+ return editMode;
174
+ }
175
+ const DX_PAGE_SIZE_OPTIONS = [
176
+ 10,
177
+ 20,
178
+ 50
179
+ ];
180
+ function resolveDxRemoteOperations(options) {
181
+ if (options.data) return false;
182
+ return {
183
+ filtering: options.filterRow ?? true,
184
+ grouping: false,
185
+ summary: false,
186
+ sorting: true,
187
+ paging: options.paging ?? true
188
+ };
189
+ }
190
+ function isHeaderFilterLookup(loadOptions) {
191
+ return Array.isArray(loadOptions.group) || loadOptions.requireGroupCount === true;
192
+ }
193
+ const DevExtremeDataGridView = forwardRef((options, ref) => {
194
+ const { t } = useCoreTranslation();
195
+ const httpClient = useCoreHttpClient();
196
+ const resourceStoreFactory = useResourceStoreFactory();
197
+ const gridRef = useRef(null);
198
+ const [activeFilter, setActiveFilter] = useState(null);
199
+ const [confirmRow, setConfirmRow] = useState(null);
200
+ const selectedRowsRef = useRef([]);
201
+ const selectedKeysRef = useRef([]);
202
+ const hasPendingEditsRef = useRef(false);
203
+ const idField = useMemo(() => getIdField(options.fields), [options.fields]);
204
+ const adapter = options.adapter ?? HydraAdapter;
205
+ const dxEditMode = resolveDxEditMode(options.editMode);
206
+ const inlineEditing = dxEditMode != null && (options.allowEdit ?? true);
207
+ const inlineToolbar = useMemo(() => inlineEditing && dxEditMode !== "row" ? resolveInlineEditToolbar(dxEditMode, options.inlineEditToolbar) : null, [
208
+ dxEditMode,
209
+ inlineEditing,
210
+ options.inlineEditToolbar
211
+ ]);
212
+ const columns = useMemo(() => mapFieldsToDxColumns(options.fields, options.visibleColumns).map((column) => ({
213
+ ...column,
214
+ allowEditing: inlineEditing && options.fields.some((field) => field.name === column.dataField && canEditFieldInline(field))
215
+ })), [
216
+ inlineEditing,
217
+ options.fields,
218
+ options.visibleColumns
219
+ ]);
220
+ const url = options.url;
221
+ const httpClientRef = useRef(httpClient);
222
+ httpClientRef.current = httpClient;
223
+ const source = useMemo(() => resourceStoreFactory({
224
+ url,
225
+ idField,
226
+ byKeyUrl: null
227
+ }), [
228
+ idField,
229
+ resourceStoreFactory,
230
+ url
231
+ ]);
232
+ const optionsRef = useRef(options);
233
+ optionsRef.current = options;
234
+ const fieldsRef = useRef(options.fields);
235
+ fieldsRef.current = options.fields;
236
+ const routingFilterRef = useRef(options.filter);
237
+ routingFilterRef.current = options.filter;
238
+ const activeFilterRef = useRef(activeFilter);
239
+ activeFilterRef.current = activeFilter;
240
+ const dataSource = useMemo(() => {
241
+ if (optionsRef.current.data) return optionsRef.current.data;
242
+ return new CustomStore({
243
+ key: idField,
244
+ load: async (loadOptions) => {
245
+ const current = optionsRef.current;
246
+ if (current.manualLoad) return {
247
+ data: [],
248
+ totalCount: 0
249
+ };
250
+ const request = {
251
+ skip: loadOptions.skip,
252
+ take: loadOptions.take
253
+ };
254
+ if (Array.isArray(loadOptions.sort) && loadOptions.sort.length > 0) request.sort = loadOptions.sort.map((rule) => {
255
+ const typedRule = rule;
256
+ return {
257
+ selector: typedRule.selector,
258
+ desc: !!typedRule.desc
259
+ };
260
+ });
261
+ else if (current.sort?.length) request.sort = current.sort;
262
+ const mergedFilter = mergeGridFilters(routingFilterRef.current, loadOptions.filter ?? activeFilterRef.current, fieldsRef.current);
263
+ if (mergedFilter.length > 0) request.filter = mergedFilter;
264
+ if (loadOptions.searchValue && loadOptions.searchExpr) {
265
+ request.searchExpr = loadOptions.searchExpr;
266
+ request.searchValue = loadOptions.searchValue;
267
+ }
268
+ if (isHeaderFilterLookup(loadOptions)) {
269
+ request.skip = 0;
270
+ request.take = 1e3;
271
+ }
272
+ const result = await source.load(request);
273
+ current.onContentReady?.();
274
+ return {
275
+ data: result.data,
276
+ totalCount: result.totalCount
277
+ };
278
+ },
279
+ update: async (key, values) => {
280
+ const current = optionsRef.current;
281
+ const currentAdapter = current.adapter ?? adapter;
282
+ const payload = serializeFormFields(values, current.fields.filter((field) => canEditFieldInline(field)), {
283
+ uploadedFiles: [],
284
+ getFieldValue: (name) => values[name],
285
+ adapter: currentAdapter
286
+ });
287
+ await httpClientRef.current.patch(currentAdapter.buildItemUrl(current.url, key), payload);
288
+ current.onContentReady?.();
289
+ }
290
+ });
291
+ }, [
292
+ adapter,
293
+ idField,
294
+ source
295
+ ]);
296
+ const refresh = useCallback(() => {
297
+ gridRef.current?.instance?.()?.refresh?.();
298
+ }, []);
299
+ useImperativeHandle(ref, () => ({
300
+ showLoading: () => gridRef.current?.instance?.()?.beginCustomLoading?.(t("grid.loading")),
301
+ hideLoading: () => gridRef.current?.instance?.()?.endCustomLoading?.(),
302
+ refresh,
303
+ reset: () => {
304
+ setActiveFilter(null);
305
+ gridRef.current?.instance?.()?.filter?.(null);
306
+ refresh();
307
+ },
308
+ loadData: async () => {
309
+ return (await source.load({})).data;
310
+ },
311
+ getSelectedRowKey: () => {
312
+ const key = selectedKeysRef.current[0];
313
+ return typeof key === "string" || typeof key === "number" ? key : void 0;
314
+ },
315
+ getSelectedRow: () => selectedRowsRef.current[0],
316
+ getSelectedRowKeys: () => selectedKeysRef.current,
317
+ getSelectedRows: () => selectedRowsRef.current,
318
+ getFilter: () => mergeGridFilters(routingFilterRef.current, activeFilter, fieldsRef.current),
319
+ filter: (filterRule) => {
320
+ const nextFilter = filterRule ? [
321
+ filterRule.field,
322
+ filterRule.operator,
323
+ filterRule.value
324
+ ] : null;
325
+ setActiveFilter(nextFilter);
326
+ gridRef.current?.instance?.()?.filter?.(nextFilter);
327
+ refresh();
328
+ },
329
+ hasEditData: () => hasPendingEditsRef.current || !!gridRef.current?.instance?.()?.hasEditData?.(),
330
+ saveChanges: async () => {
331
+ if (options.onBatchSave) {
332
+ const instance = gridRef.current?.instance?.();
333
+ const selected = instance?.getSelectedRowsData?.() ?? selectedRowsRef.current;
334
+ await options.onBatchSave(selected);
335
+ instance?.cancelEditData?.();
336
+ hasPendingEditsRef.current = false;
337
+ refresh();
338
+ return true;
339
+ }
340
+ await gridRef.current?.instance?.()?.saveEditData?.();
341
+ hasPendingEditsRef.current = false;
342
+ refresh();
343
+ return true;
344
+ }
345
+ }), [
346
+ options.onBatchSave,
347
+ refresh,
348
+ source
349
+ ]);
350
+ const handleSelectionChanged = useCallback((event) => {
351
+ const rows = event.selectedRowsData ?? [];
352
+ selectedRowsRef.current = rows;
353
+ selectedKeysRef.current = event.selectedRowKeys ?? rows.map((row) => row[idField]);
354
+ options.onSelectionChanged?.({ selectedRowsData: rows });
355
+ }, [idField, options]);
356
+ const handleRowDblClick = useCallback((event) => {
357
+ if (inlineEditing) return;
358
+ if (!event.data) return;
359
+ if (options.allowView) {
360
+ options.onView?.(event.data);
361
+ return;
362
+ }
363
+ if (options.allowEdit && options.canEditRow?.(event.data) !== false) options.onEdit?.(event.data);
364
+ }, [inlineEditing, options]);
365
+ const handleToolbarPreparing = useCallback((event) => {
366
+ const items = event.toolbarOptions?.items ?? [];
367
+ if (options.allowAdd) items.unshift({
368
+ location: "after",
369
+ widget: "dxButton",
370
+ options: {
371
+ text: t("grid.buttonNew"),
372
+ icon: "plus",
373
+ disabled: options.addDisabled,
374
+ onClick: () => options.onAdd?.()
375
+ }
376
+ });
377
+ if (inlineToolbar?.save) items.push({
378
+ location: "after",
379
+ widget: "dxButton",
380
+ options: {
381
+ text: t("grid.inlineSaveChanges"),
382
+ icon: "save",
383
+ onClick: () => void gridRef.current?.instance?.()?.saveEditData?.()
384
+ }
385
+ });
386
+ if (inlineToolbar?.revert) items.push({
387
+ location: "after",
388
+ widget: "dxButton",
389
+ options: {
390
+ text: t("grid.inlineRevertChanges"),
391
+ icon: "revert",
392
+ onClick: () => gridRef.current?.instance?.()?.cancelEditData?.()
393
+ }
394
+ });
395
+ if (event.toolbarOptions) event.toolbarOptions.items = items;
396
+ }, [
397
+ inlineToolbar,
398
+ options,
399
+ t
400
+ ]);
401
+ const handleSaving = useCallback(async (event) => {
402
+ if (!options.onBatchSave) return;
403
+ event.cancel = true;
404
+ const changedRows = event.changes?.filter((change) => change.type === "update" && change.data).map((change) => change.data) ?? [];
405
+ if (changedRows.length > 0) await options.onBatchSave(changedRows);
406
+ hasPendingEditsRef.current = false;
407
+ refresh();
408
+ }, [options.onBatchSave, refresh]);
409
+ const handleEditCanceled = useCallback(() => {
410
+ hasPendingEditsRef.current = false;
411
+ }, []);
412
+ const handleEditingChange = useCallback(() => {
413
+ hasPendingEditsRef.current = true;
414
+ }, []);
415
+ const confirmDelete = useCallback(() => {
416
+ if (confirmRow) options.onDelete?.(confirmRow);
417
+ setConfirmRow(null);
418
+ }, [confirmRow, options]);
419
+ const requestDelete = useCallback((rowData) => {
420
+ if (!rowData || options.canDeleteRow?.(rowData) === false) return;
421
+ setConfirmRow(rowData);
422
+ }, [options.canDeleteRow]);
423
+ const renderRowActions = useCallback((cell) => {
424
+ const row = cell.data;
425
+ if (!row) return null;
426
+ return /* @__PURE__ */ jsxs("div", {
427
+ className: "nb-dx-row-actions",
428
+ children: [options.allowEdit && options.canEditRow?.(row) !== false ? /* @__PURE__ */ jsx("button", {
429
+ type: "button",
430
+ className: "nb-dx-row-actions__btn",
431
+ "aria-label": t("grid.buttonEdit"),
432
+ onClick: () => options.onEdit?.(row),
433
+ children: /* @__PURE__ */ jsx("i", {
434
+ className: "dx-icon dx-icon-edit",
435
+ "aria-hidden": true
436
+ })
437
+ }) : null, options.allowDelete && options.canDeleteRow?.(row) !== false ? /* @__PURE__ */ jsx("button", {
438
+ type: "button",
439
+ className: "nb-dx-row-actions__btn nb-dx-row-actions__btn--delete",
440
+ "aria-label": t("grid.buttonDelete"),
441
+ onClick: () => requestDelete(row),
442
+ children: /* @__PURE__ */ jsx("i", {
443
+ className: "dx-icon dx-icon-trash",
444
+ "aria-hidden": true
445
+ })
446
+ }) : null]
447
+ });
448
+ }, [
449
+ options.allowDelete,
450
+ options.allowEdit,
451
+ options.canDeleteRow,
452
+ options.canEditRow,
453
+ options.onEdit,
454
+ requestDelete,
455
+ t
456
+ ]);
457
+ const remoteOperations = resolveDxRemoteOperations(options);
458
+ const hasMasterDetail = Boolean(options.detailFields && options.detailUrl);
459
+ const renderMasterDetail = useCallback((detailInfo) => {
460
+ const row = detailInfo.data;
461
+ if (!row) return null;
462
+ const detailFields = typeof options.detailFields === "function" ? options.detailFields(row) : options.detailFields;
463
+ const rowKey = row[idField];
464
+ const detailUrl = options.detailUrl?.replace("{id}", String(rowKey));
465
+ if (!detailFields?.length || !detailUrl) return null;
466
+ return /* @__PURE__ */ jsx(DevExtremeDetailGridSection, {
467
+ fields: detailFields,
468
+ url: detailUrl
469
+ });
470
+ }, [
471
+ idField,
472
+ options.detailFields,
473
+ options.detailUrl
474
+ ]);
475
+ const showToolbar = options.toolbarVisible !== false;
476
+ const showFilterRow = options.filterRow ?? true;
477
+ const showPaging = options.paging ?? true;
478
+ const pageSize = options.pageSize ?? 20;
479
+ return /* @__PURE__ */ jsx("div", {
480
+ className: "view datagrid-list data-grid-view",
481
+ children: /* @__PURE__ */ jsx("div", {
482
+ className: "view-wrapper view-wrapper-datagrid-list list-page",
483
+ children: /* @__PURE__ */ jsxs("div", {
484
+ className: "nb-dx-datagrid",
485
+ children: [
486
+ options.aboveGrid ? /* @__PURE__ */ jsx("div", {
487
+ className: "nb-dx-datagrid__above-grid",
488
+ children: options.aboveGrid
489
+ }) : null,
490
+ showToolbar && options.title ? /* @__PURE__ */ jsx("div", {
491
+ className: "nb-dx-datagrid__toolbar",
492
+ children: /* @__PURE__ */ jsx("div", {
493
+ className: "grid-header",
494
+ children: options.title
495
+ })
496
+ }) : null,
497
+ options.beforeToolbar?.(),
498
+ /* @__PURE__ */ jsx("div", {
499
+ className: "nb-dx-datagrid__grid",
500
+ children: /* @__PURE__ */ jsxs(DataGrid, {
501
+ ref: gridRef,
502
+ dataSource,
503
+ keyExpr: idField,
504
+ height: "100%",
505
+ showBorders: true,
506
+ remoteOperations,
507
+ onSelectionChanged: handleSelectionChanged,
508
+ onRowDblClick: handleRowDblClick,
509
+ onToolbarPreparing: showToolbar ? handleToolbarPreparing : void 0,
510
+ onSaving: options.onBatchSave ? handleSaving : void 0,
511
+ onEditCanceled: handleEditCanceled,
512
+ onEditingChange: handleEditingChange,
513
+ children: [
514
+ typeof remoteOperations === "object" ? /* @__PURE__ */ jsx(RemoteOperations, { ...remoteOperations }) : null,
515
+ /* @__PURE__ */ jsx(LoadPanel, {
516
+ enabled: true,
517
+ showPane: true,
518
+ shading: false
519
+ }),
520
+ options.selectionMode === "multiple" ? /* @__PURE__ */ jsx(Selection, {
521
+ mode: "multiple",
522
+ showCheckBoxesMode: "always"
523
+ }) : /* @__PURE__ */ jsx(Selection, { mode: "single" }),
524
+ showPaging ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Paging, {
525
+ enabled: true,
526
+ pageSize
527
+ }), /* @__PURE__ */ jsx(Pager, {
528
+ visible: true,
529
+ showInfo: true,
530
+ showPageSizeSelector: true,
531
+ allowedPageSizes: DX_PAGE_SIZE_OPTIONS,
532
+ displayMode: "full"
533
+ })] }) : /* @__PURE__ */ jsx(Paging, { enabled: false }),
534
+ /* @__PURE__ */ jsx(Sorting, { mode: "single" }),
535
+ showFilterRow ? /* @__PURE__ */ jsx(FilterRow, {
536
+ visible: true,
537
+ applyFilter: "auto"
538
+ }) : null,
539
+ options.headerFilter ? /* @__PURE__ */ jsx(HeaderFilter, { visible: true }) : null,
540
+ showToolbar ? /* @__PURE__ */ jsx(Toolbar, { visible: true }) : null,
541
+ hasMasterDetail ? /* @__PURE__ */ jsx(MasterDetail, {
542
+ enabled: true,
543
+ render: renderMasterDetail
544
+ }) : null,
545
+ inlineEditing && dxEditMode ? /* @__PURE__ */ jsx(Editing, {
546
+ mode: dxEditMode,
547
+ allowUpdating: options.allowEdit !== false && options.fields.some((field) => field.type !== FieldType.FILE && canEditFieldInline(field)),
548
+ useIcons: true,
549
+ selectTextOnEditStart: true
550
+ }) : null,
551
+ columns.map((column) => /* @__PURE__ */ jsx(Column, { ...column }, column.dataField)),
552
+ !inlineEditing && (options.allowDelete || options.allowEdit) ? /* @__PURE__ */ jsx(Column, {
553
+ caption: "",
554
+ width: 110,
555
+ allowSorting: false,
556
+ allowFiltering: false,
557
+ allowEditing: false,
558
+ cellRender: renderRowActions
559
+ }) : null,
560
+ /* @__PURE__ */ jsx(Item, { name: "searchPanel" })
561
+ ]
562
+ })
563
+ }),
564
+ /* @__PURE__ */ jsx(ConfirmDialog, {
565
+ open: Boolean(confirmRow),
566
+ title: t("dialog.confirmDeleteTitle"),
567
+ message: t("dialog.confirmDelete"),
568
+ variant: "danger",
569
+ cancelLabel: t("dialog.buttonCancel"),
570
+ confirmLabel: t("grid.buttonDelete"),
571
+ onCancel: () => setConfirmRow(null),
572
+ onConfirm: confirmDelete
573
+ })
574
+ ]
575
+ })
576
+ })
577
+ });
578
+ });
579
+ DevExtremeDataGridView.displayName = "DevExtremeDataGridView";
580
+ //#endregion
581
+ //#region packages/devextreme/DevExtremeFormDetailGrid.tsx
582
+ function DevExtremeFormDetailGrid({ fields, rows, allowAdding = false, allowUpdating = false, allowDeleting = false, onRowsChange }) {
583
+ const { t } = useCoreTranslation();
584
+ const columns = useMemo(() => mapFieldsToDxColumns(fields), [fields]);
585
+ return /* @__PURE__ */ jsxs("div", {
586
+ className: "nb-dx-form-detail",
587
+ children: [/* @__PURE__ */ jsx("div", {
588
+ className: "nb-dx-form-detail__heading",
589
+ children: /* @__PURE__ */ jsx("h3", {
590
+ className: "nb-dx-form-detail__title",
591
+ children: t("form.detailTitle")
592
+ })
593
+ }), /* @__PURE__ */ jsxs(DataGrid, {
594
+ dataSource: rows,
595
+ keyExpr: "__rowKey",
596
+ showBorders: true,
597
+ onInitNewRow: (event) => {
598
+ const data = event.data;
599
+ Object.assign(data, buildEmptyRow(fields), { __rowKey: crypto.randomUUID() });
600
+ },
601
+ onRowInserted: (event) => {
602
+ onRowsChange([...rows, event.data]);
603
+ },
604
+ onRowRemoved: (event) => {
605
+ const key = event.data.__rowKey;
606
+ onRowsChange(rows.filter((row) => row.__rowKey !== key));
607
+ },
608
+ onRowUpdated: (event) => {
609
+ const key = event.data.__rowKey;
610
+ onRowsChange(rows.map((row) => row.__rowKey === key ? event.data : row));
611
+ },
612
+ children: [/* @__PURE__ */ jsx(Editing, {
613
+ mode: "row",
614
+ allowAdding,
615
+ allowUpdating,
616
+ allowDeleting,
617
+ useIcons: true
618
+ }), columns.map((column) => /* @__PURE__ */ jsx(Column, { ...column }, column.dataField))]
619
+ })]
620
+ });
621
+ }
622
+ //#endregion
623
+ //#region packages/devextreme/mapFieldsToDxFormItems.ts
624
+ function resolveEditorType(field) {
625
+ switch (field.type) {
626
+ case FieldType.TEXT:
627
+ case FieldType.PASSWORD: return "dxTextBox";
628
+ case FieldType.TEXTAREA: return "dxTextArea";
629
+ case FieldType.NUMBER:
630
+ case FieldType.CURRENCY: return "dxNumberBox";
631
+ case FieldType.DATE: return "dxDateBox";
632
+ case FieldType.DATETIME: return "dxDateBox";
633
+ case FieldType.CHECKBOX: return "dxCheckBox";
634
+ case FieldType.SWITCH: return "dxSwitch";
635
+ case FieldType.SELECT:
636
+ case FieldType.ENUM:
637
+ case FieldType.ENTITY:
638
+ case FieldType.RADIO:
639
+ case FieldType.TAGS: return "dxSelectBox";
640
+ default: return "dxTextBox";
641
+ }
642
+ }
643
+ function resolveEditorOptions(field) {
644
+ const options = {};
645
+ if (field.type === FieldType.PASSWORD) options.mode = "password";
646
+ if (field.type === FieldType.TEXTAREA) options.height = field.height ?? 96;
647
+ if (field.maxLength != null) options.maxLength = field.maxLength;
648
+ if (field.type === FieldType.SELECT || field.type === FieldType.ENUM || field.type === FieldType.ENTITY || field.type === FieldType.RADIO || field.type === FieldType.TAGS) {
649
+ options.dataSource = field.data ?? [];
650
+ options.displayExpr = field.textField || "label";
651
+ options.valueExpr = field.valueField || "value";
652
+ options.searchEnabled = field.searchEnabled;
653
+ }
654
+ if (field.format) options.format = field.format;
655
+ if (field.precision > 0 && (field.type === FieldType.NUMBER || field.type === FieldType.CURRENCY)) options.format = field.format || `#,##0.${"0".repeat(field.precision)}`;
656
+ return options;
657
+ }
658
+ function mapFieldsToDxFormItems(fields) {
659
+ return fields.filter((field) => !field.isIdentity && field.visibleOnForm && !field.hidden).sort((left, right) => (left.order ?? Number.MAX_SAFE_INTEGER) - (right.order ?? Number.MAX_SAFE_INTEGER)).map((field) => ({
660
+ dataField: field.name,
661
+ label: { text: field.label || field.name },
662
+ editorType: resolveEditorType(field),
663
+ editorOptions: resolveEditorOptions(field),
664
+ colSpan: field.col,
665
+ isRequired: field.required,
666
+ helpText: field.helpText
667
+ }));
668
+ }
669
+ //#endregion
670
+ //#region packages/devextreme/DevExtremeFormView.tsx
671
+ function isEmptyValue(value) {
672
+ return value === null || value === void 0 || value === "" || Array.isArray(value) && value.length === 0;
673
+ }
674
+ function withDetailRowKeys(rows) {
675
+ return rows.map((row) => ({
676
+ ...row,
677
+ __rowKey: typeof row.__rowKey === "string" ? row.__rowKey : crypto.randomUUID()
678
+ }));
679
+ }
680
+ function validateField(field, value, formData, t) {
681
+ if (field.required && isEmptyValue(value)) return t("form.fieldRequired", { label: field.label });
682
+ for (const rule of field.validators ?? []) {
683
+ if (rule.type === "required" && isEmptyValue(value)) return rule.options.message ?? t("form.fieldRequired", { label: field.label });
684
+ if (rule.type === "email" && typeof value === "string" && value !== "" && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) return rule.options.message ?? t("form.invalidEmail");
685
+ if (rule.type === "numeric" && value !== "" && value != null && Number.isNaN(Number(value))) return rule.options.message ?? t("form.invalidNumeric");
686
+ if (rule.type === "pattern" && typeof value === "string" && !new RegExp(rule.options.pattern).test(value)) return rule.options.message ?? t("form.invalidPattern");
687
+ if (rule.type === "stringLength" && typeof value === "string") {
688
+ if (rule.options.min !== void 0 && value.length < rule.options.min) return rule.options.message ?? t("form.stringTooShort");
689
+ if (rule.options.max !== void 0 && value.length > rule.options.max) return rule.options.message ?? t("form.stringTooLong");
690
+ }
691
+ if (rule.type === "range" && value !== "" && value != null) {
692
+ const numericValue = Number(value);
693
+ if (rule.options.min !== void 0 && numericValue < rule.options.min) return rule.options.message ?? t("form.outOfRange");
694
+ if (rule.options.max !== void 0 && numericValue > rule.options.max) return rule.options.message ?? t("form.outOfRange");
695
+ }
696
+ if (rule.type === "custom") {
697
+ if (!rule.options.validationCallback({
698
+ value,
699
+ data: formData
700
+ })) return rule.options.message ?? t("validation.defaultError");
701
+ }
702
+ }
703
+ return null;
704
+ }
705
+ const DevExtremeFormView = forwardRef((options, ref) => {
706
+ const { t } = useCoreTranslation();
707
+ const httpClient = useCoreHttpClient();
708
+ const [on, emit] = useEvents();
709
+ const scopedFormErrorsEvent = `${FORM_ERRORS_EVENT}:${useId()}`;
710
+ const appliedOperationRef = useRef(null);
711
+ const [detailDirty, setDetailDirty] = useState(false);
712
+ const { isEdit, uploadedFiles, existingMediaByField, formData, formDataRef, detailRows, detailRowsRef, fieldState, setFieldState, errors, setErrors, detailErrors, setDetailErrors, prependDataRef, setNextFormData, setNextDetailRows, setFieldValue, setEditMode, resetUploadSession, resetPrependData, setExistingMedia, clearExistingMedia, upsertUploadedFile } = useFormState({
713
+ fields: options.fields,
714
+ onFieldDataChanged: options.onFieldDataChanged
715
+ });
716
+ const detailPropertyName = options.detailPropertyName ?? "items";
717
+ const formItems = useMemo(() => mapFieldsToDxFormItems(options.fields), [options.fields]);
718
+ const detailRowsWithKeys = useMemo(() => withDetailRowKeys(detailRows), [detailRows]);
719
+ const validate = useFormValidation({
720
+ accessors: {
721
+ getDetailRowCount: () => detailRowsRef.current.length,
722
+ getDetailRows: () => detailRowsRef.current,
723
+ hasPendingDetailEdits: () => detailDirty,
724
+ validateForm: useCallback(() => {
725
+ const nextErrors = {};
726
+ options.fields.forEach((field) => {
727
+ const state = fieldState[field.name];
728
+ if (field.isIdentity || state?.validationEnabled === false || state?.hidden === true || field.hidden || field.visibleOnForm === false) return;
729
+ let value = formDataRef.current[field.name];
730
+ if (field.type === FieldType.FILE) {
731
+ const uploaded = uploadedFiles.current.find((file) => file.name === field.name);
732
+ const hasExisting = !!existingMediaByField.current[field.name];
733
+ value = uploaded?.iri != null || hasExisting && uploaded === void 0 ? "present" : null;
734
+ }
735
+ const error = validateField(field, value, formDataRef.current, t);
736
+ if (error) nextErrors[field.name] = error;
737
+ });
738
+ setErrors(nextErrors);
739
+ setDetailErrors({});
740
+ return Object.keys(nextErrors).length === 0;
741
+ }, [
742
+ existingMediaByField,
743
+ fieldState,
744
+ formDataRef,
745
+ options.fields,
746
+ setDetailErrors,
747
+ setErrors,
748
+ t,
749
+ uploadedFiles
750
+ ])
751
+ },
752
+ detailFields: options.detailFields,
753
+ detailNoDataText: options.requiredDetail ? t("form.detailRequired") : t("form.detailEmpty"),
754
+ requiredDetail: options.requiredDetail,
755
+ validationErrorText: t("form.validationError")
756
+ });
757
+ const submitAccessors = useMemo(() => ({
758
+ getDetailRows: () => detailRowsRef.current,
759
+ getFieldValue: (field) => formDataRef.current[field],
760
+ getFormData: () => formDataRef.current,
761
+ getUploadedFiles: () => uploadedFiles.current,
762
+ isEditMode: () => isEdit.current
763
+ }), [
764
+ detailRowsRef,
765
+ formDataRef,
766
+ isEdit,
767
+ uploadedFiles
768
+ ]);
769
+ const { handleSave, handleDelete } = useFormSubmit({
770
+ url: options.url,
771
+ detailUrl: options.detailUrl,
772
+ fields: options.fields,
773
+ detailFields: options.detailFields,
774
+ detailPropertyName,
775
+ format: options.format,
776
+ events: options.events,
777
+ formErrorsEvent: scopedFormErrorsEvent,
778
+ httpClient,
779
+ adapter: options.adapter,
780
+ onSaveSuccess: options.onSaveSuccess,
781
+ onSaveError: options.onSaveError,
782
+ onDeleteSuccess: options.onDeleteSuccess,
783
+ onDeleteError: options.onDeleteError,
784
+ onLoadingChange: options.onLoadingChange
785
+ }, submitAccessors, emit, validate);
786
+ const handleSaveRef = useRef(handleSave);
787
+ handleSaveRef.current = handleSave;
788
+ const handleDeleteRef = useRef(handleDelete);
789
+ handleDeleteRef.current = handleDelete;
790
+ const captureExistingMedia = useCallback((row) => {
791
+ const nextMedia = {};
792
+ options.fields.forEach((field) => {
793
+ if (field.type !== FieldType.FILE) return;
794
+ const raw = row[field.name];
795
+ if (raw && typeof raw === "object") nextMedia[field.name] = raw;
796
+ });
797
+ setExistingMedia(nextMedia);
798
+ }, [options.fields, setExistingMedia]);
799
+ const applyAddPayload = useCallback((payload) => {
800
+ resetUploadSession();
801
+ setExistingMedia({});
802
+ setErrors({});
803
+ setDetailErrors({});
804
+ setNextDetailRows([]);
805
+ setDetailDirty(false);
806
+ resetPrependData();
807
+ setNextFormData(payload ? normalizeFormData(payload, options.fields, options.adapter, prependDataRef.current) : buildEmptyRow(options.fields));
808
+ setEditMode(false);
809
+ }, [
810
+ options.adapter,
811
+ options.fields,
812
+ prependDataRef,
813
+ resetPrependData,
814
+ resetUploadSession,
815
+ setDetailErrors,
816
+ setEditMode,
817
+ setErrors,
818
+ setExistingMedia,
819
+ setNextDetailRows,
820
+ setNextFormData
821
+ ]);
822
+ const applyEditPayload = useCallback((payload) => {
823
+ resetPrependData();
824
+ captureExistingMedia(payload.row);
825
+ const row = normalizeFormData(payload.row, options.fields, options.adapter, prependDataRef.current);
826
+ resetUploadSession();
827
+ setErrors({});
828
+ setDetailErrors({});
829
+ setNextFormData(row);
830
+ setEditMode(true);
831
+ setDetailDirty(false);
832
+ const detailId = row[options.fields.find((field) => field.isIdentity)?.name ?? ""];
833
+ const detailUrl = typeof detailId === "string" || typeof detailId === "number" ? options.detailUrl?.replace("{id}", String(detailId)) : void 0;
834
+ if (!detailUrl) return;
835
+ emit(FORM_EVENTS.LOADING, true);
836
+ loadDetailRows(httpClient, detailUrl, options.adapter).then((rows) => setNextDetailRows(withDetailRowKeys(rows))).finally(() => emit(FORM_EVENTS.LOADING, false));
837
+ }, [
838
+ captureExistingMedia,
839
+ emit,
840
+ httpClient,
841
+ options.adapter,
842
+ options.detailUrl,
843
+ options.fields,
844
+ prependDataRef,
845
+ resetPrependData,
846
+ resetUploadSession,
847
+ setDetailErrors,
848
+ setEditMode,
849
+ setErrors,
850
+ setNextDetailRows,
851
+ setNextFormData
852
+ ]);
853
+ useEffect(() => {
854
+ if (!options.operation) {
855
+ appliedOperationRef.current = null;
856
+ return;
857
+ }
858
+ const operationKey = `${options.operation}:${options.operationVersion ?? 0}`;
859
+ if (appliedOperationRef.current === operationKey) return;
860
+ appliedOperationRef.current = operationKey;
861
+ if (options.operation === "add") {
862
+ applyAddPayload(options.rowData ?? void 0);
863
+ return;
864
+ }
865
+ if (options.operation === "edit" && options.rowData) applyEditPayload({ row: options.rowData });
866
+ }, [
867
+ applyAddPayload,
868
+ applyEditPayload,
869
+ options.operation,
870
+ options.operationVersion,
871
+ options.rowData
872
+ ]);
873
+ useEffect(() => {
874
+ const subs = [on(scopedFormErrorsEvent, (formErrors) => {
875
+ const mapped = mapApiViolations(formErrors, detailPropertyName, t("validation.defaultError"));
876
+ setErrors((current) => ({
877
+ ...current,
878
+ ...mapped.fieldErrors
879
+ }));
880
+ setDetailErrors(mapped.detailErrors);
881
+ })];
882
+ if (options.events?.ADD) subs.push(on(options.events.ADD, (payload) => applyAddPayload(payload)));
883
+ if (options.events?.EDIT) subs.push(on(options.events.EDIT, (payload) => applyEditPayload(payload)));
884
+ if (options.events?.DELETE) subs.push(on(options.events.DELETE, (payload) => handleDeleteRef.current(payload)));
885
+ if (options.events?.SAVE) subs.push(on(options.events.SAVE, () => handleSaveRef.current()));
886
+ return () => subs.forEach((sub) => sub.unsubscribe());
887
+ }, [scopedFormErrorsEvent]);
888
+ const handleDetailRowsChange = useCallback((rows) => {
889
+ setNextDetailRows(withDetailRowKeys(rows).map(({ __rowKey, ...row }) => row));
890
+ setDetailDirty(true);
891
+ }, [setNextDetailRows]);
892
+ useImperativeHandle(ref, () => ({
893
+ getFormData: () => formDataRef.current,
894
+ getFieldValue: (name) => formDataRef.current[name],
895
+ setFieldValue,
896
+ getDetailData: () => detailRowsRef.current,
897
+ setDetailData: (data) => setNextDetailRows(data),
898
+ saveDetailData: () => void 0,
899
+ reloadDetailData: () => void 0,
900
+ setValues: (data) => {
901
+ resetPrependData();
902
+ setNextFormData(normalizeFormData(data, options.fields, void 0, prependDataRef.current));
903
+ },
904
+ save: () => handleSaveRef.current(),
905
+ deleteRow: (row) => handleDeleteRef.current({ row }),
906
+ setReadonly: (field, value) => setFieldState((current) => ({
907
+ ...current,
908
+ [field]: {
909
+ ...current[field],
910
+ readonly: value
911
+ }
912
+ })),
913
+ setDisabled: (field, value) => setFieldState((current) => ({
914
+ ...current,
915
+ [field]: {
916
+ ...current[field],
917
+ disabled: value
918
+ }
919
+ })),
920
+ enableValidation: (field) => setFieldState((current) => ({
921
+ ...current,
922
+ [field]: {
923
+ ...current[field],
924
+ validationEnabled: true
925
+ }
926
+ })),
927
+ disableValidation: (field) => setFieldState((current) => ({
928
+ ...current,
929
+ [field]: {
930
+ ...current[field],
931
+ validationEnabled: false
932
+ }
933
+ })),
934
+ setError: (field, message) => setErrors((current) => ({
935
+ ...current,
936
+ [field]: message
937
+ })),
938
+ showField: (field) => setFieldState((current) => ({
939
+ ...current,
940
+ [field]: {
941
+ ...current[field],
942
+ hidden: false
943
+ }
944
+ })),
945
+ hideField: (field) => setFieldState((current) => ({
946
+ ...current,
947
+ [field]: {
948
+ ...current[field],
949
+ hidden: true
950
+ }
951
+ })),
952
+ validate,
953
+ setIsEdit: (value) => setEditMode(value)
954
+ }), [
955
+ detailRowsRef,
956
+ formDataRef,
957
+ options.fields,
958
+ prependDataRef,
959
+ resetPrependData,
960
+ setEditMode,
961
+ setErrors,
962
+ setFieldState,
963
+ setFieldValue,
964
+ setNextDetailRows,
965
+ setNextFormData,
966
+ validate
967
+ ]);
968
+ const fileFields = options.fields.filter((field) => field.type === FieldType.FILE && field.visibleOnForm && !field.hidden && !fieldState[field.name]?.hidden);
969
+ const visibleItems = formItems.filter((item) => {
970
+ const state = fieldState[item.dataField] ?? {};
971
+ const field = options.fields.find((candidate) => candidate.name === item.dataField);
972
+ return !state.hidden && field?.type !== FieldType.FILE && field?.type !== FieldType.HTML;
973
+ });
974
+ return /* @__PURE__ */ jsxs("div", {
975
+ className: options.className ?? "nb-dx-form",
976
+ children: [
977
+ /* @__PURE__ */ jsx(Form, {
978
+ formData,
979
+ colCount: 2,
980
+ labelLocation: "top",
981
+ readOnly: options.editable === false,
982
+ onFieldDataChanged: (event) => {
983
+ if (!event.dataField) return;
984
+ setFieldValue(event.dataField, event.value);
985
+ },
986
+ children: visibleItems.map((item) => /* @__PURE__ */ jsx(SimpleItem, {
987
+ dataField: item.dataField,
988
+ label: item.label,
989
+ editorType: item.editorType,
990
+ editorOptions: {
991
+ ...item.editorOptions,
992
+ readOnly: fieldState[item.dataField]?.readonly ?? options.fields.find((field) => field.name === item.dataField)?.readonly ?? options.editable === false,
993
+ disabled: fieldState[item.dataField]?.disabled ?? options.fields.find((field) => field.name === item.dataField)?.disabled
994
+ },
995
+ colSpan: item.colSpan,
996
+ isRequired: item.isRequired,
997
+ helpText: item.helpText,
998
+ validationError: errors[item.dataField]
999
+ }, item.dataField))
1000
+ }),
1001
+ fileFields.map((field) => /* @__PURE__ */ jsxs("div", {
1002
+ className: "nb-dx-form__file-field",
1003
+ children: [
1004
+ /* @__PURE__ */ jsx("label", {
1005
+ className: "nb-dx-form__file-label",
1006
+ children: field.label
1007
+ }),
1008
+ /* @__PURE__ */ jsx(FileUploadField, {
1009
+ field,
1010
+ existingMedia: existingMediaByField.current[field.name] ?? null,
1011
+ disabled: fieldState[field.name]?.disabled ?? field.disabled ?? options.editable === false,
1012
+ readOnly: fieldState[field.name]?.readonly ?? field.readonly ?? options.editable === false,
1013
+ invalid: !!errors[field.name],
1014
+ uploadUrl: field.url ?? `${options.url}/upload`,
1015
+ httpClient,
1016
+ t,
1017
+ onUploaded: (entry) => upsertUploadedFile(entry),
1018
+ onCleared: (fieldName) => clearExistingMedia(fieldName)
1019
+ }),
1020
+ errors[field.name] ? /* @__PURE__ */ jsx("span", {
1021
+ className: "nb-dx-form__error",
1022
+ children: errors[field.name]
1023
+ }) : null
1024
+ ]
1025
+ }, field.name)),
1026
+ options.detailFields?.length ? /* @__PURE__ */ jsx(DevExtremeFormDetailGrid, {
1027
+ fields: options.detailFields,
1028
+ rows: detailRowsWithKeys,
1029
+ allowAdding: options.allowAdding,
1030
+ allowUpdating: options.allowUpdating,
1031
+ allowDeleting: options.allowDeleting,
1032
+ detailErrors,
1033
+ onRowsChange: handleDetailRowsChange
1034
+ }) : null
1035
+ ]
1036
+ });
1037
+ });
1038
+ DevExtremeFormView.displayName = "DevExtremeFormView";
1039
+ //#endregion
1040
+ //#region packages/devextreme/DevExtremeThemeSync.tsx
1041
+ function readNubitTheme() {
1042
+ const theme = document.documentElement.dataset.theme;
1043
+ if (theme === "dark" || theme === "light") return theme;
1044
+ return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
1045
+ }
1046
+ function applyDevExtremeTheme(theme, basePath) {
1047
+ const href = `${basePath}dx.${theme}.css`;
1048
+ const id = "nb-devextreme-theme-link";
1049
+ let link = document.getElementById(id);
1050
+ if (link?.getAttribute("data-dx-theme-href") === href) return;
1051
+ if (link) {
1052
+ link.href = href;
1053
+ link.setAttribute("data-dx-theme-href", href);
1054
+ return;
1055
+ }
1056
+ link = document.createElement("link");
1057
+ link.id = id;
1058
+ link.rel = "stylesheet";
1059
+ link.href = href;
1060
+ link.setAttribute("data-dx-theme-href", href);
1061
+ document.head.appendChild(link);
1062
+ }
1063
+ /**
1064
+ * Swaps DevExtreme base theme CSS when Nubit `data-theme` changes.
1065
+ * Mount once inside `ThemeProvider` (typically via `DevExtremeCrudProvider`).
1066
+ */
1067
+ function DevExtremeThemeSync({ basePath = "/devextreme-themes/" }) {
1068
+ useEffect(() => {
1069
+ const sync = () => applyDevExtremeTheme(readNubitTheme(), basePath);
1070
+ sync();
1071
+ const observer = new MutationObserver(sync);
1072
+ observer.observe(document.documentElement, {
1073
+ attributes: true,
1074
+ attributeFilter: ["data-theme", "class"]
1075
+ });
1076
+ const mq = window.matchMedia("(prefers-color-scheme: dark)");
1077
+ const onSystemChange = () => {
1078
+ if (!document.documentElement.dataset.theme) sync();
1079
+ };
1080
+ mq.addEventListener("change", onSystemChange);
1081
+ return () => {
1082
+ observer.disconnect();
1083
+ mq.removeEventListener("change", onSystemChange);
1084
+ };
1085
+ }, [basePath]);
1086
+ return null;
1087
+ }
1088
+ //#endregion
1089
+ //#region packages/devextreme/DevExtremeCrudProvider.tsx
1090
+ const defaultDevExtremeViews = {
1091
+ DataGridView: DevExtremeDataGridView,
1092
+ FormView: DevExtremeFormView
1093
+ };
1094
+ function DevExtremeCrudProvider({ children, views, basePath, syncTheme = true }) {
1095
+ return /* @__PURE__ */ jsxs(CrudViewProvider, {
1096
+ views: useMemo(() => ({
1097
+ DataGridView: views?.DataGridView ?? defaultDevExtremeViews.DataGridView,
1098
+ FormView: views?.FormView ?? defaultDevExtremeViews.FormView
1099
+ }), [views?.DataGridView, views?.FormView]),
1100
+ children: [syncTheme ? /* @__PURE__ */ jsx(DevExtremeThemeSync, { basePath }) : null, children]
1101
+ });
1102
+ }
1103
+ //#endregion
1104
+ export { DevExtremeCrudProvider, DevExtremeDataGridView, DevExtremeDetailGridSection, DevExtremeFormDetailGrid, DevExtremeFormView, DevExtremeThemeSync, convertDxFilterToNubit, flattenDxFilter, mapFieldsToDxColumns, mapFieldsToDxFormItems, mergeGridFilters };