@bsol-oss/react-datatable5 5.0.1 → 6.0.1

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 (44) hide show
  1. package/dist/index.d.ts +124 -26
  2. package/dist/index.js +1090 -93
  3. package/dist/index.mjs +1090 -99
  4. package/dist/types/components/Controls/TablePagination.d.ts +1 -0
  5. package/dist/types/components/DataTable/CardHeader.d.ts +13 -0
  6. package/dist/types/components/DataTable/DataDisplay.d.ts +4 -0
  7. package/dist/types/components/DataTable/DataTable.d.ts +1 -1
  8. package/dist/types/components/DataTable/DataTableContext.d.ts +2 -1
  9. package/dist/types/components/DataTable/DataTableServer.d.ts +1 -1
  10. package/dist/types/components/DataTable/Table.d.ts +1 -1
  11. package/dist/types/components/DataTable/TableCardContainer.d.ts +2 -1
  12. package/dist/types/components/DataTable/TableCards.d.ts +1 -1
  13. package/dist/types/components/DataTable/useDataFromUrl.d.ts +5 -4
  14. package/dist/types/components/DataTable/useDataTableContext.d.ts +1 -1
  15. package/dist/types/components/DataTable/useDataTableServer.d.ts +1 -2
  16. package/dist/types/components/DataTable/utils/getColumns.d.ts +13 -0
  17. package/dist/types/components/DatePicker/DatePicker.d.ts +21 -0
  18. package/dist/types/components/DatePicker/RangeDatePicker.d.ts +18 -0
  19. package/dist/types/components/DatePicker/getMultiDates.d.ts +7 -0
  20. package/dist/types/components/DatePicker/getRangeDates.d.ts +6 -0
  21. package/dist/types/components/Form/Form.d.ts +33 -0
  22. package/dist/types/components/Form/SchemaFormContext.d.ts +15 -0
  23. package/dist/types/components/Form/components/BooleanPicker.d.ts +4 -0
  24. package/dist/types/components/Form/components/DatePicker.d.ts +4 -0
  25. package/dist/types/components/Form/components/IdPicker.d.ts +7 -0
  26. package/dist/types/components/Form/components/IdViewer.d.ts +8 -0
  27. package/dist/types/components/Form/components/NumberInputField.d.ts +4 -0
  28. package/dist/types/components/Form/components/ObjectInput.d.ts +4 -0
  29. package/dist/types/components/Form/components/StringInputField.d.ts +10 -0
  30. package/dist/types/components/Form/useSchemaContext.d.ts +10 -0
  31. package/dist/types/components/Form/utils/clearEmptyString.d.ts +3 -0
  32. package/dist/types/components/Form/utils/getTableData.d.ts +12 -0
  33. package/dist/types/components/Form/utils/idListSanityCheck.d.ts +1 -0
  34. package/dist/types/components/Form/utils/snakeToLabel.d.ts +1 -0
  35. package/dist/types/components/ui/accordion.d.ts +12 -0
  36. package/dist/types/components/ui/checkbox-card.d.ts +13 -0
  37. package/dist/types/components/ui/data-list.d.ts +11 -0
  38. package/dist/types/components/ui/link-button.d.ts +5 -0
  39. package/dist/types/components/ui/number-input.d.ts +8 -0
  40. package/dist/types/components/ui/pagination.d.ts +20 -0
  41. package/dist/types/components/ui/radio-card.d.ts +16 -0
  42. package/dist/types/components/ui/toggle-tip.d.ts +10 -0
  43. package/dist/types/index.d.ts +9 -2
  44. package/package.json +8 -3
package/dist/index.mjs CHANGED
@@ -1,31 +1,62 @@
1
- import { jsxs, Fragment, jsx } from 'react/jsx-runtime';
2
- import { IconButton, Button as Button$1, Portal, Dialog, useDisclosure, Flex, DialogRoot as DialogRoot$1, DialogBackdrop, DialogTrigger as DialogTrigger$1, DialogContent as DialogContent$1, DialogCloseTrigger as DialogCloseTrigger$1, DialogHeader as DialogHeader$1, DialogTitle as DialogTitle$1, DialogBody as DialogBody$1, DialogFooter as DialogFooter$1, Text, Menu, AbsoluteCenter, Tag as Tag$1, Grid, Image, Checkbox as Checkbox$1, Table as Table$1, Box, Tooltip as Tooltip$1, Spinner, Icon, MenuRoot as MenuRoot$1, MenuTrigger as MenuTrigger$1, Span, EmptyState as EmptyState$1, VStack, List, Card, Input, Slider as Slider$1, HStack, For, RadioGroup as RadioGroup$1, Group, Switch as Switch$1, InputElement } from '@chakra-ui/react';
1
+ import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
2
+ import { Button as Button$1, AbsoluteCenter, Spinner, Span, IconButton, Portal, Dialog, useDisclosure, Flex, DialogRoot as DialogRoot$1, DialogBackdrop, DialogTrigger as DialogTrigger$1, DialogContent as DialogContent$1, DialogCloseTrigger as DialogCloseTrigger$1, DialogHeader as DialogHeader$1, DialogTitle as DialogTitle$1, DialogBody as DialogBody$1, DialogFooter as DialogFooter$1, Text, Menu, Tag as Tag$1, Grid, Image, Card, DataList, Checkbox as Checkbox$1, Table as Table$1, Box, Tooltip as Tooltip$1, Icon, MenuRoot as MenuRoot$1, MenuTrigger as MenuTrigger$1, EmptyState as EmptyState$1, VStack, List, Input, Slider as Slider$1, HStack, For, RadioGroup as RadioGroup$1, createRecipeContext, createContext as createContext$1, Pagination, usePaginationContext, Switch as Switch$1, Group, InputElement, Popover, RadioCard, Field as Field$1, NumberInput, Accordion, CheckboxCard as CheckboxCard$1, Show, Heading, Alert, Center } from '@chakra-ui/react';
3
3
  import { AiOutlineColumnWidth } from 'react-icons/ai';
4
- import { MdFilterAlt, MdOutlineMoveDown, MdOutlineSort, MdOutlineViewColumn, MdFilterListAlt, MdPushPin, MdCancel, MdClear, MdArrowUpward, MdArrowDownward, MdFirstPage, MdArrowBack, MdArrowForward, MdLastPage, MdOutlineChecklist, MdClose, MdSearch } from 'react-icons/md';
5
4
  import * as React from 'react';
6
- import { createContext, useContext, useEffect, useState, useRef } from 'react';
7
- import { LuX, LuCheck, LuChevronRight } from 'react-icons/lu';
5
+ import React__default, { createContext, useContext, useEffect, useState, useRef } from 'react';
6
+ import { MdFilterAlt, MdOutlineMoveDown, MdOutlineSort, MdOutlineViewColumn, MdFilterListAlt, MdPushPin, MdCancel, MdClear, MdArrowUpward, MdArrowDownward, MdOutlineChecklist, MdClose, MdSearch } from 'react-icons/md';
7
+ import { LuX, LuCheck, LuChevronRight, LuChevronDown } from 'react-icons/lu';
8
8
  import { FaUpDown, FaGripLinesVertical } from 'react-icons/fa6';
9
9
  import { BiDownArrow, BiUpArrow } from 'react-icons/bi';
10
10
  import { CgClose } from 'react-icons/cg';
11
11
  import { IoMdEye, IoMdCheckbox } from 'react-icons/io';
12
- import { makeStateUpdater, functionalUpdate, useReactTable, getCoreRowModel, getFilteredRowModel, getSortedRowModel, getPaginationRowModel, flexRender } from '@tanstack/react-table';
12
+ import { makeStateUpdater, functionalUpdate, useReactTable, getCoreRowModel, getFilteredRowModel, getSortedRowModel, getPaginationRowModel, flexRender, createColumnHelper } from '@tanstack/react-table';
13
13
  import { rankItem } from '@tanstack/match-sorter-utils';
14
14
  import { BsExclamationCircleFill } from 'react-icons/bs';
15
15
  import { GrAscend, GrDescend } from 'react-icons/gr';
16
16
  import { IoReload } from 'react-icons/io5';
17
- import { HiColorSwatch } from 'react-icons/hi';
17
+ import { HiColorSwatch, HiOutlineInformationCircle } from 'react-icons/hi';
18
+ import { HiMiniEllipsisHorizontal, HiChevronLeft, HiChevronRight } from 'react-icons/hi2';
18
19
  import { monitorForElements, draggable, dropTargetForElements } from '@atlaskit/pragmatic-drag-and-drop/element/adapter';
19
20
  import invariant from 'tiny-invariant';
20
21
  import axios from 'axios';
22
+ import { useFormContext, useForm, FormProvider } from 'react-hook-form';
23
+ import { useQuery, QueryClient, QueryClientProvider } from '@tanstack/react-query';
24
+ import dayjs from 'dayjs';
25
+ import Dayzed from 'dayzed';
26
+
27
+ const TableContext = createContext({
28
+ table: {},
29
+ refreshData: () => { },
30
+ globalFilter: "",
31
+ setGlobalFilter: () => { },
32
+ loading: false,
33
+ hasError: false,
34
+ });
35
+
36
+ const useDataTableContext = () => {
37
+ const { table, refreshData, globalFilter, setGlobalFilter, loading, hasError, } = useContext(TableContext);
38
+ return {
39
+ table,
40
+ refreshData,
41
+ globalFilter,
42
+ setGlobalFilter,
43
+ loading,
44
+ hasError,
45
+ };
46
+ };
47
+
48
+ const Button = React.forwardRef(function Button(props, ref) {
49
+ const { loading, disabled, loadingText, children, ...rest } = props;
50
+ return (jsx(Button$1, { disabled: loading || disabled, ref: ref, ...rest, children: loading && !loadingText ? (jsxs(Fragment, { children: [jsx(AbsoluteCenter, { display: "inline-flex", children: jsx(Spinner, { size: "inherit", color: "inherit" }) }), jsx(Span, { opacity: 0, children: children })] })) : loading && loadingText ? (jsxs(Fragment, { children: [jsx(Spinner, { size: "inherit", color: "inherit" }), loadingText] })) : (children) }));
51
+ });
21
52
 
22
53
  const DensityToggleButton = ({ text, icon = jsx(AiOutlineColumnWidth, {}), }) => {
23
54
  const { table } = useDataTableContext();
24
- return (jsxs(Fragment, { children: [!!text === false && (jsx(IconButton, { variant: "ghost", "aria-label": "Toggle Density", icon: icon, onClick: () => {
55
+ return (jsxs(Fragment, { children: [!!text === false && (jsx(IconButton, { variant: "ghost", "aria-label": "Toggle Density", onClick: () => {
25
56
  table.toggleDensity();
26
- } })), !!text !== false && (jsx(Button$1, { leftIcon: icon, variant: "ghost", "aria-label": "Toggle Density", onClick: () => {
57
+ }, children: icon })), !!text !== false && (jsxs(Button, { variant: "ghost", "aria-label": "Toggle Density", onClick: () => {
27
58
  table.toggleDensity();
28
- }, children: text }))] }));
59
+ }, children: [icon, text] }))] }));
29
60
  };
30
61
 
31
62
  const CloseButton = React.forwardRef(function CloseButton(props, ref) {
@@ -58,27 +89,6 @@ const EditOrderButton = ({ text, icon = jsx(MdOutlineMoveDown, {}), title = "Cha
58
89
  return (jsx(Fragment, { children: jsxs(DialogRoot$1, { size: "cover", children: [jsx(DialogBackdrop, {}), jsx(DialogTrigger$1, { children: jsxs(Button$1, { variant: "ghost", children: [icon, text] }) }), jsxs(DialogContent$1, { children: [jsx(DialogCloseTrigger$1, {}), jsxs(DialogHeader$1, { children: [jsx(DialogTitle$1, {}), title] }), jsx(DialogBody$1, { children: jsx(Flex, { flexFlow: "column", gap: "0.25rem", children: jsx(TableOrderer, {}) }) }), jsx(DialogFooter$1, {})] })] }) }));
59
90
  };
60
91
 
61
- const TableContext = createContext({
62
- table: {},
63
- refreshData: () => { },
64
- globalFilter: "",
65
- setGlobalFilter: () => { },
66
- loading: false,
67
- hasError: false,
68
- });
69
-
70
- const useDataTableContext = () => {
71
- const { table, refreshData, globalFilter, setGlobalFilter, loading, hasError, } = useContext(TableContext);
72
- return {
73
- table,
74
- refreshData,
75
- globalFilter,
76
- setGlobalFilter,
77
- loading,
78
- hasError,
79
- };
80
- };
81
-
82
92
  const TableSorter = () => {
83
93
  const { table } = useDataTableContext();
84
94
  return (jsx(Fragment, { children: table.getHeaderGroups().map((headerGroup) => (jsx(Fragment, { children: headerGroup.headers.map((header) => {
@@ -167,6 +177,49 @@ const RowCountText = () => {
167
177
  return jsx(Text, { children: table.getRowCount() });
168
178
  };
169
179
 
180
+ const Tag = React.forwardRef(function Tag(props, ref) {
181
+ const { startElement, endElement, onClose, closable = !!onClose, children, ...rest } = props;
182
+ return (jsxs(Tag$1.Root, { ref: ref, ...rest, children: [startElement && (jsx(Tag$1.StartElement, { children: startElement })), jsx(Tag$1.Label, { children: children }), endElement && (jsx(Tag$1.EndElement, { children: endElement })), closable && (jsx(Tag$1.EndElement, { children: jsx(Tag$1.CloseTrigger, { onClick: onClose }) }))] }));
183
+ });
184
+
185
+ const CardHeader = ({ row, imageColumnId = undefined, titleColumnId = undefined, tagColumnId = undefined, tagIcon = undefined, showTag = true, imageProps = {}, }) => {
186
+ if (!!row.original === false) {
187
+ return jsx(Fragment, {});
188
+ }
189
+ const isShowFirstColumn = !!titleColumnId || showTag;
190
+ return (jsxs(Grid, { templateRows: "auto auto", gap: "1rem", children: [!!imageColumnId && (jsx(Image, { width: "100%", src: row.original[imageColumnId], ...imageProps })), isShowFirstColumn && (jsxs(Flex, { gap: "0.5rem", flexFlow: "wrap", children: [!!titleColumnId && (jsx(Text, { fontWeight: "bold", fontSize: "large", children: row.original[titleColumnId] })), showTag && (jsx(Tag, { fontSize: "large", startElement: tagIcon && tagIcon({}), children: row.original[tagColumnId] }))] }))] }));
191
+ };
192
+
193
+ const snakeToLabel = (str) => {
194
+ return str
195
+ .split("_") // Split by underscore
196
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()) // Capitalize each word
197
+ .join(" "); // Join with space
198
+ };
199
+
200
+ const DataDisplay = ({ variant = "" }) => {
201
+ const { table } = useContext(TableContext);
202
+ if (variant == "horizontal") {
203
+ return (jsx(Flex, { flexFlow: "column", gap: "1", children: table.getRowModel().rows.map((row) => {
204
+ return (jsx(Card.Root, { children: jsx(Card.Body, { children: jsx(DataList.Root, { gap: 4, padding: 4, display: "grid", variant: "subtle", orientation: "horizontal", overflow: 'auto', children: row.getVisibleCells().map((cell) => {
205
+ return (jsxs(DataList.Item, { children: [jsx(DataList.ItemLabel, { children: snakeToLabel(cell.column.id) }), jsx(DataList.ItemValue, { children: `${cell.getValue()}` })] }, cell.id));
206
+ }) }) }) }, `chakra-table-card-${row.id}`));
207
+ }) }));
208
+ }
209
+ if (variant == "stats") {
210
+ return (jsx(Flex, { flexFlow: "column", gap: "1", children: table.getRowModel().rows.map((row) => {
211
+ return (jsx(Card.Root, { children: jsx(Card.Body, { children: jsx(DataList.Root, { gap: 4, padding: 4, display: "flex", flexFlow: "row", variant: "subtle", overflow: 'auto', children: row.getVisibleCells().map((cell) => {
212
+ return (jsxs(DataList.Item, { display: "flex", justifyContent: "center", alignItems: "center", flex: "1 0 10rem", children: [jsx(DataList.ItemLabel, { children: snakeToLabel(cell.column.id) }), jsx(DataList.ItemValue, { children: `${cell.getValue()}` })] }, cell.id));
213
+ }) }) }) }, `chakra-table-card-${row.id}`));
214
+ }) }));
215
+ }
216
+ return (jsx(Flex, { flexFlow: "column", gap: "1", children: table.getRowModel().rows.map((row) => {
217
+ return (jsx(Card.Root, { children: jsx(Card.Body, { children: jsx(DataList.Root, { gap: 4, padding: 4, display: "grid", variant: "subtle", gridTemplateColumns: "repeat(auto-fit, minmax(20rem, 1fr))", children: row.getVisibleCells().map((cell) => {
218
+ return (jsxs(DataList.Item, { children: [jsx(DataList.ItemLabel, { children: snakeToLabel(cell.column.id) }), jsx(DataList.ItemValue, { children: `${cell.getValue()}` })] }, cell.id));
219
+ }) }) }) }, `chakra-table-card-${row.id}`));
220
+ }) }));
221
+ };
222
+
170
223
  // Reference: https://tanstack.com/table/latest/docs/framework/react/examples/custom-features
171
224
  // TypeScript setup for our new feature with all of the same type-safety as stock TanStack Table features
172
225
  // end of TS setup!
@@ -300,10 +353,10 @@ const DataTable = ({ columns, data, enableRowSelection = true, enableMultiRowSel
300
353
  });
301
354
  useEffect(() => {
302
355
  setColumnOrder(table.getAllLeafColumns().map((column) => column.id));
303
- }, []);
356
+ }, [table, setColumnOrder]);
304
357
  useEffect(() => {
305
358
  onRowSelect(table.getState().rowSelection, data);
306
- }, [table.getState().rowSelection]);
359
+ }, [data, onRowSelect, table]);
307
360
  return (jsx(TableContext.Provider, { value: {
308
361
  table: { ...table },
309
362
  refreshData: () => {
@@ -319,7 +372,7 @@ const DataTable = ({ columns, data, enableRowSelection = true, enableMultiRowSel
319
372
  const DataTableServer = ({ columns, enableRowSelection = true, enableMultiRowSelection = true, enableSubRowSelection = true, onRowSelect = () => { }, columnOrder, columnFilters, columnVisibility, density, globalFilter, pagination, sorting, rowSelection, setPagination, setSorting, setColumnFilters, setRowSelection, setGlobalFilter, setColumnOrder, setDensity, setColumnVisibility, data, loading, hasError, refreshData, children, }) => {
320
373
  const table = useReactTable({
321
374
  _features: [DensityFeature],
322
- data: data.results,
375
+ data: data.data,
323
376
  rowCount: data.count ?? 0,
324
377
  columns: columns,
325
378
  getCoreRowModel: getCoreRowModel(),
@@ -368,7 +421,7 @@ const DataTableServer = ({ columns, enableRowSelection = true, enableMultiRowSel
368
421
  setColumnOrder(table.getAllLeafColumns().map((column) => column.id));
369
422
  }, []);
370
423
  useEffect(() => {
371
- onRowSelect(table.getState().rowSelection, data.results);
424
+ onRowSelect(table.getState().rowSelection, data.data);
372
425
  }, [table.getState().rowSelection]);
373
426
  useEffect(() => {
374
427
  table.resetPagination();
@@ -383,27 +436,6 @@ const DataTableServer = ({ columns, enableRowSelection = true, enableMultiRowSel
383
436
  }, children: children }));
384
437
  };
385
438
 
386
- const Tag = React.forwardRef(function Tag(props, ref) {
387
- const { startElement, endElement, onClose, closable = !!onClose, children, ...rest } = props;
388
- return (jsxs(Tag$1.Root, { ref: ref, ...rest, children: [startElement && (jsx(Tag$1.StartElement, { children: startElement })), jsx(Tag$1.Label, { children: children }), endElement && (jsx(Tag$1.EndElement, { children: endElement })), closable && (jsx(Tag$1.EndElement, { children: jsx(Tag$1.CloseTrigger, { onClick: onClose }) }))] }));
389
- });
390
-
391
- const DefaultCard = ({ row, imageColumnId = undefined, titleColumnId = undefined, tagColumnId = undefined, tagIcon = undefined, showTag = true, }) => {
392
- if (!!row.original === false) {
393
- return jsx(Fragment, {});
394
- }
395
- // const imageIdExists = Object.keys(row.original).some((key) => {
396
- // return key === imageColumnId;
397
- // });
398
- // const titleIdExists = Object.keys(row.original).some((key) => {
399
- // return key === titleColumnId;
400
- // });
401
- // const tagIdExists = Object.keys(row.original).some((key) => {
402
- // return key === tagColumnId;
403
- // });
404
- return (jsxs(Grid, { templateRows: "auto auto", gap: "1rem", children: [jsx(Flex, { justifyContent: "center", alignItems: "center", children: jsx(Image, { src: row.original[imageColumnId] }) }), jsxs(Flex, { gap: "0.5rem", flexFlow: "wrap", children: [jsx(Text, { fontWeight: "bold", fontSize: "large", children: row.original[titleColumnId] }), showTag && (jsx(Tag, { fontSize: "large", startElement: tagIcon && tagIcon({}), children: row.original[tagColumnId] }))] })] }));
405
- };
406
-
407
439
  const Checkbox = React.forwardRef(function Checkbox(props, ref) {
408
440
  const { icon, children, inputProps, rootRef, ...rest } = props;
409
441
  return (jsxs(Checkbox$1.Root, { ref: rootRef, ...rest, children: [jsx(Checkbox$1.HiddenInput, { ref: ref, ...inputProps }), jsx(Checkbox$1.Control, { children: icon || jsx(Checkbox$1.Indicator, {}) }), children != null && (jsx(Checkbox$1.Label, { children: children }))] }));
@@ -545,11 +577,6 @@ const TableFooter = ({ pinnedBgColor = { light: "gray.50", dark: "gray.700" }, s
545
577
  jsx(Fragment, {})), header.column.getIsSorted() === "asc" && (jsx(BiUpArrow, {})), header.column.getIsSorted() === "desc" && (jsx(BiDownArrow, {}))] })) })] }) }) }) }) }, `chakra-table-footer-${footerGroup.id}`)))] }, `chakra-table-footergroup-${footerGroup.id}`))) }));
546
578
  };
547
579
 
548
- const Button = React.forwardRef(function Button(props, ref) {
549
- const { loading, disabled, loadingText, children, ...rest } = props;
550
- return (jsx(Button$1, { disabled: loading || disabled, ref: ref, ...rest, children: loading && !loadingText ? (jsxs(Fragment, { children: [jsx(AbsoluteCenter, { display: "inline-flex", children: jsx(Spinner, { size: "inherit", color: "inherit" }) }), jsx(Span, { opacity: 0, children: children })] })) : loading && loadingText ? (jsxs(Fragment, { children: [jsx(Spinner, { size: "inherit", color: "inherit" }), loadingText] })) : (children) }));
551
- });
552
-
553
580
  const TableHeader = ({ canResize, pinnedBgColor = { light: "gray.50", dark: "gray.700" }, showSelector = false, isSticky = true, alwaysShowSelector = true, tHeadProps = {}, }) => {
554
581
  const { table } = useDataTableContext();
555
582
  const SELECTION_BOX_WIDTH = 20;
@@ -656,9 +683,9 @@ const ReloadButton = ({ text = "Reload", variant = "icon", }) => {
656
683
  refreshData();
657
684
  }, "aria-label": "refresh", children: jsx(IoReload, {}) }) }));
658
685
  }
659
- return (jsx(Button, { variant: "ghost", leftIcon: jsx(IoReload, {}), onClick: () => {
686
+ return (jsxs(Button, { variant: "ghost", onClick: () => {
660
687
  refreshData();
661
- }, children: text }));
688
+ }, children: [jsx(IoReload, {}), " ", text] }));
662
689
  };
663
690
 
664
691
  const EmptyState = React.forwardRef(function EmptyState(props, ref) {
@@ -675,17 +702,20 @@ const Table = ({ children, emptyComponent = EmptyResult, ...props }) => {
675
702
  return (jsx(Table$1.Root, { stickyHeader: true, variant: "outline", width: table.getCenterTotalSize(), ...props, children: children }));
676
703
  };
677
704
 
678
- const TableCardContainer = ({ children, ...props }) => {
679
- return (jsx(Grid, { gridTemplateColumns: ["1fr", "1fr 1fr", "1fr 1fr 1fr"], gap: "0.5rem", ...props, children: children }));
705
+ const TableCardContainer = ({ children, variant = "", ...props }) => {
706
+ if (variant === "carousel") {
707
+ return (jsx(Flex, { overflow: "scroll", gap: "1rem", children: children }));
708
+ }
709
+ return (jsx(Grid, { gridTemplateColumns: "repeat(auto-fit, minmax(20rem, 1fr))", gap: "0.5rem", ...props, children: children }));
680
710
  };
681
711
 
682
712
  const DefaultCardTitle = () => {
683
713
  return jsx(Fragment, {});
684
714
  };
685
- const TableCards = ({ isSelectable = false, showDisplayNameOnly = false, renderTitle = DefaultCardTitle, cardBodyProps = {} }) => {
715
+ const TableCards = ({ isSelectable = false, showDisplayNameOnly = false, renderTitle = DefaultCardTitle, cardBodyProps = {}, }) => {
686
716
  const { table } = useContext(TableContext);
687
717
  return (jsx(Fragment, { children: table.getRowModel().rows.map((row) => {
688
- return (jsx(Card.Root, { children: jsxs(Card.Body, { display: "flex", flexFlow: "column", gap: "0.5rem", ...cardBodyProps, children: [isSelectable && (jsx(Checkbox, { isChecked: row.getIsSelected(),
718
+ return (jsx(Card.Root, { flex: "1 0 20rem", children: jsxs(Card.Body, { display: "flex", flexFlow: "column", gap: "0.5rem", ...cardBodyProps, children: [isSelectable && (jsx(Checkbox, { isChecked: row.getIsSelected(),
689
719
  disabled: !row.getCanSelect(),
690
720
  // indeterminate: row.getIsSomeSelected(),
691
721
  onChange: row.getToggleSelectedHandler() })), renderTitle(row), jsx(Grid, { templateColumns: "auto 1fr", gap: "1rem", children: row.getVisibleCells().map((cell) => {
@@ -736,9 +766,9 @@ const SliderMarks = React.forwardRef(function SliderMarks(props, ref) {
736
766
  });
737
767
 
738
768
  const RangeFilter = ({ range, setRange, defaultValue, min, max, step, }) => {
739
- return (jsx(Box, { p: 8, children: jsx(Slider, { width: "full", min: min, max: max, defaultValue: defaultValue, step: step, name: `Selected Range: ${range[0]} - ${range[1]}`,
740
- // value={field.value}
741
- onValueChange: (val) => setRange(val.value) }) }));
769
+ return (jsxs(Flex, { p: 2, gap: 2, flexFlow: 'column', children: [jsx(Text, { children: `${range[0]} - ${range[1]}` }), jsx(Slider, { width: "full", min: min, max: max, defaultValue: defaultValue, step: step, name: `Selected Range: ${range[0]} - ${range[1]}`,
770
+ // value={field.value}
771
+ onValueChange: (val) => setRange(val.value) })] }));
742
772
  };
743
773
 
744
774
  const TagFilter = ({ availableTags, selectedTags, onTagChange, }) => {
@@ -767,9 +797,9 @@ const Filter = ({ column }) => {
767
797
  // items: filterOptions,
768
798
  // });
769
799
  if (column.columns.length > 0) {
770
- return (jsxs(Flex, { flexFlow: "column", gap: "0.25rem", children: [jsx(Text, { children: displayName }), column.columns.map((column) => {
771
- return jsx(Filter, { column: column }, column.id);
772
- })] }, column.id));
800
+ return (jsxs(Flex, { flexFlow: "column", gap: 1, children: [jsx(Text, { children: displayName }), jsx(Grid, { gridTemplateColumns: "repeat(auto-fit, minmax(20rem, 1fr))", gap: 1, children: column.columns.map((column) => {
801
+ return jsx(Filter, { column: column }, column.id);
802
+ }) }, column.id)] }));
773
803
  }
774
804
  if (!column.getCanFilter()) {
775
805
  return jsx(Fragment, {});
@@ -777,7 +807,7 @@ const Filter = ({ column }) => {
777
807
  if (filterVariant === "select") {
778
808
  return (jsxs(Flex, { flexFlow: "column", gap: "0.25rem", children: [jsx(Text, { children: displayName }), jsx(RadioGroup, { value: column.getFilterValue() ? String(column.getFilterValue()) : "", onValueChange: (details) => {
779
809
  column.setFilterValue(details.value);
780
- }, children: jsx(Flex, { flexFlow: 'wrap', gap: '0.5rem', children: filterOptions.map((item) => (jsx(Radio, { value: item, children: item }, item))) }) })] }, column.id));
810
+ }, children: jsx(Flex, { flexFlow: "wrap", gap: "0.5rem", children: filterOptions.map((item) => (jsx(Radio, { value: item, children: item }, item))) }) })] }, column.id));
781
811
  }
782
812
  if (filterVariant === "tag") {
783
813
  return (jsxs(Flex, { flexFlow: "column", gap: "0.25rem", children: [jsx(Text, { children: displayName }), jsx(TagFilter, { availableTags: filterOptions, selectedTags: (column.getFilterValue() ?? []), onTagChange: (tags) => {
@@ -807,10 +837,10 @@ const Filter = ({ column }) => {
807
837
  step: 1,
808
838
  defaultValue: [4, 50],
809
839
  };
810
- return (jsx(RangeFilter, { range: filterValue, setRange: function (value) {
811
- // throw new Error("Function not implemented.");
812
- column.setFilterValue(value);
813
- }, defaultValue: defaultValue, min: min, max: max, step: step }));
840
+ return (jsxs(Flex, { flexFlow: "column", gap: "0.25rem", children: [jsx(Text, { children: displayName }), jsx(RangeFilter, { range: filterValue, setRange: function (value) {
841
+ // throw new Error("Function not implemented.");
842
+ column.setFilterValue(value);
843
+ }, defaultValue: defaultValue, min: min, max: max, step: step })] }, column.id));
814
844
  }
815
845
  if (filterVariant === "dateRange") {
816
846
  const [start, end] = column.getFilterValue() ?? [
@@ -914,25 +944,91 @@ const TableOrderer = () => {
914
944
  return (jsx(Fragment, { children: jsx(ColumnOrderChanger, { columns: table.getState().columnOrder }) }));
915
945
  };
916
946
 
947
+ const { withContext } = createRecipeContext({ key: "button" });
948
+ // Replace "a" with your framework's link component
949
+ const LinkButton = withContext("a");
950
+
951
+ const [RootPropsProvider, useRootProps] = createContext$1({
952
+ name: "RootPropsProvider",
953
+ });
954
+ const variantMap = {
955
+ outline: { default: "ghost", ellipsis: "plain", current: "outline" },
956
+ solid: { default: "outline", ellipsis: "outline", current: "solid" },
957
+ subtle: { default: "ghost", ellipsis: "plain", current: "subtle" },
958
+ };
959
+ const PaginationRoot = React.forwardRef(function PaginationRoot(props, ref) {
960
+ const { size = "sm", variant = "outline", getHref, ...rest } = props;
961
+ return (jsx(RootPropsProvider, { value: { size, variantMap: variantMap[variant], getHref }, children: jsx(Pagination.Root, { ref: ref, type: getHref ? "link" : "button", ...rest }) }));
962
+ });
963
+ const PaginationEllipsis = React.forwardRef(function PaginationEllipsis(props, ref) {
964
+ const { size, variantMap } = useRootProps();
965
+ return (jsx(Pagination.Ellipsis, { ref: ref, ...props, asChild: true, children: jsx(Button$1, { as: "span", variant: variantMap.ellipsis, size: size, children: jsx(HiMiniEllipsisHorizontal, {}) }) }));
966
+ });
967
+ const PaginationItem = React.forwardRef(function PaginationItem(props, ref) {
968
+ const { page } = usePaginationContext();
969
+ const { size, variantMap, getHref } = useRootProps();
970
+ const current = page === props.value;
971
+ const variant = current ? variantMap.current : variantMap.default;
972
+ if (getHref) {
973
+ return (jsx(LinkButton, { href: getHref(props.value), variant: variant, size: size, children: props.value }));
974
+ }
975
+ return (jsx(Pagination.Item, { ref: ref, ...props, asChild: true, children: jsx(Button$1, { variant: variant, size: size, children: props.value }) }));
976
+ });
977
+ const PaginationPrevTrigger = React.forwardRef(function PaginationPrevTrigger(props, ref) {
978
+ const { size, variantMap, getHref } = useRootProps();
979
+ const { previousPage } = usePaginationContext();
980
+ if (getHref) {
981
+ return (jsx(LinkButton, { href: previousPage != null ? getHref(previousPage) : undefined, variant: variantMap.default, size: size, children: jsx(HiChevronLeft, {}) }));
982
+ }
983
+ return (jsx(Pagination.PrevTrigger, { ref: ref, asChild: true, ...props, children: jsx(IconButton, { variant: variantMap.default, size: size, children: jsx(HiChevronLeft, {}) }) }));
984
+ });
985
+ const PaginationNextTrigger = React.forwardRef(function PaginationNextTrigger(props, ref) {
986
+ const { size, variantMap, getHref } = useRootProps();
987
+ const { nextPage } = usePaginationContext();
988
+ if (getHref) {
989
+ return (jsx(LinkButton, { href: nextPage != null ? getHref(nextPage) : undefined, variant: variantMap.default, size: size, children: jsx(HiChevronRight, {}) }));
990
+ }
991
+ return (jsx(Pagination.NextTrigger, { ref: ref, asChild: true, ...props, children: jsx(IconButton, { variant: variantMap.default, size: size, children: jsx(HiChevronRight, {}) }) }));
992
+ });
993
+ const PaginationItems = (props) => {
994
+ return (jsx(Pagination.Context, { children: ({ pages }) => pages.map((page, index) => {
995
+ return page.type === "ellipsis" ? (jsx(PaginationEllipsis, { index: index, ...props }, index)) : (jsx(PaginationItem, { type: "page", value: page.value, ...props }, index));
996
+ }) }));
997
+ };
998
+ const PaginationPageText = React.forwardRef(function PaginationPageText(props, ref) {
999
+ const { format = "compact", ...rest } = props;
1000
+ const { page, totalPages, pageRange, count } = usePaginationContext();
1001
+ const content = React.useMemo(() => {
1002
+ if (format === "short")
1003
+ return `${page} / ${totalPages}`;
1004
+ if (format === "compact")
1005
+ return `${page} of ${totalPages}`;
1006
+ return `${pageRange.start + 1} - ${Math.min(pageRange.end, count)} of ${count}`;
1007
+ }, [format, page, totalPages, pageRange, count]);
1008
+ return (jsx(Text, { fontWeight: "medium", ref: ref, ...rest, children: content }));
1009
+ });
1010
+
917
1011
  const TablePagination = () => {
918
- const { firstPage, getCanPreviousPage, previousPage, getState, nextPage, getCanNextPage, lastPage, } = useDataTableContext().table;
919
- return (jsxs(Group, { attached: true, children: [jsx(IconButton, { onClick: () => firstPage(), disabled: !getCanPreviousPage(), "aria-label": "first-page", variant: "ghost", children: jsx(MdFirstPage, {}) }), jsx(IconButton, { onClick: () => previousPage(), disabled: !getCanPreviousPage(), "aria-label": "previous-page", variant: "ghost", children: jsx(MdArrowBack, {}) }), jsx(Button, { variant: "ghost", onClick: () => { }, disabled: !getCanPreviousPage(), children: getState().pagination.pageIndex + 1 }), jsx(IconButton, { onClick: () => nextPage(), disabled: !getCanNextPage(), "aria-label": "next-page", variant: "ghost", children: jsx(MdArrowForward, {}) }), jsx(IconButton, { onClick: () => lastPage(), disabled: !getCanNextPage(), "aria-label": "last-page", variant: "ghost", children: jsx(MdLastPage, {}) })] }));
1012
+ const { table } = useDataTableContext();
1013
+ return (jsx(PaginationRoot, { page: table.getState().pagination.pageIndex + 1, count: table.getRowCount(), pageSize: table.getState().pagination.pageSize, onPageChange: (e) => {
1014
+ table.setPageIndex(e.page - 1);
1015
+ }, children: jsxs(HStack, { children: [jsx(PaginationPageText, { format: "long" }), jsx(PaginationPrevTrigger, {}), jsx(PaginationItems, {}), jsx(PaginationNextTrigger, {})] }) }));
920
1016
  };
921
1017
 
922
1018
  const SelectAllRowsToggle = ({ selectAllIcon = jsx(MdOutlineChecklist, {}), clearAllIcon = jsx(MdClear, {}), selectAllText = "", clearAllText = "", }) => {
923
1019
  const { table } = useDataTableContext();
924
- return (jsxs(Fragment, { children: [!!selectAllText === false && (jsx(IconButton, { icon: table.getIsAllRowsSelected() ? clearAllIcon : selectAllIcon, variant: "ghost", "aria-label": table.getIsAllRowsSelected() ? clearAllText : selectAllText, onClick: (event) => {
1020
+ return (jsxs(Fragment, { children: [!!selectAllText === false && (jsx(IconButton, { variant: "ghost", "aria-label": table.getIsAllRowsSelected() ? clearAllText : selectAllText, onClick: (event) => {
925
1021
  table.getToggleAllRowsSelectedHandler()(event);
926
- } })), !!selectAllText !== false && (jsx(Button$1, { leftIcon: table.getIsAllRowsSelected() ? clearAllIcon : selectAllIcon, variant: "ghost", onClick: (event) => {
1022
+ }, children: table.getIsAllRowsSelected() ? clearAllIcon : selectAllIcon })), !!selectAllText !== false && (jsxs(Button$1, { variant: "ghost", onClick: (event) => {
927
1023
  table.getToggleAllRowsSelectedHandler()(event);
928
- }, children: table.getIsAllRowsSelected() ? clearAllText : selectAllText }))] }));
1024
+ }, children: [table.getIsAllRowsSelected() ? clearAllIcon : selectAllIcon, table.getIsAllRowsSelected() ? clearAllText : selectAllText] }))] }));
929
1025
  };
930
1026
 
931
1027
  const TableSelector = () => {
932
1028
  const { table } = useContext(TableContext);
933
- return (jsxs(Fragment, { children: [table.getSelectedRowModel().rows.length > 0 && (jsxs(Button$1, { onClick: () => { }, variant: "ghost", display: "flex", gap: "0.25rem", children: [jsx(Box, { fontSize: "sm", children: `${table.getSelectedRowModel().rows.length}` }), jsx(Icon, { as: IoMdCheckbox })] })), !table.getIsAllPageRowsSelected() && jsx(SelectAllRowsToggle, {}), table.getSelectedRowModel().rows.length > 0 && (jsx(IconButton, { variant: "ghost", icon: jsx(Icon, { as: MdClear }), onClick: () => {
1029
+ return (jsxs(Fragment, { children: [table.getSelectedRowModel().rows.length > 0 && (jsxs(Button$1, { onClick: () => { }, variant: "ghost", display: "flex", gap: "0.25rem", children: [jsx(Box, { fontSize: "sm", children: `${table.getSelectedRowModel().rows.length}` }), jsx(Icon, { as: IoMdCheckbox })] })), !table.getIsAllPageRowsSelected() && jsx(SelectAllRowsToggle, {}), table.getSelectedRowModel().rows.length > 0 && (jsx(IconButton, { variant: "ghost", onClick: () => {
934
1030
  table.resetRowSelection();
935
- }, "aria-label": "reset selection" }))] }));
1031
+ }, "aria-label": "reset selection", children: jsx(MdClear, {}) }))] }));
936
1032
  };
937
1033
 
938
1034
  const Switch = React.forwardRef(function Switch(props, ref) {
@@ -1035,7 +1131,11 @@ const useDataFromUrl = ({ url, params = {}, disableFirstFetch = false, onFetchSu
1035
1131
  const [hasError, setHasError] = useState(false);
1036
1132
  const [data, setData] = useState(defaultData);
1037
1133
  const [timer, setTimer] = useState();
1038
- const refreshData = async ({ debounce, delay } = { debounce: false, delay: 1000 }) => {
1134
+ const refreshData = async (config = {
1135
+ debounce: false,
1136
+ delay: 1000,
1137
+ }) => {
1138
+ const { debounce, delay } = config;
1039
1139
  if (debounce) {
1040
1140
  await debouncedGetData(delay);
1041
1141
  return;
@@ -1162,30 +1262,25 @@ const useDataTableServer = ({ url, onFetchSuccess = () => { }, default: { sortin
1162
1262
  const { data, loading, hasError, refreshData } = useDataFromUrl({
1163
1263
  url: url,
1164
1264
  defaultData: {
1165
- success: false,
1166
- results: [],
1265
+ data: [],
1167
1266
  count: 0,
1168
1267
  },
1169
1268
  params: {
1170
- pagination: JSON.stringify({
1171
- offset: pagination.pageIndex * pagination.pageSize,
1172
- rows: pagination.pageSize,
1173
- }),
1174
- sorting: JSON.stringify(sorting.length > 0
1175
- ? { field: sorting[0].id, sort: sorting[0].desc ? "desc" : "asc" }
1176
- : {}),
1177
- where: JSON.stringify(columnFilters.reduce((accumulator, filter) => {
1269
+ offset: pagination.pageIndex * pagination.pageSize,
1270
+ limit: pagination.pageSize,
1271
+ sorting,
1272
+ where: columnFilters.reduce((accumulator, filter) => {
1178
1273
  const obj = {};
1179
1274
  obj[filter.id] = filter.value;
1180
1275
  return { ...accumulator, ...obj };
1181
- }, {})),
1276
+ }, {}),
1182
1277
  searching: globalFilter,
1183
1278
  },
1184
1279
  disableFirstFetch: true,
1185
1280
  onFetchSuccess: onFetchSuccess,
1186
1281
  });
1187
1282
  useEffect(() => {
1188
- refreshData({ debounce, debounceDelay });
1283
+ refreshData({ debounce, delay: debounceDelay });
1189
1284
  }, [pagination, sorting, columnFilters, globalFilter, url]);
1190
1285
  return {
1191
1286
  sorting,
@@ -1238,6 +1333,7 @@ const InputGroup = React.forwardRef(function InputGroup(props, ref) {
1238
1333
  ps: `calc(var(--input-height) - ${startOffset})`,
1239
1334
  }),
1240
1335
  ...(endElement && { pe: `calc(var(--input-height) - ${endOffset})` }),
1336
+ // @ts-expect-error chakra generated files
1241
1337
  ...children.props,
1242
1338
  }), endElement && (jsx(InputElement, { placement: "end", ...endElementProps, children: endElement }))] }));
1243
1339
  });
@@ -1249,4 +1345,899 @@ const GlobalFilter = () => {
1249
1345
  } }) }) }));
1250
1346
  };
1251
1347
 
1252
- export { DataTable, DataTableServer, DefaultCard, DefaultCardTitle, DefaultTable, DensityToggleButton, EditFilterButton, EditOrderButton, EditSortingButton, EditViewButton, FilterOptions, GlobalFilter, PageSizeControl, ReloadButton, ResetFilteringButton, ResetSelectionButton, ResetSortingButton, RowCountText, Table, TableBody, TableCardContainer, TableCards, TableComponent, TableControls, TableFilter, TableFilterTags, TableFooter, TableHeader, TableLoadingComponent, TableOrderer, TablePagination, TableSelector, TableSorter, TableViewer, TextCell, useDataFromUrl, useDataTable, useDataTableContext, useDataTableServer };
1348
+ const idListSanityCheck = (param, idList, properties) => {
1349
+ const allKeyExists = idList.every((key) => Object.keys(properties).some((column) => column == key));
1350
+ if (!allKeyExists) {
1351
+ const wrongKey = idList.find((key) => !Object.keys(properties).some((column) => column == key));
1352
+ throw new Error(`The key ${wrongKey} in ${param} does not exist in schema.`);
1353
+ }
1354
+ };
1355
+
1356
+ const widthSanityCheck = (widthList, ignoreList, properties) => {
1357
+ const widthListToolong = widthList.length > Object.keys(properties).length;
1358
+ if (widthListToolong) {
1359
+ throw new Error(`The width list is too long given from the number of properties.`);
1360
+ }
1361
+ const widthListToolongWithIgnore = widthList.length > Object.keys(properties).length - ignoreList.length;
1362
+ if (widthListToolongWithIgnore) {
1363
+ throw new Error(`The width list is too long given from the number of remaining properties after ignore some.`);
1364
+ }
1365
+ };
1366
+ const getColumns = ({ schema, ignore = [], width = [], meta = {}, defaultWidth = 400, }) => {
1367
+ const { properties } = schema;
1368
+ idListSanityCheck("ignore", ignore, properties);
1369
+ widthSanityCheck(width, ignore, properties);
1370
+ idListSanityCheck("meta", Object.keys(meta), properties);
1371
+ const keys = Object.keys(properties);
1372
+ const ignored = keys.filter((key) => {
1373
+ return !ignore.some((shouldIgnoreKey) => key === shouldIgnoreKey);
1374
+ });
1375
+ const columnHelper = createColumnHelper();
1376
+ // @ts-expect-error find type for unknown
1377
+ const columns = [
1378
+ ...ignored.map((column, index) => {
1379
+ return columnHelper.accessor(column, {
1380
+ cell: (props) => {
1381
+ // @ts-expect-error find type for unknown
1382
+ return jsx(TextCell, { children: props.row.original[column] });
1383
+ },
1384
+ header: (columnHeader) => {
1385
+ const displayName = columnHeader.column.columnDef.meta?.displayName ??
1386
+ snakeToLabel(column);
1387
+ return jsx("span", { children: displayName });
1388
+ },
1389
+ footer: (columnFooter) => {
1390
+ const displayName = columnFooter.column.columnDef.meta?.displayName ??
1391
+ snakeToLabel(column);
1392
+ return jsx("span", { children: displayName });
1393
+ },
1394
+ size: width[index] ?? defaultWidth,
1395
+ meta: Object.keys(meta).length > 0 ? meta[column] : {},
1396
+ });
1397
+ }),
1398
+ ];
1399
+ return columns;
1400
+ };
1401
+
1402
+ //@ts-expect-error TODO: find appropriate type
1403
+ const SchemaFormContext = createContext({
1404
+ schema: {},
1405
+ serverUrl: "",
1406
+ order: [],
1407
+ ignore: [],
1408
+ onSubmit: () => { },
1409
+ preLoadedValues: {},
1410
+ rowNumber: 0,
1411
+ displayText: {},
1412
+ });
1413
+
1414
+ const PopoverContent = React.forwardRef(function PopoverContent(props, ref) {
1415
+ const { portalled = true, portalRef, ...rest } = props;
1416
+ return (jsx(Portal, { disabled: !portalled, container: portalRef, children: jsx(Popover.Positioner, { children: jsx(Popover.Content, { ref: ref, ...rest }) }) }));
1417
+ });
1418
+ React.forwardRef(function PopoverArrow(props, ref) {
1419
+ return (jsx(Popover.Arrow, { ...props, ref: ref, children: jsx(Popover.ArrowTip, {}) }));
1420
+ });
1421
+ React.forwardRef(function PopoverCloseTrigger(props, ref) {
1422
+ return (jsx(Popover.CloseTrigger, { position: "absolute", top: "1", insetEnd: "1", ...props, asChild: true, ref: ref, children: jsx(CloseButton, { size: "sm" }) }));
1423
+ });
1424
+ const PopoverTitle = Popover.Title;
1425
+ Popover.Description;
1426
+ Popover.Footer;
1427
+ Popover.Header;
1428
+ const PopoverRoot = Popover.Root;
1429
+ const PopoverBody = Popover.Body;
1430
+ const PopoverTrigger = Popover.Trigger;
1431
+
1432
+ const RadioCardItem = React.forwardRef(function RadioCardItem(props, ref) {
1433
+ const { inputProps, label, description, addon, icon, indicator = jsx(RadioCard.ItemIndicator, {}), indicatorPlacement = "end", ...rest } = props;
1434
+ const hasContent = label || description || icon;
1435
+ const ContentWrapper = indicator ? RadioCard.ItemContent : React.Fragment;
1436
+ return (jsxs(RadioCard.Item, { ...rest, children: [jsx(RadioCard.ItemHiddenInput, { ref: ref, ...inputProps }), jsxs(RadioCard.ItemControl, { children: [indicatorPlacement === "start" && indicator, hasContent && (jsxs(ContentWrapper, { children: [icon, label && jsx(RadioCard.ItemText, { children: label }), description && (jsx(RadioCard.ItemDescription, { children: description })), indicatorPlacement === "inside" && indicator] })), indicatorPlacement === "end" && indicator] }), addon && jsx(RadioCard.ItemAddon, { children: addon })] }));
1437
+ });
1438
+ const RadioCardRoot = RadioCard.Root;
1439
+ RadioCard.Label;
1440
+ RadioCard.ItemIndicator;
1441
+
1442
+ const Field = React.forwardRef(function Field(props, ref) {
1443
+ const { label, children, helperText, errorText, optionalText, ...rest } = props;
1444
+ return (jsxs(Field$1.Root, { ref: ref, ...rest, children: [label && (jsxs(Field$1.Label, { children: [label, jsx(Field$1.RequiredIndicator, { fallback: optionalText })] })), children, helperText && (jsx(Field$1.HelperText, { children: helperText })), errorText && (jsx(Field$1.ErrorText, { children: errorText }))] }));
1445
+ });
1446
+
1447
+ const useSchemaContext = () => {
1448
+ const { schema, serverUrl, order, ignore, onSubmit, preLoadedValues, rowNumber, displayText, } = useContext(SchemaFormContext);
1449
+ return {
1450
+ schema,
1451
+ serverUrl,
1452
+ order,
1453
+ ignore,
1454
+ onSubmit,
1455
+ preLoadedValues,
1456
+ rowNumber,
1457
+ displayText,
1458
+ };
1459
+ };
1460
+
1461
+ const getTableData = async ({ serverUrl, in_table, searching = '', where = [], limit = 10, }) => {
1462
+ if (serverUrl === undefined || serverUrl.length == 0) {
1463
+ throw new Error('The serverUrl is missing');
1464
+ }
1465
+ if (in_table === undefined || in_table.length == 0) {
1466
+ throw new Error('The in_table is missing');
1467
+ }
1468
+ const options = {
1469
+ method: "GET",
1470
+ url: `${serverUrl}/api/g/${in_table}`,
1471
+ headers: {
1472
+ Apikey: "YOUR_SECRET_TOKEN",
1473
+ "Content-Type": "application/json",
1474
+ },
1475
+ params: {
1476
+ searching,
1477
+ where,
1478
+ limit,
1479
+ },
1480
+ };
1481
+ try {
1482
+ const { data } = await axios.request(options);
1483
+ console.log(data);
1484
+ return data;
1485
+ }
1486
+ catch (error) {
1487
+ console.error(error);
1488
+ throw error;
1489
+ }
1490
+ };
1491
+
1492
+ const IdPicker = ({ column, in_table, column_ref, display_column, }) => {
1493
+ const { formState: { errors }, setValue, } = useFormContext();
1494
+ const { schema, serverUrl, displayText } = useSchemaContext();
1495
+ const { fieldRequired } = displayText;
1496
+ const { required } = schema;
1497
+ const isRequired = required?.some((columnId) => columnId === column);
1498
+ if (schema.properties == undefined) {
1499
+ throw new Error("schema properties when using DatePicker");
1500
+ }
1501
+ const { gridColumn, gridRow, title } = schema.properties[column];
1502
+ const [selectedId, setSelectedId] = useState();
1503
+ const [searchText, setSearchText] = useState();
1504
+ const [limit, setLimit] = useState(10);
1505
+ const [openSearchResult, setOpenSearchResult] = useState();
1506
+ const ref = useRef(null);
1507
+ const query = useQuery({
1508
+ queryKey: [`idpicker`, searchText, in_table, limit],
1509
+ queryFn: async () => {
1510
+ return await getTableData({
1511
+ serverUrl,
1512
+ searching: searchText ?? "",
1513
+ in_table: in_table,
1514
+ limit: limit,
1515
+ });
1516
+ },
1517
+ staleTime: 10000,
1518
+ });
1519
+ const { isLoading, isFetching, data, isPending, isError } = query;
1520
+ const dataList = data?.data ?? [];
1521
+ const count = data?.count ?? 0;
1522
+ const isDirty = (searchText?.length ?? 0) > 0;
1523
+ const onSearchChange = async (event) => {
1524
+ setSearchText(event.target.value);
1525
+ setLimit(10);
1526
+ };
1527
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1528
+ const getItemList = (data) => {
1529
+ return data.map((item) => {
1530
+ return {
1531
+ label: item[display_column],
1532
+ key: item[column_ref],
1533
+ value: item[column_ref],
1534
+ };
1535
+ });
1536
+ };
1537
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1538
+ const getIdMap = (data) => {
1539
+ return Object.fromEntries(data.map((item) => {
1540
+ return [
1541
+ item[column_ref],
1542
+ {
1543
+ ...item,
1544
+ },
1545
+ ];
1546
+ }));
1547
+ };
1548
+ const getSelectedName = () => {
1549
+ const selectedItem = getIdMap(dataList)[selectedId ?? ""];
1550
+ if (selectedItem == undefined) {
1551
+ return "";
1552
+ }
1553
+ return selectedItem[display_column];
1554
+ };
1555
+ if (selectedId != undefined) {
1556
+ return (jsx(Field, { label: `${title ?? snakeToLabel(column)}`, required: isRequired, gridColumn,
1557
+ gridRow, children: jsx(Tag, { closable: true, onClick: () => {
1558
+ setSelectedId(undefined);
1559
+ setValue(column, "");
1560
+ }, children: getSelectedName() }) }));
1561
+ }
1562
+ return (jsxs(Field, { label: `${title ?? snakeToLabel(column)}`, required: isRequired, alignItems: "stretch", gridColumn,
1563
+ gridRow, children: [jsx(Input, { placeholder: "Type to search", onChange: (event) => {
1564
+ onSearchChange(event);
1565
+ setOpenSearchResult(true);
1566
+ }, autoComplete: "off", ref: ref }), jsxs(PopoverRoot, { open: openSearchResult, onOpenChange: (e) => setOpenSearchResult(e.open), closeOnInteractOutside: true, initialFocusEl: () => ref.current, children: [jsx(PopoverTrigger, {}), jsx(PopoverContent, { children: jsxs(PopoverBody, { children: [jsx(PopoverTitle, {}), jsxs(RadioCardRoot, { display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(15rem, 1fr))", overflow: "auto", maxHeight: "50vh", children: [isFetching && jsx(Fragment, { children: "isFetching" }), isLoading && jsx(Fragment, { children: "isLoading" }), isPending && jsx(Fragment, { children: "isPending" }), isError && jsx(Fragment, { children: "isError" }), jsx(Text, { children: `Search Result: ${count}, Showing ${limit}` }), jsx(Button, { onClick: async () => {
1567
+ setOpenSearchResult(false);
1568
+ }, children: "close" }),
1569
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1570
+ getItemList(dataList).map((item) => (jsx(RadioCardItem, { label: item.label, description: item.description, value: item.value, onClick: () => {
1571
+ setSelectedId(item.key);
1572
+ setValue(column, item.key);
1573
+ setOpenSearchResult(false);
1574
+ }, indicator: false }, item.key))), isDirty && (jsxs(Fragment, { children: [dataList.length <= 0 && jsx(Fragment, { children: "Empty Search Result" }), " ", count > dataList.length && (jsx(Fragment, { children: jsx(Button, { onClick: async () => {
1575
+ setLimit((limit) => limit + 10);
1576
+ await getTableData({
1577
+ serverUrl,
1578
+ searching: searchText ?? "",
1579
+ in_table: in_table,
1580
+ limit: limit + 10,
1581
+ });
1582
+ }, children: "show more" }) }))] }))] })] }) })] }), errors[`${column}`] && (jsx(Text, { color: "red.400", children: fieldRequired ?? "The field is requried" }))] }));
1583
+ };
1584
+
1585
+ const ToggleTip = React.forwardRef(function ToggleTip(props, ref) {
1586
+ const { showArrow, children, portalled = true, content, portalRef, ...rest } = props;
1587
+ return (jsxs(Popover.Root, { ...rest, positioning: { ...rest.positioning, gutter: 4 }, children: [jsx(Popover.Trigger, { asChild: true, children: children }), jsx(Portal, { disabled: !portalled, container: portalRef, children: jsx(Popover.Positioner, { children: jsxs(Popover.Content, { width: "auto", px: "2", py: "1", textStyle: "xs", rounded: "sm", ref: ref, children: [showArrow && (jsx(Popover.Arrow, { children: jsx(Popover.ArrowTip, {}) })), content] }) }) })] }));
1588
+ });
1589
+ const InfoTip = React.forwardRef(function InfoTip(props, ref) {
1590
+ const { children, ...rest } = props;
1591
+ return (jsx(ToggleTip, { content: children, ...rest, ref: ref, children: jsx(IconButton, { variant: "ghost", "aria-label": "info", size: "2xs", colorPalette: "gray", children: jsx(HiOutlineInformationCircle, {}) }) }));
1592
+ });
1593
+
1594
+ const DataListRoot = DataList.Root;
1595
+ const DataListItem = React.forwardRef(function DataListItem(props, ref) {
1596
+ const { label, info, value, children, grow, ...rest } = props;
1597
+ return (jsxs(DataList.Item, { ref: ref, ...rest, children: [jsxs(DataList.ItemLabel, { flex: grow ? "1" : undefined, children: [label, info && jsx(InfoTip, { children: info })] }), jsx(DataList.ItemValue, { flex: grow ? "1" : undefined, children: value }), children] }));
1598
+ });
1599
+
1600
+ const IdViewer = ({ value, in_table, column_ref, display_column, column, }) => {
1601
+ const { schema, serverUrl } = useSchemaContext();
1602
+ if (schema.properties == undefined) {
1603
+ throw new Error("schema properties when using DatePicker");
1604
+ }
1605
+ const { title } = schema.properties[column];
1606
+ const query = useQuery({
1607
+ queryKey: [`idpicker`, in_table, value],
1608
+ queryFn: async () => {
1609
+ return await getTableData({
1610
+ serverUrl,
1611
+ in_table: in_table,
1612
+ where: [
1613
+ {
1614
+ id: column_ref,
1615
+ value: value,
1616
+ },
1617
+ ],
1618
+ });
1619
+ },
1620
+ staleTime: 10000,
1621
+ });
1622
+ const getDataListProps = (value) => {
1623
+ if (value == undefined || value.length <= 0) {
1624
+ return {
1625
+ value: "<empty>",
1626
+ color: "gray.400",
1627
+ };
1628
+ }
1629
+ return {
1630
+ value: value,
1631
+ };
1632
+ };
1633
+ return (jsx(Fragment, { children: jsx(DataListItem, { label: `${title ?? snakeToLabel(column)}`, ...getDataListProps((query.data?.data[0] ?? {})[display_column]) }) }));
1634
+ };
1635
+
1636
+ const NumberInputRoot = React.forwardRef(function NumberInput$1(props, ref) {
1637
+ const { children, ...rest } = props;
1638
+ return (jsxs(NumberInput.Root, { ref: ref, variant: "outline", ...rest, children: [children, jsxs(NumberInput.Control, { children: [jsx(NumberInput.IncrementTrigger, {}), jsx(NumberInput.DecrementTrigger, {})] })] }));
1639
+ });
1640
+ const NumberInputField$1 = NumberInput.Input;
1641
+ NumberInput.Scrubber;
1642
+ NumberInput.Label;
1643
+
1644
+ const NumberInputField = ({ column }) => {
1645
+ const { register, formState: { errors }, } = useFormContext();
1646
+ const { schema, displayText } = useSchemaContext();
1647
+ const { fieldRequired } = displayText;
1648
+ const { required } = schema;
1649
+ const isRequired = required?.some((columnId) => columnId === column);
1650
+ if (schema.properties == undefined) {
1651
+ throw new Error("schema properties when using String Input Field");
1652
+ }
1653
+ const { gridColumn, gridRow, title } = schema.properties[column];
1654
+ return (jsxs(Field, { label: `${title ?? snakeToLabel(column)}`, required: isRequired, gridColumn, gridRow, children: [jsx(NumberInputRoot, { children: jsx(NumberInputField$1, { ...register(column, { required: isRequired }) }) }), errors[`${column}`] && (jsx(Text, { color: "red.400", children: fieldRequired ?? "The field is requried" }))] }));
1655
+ };
1656
+
1657
+ const StringInputField = ({ column }) => {
1658
+ const { register, formState: { errors }, } = useFormContext();
1659
+ const { schema, displayText } = useSchemaContext();
1660
+ const { fieldRequired } = displayText;
1661
+ const { required } = schema;
1662
+ const isRequired = required?.some((columnId) => columnId === column);
1663
+ if (schema.properties == undefined) {
1664
+ throw new Error("schema properties when using String Input Field");
1665
+ }
1666
+ const { gridColumn, gridRow, title } = schema.properties[column];
1667
+ return (jsx(Fragment, { children: jsxs(Field, { label: `${title ?? snakeToLabel(column)}`, required: isRequired, gridColumn: gridColumn ?? "span 4", gridRow: gridRow ?? "span 1", children: [jsx(Input, { ...register(column, { required: isRequired }), autoComplete: "off" }), errors[`${column}`] && (jsx(Text, { color: "red.400", children: fieldRequired ?? "The field is requried" }))] }) }));
1668
+ };
1669
+
1670
+ const clearEmptyString = (object) => {
1671
+ return Object.fromEntries(Object.entries(object).filter(([, value]) => value !== ""));
1672
+ };
1673
+
1674
+ const AccordionItemTrigger = React.forwardRef(function AccordionItemTrigger(props, ref) {
1675
+ const { children, indicatorPlacement = "end", ...rest } = props;
1676
+ return (jsxs(Accordion.ItemTrigger, { ...rest, ref: ref, children: [indicatorPlacement === "start" && (jsx(Accordion.ItemIndicator, { rotate: { base: "-90deg", _open: "0deg" }, children: jsx(LuChevronDown, {}) })), jsx(HStack, { gap: "4", flex: "1", textAlign: "start", width: "full", children: children }), indicatorPlacement === "end" && (jsx(Accordion.ItemIndicator, { children: jsx(LuChevronDown, {}) }))] }));
1677
+ });
1678
+ const AccordionItemContent = React.forwardRef(function AccordionItemContent(props, ref) {
1679
+ return (jsx(Accordion.ItemContent, { children: jsx(Accordion.ItemBody, { ...props, ref: ref }) }));
1680
+ });
1681
+ const AccordionRoot = Accordion.Root;
1682
+ const AccordionItem = Accordion.Item;
1683
+
1684
+ const CheckboxCard = React.forwardRef(function CheckboxCard(props, ref) {
1685
+ const { inputProps, label, description, icon, addon, indicator = jsx(CheckboxCard$1.Indicator, {}), indicatorPlacement = "end", ...rest } = props;
1686
+ const hasContent = label || description || icon;
1687
+ const ContentWrapper = indicator ? CheckboxCard$1.Content : React.Fragment;
1688
+ return (jsxs(CheckboxCard$1.Root, { ...rest, children: [jsx(CheckboxCard$1.HiddenInput, { ref: ref, ...inputProps }), jsxs(CheckboxCard$1.Control, { children: [indicatorPlacement === "start" && indicator, hasContent && (jsxs(ContentWrapper, { children: [icon, label && (jsx(CheckboxCard$1.Label, { children: label })), description && (jsx(CheckboxCard$1.Description, { children: description })), indicatorPlacement === "inside" && indicator] })), indicatorPlacement === "end" && indicator] }), addon && jsx(CheckboxCard$1.Addon, { children: addon })] }));
1689
+ });
1690
+ CheckboxCard$1.Indicator;
1691
+
1692
+ const BooleanPicker = ({ column }) => {
1693
+ const { formState: { errors }, setValue, getValues, } = useFormContext();
1694
+ const { schema, displayText } = useSchemaContext();
1695
+ const { fieldRequired } = displayText;
1696
+ const { required } = schema;
1697
+ const isRequired = required?.some((columnId) => columnId === column);
1698
+ if (schema.properties == undefined) {
1699
+ throw new Error("schema properties when using BooleanPicker");
1700
+ }
1701
+ const { gridColumn, gridRow, title } = schema.properties[column];
1702
+ return (jsxs(Field, { label: `${title ?? snakeToLabel(column)}`, required: isRequired, alignItems: "stretch", gridColumn,
1703
+ gridRow, children: [jsx(CheckboxCard
1704
+ // label={snakeToLabel(column)}
1705
+ , {
1706
+ // label={snakeToLabel(column)}
1707
+ value: getValues(column), variant: "surface", onSelect: () => {
1708
+ setValue(column, !getValues(column));
1709
+ } }), errors[`${column}`] && (jsx(Text, { color: "red.400", children: fieldRequired ?? "The field is requried" }))] }));
1710
+ };
1711
+
1712
+ const monthNamesShort = [
1713
+ "Jan",
1714
+ "Feb",
1715
+ "Mar",
1716
+ "Apr",
1717
+ "May",
1718
+ "Jun",
1719
+ "Jul",
1720
+ "Aug",
1721
+ "Sep",
1722
+ "Oct",
1723
+ "Nov",
1724
+ "Dec",
1725
+ ];
1726
+ const weekdayNamesShort$1 = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
1727
+ const Calendar$1 = ({ calendars, getBackProps, getForwardProps, getDateProps, firstDayOfWeek = 0, }) => {
1728
+ if (calendars.length) {
1729
+ return (jsxs(Grid, { children: [jsxs(Grid, { templateColumns: "repeat(4, auto)", justifyContent: "center", children: [jsx(Button$1, { variant: "ghost", ...getBackProps({
1730
+ calendars,
1731
+ offset: 12,
1732
+ }), children: "<<" }), jsx(Button$1, { variant: "ghost", ...getBackProps({ calendars }), children: "Back" }), jsx(Button$1, { variant: "ghost", ...getForwardProps({ calendars }), children: "Next" }), jsx(Button$1, { variant: "ghost", ...getForwardProps({
1733
+ calendars,
1734
+ offset: 12,
1735
+ }), children: ">>" })] }), jsx(Grid, { templateColumns: "repeat(2, auto)", justifyContent: "center", children: calendars.map((calendar) => (jsxs(Grid, { gap: 4, children: [jsxs(Grid, { justifyContent: "center", children: [monthNamesShort[calendar.month], " ", calendar.year] }), jsxs(Grid, { templateColumns: "repeat(7, auto)", justifyContent: "center", children: [[0, 1, 2, 3, 4, 5, 6].map((weekdayNum) => {
1736
+ const weekday = (weekdayNum + firstDayOfWeek) % 7;
1737
+ return (jsx(Text, { textAlign: "center", children: weekdayNamesShort$1[weekday] }, `${calendar.month}${calendar.year}${weekday}`));
1738
+ }), calendar.weeks.map((week, weekIndex) => week.map((dateObj, index) => {
1739
+ const key = `${calendar.month}${calendar.year}${weekIndex}${index}`;
1740
+ if (!dateObj) {
1741
+ return jsx(Grid, {}, key);
1742
+ }
1743
+ const { date, selected, selectable, today } = dateObj;
1744
+ const getDateColor = ({ today, selected, selectable, }) => {
1745
+ if (!selectable) {
1746
+ return "gray";
1747
+ }
1748
+ if (selected) {
1749
+ return "blue";
1750
+ }
1751
+ if (today) {
1752
+ return "green";
1753
+ }
1754
+ return "";
1755
+ };
1756
+ const getVariant = ({ today, selected, selectable, }) => {
1757
+ if (!selectable) {
1758
+ return "solid";
1759
+ }
1760
+ if (selected) {
1761
+ return "solid";
1762
+ }
1763
+ if (today) {
1764
+ return "solid";
1765
+ }
1766
+ return "ghost";
1767
+ };
1768
+ const color = getDateColor({ today, selected, selectable });
1769
+ const variant = getVariant({ today, selected, selectable });
1770
+ return (jsx(Button$1, { variant: variant, colorPalette: color, ...getDateProps({ dateObj }), children: selectable ? date.getDate() : "X" }, key));
1771
+ }))] })] }, `${calendar.month}${calendar.year}`))) })] }));
1772
+ }
1773
+ return null;
1774
+ };
1775
+ let DatePicker$1 = class DatePicker extends React__default.Component {
1776
+ render() {
1777
+ return (jsx(Dayzed, { onDateSelected: this.props.onDateSelected, selected: this.props.selected, firstDayOfWeek: this.props.firstDayOfWeek, showOutsideDays: this.props.showOutsideDays, date: this.props.date, minDate: this.props.minDate, maxDate: this.props.maxDate, monthsToDisplay: this.props.monthsToDisplay, render: (dayzedData) => (jsx(Calendar$1, { ...dayzedData, firstDayOfWeek: this.props.firstDayOfWeek })) }));
1778
+ }
1779
+ };
1780
+
1781
+ const DatePicker = ({ column }) => {
1782
+ const { formState: { errors }, setValue, getValues, } = useFormContext();
1783
+ const { schema, displayText } = useSchemaContext();
1784
+ const { fieldRequired } = displayText;
1785
+ const { required } = schema;
1786
+ const isRequired = required?.some((columnId) => columnId === column);
1787
+ const [open, setOpen] = useState(false);
1788
+ if (schema.properties == undefined) {
1789
+ throw new Error("schema properties when using DatePicker");
1790
+ }
1791
+ const { gridColumn, gridRow, title } = schema.properties[column];
1792
+ return (jsxs(Field, { label: `${title ?? snakeToLabel(column)}`, required: isRequired, alignItems: "stretch", gridColumn,
1793
+ gridRow, children: [jsxs(PopoverRoot, { open: open, onOpenChange: (e) => setOpen(e.open), closeOnInteractOutside: true, positioning: { sameWidth: true }, children: [jsx(PopoverTrigger, { asChild: true, children: jsx(Button, { size: "sm", variant: "outline", onClick: () => {
1794
+ setOpen(true);
1795
+ }, children: getValues(column) !== undefined
1796
+ ? dayjs(getValues(column)).format("YYYY-MM-DD")
1797
+ : "" }) }), jsx(PopoverContent, { width: "auto", children: jsxs(PopoverBody, { children: [jsx(PopoverTitle, {}), jsx(DatePicker$1, { selected: new Date(getValues(column)), onDateSelected: ({ selected, selectable, date }) => {
1798
+ console.log(date, selected, selectable, "jasdio");
1799
+ setValue(column, dayjs(date).format("YYYY-MM-DD"));
1800
+ setOpen(false);
1801
+ } })] }) })] }), errors[`${column}`] && (jsx(Text, { color: "red.400", children: fieldRequired ?? "The field is requried" }))] }));
1802
+ };
1803
+
1804
+ const ObjectInput = ({ column }) => {
1805
+ const { formState: { errors }, setValue, getValues, } = useFormContext();
1806
+ const { schema, displayText } = useSchemaContext();
1807
+ const { addNew, fieldRequired, save } = displayText;
1808
+ const { required } = schema;
1809
+ const isRequired = required?.some((columnId) => columnId === column);
1810
+ const entries = Object.entries(getValues(column) ?? {});
1811
+ const [showNewEntries, setShowNewEntries] = useState(false);
1812
+ const [newKey, setNewKey] = useState();
1813
+ const [newValue, setNewValue] = useState();
1814
+ if (schema.properties == undefined) {
1815
+ throw new Error("schema properties when using DatePicker");
1816
+ }
1817
+ const { gridColumn, gridRow, title } = schema.properties[column];
1818
+ return (jsxs(Field, { label: `${title ?? snakeToLabel(column)}`, required: isRequired, alignItems: "stretch", gridColumn, gridRow, children: [entries.map(([key, value]) => {
1819
+ return (jsxs(Grid, { templateColumns: "1fr 1fr auto", gap: 1, children: [jsx(Input, { value: key, onChange: (e) => {
1820
+ const filtered = entries.filter(([target]) => {
1821
+ return target !== key;
1822
+ });
1823
+ setValue(column, Object.fromEntries([...filtered, [e.target.value, value]]));
1824
+ }, autoComplete: "off" }), jsx(Input, { value: value, onChange: (e) => {
1825
+ setValue(column, {
1826
+ ...getValues(column),
1827
+ [key]: e.target.value,
1828
+ });
1829
+ }, autoComplete: "off" }), jsx(IconButton, { variant: "ghost", onClick: () => {
1830
+ const filtered = entries.filter(([target]) => {
1831
+ return target !== key;
1832
+ });
1833
+ setValue(column, Object.fromEntries([...filtered]));
1834
+ }, children: jsx(CgClose, {}) })] }));
1835
+ }), jsx(Show, { when: showNewEntries, children: jsxs(Card.Root, { children: [jsx(Card.Body, { gap: "2", children: jsxs(Grid, { templateColumns: "1fr 1fr auto", gap: 1, children: [jsx(Input, { value: newKey, onChange: (e) => {
1836
+ setNewKey(e.target.value);
1837
+ }, autoComplete: "off" }), jsx(Input, { value: newValue, onChange: (e) => {
1838
+ setNewValue(e.target.value);
1839
+ }, autoComplete: "off" })] }) }), jsxs(Card.Footer, { justifyContent: "flex-end", children: [jsx(IconButton, { variant: "subtle", onClick: () => {
1840
+ setShowNewEntries(false);
1841
+ setNewKey(undefined);
1842
+ setNewValue(undefined);
1843
+ }, children: jsx(CgClose, {}) }), jsx(Button, { onClick: () => {
1844
+ if (!!newKey === false) {
1845
+ setShowNewEntries(false);
1846
+ setNewKey(undefined);
1847
+ setNewValue(undefined);
1848
+ return;
1849
+ }
1850
+ setValue(column, Object.fromEntries([...entries, [newKey, newValue]]));
1851
+ setShowNewEntries(false);
1852
+ setNewKey(undefined);
1853
+ setNewValue(undefined);
1854
+ }, children: save ?? "Save" })] })] }) }), jsx(Button, { onClick: () => {
1855
+ setShowNewEntries(true);
1856
+ setNewKey(undefined);
1857
+ setNewValue(undefined);
1858
+ }, children: addNew ?? "Add New" }), errors[`${column}`] && (jsx(Text, { color: "red.400", children: fieldRequired ?? "The field is requried" }))] }));
1859
+ };
1860
+
1861
+ const idPickerSanityCheck = (column, in_table, column_ref, display_column) => {
1862
+ console.log(!!in_table, "okgsd");
1863
+ if (!!in_table == false) {
1864
+ throw new Error(`The key in_table does not exist in properties of column ${column}.`);
1865
+ }
1866
+ if (!!column_ref == false) {
1867
+ throw new Error(`The key column_ref does not exist in properties of column ${column}.`);
1868
+ }
1869
+ if (!!display_column == false) {
1870
+ throw new Error(`The key display_column does not exist in properties of column ${column}.`);
1871
+ }
1872
+ };
1873
+ const FormInternal = () => {
1874
+ const { schema, serverUrl, displayText, order, ignore, onSubmit, preLoadedValues, rowNumber, } = useSchemaContext();
1875
+ const { title, submit, empty, cancel, submitSuccess, submitAgain, confirm } = displayText;
1876
+ const methods = useFormContext();
1877
+ const [isSuccess, setIsSuccess] = useState(false);
1878
+ const [isError, setIsError] = useState(false);
1879
+ const [isSubmiting, setIsSubmiting] = useState(false);
1880
+ const [isConfirming, setIsConfirming] = useState(false);
1881
+ const [validatedData, setValidatedData] = useState();
1882
+ const [error, setError] = useState();
1883
+ const { properties } = schema;
1884
+ const onBeforeSubmit = () => {
1885
+ setIsSubmiting(true);
1886
+ };
1887
+ const onAfterSubmit = () => {
1888
+ setIsSubmiting(false);
1889
+ };
1890
+ const onSubmitError = () => {
1891
+ setIsError(true);
1892
+ };
1893
+ const onSubmitSuccess = () => {
1894
+ setIsSuccess(true);
1895
+ };
1896
+ const defaultOnSubmit = async (data) => {
1897
+ const options = {
1898
+ method: "POST",
1899
+ url: `${serverUrl}/api/g/${schema.title}`,
1900
+ headers: {
1901
+ Apikey: "YOUR_SECRET_TOKEN",
1902
+ "Content-Type": "application/json",
1903
+ },
1904
+ data: clearEmptyString(data),
1905
+ };
1906
+ try {
1907
+ onBeforeSubmit();
1908
+ await axios.request(options);
1909
+ onSubmitSuccess();
1910
+ }
1911
+ catch (error) {
1912
+ setIsError(true);
1913
+ setError(error);
1914
+ onSubmitError();
1915
+ }
1916
+ finally {
1917
+ onAfterSubmit();
1918
+ }
1919
+ };
1920
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1921
+ const onFormSubmit = async (data) => {
1922
+ if (onSubmit === undefined) {
1923
+ defaultOnSubmit(data);
1924
+ return;
1925
+ }
1926
+ onSubmit(data);
1927
+ };
1928
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1929
+ const onValid = (data) => {
1930
+ setValidatedData(data);
1931
+ setIsError(false);
1932
+ setIsConfirming(true);
1933
+ };
1934
+ const renderOrder = (order, origin_list) => {
1935
+ const not_exist = origin_list.filter((columnA) => !order.some((columnB) => columnA === columnB));
1936
+ return [...order, ...not_exist];
1937
+ };
1938
+ const ordered = renderOrder(order, Object.keys(properties));
1939
+ const getDataListProps = (value) => {
1940
+ if (value == undefined || value.length <= 0) {
1941
+ return {
1942
+ value: `<${empty ?? "Empty"}>`,
1943
+ color: "gray.400",
1944
+ };
1945
+ }
1946
+ return {
1947
+ value: value,
1948
+ };
1949
+ };
1950
+ useEffect(() => {
1951
+ const loadData = () => {
1952
+ Object.entries(preLoadedValues).map(([column, value]) => {
1953
+ methods.setValue(column, value);
1954
+ });
1955
+ };
1956
+ loadData();
1957
+ }, [preLoadedValues, methods]);
1958
+ if (isSuccess) {
1959
+ return (jsxs(Grid, { gap: 2, children: [jsx(Heading, { children: title ?? snakeToLabel(schema.title ?? "") }), jsxs(Alert.Root, { status: "success", children: [jsx(Alert.Indicator, {}), jsx(Alert.Title, { children: submitSuccess ?? "Data uploaded to the server. Fire on!" })] }), jsx(Button, { onClick: () => {
1960
+ setIsError(false);
1961
+ setIsSubmiting(false);
1962
+ setIsSuccess(false);
1963
+ setIsConfirming(false);
1964
+ setValidatedData(undefined);
1965
+ methods.reset();
1966
+ }, formNoValidate: true, children: submitAgain ?? "Submit Again" })] }));
1967
+ }
1968
+ if (isConfirming) {
1969
+ return (jsxs(Grid, { gap: 2, children: [jsx(Heading, { children: title ?? snakeToLabel(schema.title ?? "") }), jsx(DataListRoot, { orientation: "horizontal", gap: 4, display: "grid", gridTemplateColumns: "repeat(12, 1fr)", gridTemplateRows: `repeat(${rowNumber ?? "auto-fit"}, auto)`, children: ordered.map((column) => {
1970
+ if (properties === undefined) {
1971
+ return jsx(Fragment, {});
1972
+ }
1973
+ const key = column;
1974
+ const values = properties[column];
1975
+ const shouldIgnore = ignore.some((column) => {
1976
+ return column == key;
1977
+ });
1978
+ if (shouldIgnore) {
1979
+ return jsx(Fragment, {});
1980
+ }
1981
+ const { type, variant, in_table, column_ref, display_column, gridColumn, gridRow, } = values;
1982
+ if (type === "string") {
1983
+ if (variant === "id-picker") {
1984
+ idPickerSanityCheck(column, in_table, column_ref, display_column);
1985
+ return (jsx(IdViewer, { value: (validatedData ?? {})[column], in_table,
1986
+ column_ref,
1987
+ display_column,
1988
+ column,
1989
+ gridColumn,
1990
+ gridRow }, `form-${key}`));
1991
+ }
1992
+ if (variant === "date-picker") {
1993
+ const value = (validatedData ?? {})[column];
1994
+ if (!!value === false) {
1995
+ return (jsx(DataListItem, { gridColumn: gridColumn ?? "span 4", gridRow: gridRow ?? "span 1", label: `${snakeToLabel(column)}`, ...getDataListProps(undefined) }, `form-${key}`));
1996
+ }
1997
+ const date = dayjs(value).format("YYYY-MM-DD");
1998
+ return (jsx(DataListItem, { gridColumn: gridColumn ?? "span 4", gridRow: gridRow ?? "span 1", label: `${snakeToLabel(column)}`, ...getDataListProps(date) }, `form-${key}`));
1999
+ }
2000
+ return (jsx(DataListItem, { gridColumn: gridColumn ?? "span 4", gridRow: gridRow ?? "span 4", label: `${snakeToLabel(column)}`, ...getDataListProps((validatedData ?? {})[column]) }, `form-${key}`));
2001
+ }
2002
+ if (type === "object") {
2003
+ const value = (validatedData ?? {})[column];
2004
+ if (!!value === false) {
2005
+ return (jsx(DataListItem, { gridColumn: gridColumn ?? "span 4", gridRow: gridRow ?? "span 1", label: `${snakeToLabel(column)}`, ...getDataListProps(undefined) }, `form-${key}`));
2006
+ }
2007
+ return (jsxs(Flex, { flexFlow: "column", gap: 2, gridColumn: gridColumn ?? "span 4", gridRow: gridRow ?? "span 1", children: [jsx(Text, { children: snakeToLabel(column) }), jsx(DataListRoot, { orientation: "horizontal", padding: 4, borderColor: "gray.200", borderWidth: 1, borderRadius: 4, children: Object.entries(value).map(([key, value]) => {
2008
+ return (jsx(DataListItem, { label: `${key}`, ...getDataListProps(value) }, `form-${column}-${key}`));
2009
+ }) })] }));
2010
+ }
2011
+ if (type === "boolean") {
2012
+ return (jsx(DataListItem, { gridColumn: gridColumn ?? "span 4", gridRow: gridRow ?? "span 4", label: `${snakeToLabel(column)}`, ...getDataListProps((validatedData ?? {})[column]) }, `form-${key}`));
2013
+ }
2014
+ if (type === "number" || type === "integer") {
2015
+ return (jsx(DataListItem, { gridColumn: gridColumn ?? "span 4", gridRow: gridRow ?? "span 4", label: `${snakeToLabel(column)}`, ...getDataListProps((validatedData ?? {})[column]) }, `form-${key}`));
2016
+ }
2017
+ if (type === "array") {
2018
+ return jsx(Fragment, { children: `array ${column}` });
2019
+ }
2020
+ if (type === "null") {
2021
+ return jsx(Fragment, { children: `null ${column}` });
2022
+ }
2023
+ return jsx(Fragment, { children: `unknown type ${column}` });
2024
+ }) }), jsx(Button, { onClick: () => {
2025
+ onFormSubmit(validatedData);
2026
+ }, children: confirm ?? "Confirm" }), jsx(Button, { onClick: () => {
2027
+ setIsConfirming(false);
2028
+ }, variant: "subtle", children: cancel ?? "Cancel" }), isSubmiting && (jsx(Box, { pos: "absolute", inset: "0", bg: "bg/80", children: jsx(Center, { h: "full", children: jsx(Spinner, { color: "teal.500" }) }) })), isError && (jsx(Fragment, { children: jsx(Alert.Root, { status: "error", children: jsx(Alert.Title, { children: jsx(AccordionRoot, { collapsible: true, defaultValue: ["b"], children: jsxs(AccordionItem, { value: "b", children: [jsxs(AccordionItemTrigger, { children: [jsx(Alert.Indicator, {}), `${error}`] }), jsx(AccordionItemContent, { children: `${JSON.stringify(error)}` })] }) }) }) }) }))] }));
2029
+ }
2030
+ return (jsxs(Fragment, { children: [jsxs(Grid, { gap: 2, children: [jsx(Heading, { children: title ?? snakeToLabel(schema.title ?? "") }), jsx(Grid, { gap: 4, gridTemplateColumns: "repeat(12, 1fr)", gridTemplateRows: `repeat(${rowNumber ?? "auto-fit"}, auto)`, children: ordered.map((column) => {
2031
+ if (properties === undefined) {
2032
+ return jsx(Fragment, {});
2033
+ }
2034
+ const key = column;
2035
+ const values = properties[column];
2036
+ const shouldIgnore = ignore.some((column) => {
2037
+ return column == key;
2038
+ });
2039
+ if (shouldIgnore) {
2040
+ return jsx(Fragment, {});
2041
+ }
2042
+ //@ts-expect-error TODO: add more fields to support form-creation
2043
+ const { type, variant, in_table, column_ref, display_column } = values;
2044
+ if (type === "string") {
2045
+ if (variant === "id-picker") {
2046
+ idPickerSanityCheck(column, in_table, column_ref, display_column);
2047
+ return (jsx(IdPicker, { column: key, in_table: in_table, column_ref: column_ref, display_column: display_column }, `form-${key}`));
2048
+ }
2049
+ if (variant === "date-picker") {
2050
+ return jsx(DatePicker, { column: key }, `form-${key}`);
2051
+ }
2052
+ return jsx(StringInputField, { column: key }, `form-${key}`);
2053
+ }
2054
+ if (type === "number" || type === "integer") {
2055
+ return jsx(NumberInputField, { column: key }, `form-${key}`);
2056
+ }
2057
+ if (type === "boolean") {
2058
+ return jsx(BooleanPicker, { column: key }, `form-${key}`);
2059
+ }
2060
+ if (type === "object") {
2061
+ return (jsx(Fragment, { children: jsx(ObjectInput, { column: key }, `form-${key}`) }));
2062
+ }
2063
+ if (type === "array") {
2064
+ return jsx(Fragment, { children: `array ${column}` });
2065
+ }
2066
+ if (type === "null") {
2067
+ return jsx(Fragment, { children: `null ${column}` });
2068
+ }
2069
+ return jsx(Fragment, { children: "missing type" });
2070
+ }) }), jsx(Button, { onClick: () => {
2071
+ methods.handleSubmit(onValid)();
2072
+ }, formNoValidate: true, children: submit ?? "Submit" })] }), isError && (jsxs(Fragment, { children: ["isError", jsxs(Fragment, { children: [" ", `${error}`] })] }))] }));
2073
+ };
2074
+ const Form = ({ schema, serverUrl, order = [], ignore = [], onSubmit = undefined, preLoadedValues = {}, rowNumber = undefined, displayText = {}, }) => {
2075
+ const queryClient = new QueryClient();
2076
+ const methods = useForm();
2077
+ const { properties } = schema;
2078
+ idListSanityCheck("order", order, properties);
2079
+ idListSanityCheck("ignore", ignore, properties);
2080
+ idListSanityCheck("preLoadedValues", Object.keys(preLoadedValues), properties);
2081
+ return (jsx(QueryClientProvider, { client: queryClient, children: jsx(SchemaFormContext.Provider, { value: {
2082
+ schema,
2083
+ serverUrl,
2084
+ displayText,
2085
+ order,
2086
+ ignore,
2087
+ // @ts-expect-error TODO: find appropriate types
2088
+ onSubmit,
2089
+ preLoadedValues,
2090
+ rowNumber,
2091
+ }, children: jsx(FormProvider, { ...methods, children: jsx(FormInternal, {}) }) }) }));
2092
+ };
2093
+
2094
+ const getMultiDates = ({ selected, selectedDate, selectedDates, selectable, }) => {
2095
+ if (!selectable) {
2096
+ return [...selectedDates];
2097
+ }
2098
+ if (selected) {
2099
+ // Remove
2100
+ return selectedDates.filter((time) => {
2101
+ return selectedDate.getTime() !== time.getTime();
2102
+ });
2103
+ }
2104
+ else {
2105
+ // Add
2106
+ return [...selectedDates, selectedDate];
2107
+ }
2108
+ };
2109
+
2110
+ const getRangeDates = ({ selectable, date, selectedDates, }) => {
2111
+ if (!selectable) {
2112
+ return;
2113
+ }
2114
+ const dateTime = date.getTime();
2115
+ const newDates = [...selectedDates];
2116
+ if (selectedDates.length) {
2117
+ if (selectedDates.length === 1) {
2118
+ const firstTime = selectedDates[0].getTime();
2119
+ if (firstTime < dateTime) {
2120
+ newDates.push(date);
2121
+ }
2122
+ else {
2123
+ newDates.unshift(date);
2124
+ }
2125
+ return newDates;
2126
+ }
2127
+ else if (newDates.length === 2) {
2128
+ return [date];
2129
+ }
2130
+ }
2131
+ else {
2132
+ newDates.push(date);
2133
+ return newDates;
2134
+ }
2135
+ };
2136
+
2137
+ const monthNamesFull = [
2138
+ "January",
2139
+ "February",
2140
+ "March",
2141
+ "April",
2142
+ "May",
2143
+ "June",
2144
+ "July",
2145
+ "August",
2146
+ "September",
2147
+ "October",
2148
+ "November",
2149
+ "December",
2150
+ ];
2151
+ const weekdayNamesShort = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
2152
+ function Calendar({ calendars, getBackProps, getForwardProps, getDateProps, selected = [], firstDayOfWeek = 0, }) {
2153
+ const [hoveredDate, setHoveredDate] = useState();
2154
+ const onMouseLeave = () => {
2155
+ setHoveredDate(undefined);
2156
+ };
2157
+ const onMouseEnter = (date) => {
2158
+ setHoveredDate(date);
2159
+ };
2160
+ const isInRange = (date) => {
2161
+ if (selected.length) {
2162
+ const firstSelected = selected[0].getTime();
2163
+ if (selected.length === 2) {
2164
+ const secondSelected = selected[1].getTime();
2165
+ return (firstSelected < date.getTime() && secondSelected > date.getTime());
2166
+ }
2167
+ else {
2168
+ return !!(hoveredDate &&
2169
+ ((firstSelected < date.getTime() &&
2170
+ hoveredDate.getTime() >= date.getTime()) ||
2171
+ (date.getTime() < firstSelected &&
2172
+ date.getTime() >= hoveredDate.getTime())));
2173
+ }
2174
+ }
2175
+ return false;
2176
+ };
2177
+ if (calendars.length) {
2178
+ return (jsxs(Grid, { onMouseLeave: onMouseLeave, children: [jsxs(Grid, { templateColumns: "repeat(4, auto)", justifyContent: "center", children: [jsx(Button$1, { variant: "ghost", ...getBackProps({
2179
+ calendars,
2180
+ offset: 12,
2181
+ }), children: "<<" }), jsx(Button$1, { variant: "ghost", ...getBackProps({ calendars }), children: "Back" }), jsx(Button$1, { variant: "ghost", ...getForwardProps({ calendars }), children: "Next" }), jsx(Button$1, { variant: "ghost", ...getForwardProps({
2182
+ calendars,
2183
+ offset: 12,
2184
+ }), children: ">>" })] }), jsx(Grid, { templateColumns: "repeat(2, auto)", justifyContent: "center", gap: 4, children: calendars.map((calendar) => (jsxs(Grid, { gap: 4, children: [jsxs(Grid, { justifyContent: "center", children: [monthNamesFull[calendar.month], " ", calendar.year] }), jsx(Grid, { templateColumns: "repeat(7, auto)", justifyContent: "center", children: [0, 1, 2, 3, 4, 5, 6].map((weekdayNum) => {
2185
+ const weekday = (weekdayNum + firstDayOfWeek) % 7;
2186
+ return (jsx(Box, { minWidth: "48px", textAlign: 'center', children: weekdayNamesShort[weekday] }, `${calendar.month}${calendar.year}${weekday}`));
2187
+ }) }), jsx(Grid, { templateColumns: "repeat(7, auto)", justifyContent: "center", children: calendar.weeks.map((week, windex) => week.map((dateObj, index) => {
2188
+ const key = `${calendar.month}${calendar.year}${windex}${index}`;
2189
+ if (!dateObj) {
2190
+ return jsx(Box, {}, key);
2191
+ }
2192
+ const { date, selected, selectable, today } = dateObj;
2193
+ const getStyle = ({ selected, unavailable, today, isInRange, }) => {
2194
+ if (unavailable) {
2195
+ return {
2196
+ colorPalette: "gray",
2197
+ variant: "solid",
2198
+ };
2199
+ }
2200
+ if (selected) {
2201
+ return {
2202
+ colorPalette: "blue",
2203
+ variant: "solid",
2204
+ };
2205
+ }
2206
+ if (isInRange) {
2207
+ return {
2208
+ colorPalette: "blue",
2209
+ variant: "subtle",
2210
+ };
2211
+ }
2212
+ if (today) {
2213
+ return {
2214
+ colorPalette: "green",
2215
+ variant: "solid",
2216
+ };
2217
+ }
2218
+ return { variant: "ghost" };
2219
+ };
2220
+ return (jsx(Button$1, { ...getDateProps({
2221
+ dateObj,
2222
+ onMouseEnter: () => {
2223
+ onMouseEnter(date);
2224
+ },
2225
+ }), ...getStyle({
2226
+ selected,
2227
+ unavailable: !selectable,
2228
+ today,
2229
+ isInRange: isInRange(date),
2230
+ }), children: selectable ? date.getDate() : "X" }, key));
2231
+ })) })] }, `${calendar.month}${calendar.year}`))) })] }));
2232
+ }
2233
+ return null;
2234
+ }
2235
+ class RangeDatePicker extends React__default.Component {
2236
+ render() {
2237
+ return (jsx(Dayzed, { onDateSelected: this.props.onDateSelected, selected: this.props.selected, firstDayOfWeek: this.props.firstDayOfWeek, showOutsideDays: this.props.showOutsideDays, date: this.props.date, minDate: this.props.minDate, maxDate: this.props.maxDate, monthsToDisplay: this.props.monthsToDisplay, render: (dayzedData) => (jsx(Calendar, { ...dayzedData,
2238
+ firstDayOfWeek: this.props.firstDayOfWeek,
2239
+ selected: this.props.selected })) }));
2240
+ }
2241
+ }
2242
+
2243
+ export { CardHeader, DataDisplay, DataTable, DataTableServer, DefaultCardTitle, DefaultTable, DensityToggleButton, EditFilterButton, EditOrderButton, EditSortingButton, EditViewButton, FilterOptions, Form, GlobalFilter, PageSizeControl, ReloadButton, ResetFilteringButton, ResetSelectionButton, ResetSortingButton, RowCountText, Table, TableBody, TableCardContainer, TableCards, TableComponent, TableControls, TableFilter, TableFilterTags, TableFooter, TableHeader, TableLoadingComponent, TableOrderer, TablePagination, TableSelector, TableSorter, TableViewer, TextCell, getColumns, getMultiDates, getRangeDates, useDataFromUrl, useDataTable, useDataTableContext, useDataTableServer, widthSanityCheck };