next-data-kit 9.9.2 → 11.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/MIGRATION.md +75 -0
  2. package/README.md +289 -698
  3. package/dist/chunk-5D747NEB.js +12 -0
  4. package/dist/chunk-5D747NEB.js.map +1 -0
  5. package/dist/index.d.ts +109 -110
  6. package/dist/index.js +109 -205
  7. package/dist/index.js.map +1 -1
  8. package/dist/server/drizzle.d.ts +11 -0
  9. package/dist/server/drizzle.js +39 -0
  10. package/dist/server/drizzle.js.map +1 -0
  11. package/dist/server.d.ts +273 -88
  12. package/dist/server.js +269 -282
  13. package/dist/server.js.map +1 -1
  14. package/dist/source--l-z9HHB.d.ts +60 -0
  15. package/package.json +75 -107
  16. package/registry/r/data-kit.json +74 -0
  17. package/registry/r/registry.json +72 -0
  18. package/dist/action-DCmAhOQa.d.cts +0 -196
  19. package/dist/action-DCmAhOQa.d.ts +0 -196
  20. package/dist/chunk-5TIEIY7M.cjs +0 -393
  21. package/dist/chunk-5TIEIY7M.cjs.map +0 -1
  22. package/dist/chunk-MTJATM72.cjs +0 -2423
  23. package/dist/chunk-MTJATM72.cjs.map +0 -1
  24. package/dist/chunk-O377UO7C.js +0 -2379
  25. package/dist/chunk-O377UO7C.js.map +0 -1
  26. package/dist/chunk-VFSNUXOW.js +0 -382
  27. package/dist/chunk-VFSNUXOW.js.map +0 -1
  28. package/dist/client/components/data-kit-infinity.d.ts +0 -23
  29. package/dist/client/components/data-kit-infinity.d.ts.map +0 -1
  30. package/dist/client/components/data-kit-table.d.ts +0 -34
  31. package/dist/client/components/data-kit-table.d.ts.map +0 -1
  32. package/dist/client/components/data-kit.d.ts +0 -25
  33. package/dist/client/components/data-kit.d.ts.map +0 -1
  34. package/dist/client/components/index.d.ts +0 -4
  35. package/dist/client/components/index.d.ts.map +0 -1
  36. package/dist/client/components/ui/button.d.ts +0 -14
  37. package/dist/client/components/ui/button.d.ts.map +0 -1
  38. package/dist/client/components/ui/checkbox.d.ts +0 -5
  39. package/dist/client/components/ui/checkbox.d.ts.map +0 -1
  40. package/dist/client/components/ui/dropdown-menu.d.ts +0 -28
  41. package/dist/client/components/ui/dropdown-menu.d.ts.map +0 -1
  42. package/dist/client/components/ui/index.d.ts +0 -8
  43. package/dist/client/components/ui/index.d.ts.map +0 -1
  44. package/dist/client/components/ui/pagination.d.ts +0 -14
  45. package/dist/client/components/ui/pagination.d.ts.map +0 -1
  46. package/dist/client/components/ui/popover.d.ts +0 -10
  47. package/dist/client/components/ui/popover.d.ts.map +0 -1
  48. package/dist/client/components/ui/select.d.ts +0 -18
  49. package/dist/client/components/ui/select.d.ts.map +0 -1
  50. package/dist/client/components/ui/table.d.ts +0 -11
  51. package/dist/client/components/ui/table.d.ts.map +0 -1
  52. package/dist/client/context/index.d.ts +0 -22
  53. package/dist/client/context/index.d.ts.map +0 -1
  54. package/dist/client/hooks/index.d.ts +0 -7
  55. package/dist/client/hooks/index.d.ts.map +0 -1
  56. package/dist/client/hooks/useDataKit.d.ts +0 -9
  57. package/dist/client/hooks/useDataKit.d.ts.map +0 -1
  58. package/dist/client/hooks/usePagination.d.ts +0 -18
  59. package/dist/client/hooks/usePagination.d.ts.map +0 -1
  60. package/dist/client/hooks/useSelection.d.ts +0 -13
  61. package/dist/client/hooks/useSelection.d.ts.map +0 -1
  62. package/dist/client/index.d.ts +0 -11
  63. package/dist/client/index.d.ts.map +0 -1
  64. package/dist/client/utils/cn.d.ts +0 -10
  65. package/dist/client/utils/cn.d.ts.map +0 -1
  66. package/dist/client/utils/index.d.ts +0 -60
  67. package/dist/client/utils/index.d.ts.map +0 -1
  68. package/dist/client.cjs +0 -85
  69. package/dist/client.cjs.map +0 -1
  70. package/dist/client.d.cts +0 -62
  71. package/dist/client.d.ts +0 -7
  72. package/dist/client.d.ts.map +0 -1
  73. package/dist/client.js +0 -4
  74. package/dist/client.js.map +0 -1
  75. package/dist/index-DUVfK8q6.d.ts +0 -284
  76. package/dist/index-qXbjvUTB.d.cts +0 -284
  77. package/dist/index.cjs +0 -300
  78. package/dist/index.cjs.map +0 -1
  79. package/dist/index.d.cts +0 -117
  80. package/dist/internal/hooks.cjs +0 -12
  81. package/dist/internal/hooks.cjs.map +0 -1
  82. package/dist/internal/hooks.d.cts +0 -1
  83. package/dist/internal/hooks.d.ts +0 -1
  84. package/dist/internal/hooks.js +0 -3
  85. package/dist/internal/hooks.js.map +0 -1
  86. package/dist/server/utils.d.ts +0 -52
  87. package/dist/server/utils.d.ts.map +0 -1
  88. package/dist/server.cjs +0 -315
  89. package/dist/server.cjs.map +0 -1
  90. package/dist/server.d.cts +0 -99
  91. package/dist/styles.css +0 -2
  92. package/dist/types/client/component.d.ts +0 -129
  93. package/dist/types/client/component.d.ts.map +0 -1
  94. package/dist/types/client/hook.d.ts +0 -116
  95. package/dist/types/client/hook.d.ts.map +0 -1
  96. package/dist/types/client/selectable.d.ts +0 -43
  97. package/dist/types/client/selectable.d.ts.map +0 -1
  98. package/dist/types/index.cjs +0 -4
  99. package/dist/types/index.cjs.map +0 -1
  100. package/dist/types/index.d.cts +0 -291
  101. package/dist/types/index.d.ts +0 -12
  102. package/dist/types/index.d.ts.map +0 -1
  103. package/dist/types/index.js +0 -3
  104. package/dist/types/index.js.map +0 -1
  105. package/dist/types/next-data-kit.d.ts +0 -95
  106. package/dist/types/next-data-kit.d.ts.map +0 -1
  107. package/dist/types/server/action.d.ts +0 -44
  108. package/dist/types/server/action.d.ts.map +0 -1
  109. package/dist/types/server/database/mongo.d.ts +0 -56
  110. package/dist/types/server/database/mongo.d.ts.map +0 -1
  111. package/dist/useDataKit-XFp3_mUc.d.cts +0 -276
  112. package/dist/useDataKit-XFp3_mUc.d.ts +0 -276
@@ -0,0 +1,12 @@
1
+ // src/server/source/define.ts
2
+ var sourceDefine = (props) => {
3
+ const { operator, and, or, list } = props;
4
+ const translate = (condition) => "or" in condition ? or(condition.or.map(translate)) : "native" in condition ? condition.native : operator[condition.operator]({ field: condition.field, value: condition.value });
5
+ return {
6
+ list: (props2) => list({ where: props2.filter.length ? and(props2.filter.map(translate)) : void 0, sort: props2.sort, page: props2.page })
7
+ };
8
+ };
9
+
10
+ export { sourceDefine };
11
+ //# sourceMappingURL=chunk-5D747NEB.js.map
12
+ //# sourceMappingURL=chunk-5D747NEB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server/source/define.ts"],"names":["props"],"mappings":";AAKO,IAAM,YAAA,GAAe,CAC3B,KAAA,KAM0B;AAE1B,EAAA,MAAM,EAAE,QAAA,EAAU,GAAA,EAAK,EAAA,EAAI,MAAK,GAAI,KAAA;AAGpC,EAAA,MAAM,SAAA,GAAY,CAAC,SAAA,KAClB,IAAA,IAAQ,SAAA,GAAY,EAAA,CAAG,SAAA,CAAU,EAAA,CAAG,GAAA,CAAI,SAAS,CAAC,CAAA,GAAI,QAAA,IAAY,SAAA,GAAa,SAAA,CAAU,MAAA,GAAqB,QAAA,CAAS,SAAA,CAAU,QAAQ,CAAA,CAAE,EAAE,KAAA,EAAO,SAAA,CAAU,KAAA,EAAO,KAAA,EAAO,SAAA,CAAU,KAAA,EAAgB,CAAA;AAEvM,EAAA,OAAO;AAAA,IACN,IAAA,EAAM,CAACA,MAAAA,KAAU,IAAA,CAAK,EAAE,KAAA,EAAOA,MAAAA,CAAM,MAAA,CAAO,MAAA,GAAS,GAAA,CAAIA,MAAAA,CAAM,OAAO,GAAA,CAAI,SAAS,CAAC,CAAA,GAAI,MAAA,EAAW,IAAA,EAAMA,OAAM,IAAA,EAAM,IAAA,EAAMA,MAAAA,CAAM,IAAA,EAAM;AAAA,GACxI;AACD","file":"chunk-5D747NEB.js","sourcesContent":["import type { TDataKitCondition, TDataKitOperator, TDataKitSort } from '../../types';\nimport type { TDataKitSource } from '../../types/server/source';\n\n// ** Build a source for any database: map the 11 operators to your query language once, then run the query in `list`\n// ** `between` always gets both ends; `in` / `nin` get an array; `contains` gets raw text (escape it); `null` gets true (is null) or false\nexport const sourceDefine = <TRow, TNative>(\n\tprops: Readonly<{\n\t\toperator: { [TKey in TDataKitOperator]: (props: Readonly<{ field: string; value: TKey extends 'in' | 'nin' ? unknown[] : TKey extends 'between' ? [unknown, unknown] : TKey extends 'null' ? boolean : unknown }>) => TNative };\n\t\tand: (list: TNative[]) => TNative;\n\t\tor: (list: TNative[]) => TNative;\n\t\tlist: (props: Readonly<{ where: TNative | undefined; sort: TDataKitSort[]; page: { offset: number; limit: number; count: boolean } }>) => Promise<{ rows: TRow[]; total: number | null }>;\n\t}>,\n): TDataKitSource<TRow> => {\n\t// ** Deconstruct Props\n\tconst { operator, and, or, list } = props;\n\n\t// ** A custom filter's `native` query passes through untouched\n\tconst translate = (condition: TDataKitCondition): TNative =>\n\t\t'or' in condition ? or(condition.or.map(translate)) : 'native' in condition ? (condition.native as TNative) : operator[condition.operator]({ field: condition.field, value: condition.value as never });\n\n\treturn {\n\t\tlist: (props) => list({ where: props.filter.length ? and(props.filter.map(translate)) : undefined, sort: props.sort, page: props.page }),\n\t};\n};\n"]}
package/dist/index.d.ts CHANGED
@@ -1,117 +1,116 @@
1
- import { T as TDataKitInput, a as TMongoFilterQuery, b as TFilterCustomConfigWithFilter, c as TSortOptions, d as TDataKitAdapter, e as TDataKitResult, f as TMongoModel, g as TPaginationInfo } from './useDataKit-XFp3_mUc.js';
2
- export { p as TDataKitActions, r as TDataKitColumn, o as TDataKitState, m as TFilterConfig, n as TFilterCustomConfig, j as TMongoFilterOperators, k as TMongoRootFilterOperators, l as TSortEntry, i as TSortOrder, h as TUseDataKitOptions, q as TUseDataKitReturn, u as useDataKit } from './useDataKit-XFp3_mUc.js';
3
- import { Model } from 'mongoose';
4
- export { f as DataKit, e as DataKitContext, D as DataKitProvider, y as TDataKitBulkAction, w as TDataKitComponentColumn, m as TDataKitContextValue, z as TDataKitController, x as TDataKitFilterItem, B as TDataKitMemoryMode, C as TDataKitRef, A as TDataKitSelectableItem, v as TExtractDataKitItemType, r as TSelectable, o as TSelectionActions, q as TSelectionMode, n as TSelectionState, T as TUsePaginationReturn, p as TUseSelectionReturn, c as createDataKitContext, k as debounce, j as formatNumber, g as getColumnValue, i as getNextSortValue, h as getSortValue, l as keyToSortEntries, s as sortEntriesToKey, t as throttle, d as useDataKitContext, b as usePagination, u as useSelection, a as useSelectionWithTotal } from './index-DUVfK8q6.js';
5
- import 'react';
6
- import 'react/jsx-runtime';
1
+ import * as react from 'react';
7
2
 
8
- /**
9
- * next-data-kit - Server Action Types
10
- *
11
- * Types for the server action and data kit operations.
12
- */
13
-
14
- /**
15
- * Extract document type from a Mongoose Model.
16
- */
17
- type TExtractDocType<M> = M extends Model<infer TRawDocType, any, any, any, any, any> ? TRawDocType : never;
18
- /**
19
- * Base options shared by both mongoose and adapter versions
20
- */
21
- type TBaseOptions<TDoc, R> = {
22
- input: TDataKitInput<TDoc>;
23
- item: (item: TDoc) => Promise<R> | R;
24
- filterAllowed?: string[];
25
- maxLimit?: number;
26
- queryAllowed?: (keyof TDoc | string)[];
27
- sortAllowed?: (keyof TDoc | string)[];
3
+ type TDataKitSort = {
4
+ field: string;
5
+ direction: 'asc' | 'desc';
28
6
  };
29
- /**
30
- * Options when using a Mongoose model
31
- */
32
- type TMongooseOptions<M, TDoc, R> = TBaseOptions<TDoc, R> & {
33
- model: M;
34
- adapter?: never;
35
- filter?: ((filterInput?: Record<string, unknown>) => TMongoFilterQuery<TDoc>) | TMongoFilterQuery<TDoc>;
36
- filterCustom?: TFilterCustomConfigWithFilter<TDoc, TMongoFilterQuery<TDoc>>;
37
- defaultSort?: TSortOptions<TDoc>;
7
+ type TDataKitVariant = 'text' | 'number' | 'range' | 'select' | 'multiSelect' | 'boolean' | 'date' | 'dateRange';
8
+ type TDataKitInput = {
9
+ page: {
10
+ number: number;
11
+ size: number;
12
+ };
13
+ sort: {
14
+ column: string;
15
+ direction: 'asc' | 'desc';
16
+ }[];
17
+ filter: Record<string, string>;
18
+ search?: string;
38
19
  };
39
- /**
40
- * Options when using a custom adapter
41
- */
42
- type TAdapterOptions<TDoc, R> = TBaseOptions<TDoc, R> & {
43
- adapter: TDataKitAdapter<TDoc>;
44
- model?: never;
45
- filter?: never;
46
- filterCustom?: TFilterCustomConfigWithFilter<TDoc, unknown>;
47
- defaultSort?: never;
20
+ type TDataKitColumnMeta = {
21
+ filter?: TDataKitVariant | 'custom';
22
+ option?: string[];
23
+ preset?: string[];
24
+ sort: boolean;
25
+ hidden: boolean;
26
+ };
27
+ type TDataKitData<TRow> = TDataKitInput & {
28
+ rows: TRow[];
29
+ total: number | null;
30
+ meta: {
31
+ column: Record<string, TDataKitColumnMeta>;
32
+ search: boolean;
33
+ sort: TDataKitInput['sort'];
34
+ };
48
35
  };
49
36
 
50
- /**
51
- * next-data-kit - Server Action
52
- *
53
- * The main server-side function for handling table data fetching
54
- * with pagination, filtering, and sorting.
55
- */
56
-
57
- /**
58
- * Server action with Mongoose model (auto-infers document type)
59
- */
60
- declare function dataKitServerAction<M extends Model<any>, R = unknown>(props: Readonly<TMongooseOptions<M, TExtractDocType<M>, R>>): Promise<TDataKitResult<R>>;
61
- /**
62
- * Server action with custom adapter
63
- */
64
- declare function dataKitServerAction<TDoc, R = unknown>(props: Readonly<TAdapterOptions<TDoc, R>>): Promise<TDataKitResult<R>>;
65
-
66
- /**
67
- * next-data-kit - Mongoose Adapter
68
- *
69
- * Database adapter for Mongoose/MongoDB.
70
- */
71
-
72
- declare const mongooseAdapter: <DocType = unknown>(model: TMongoModel<DocType>, options?: Readonly<{
73
- filter?: ((filterInput?: Record<string, unknown>) => TMongoFilterQuery<DocType>) | TMongoFilterQuery<DocType>;
74
- filterCustom?: TFilterCustomConfigWithFilter<DocType, TMongoFilterQuery<DocType>>;
75
- defaultSort?: TSortOptions<DocType>;
76
- }>) => TDataKitAdapter<DocType>;
77
-
78
- /**
79
- * next-data-kit - Memory Adapter
80
- *
81
- * In-memory adapter for demos, tests, and local playgrounds.
82
- * Implements the React Data Kit adapter contract over an array dataset.
83
- */
84
-
85
- /**
86
- * Creates an adapter that pages/filters/sorts an in-memory dataset.
87
- */
88
- declare const adapterMemory: <T extends Record<string, unknown>>(dataset: ReadonlyArray<T>, options?: Readonly<{
89
- /** default behavior for filter keys not present in filterConfig */
90
- defaultFilterType?: "regex" | "exact";
91
- }>) => TDataKitAdapter<T>;
92
-
93
- /**
94
- * next-data-kit - Server Utilities
95
- */
37
+ declare const useDataKit: <TRow extends {
38
+ id: string;
39
+ }>(props: Readonly<{
40
+ data: TDataKitData<TRow>;
41
+ source: {
42
+ navigate: (url: string) => void;
43
+ refresh?: () => void;
44
+ } | {
45
+ fetch: (input: unknown) => Promise<TDataKitData<TRow>>;
46
+ url?: boolean;
47
+ };
48
+ key?: string;
49
+ append?: boolean;
50
+ refetch?: {
51
+ intervalMs: number;
52
+ };
53
+ }>) => {
54
+ key: string | undefined;
55
+ rows: TRow[];
56
+ total: number | null;
57
+ meta: {
58
+ column: Record<string, TDataKitColumnMeta>;
59
+ search: boolean;
60
+ sort: TDataKitInput["sort"];
61
+ };
62
+ page: {
63
+ number: number;
64
+ size: number;
65
+ count: number | null;
66
+ next: boolean;
67
+ };
68
+ sort: {
69
+ column: string;
70
+ direction: "asc" | "desc";
71
+ }[];
72
+ filter: Record<string, string>;
73
+ search: string;
74
+ state: {
75
+ isPending: boolean;
76
+ error: Error | null;
77
+ };
78
+ input: TDataKitInput;
79
+ url: (input: TDataKitInput) => string;
80
+ set: {
81
+ page: (number: number) => void;
82
+ size: (size: number) => void;
83
+ sort: (sort: TDataKitInput["sort"]) => void;
84
+ filter: (filter: Record<string, string | undefined>) => void;
85
+ search: (search: string) => void;
86
+ };
87
+ refresh: () => void;
88
+ reset: () => void;
89
+ row: {
90
+ push: (props: Readonly<{
91
+ row: TRow;
92
+ position?: "start" | "end";
93
+ }>) => void;
94
+ update: (props: Readonly<{
95
+ id: string;
96
+ data: Partial<TRow>;
97
+ }>) => void;
98
+ remove: (props: Readonly<{
99
+ id: string;
100
+ }>) => void;
101
+ };
102
+ selection: {
103
+ ids: string[];
104
+ set: react.Dispatch<react.SetStateAction<string[]>>;
105
+ clear: () => void;
106
+ };
107
+ };
96
108
 
97
- /**
98
- * Helper to escape regex special characters in a string
99
- */
100
- declare const escapeRegex: (str: string) => string;
101
- /**
102
- * Create a search filter for multiple fields
103
- *
104
- * @example
105
- * ```typescript
106
- * filterCustom: {
107
- * search: createSearchFilter(['name', 'email', 'phone'])
108
- * }
109
- * ```
110
- */
111
- declare const createSearchFilter: <T>(fields: (keyof T | string)[]) => ((value: unknown) => TMongoFilterQuery<T>);
112
- /**
113
- * Calculate pagination info from page, limit, and total
114
- */
115
- declare const calculatePagination: (page: number, limit: number, total: number) => TPaginationInfo;
109
+ declare const urlEncode: (props: Readonly<{
110
+ input: TDataKitInput;
111
+ key?: string;
112
+ search?: string;
113
+ remove?: string[];
114
+ }>) => string;
116
115
 
117
- export { type TAdapterOptions, type TBaseOptions, TDataKitAdapter, TDataKitInput, TDataKitResult, type TExtractDocType, TFilterCustomConfigWithFilter, TMongoFilterQuery, TMongoModel, type TMongooseOptions, TPaginationInfo, TSortOptions, adapterMemory, calculatePagination, createSearchFilter, dataKitServerAction, escapeRegex, mongooseAdapter };
116
+ export { type TDataKitColumnMeta, type TDataKitData, type TDataKitInput, type TDataKitSort, type TDataKitVariant, urlEncode, useDataKit };
package/dist/index.js CHANGED
@@ -1,217 +1,121 @@
1
- import { isProvided, isSafeKey, escapeRegex, getValueByPath, matchesExact, matchesRegexLike, normalizeSorts, compareValues } from './chunk-O377UO7C.js';
2
- export { DataKit, DefaultDataKitContext as DataKitContext, DefaultDataKitProvider as DataKitProvider, calculatePagination, createDataKitContext, createSearchFilter, escapeRegex, useDefaultDataKitContext as useDataKitContext, usePagination, useSelection, useSelectionWithTotal } from './chunk-O377UO7C.js';
3
- export { debounce, formatNumber, getColumnValue, getNextSortValue, getSortValue, keyToSortEntries, sortEntriesToKey, throttle, useDataKit } from './chunk-VFSNUXOW.js';
1
+ 'use client';
4
2
 
5
- // src/server/adapters/mongoose.ts
6
- var mongooseAdapter = (model, options = {}) => {
7
- const { filter: customFilter, filterCustom, defaultSort = { _id: -1 } } = options;
8
- return async ({ filter, sorts, limit, skip, input }) => {
9
- let sortOption;
10
- if (input.sort && Object.keys(input.sort).length > 0) {
11
- sortOption = input.sort;
12
- } else if (sorts && sorts.length > 0) {
13
- sortOption = sorts.reduce((acc, s) => {
14
- if (s?.path && (s.value === 1 || s.value === -1)) {
15
- acc[s.path] = s.value;
16
- }
17
- return acc;
18
- }, {});
19
- } else {
20
- sortOption = defaultSort;
21
- }
22
- let filterQuery = {};
23
- if (input.query) {
24
- Object.entries(input.query).forEach(([key, value]) => {
25
- if (isProvided(value) && isSafeKey(key)) {
26
- filterQuery[key] = value;
27
- }
28
- });
29
- }
30
- if (customFilter) {
31
- const customQuery = typeof customFilter === "function" ? customFilter(filter) : customFilter;
32
- filterQuery = { ...filterQuery, ...customQuery };
33
- }
34
- if (filter && !customFilter) {
35
- if (input.filterConfig) {
36
- Object.entries(filter).forEach(([key, value]) => {
37
- if (filterCustom && filterCustom[key]) return;
38
- if (isProvided(value) && isSafeKey(key) && input.filterConfig?.[key]) {
39
- const config = input.filterConfig[key];
40
- const fieldName = config?.field ?? key;
41
- if (config?.type === "REGEX") {
42
- filterQuery[fieldName] = {
43
- $regex: escapeRegex(String(value)),
44
- $options: "i"
45
- };
46
- } else if (config?.type === "EXACT") {
47
- filterQuery[fieldName] = value;
48
- }
49
- }
50
- });
51
- } else {
52
- Object.entries(filter).forEach(([key, value]) => {
53
- if (filterCustom && filterCustom[key]) return;
54
- if (isProvided(value) && isSafeKey(key)) {
55
- if (typeof value === "string") {
56
- filterQuery[key] = {
57
- $regex: escapeRegex(value),
58
- $options: "i"
59
- };
60
- } else if (typeof value === "number" || typeof value === "boolean") {
61
- filterQuery[key] = value;
62
- }
63
- }
64
- });
65
- }
66
- }
67
- if (filterCustom && filter) {
68
- Object.entries(filter).forEach(([key, value]) => {
69
- if (isProvided(value) && isSafeKey(key) && filterCustom[key]) {
70
- const customFilter2 = filterCustom[key](value);
71
- filterQuery = { ...filterQuery, ...customFilter2 };
72
- }
73
- });
74
- }
75
- const total = await model.countDocuments(filterQuery);
76
- const items = await model.find(filterQuery).sort(sortOption).limit(limit).skip(skip);
77
- return { items, total };
3
+ // src/hook/index.ts
4
+ import { useEffect, useRef, useState, useTransition } from "react";
5
+
6
+ // src/url/index.ts
7
+ var reserved = ["page", "size", "sort", "search"];
8
+ var urlEncode = (props) => {
9
+ const { input, key, search, remove = [] } = props;
10
+ const prefix = key ? `${key}.` : "";
11
+ const params = new URLSearchParams(search);
12
+ [...params.keys()].filter((name) => key ? name.startsWith(prefix) : reserved.includes(name) || name in input.filter || remove.includes(name)).forEach((name) => params.delete(name));
13
+ if (input.page.number > 1) params.set(`${prefix}page`, String(input.page.number));
14
+ params.set(`${prefix}size`, String(input.page.size));
15
+ if (input.sort.length) params.set(`${prefix}sort`, input.sort.map((sort) => `${sort.column}.${sort.direction}`).join(","));
16
+ if (input.search) params.set(`${prefix}search`, input.search);
17
+ Object.entries(input.filter).forEach(([name, value]) => {
18
+ if (value) params.set(`${prefix}${name}`, value);
19
+ });
20
+ return params.toString();
21
+ };
22
+ var urlDecode = (props) => {
23
+ const { searchParams, key } = props;
24
+ const prefix = key ? `${key}.` : "";
25
+ const entries = (searchParams instanceof URLSearchParams ? [...searchParams.entries()] : Object.entries(searchParams).map(([name, value]) => [name, Array.isArray(value) ? value[0] : value])).filter((entry) => typeof entry[1] === "string" && entry[0].startsWith(prefix)).map(([name, value]) => [name.slice(prefix.length), value]);
26
+ const values = Object.fromEntries(entries);
27
+ return {
28
+ page: { number: values.page, size: values.size },
29
+ sort: (values.sort ?? "").split(",").filter(Boolean).map((sort) => ({ column: sort.slice(0, sort.lastIndexOf(".")), direction: sort.slice(sort.lastIndexOf(".") + 1) })),
30
+ search: values.search,
31
+ filter: Object.fromEntries(entries.filter(([name]) => !reserved.includes(name)))
78
32
  };
79
33
  };
80
34
 
81
- // src/server/action.ts
82
- async function executeDataKit(input, adapter, item, maxLimit, filterAllowed, queryAllowed, sortAllowed) {
83
- if (input.query) {
84
- const safeQuery = {};
85
- Object.keys(input.query).forEach((key) => {
86
- if (queryAllowed && !queryAllowed.includes(key)) {
87
- throw new Error(`[Security] Query field '${key}' is not allowed.`);
88
- }
89
- const val = input.query[key];
90
- if (val !== null && typeof val === "object") {
91
- throw new Error(`[Security] Query value for '${key}' must be a primitive.`);
92
- }
93
- if (val !== void 0) {
94
- safeQuery[key] = val;
95
- }
96
- });
97
- input.query = safeQuery;
98
- }
99
- if (input.filter) {
100
- const safeFilter = {};
101
- Object.keys(input.filter).forEach((key) => {
102
- if (filterAllowed && !filterAllowed.includes(key)) {
103
- throw new Error(`[Security] Filter field '${key}' is not allowed.`);
104
- }
105
- const val = input.filter[key];
106
- if (val !== null && typeof val === "object") {
107
- throw new Error(`[Security] Filter value for '${key}' must be a primitive.`);
108
- }
109
- if (val !== void 0) {
110
- safeFilter[key] = val;
111
- }
112
- });
113
- input.filter = safeFilter;
114
- }
115
- if (input.sorts && sortAllowed) {
116
- input.sorts.forEach((sort) => {
117
- if (!sortAllowed.includes(sort.path)) {
118
- throw new Error(`[Security] Sort field '${sort.path}' is not allowed.`);
119
- }
120
- });
35
+ // src/hook/index.ts
36
+ var useDataKit = (props) => {
37
+ const { data, source, key, append, refetch } = props;
38
+ const [isPending, startTransition] = useTransition();
39
+ const [result, setResult] = useState(data);
40
+ const [previous, setPrevious] = useState(data);
41
+ const [error, setError] = useState(null);
42
+ const [selected, setSelected] = useState([]);
43
+ const sequence = useRef(0);
44
+ if (data !== previous) {
45
+ setPrevious(data);
46
+ setResult(data);
47
+ setSelected((ids) => ids.filter((id) => data.rows.some((row) => row.id === id)));
121
48
  }
122
- switch (input.action ?? "FETCH") {
123
- case "FETCH": {
124
- if (!input.limit || !input.page) {
125
- throw new Error("Invalid input: missing limit or page");
126
- }
127
- const limit = Math.min(input.limit, maxLimit);
128
- const skip = limit * (input.page - 1);
129
- const { items, total } = await adapter({
130
- filter: input.filter ?? {},
131
- sorts: input.sorts ?? [],
132
- limit,
133
- page: input.page,
134
- skip,
135
- input
136
- });
137
- const processedItems = await Promise.all(items.map((dataItem) => item(dataItem)));
138
- return {
139
- type: "ITEMS",
140
- items: processedItems,
141
- documentTotal: total
142
- };
49
+ const current = { page: result.page, sort: result.sort, filter: result.filter, ...result.search && { search: result.search } };
50
+ const url = (input) => `${window.location.pathname}?${urlEncode({ input, key, search: window.location.search, remove: Object.keys(current.filter) })}`;
51
+ const go = (input, more) => {
52
+ setError(null);
53
+ if ("navigate" in source) {
54
+ startTransition(() => source.navigate(url(input)));
55
+ return;
143
56
  }
144
- default:
145
- throw new Error(`Unsupported action: ${input.action}`);
146
- }
147
- }
148
- async function dataKitServerAction(props) {
149
- const { input, item, maxLimit = 100, queryAllowed, filterAllowed: explicitFilterAllowed, sortAllowed } = props;
150
- const filterAllowed = explicitFilterAllowed;
151
- let finalAdapter;
152
- if ("adapter" in props && props.adapter) {
153
- finalAdapter = props.adapter;
154
- } else if ("model" in props && props.model) {
155
- const model = props.model;
156
- finalAdapter = mongooseAdapter(model, {
157
- filter: props.filter,
158
- filterCustom: props.filterCustom,
159
- defaultSort: props.defaultSort
160
- });
161
- } else {
162
- throw new Error("Either model or adapter must be provided");
163
- }
164
- return executeDataKit(input, finalAdapter, item, maxLimit, filterAllowed, queryAllowed, sortAllowed);
165
- }
166
-
167
- // src/server/adapters/memory.ts
168
- var adapterMemory = (dataset, options = {}) => {
169
- const { defaultFilterType = "exact" } = options;
170
- return async ({ filter, sorts, limit, skip, input }) => {
171
- const filterConfig = input.filterConfig;
172
- const query = input.query ?? {};
173
- let rows = dataset.filter((row) => {
174
- for (const [key, value] of Object.entries(query)) {
175
- if (!isProvided(value)) continue;
176
- const rowValue = getValueByPath(row, key);
177
- if (!matchesExact(rowValue, value)) return false;
178
- }
179
- return true;
180
- });
181
- const effectiveFilter = filter ?? {};
182
- rows = rows.filter((row) => {
183
- for (const [key, value] of Object.entries(effectiveFilter)) {
184
- if (!isProvided(value)) continue;
185
- const config = filterConfig?.[key];
186
- const field = config?.field ?? key;
187
- const rowValue = getValueByPath(row, field);
188
- const type = config?.type ?? defaultFilterType;
189
- if (type === "regex") {
190
- if (!matchesRegexLike(rowValue, value)) return false;
191
- } else {
192
- if (!matchesExact(rowValue, value)) return false;
193
- }
57
+ const request = ++sequence.current;
58
+ startTransition(async () => {
59
+ try {
60
+ const next2 = await source.fetch(input);
61
+ if (request !== sequence.current) return;
62
+ if (source.url && !more) window.history.pushState(null, "", url(next2));
63
+ startTransition(() => setResult((value) => more ? { ...next2, rows: [...value.rows, ...next2.rows.filter((row) => !value.rows.some((item) => item.id === row.id))] } : next2));
64
+ } catch (caught) {
65
+ if (request === sequence.current) setError(caught instanceof Error ? caught : new Error(String(caught)));
194
66
  }
195
- return true;
196
67
  });
197
- const normalizedSorts = normalizeSorts(sorts);
198
- if (normalizedSorts.length > 0) {
199
- rows = [...rows].sort((ra, rb) => {
200
- for (const s of normalizedSorts) {
201
- const av = getValueByPath(ra, s.path);
202
- const bv = getValueByPath(rb, s.path);
203
- const cmp = compareValues(av, bv);
204
- if (cmp !== 0) return s.value === 1 ? cmp : -cmp;
205
- }
206
- return 0;
207
- });
68
+ };
69
+ const refresh = () => "navigate" in source ? source.refresh?.() : go(current);
70
+ useEffect(() => {
71
+ if ("navigate" in source || !source.url) return;
72
+ const listener = () => go(urlDecode({ searchParams: new URLSearchParams(window.location.search), key }));
73
+ window.addEventListener("popstate", listener);
74
+ return () => window.removeEventListener("popstate", listener);
75
+ });
76
+ useEffect(() => {
77
+ if (!refetch) return;
78
+ const interval = setInterval(refresh, refetch.intervalMs);
79
+ return () => clearInterval(interval);
80
+ });
81
+ const count = result.total === null ? null : Math.max(1, Math.ceil(result.total / result.page.size));
82
+ const next = result.total === null ? result.rows.length >= result.page.size : result.page.number < (count ?? 1);
83
+ return {
84
+ key,
85
+ rows: result.rows,
86
+ total: result.total,
87
+ meta: result.meta,
88
+ page: { number: result.page.number, size: result.page.size, count, next },
89
+ sort: result.sort,
90
+ filter: result.filter,
91
+ search: result.search ?? "",
92
+ state: { isPending, error },
93
+ input: current,
94
+ url,
95
+ set: {
96
+ page: (number) => go({ ...current, page: { ...current.page, number } }, append && number === current.page.number + 1),
97
+ size: (size) => go({ ...current, page: { number: 1, size } }),
98
+ sort: (sort) => go({ ...current, page: { ...current.page, number: 1 }, sort }),
99
+ // ** A changed filter or search always starts again from page 1; undefined or "" clears it
100
+ filter: (filter) => go({ ...current, page: { ...current.page, number: 1 }, filter: Object.fromEntries(Object.entries({ ...current.filter, ...filter }).filter((entry) => Boolean(entry[1]))) }),
101
+ search: (search) => go({ ...current, page: { ...current.page, number: 1 }, ...search.trim() ? { search: search.trim() } : { search: void 0 } })
102
+ },
103
+ refresh,
104
+ reset: () => go({ page: { number: 1, size: result.page.size }, sort: [], filter: {} }),
105
+ row: {
106
+ push: (props2) => setResult((value) => ({ ...value, total: value.total === null ? null : value.total + 1, rows: props2.position === "end" ? [...value.rows, props2.row] : [props2.row, ...value.rows] })),
107
+ update: (props2) => setResult((value) => ({ ...value, rows: value.rows.map((row) => row.id === props2.id ? { ...row, ...props2.data } : row) })),
108
+ remove: (props2) => setResult((value) => ({ ...value, total: value.total === null ? null : value.total - 1, rows: value.rows.filter((row) => row.id !== props2.id) }))
109
+ },
110
+ selection: {
111
+ ids: selected,
112
+ set: setSelected,
113
+ clear: () => setSelected([])
208
114
  }
209
- const total = rows.length;
210
- const items = rows.slice(skip, skip + limit);
211
- return { items, total };
212
115
  };
213
116
  };
214
-
215
- export { adapterMemory, dataKitServerAction, mongooseAdapter };
216
- //# sourceMappingURL=index.js.map
117
+ export {
118
+ urlEncode,
119
+ useDataKit
120
+ };
217
121
  //# sourceMappingURL=index.js.map