next-data-kit 10.0.0 → 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.
- package/MIGRATION.md +35 -3
- package/README.md +360 -94
- package/dist/chunk-5D747NEB.js +12 -0
- package/dist/chunk-5D747NEB.js.map +1 -0
- package/dist/index.d.ts +53 -22
- package/dist/index.js +44 -33
- package/dist/index.js.map +1 -1
- package/dist/server/drizzle.d.ts +11 -0
- package/dist/server/drizzle.js +39 -0
- package/dist/server/drizzle.js.map +1 -0
- package/dist/server.d.ts +227 -74
- package/dist/server.js +247 -71
- package/dist/server.js.map +1 -1
- package/dist/source--l-z9HHB.d.ts +60 -0
- package/package.json +31 -9
- package/registry/r/data-kit.json +35 -19
- package/registry/r/registry.json +58 -9
package/dist/index.d.ts
CHANGED
|
@@ -1,29 +1,48 @@
|
|
|
1
|
+
import * as react from 'react';
|
|
2
|
+
|
|
1
3
|
type TDataKitSort = {
|
|
2
4
|
field: string;
|
|
3
5
|
direction: 'asc' | 'desc';
|
|
4
6
|
};
|
|
7
|
+
type TDataKitVariant = 'text' | 'number' | 'range' | 'select' | 'multiSelect' | 'boolean' | 'date' | 'dateRange';
|
|
5
8
|
type TDataKitInput = {
|
|
6
9
|
page: {
|
|
7
10
|
number: number;
|
|
8
11
|
size: number;
|
|
9
12
|
};
|
|
10
|
-
sort:
|
|
11
|
-
|
|
13
|
+
sort: {
|
|
14
|
+
column: string;
|
|
15
|
+
direction: 'asc' | 'desc';
|
|
16
|
+
}[];
|
|
17
|
+
filter: Record<string, string>;
|
|
18
|
+
search?: string;
|
|
19
|
+
};
|
|
20
|
+
type TDataKitColumnMeta = {
|
|
21
|
+
filter?: TDataKitVariant | 'custom';
|
|
22
|
+
option?: string[];
|
|
23
|
+
preset?: string[];
|
|
24
|
+
sort: boolean;
|
|
25
|
+
hidden: boolean;
|
|
12
26
|
};
|
|
13
|
-
type
|
|
14
|
-
|
|
15
|
-
total: number;
|
|
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
|
+
};
|
|
16
35
|
};
|
|
17
36
|
|
|
18
|
-
declare const useDataKit: <
|
|
37
|
+
declare const useDataKit: <TRow extends {
|
|
19
38
|
id: string;
|
|
20
39
|
}>(props: Readonly<{
|
|
21
|
-
|
|
40
|
+
data: TDataKitData<TRow>;
|
|
22
41
|
source: {
|
|
23
42
|
navigate: (url: string) => void;
|
|
24
43
|
refresh?: () => void;
|
|
25
44
|
} | {
|
|
26
|
-
fetch: (input: unknown) => Promise<
|
|
45
|
+
fetch: (input: unknown) => Promise<TDataKitData<TRow>>;
|
|
27
46
|
url?: boolean;
|
|
28
47
|
};
|
|
29
48
|
key?: string;
|
|
@@ -33,35 +52,48 @@ declare const useDataKit: <TItem extends {
|
|
|
33
52
|
};
|
|
34
53
|
}>) => {
|
|
35
54
|
key: string | undefined;
|
|
36
|
-
|
|
37
|
-
total: number;
|
|
55
|
+
rows: TRow[];
|
|
56
|
+
total: number | null;
|
|
57
|
+
meta: {
|
|
58
|
+
column: Record<string, TDataKitColumnMeta>;
|
|
59
|
+
search: boolean;
|
|
60
|
+
sort: TDataKitInput["sort"];
|
|
61
|
+
};
|
|
38
62
|
page: {
|
|
39
63
|
number: number;
|
|
40
64
|
size: number;
|
|
41
|
-
count: number;
|
|
65
|
+
count: number | null;
|
|
66
|
+
next: boolean;
|
|
42
67
|
};
|
|
43
|
-
sort:
|
|
44
|
-
|
|
68
|
+
sort: {
|
|
69
|
+
column: string;
|
|
70
|
+
direction: "asc" | "desc";
|
|
71
|
+
}[];
|
|
72
|
+
filter: Record<string, string>;
|
|
73
|
+
search: string;
|
|
45
74
|
state: {
|
|
46
75
|
isPending: boolean;
|
|
47
76
|
error: Error | null;
|
|
48
77
|
};
|
|
78
|
+
input: TDataKitInput;
|
|
79
|
+
url: (input: TDataKitInput) => string;
|
|
49
80
|
set: {
|
|
50
81
|
page: (number: number) => void;
|
|
51
82
|
size: (size: number) => void;
|
|
52
|
-
sort: (sort:
|
|
53
|
-
filter: (filter: Record<string,
|
|
83
|
+
sort: (sort: TDataKitInput["sort"]) => void;
|
|
84
|
+
filter: (filter: Record<string, string | undefined>) => void;
|
|
85
|
+
search: (search: string) => void;
|
|
54
86
|
};
|
|
55
87
|
refresh: () => void;
|
|
56
88
|
reset: () => void;
|
|
57
|
-
|
|
89
|
+
row: {
|
|
58
90
|
push: (props: Readonly<{
|
|
59
|
-
|
|
91
|
+
row: TRow;
|
|
60
92
|
position?: "start" | "end";
|
|
61
93
|
}>) => void;
|
|
62
94
|
update: (props: Readonly<{
|
|
63
95
|
id: string;
|
|
64
|
-
data: Partial<
|
|
96
|
+
data: Partial<TRow>;
|
|
65
97
|
}>) => void;
|
|
66
98
|
remove: (props: Readonly<{
|
|
67
99
|
id: string;
|
|
@@ -69,9 +101,7 @@ declare const useDataKit: <TItem extends {
|
|
|
69
101
|
};
|
|
70
102
|
selection: {
|
|
71
103
|
ids: string[];
|
|
72
|
-
|
|
73
|
-
toggle: (id: string) => void;
|
|
74
|
-
all: () => void;
|
|
104
|
+
set: react.Dispatch<react.SetStateAction<string[]>>;
|
|
75
105
|
clear: () => void;
|
|
76
106
|
};
|
|
77
107
|
};
|
|
@@ -80,6 +110,7 @@ declare const urlEncode: (props: Readonly<{
|
|
|
80
110
|
input: TDataKitInput;
|
|
81
111
|
key?: string;
|
|
82
112
|
search?: string;
|
|
113
|
+
remove?: string[];
|
|
83
114
|
}>) => string;
|
|
84
115
|
|
|
85
|
-
export { type
|
|
116
|
+
export { type TDataKitColumnMeta, type TDataKitData, type TDataKitInput, type TDataKitSort, type TDataKitVariant, urlEncode, useDataKit };
|
package/dist/index.js
CHANGED
|
@@ -1,19 +1,21 @@
|
|
|
1
1
|
'use client';
|
|
2
2
|
|
|
3
3
|
// src/hook/index.ts
|
|
4
|
-
import { useEffect, useState, useTransition } from "react";
|
|
4
|
+
import { useEffect, useRef, useState, useTransition } from "react";
|
|
5
5
|
|
|
6
6
|
// src/url/index.ts
|
|
7
|
+
var reserved = ["page", "size", "sort", "search"];
|
|
7
8
|
var urlEncode = (props) => {
|
|
8
|
-
const { input, key, search } = props;
|
|
9
|
+
const { input, key, search, remove = [] } = props;
|
|
9
10
|
const prefix = key ? `${key}.` : "";
|
|
10
11
|
const params = new URLSearchParams(search);
|
|
11
|
-
[...params.keys()].filter((name) => key ? name.startsWith(prefix) :
|
|
12
|
+
[...params.keys()].filter((name) => key ? name.startsWith(prefix) : reserved.includes(name) || name in input.filter || remove.includes(name)).forEach((name) => params.delete(name));
|
|
12
13
|
if (input.page.number > 1) params.set(`${prefix}page`, String(input.page.number));
|
|
13
14
|
params.set(`${prefix}size`, String(input.page.size));
|
|
14
|
-
if (input.sort.length) params.set(`${prefix}sort`, input.sort.map((sort) => `${sort.
|
|
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);
|
|
15
17
|
Object.entries(input.filter).forEach(([name, value]) => {
|
|
16
|
-
if (value
|
|
18
|
+
if (value) params.set(`${prefix}${name}`, value);
|
|
17
19
|
});
|
|
18
20
|
return params.toString();
|
|
19
21
|
};
|
|
@@ -24,40 +26,46 @@ var urlDecode = (props) => {
|
|
|
24
26
|
const values = Object.fromEntries(entries);
|
|
25
27
|
return {
|
|
26
28
|
page: { number: values.page, size: values.size },
|
|
27
|
-
sort: (values.sort ?? "").split(",").filter(Boolean).map((sort) => ({
|
|
28
|
-
|
|
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)))
|
|
29
32
|
};
|
|
30
33
|
};
|
|
31
34
|
|
|
32
35
|
// src/hook/index.ts
|
|
33
36
|
var useDataKit = (props) => {
|
|
34
|
-
const {
|
|
37
|
+
const { data, source, key, append, refetch } = props;
|
|
35
38
|
const [isPending, startTransition] = useTransition();
|
|
36
|
-
const [result, setResult] = useState(
|
|
37
|
-
const [previous, setPrevious] = useState(
|
|
39
|
+
const [result, setResult] = useState(data);
|
|
40
|
+
const [previous, setPrevious] = useState(data);
|
|
38
41
|
const [error, setError] = useState(null);
|
|
39
42
|
const [selected, setSelected] = useState([]);
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
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)));
|
|
43
48
|
}
|
|
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) })}`;
|
|
44
51
|
const go = (input, more) => {
|
|
45
52
|
setError(null);
|
|
46
53
|
if ("navigate" in source) {
|
|
47
|
-
startTransition(() => source.navigate(
|
|
54
|
+
startTransition(() => source.navigate(url(input)));
|
|
48
55
|
return;
|
|
49
56
|
}
|
|
57
|
+
const request = ++sequence.current;
|
|
50
58
|
startTransition(async () => {
|
|
51
59
|
try {
|
|
52
|
-
const
|
|
53
|
-
if (
|
|
54
|
-
|
|
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));
|
|
55
64
|
} catch (caught) {
|
|
56
|
-
setError(caught instanceof Error ? caught : new Error(String(caught)));
|
|
65
|
+
if (request === sequence.current) setError(caught instanceof Error ? caught : new Error(String(caught)));
|
|
57
66
|
}
|
|
58
67
|
});
|
|
59
68
|
};
|
|
60
|
-
const current = { page: result.page, sort: result.sort, filter: result.filter };
|
|
61
69
|
const refresh = () => "navigate" in source ? source.refresh?.() : go(current);
|
|
62
70
|
useEffect(() => {
|
|
63
71
|
if ("navigate" in source || !source.url) return;
|
|
@@ -70,35 +78,38 @@ var useDataKit = (props) => {
|
|
|
70
78
|
const interval = setInterval(refresh, refetch.intervalMs);
|
|
71
79
|
return () => clearInterval(interval);
|
|
72
80
|
});
|
|
73
|
-
const count = Math.max(1, Math.ceil(result.total / result.page.size));
|
|
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);
|
|
74
83
|
return {
|
|
75
84
|
key,
|
|
76
|
-
|
|
85
|
+
rows: result.rows,
|
|
77
86
|
total: result.total,
|
|
78
|
-
|
|
87
|
+
meta: result.meta,
|
|
88
|
+
page: { number: result.page.number, size: result.page.size, count, next },
|
|
79
89
|
sort: result.sort,
|
|
80
90
|
filter: result.filter,
|
|
91
|
+
search: result.search ?? "",
|
|
81
92
|
state: { isPending, error },
|
|
93
|
+
input: current,
|
|
94
|
+
url,
|
|
82
95
|
set: {
|
|
83
96
|
page: (number) => go({ ...current, page: { ...current.page, number } }, append && number === current.page.number + 1),
|
|
84
97
|
size: (size) => go({ ...current, page: { number: 1, size } }),
|
|
85
98
|
sort: (sort) => go({ ...current, page: { ...current.page, number: 1 }, sort }),
|
|
86
|
-
// ** A changed filter always starts again from page 1
|
|
87
|
-
filter: (filter) => go({ ...current, page: { ...current.page, number: 1 }, filter: { ...current.filter, ...filter } })
|
|
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 } })
|
|
88
102
|
},
|
|
89
103
|
refresh,
|
|
90
|
-
reset: () => go({ page: { number: 1, size: result.page.size }, sort: [], filter:
|
|
91
|
-
|
|
92
|
-
push: (props2) => setResult((value) => ({ ...value, total: value.total + 1,
|
|
93
|
-
update: (props2) => setResult((value) => ({ ...value,
|
|
94
|
-
remove: (props2) => setResult((value) => ({ ...value, total: value.total - 1,
|
|
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) }))
|
|
95
109
|
},
|
|
96
110
|
selection: {
|
|
97
111
|
ids: selected,
|
|
98
|
-
|
|
99
|
-
toggle: (id) => setSelected((ids) => ids.includes(id) ? ids.filter((value) => value !== id) : [...ids, id]),
|
|
100
|
-
// ** Selects every row on this page, or clears them when they're all selected already
|
|
101
|
-
all: () => setSelected((ids) => result.items.every((item) => ids.includes(item.id)) ? [] : result.items.map((item) => item.id)),
|
|
112
|
+
set: setSelected,
|
|
102
113
|
clear: () => setSelected([])
|
|
103
114
|
}
|
|
104
115
|
};
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hook/index.ts","../src/url/index.ts"],"sourcesContent":["import { useEffect, useState, useTransition } from 'react';\nimport type { TDataKitInput, TDataKitResult, TDataKitSort } from '../types';\nimport { urlDecode, urlEncode } from '../url';\n\n// ** One hook for a table's state: page, sort, filter, selection and local item edits\n// ** source.navigate: state lives in the URL and the server page renders the next `initial` (Next: router.push)\n// ** source.fetch: the host's own authed action returns the next result (infinite scroll, apps without server rendering)\nexport const useDataKit = <TItem extends { id: string }>(\n\tprops: Readonly<{\n\t\tinitial: TDataKitResult<TItem>;\n\t\tsource: { navigate: (url: string) => void; refresh?: () => void } | { fetch: (input: unknown) => Promise<TDataKitResult<TItem>>; url?: boolean };\n\t\tkey?: string;\n\t\t// ** fetch only: add the next page under the current items instead of replacing them\n\t\tappend?: boolean;\n\t\trefetch?: { intervalMs: number };\n\t}>,\n) => {\n\t// ** Deconstruct Props\n\tconst { initial, source, key, append, refetch } = props;\n\n\tconst [isPending, startTransition] = useTransition();\n\tconst [result, setResult] = useState(initial);\n\tconst [previous, setPrevious] = useState(initial);\n\tconst [error, setError] = useState<Error | null>(null);\n\tconst [selected, setSelected] = useState<string[]>([]);\n\n\t// ** A new server-rendered `initial` (navigation, router.refresh) replaces local state\n\tif (initial !== previous) {\n\t\tsetPrevious(initial);\n\t\tsetResult(initial);\n\t}\n\n\tconst go = (input: TDataKitInput | unknown, more?: boolean) => {\n\t\tsetError(null);\n\t\tif ('navigate' in source) {\n\t\t\tstartTransition(() => source.navigate(`${window.location.pathname}?${urlEncode({ input: input as TDataKitInput, key, search: window.location.search })}`));\n\t\t\treturn;\n\t\t}\n\t\tstartTransition(async () => {\n\t\t\ttry {\n\t\t\t\tconst next = await source.fetch(input);\n\t\t\t\tif (source.url && !more) window.history.pushState(null, '', `${window.location.pathname}?${urlEncode({ input: next, key, search: window.location.search })}`);\n\t\t\t\tstartTransition(() => setResult((current) => (more ? { ...next, items: [...current.items, ...next.items] } : next)));\n\t\t\t} catch (caught) {\n\t\t\t\tsetError(caught instanceof Error ? caught : new Error(String(caught)));\n\t\t\t}\n\t\t});\n\t};\n\n\tconst current: TDataKitInput = { page: result.page, sort: result.sort, filter: result.filter };\n\tconst refresh = () => ('navigate' in source ? source.refresh?.() : go(current));\n\n\t// ** fetch + url: back/forward re-reads the URL\n\tuseEffect(() => {\n\t\tif ('navigate' in source || !source.url) return;\n\t\tconst listener = () => go(urlDecode({ searchParams: new URLSearchParams(window.location.search), key }));\n\t\twindow.addEventListener('popstate', listener);\n\t\treturn () => window.removeEventListener('popstate', listener);\n\t});\n\n\tuseEffect(() => {\n\t\tif (!refetch) return;\n\t\tconst interval = setInterval(refresh, refetch.intervalMs);\n\t\treturn () => clearInterval(interval);\n\t});\n\n\tconst count = Math.max(1, Math.ceil(result.total / result.page.size));\n\n\treturn {\n\t\tkey,\n\t\titems: result.items,\n\t\ttotal: result.total,\n\t\tpage: { number: result.page.number, size: result.page.size, count },\n\t\tsort: result.sort,\n\t\tfilter: result.filter,\n\t\tstate: { isPending, error },\n\t\tset: {\n\t\t\tpage: (number: number) => go({ ...current, page: { ...current.page, number } }, append && number === current.page.number + 1),\n\t\t\tsize: (size: number) => go({ ...current, page: { number: 1, size } }),\n\t\t\tsort: (sort: TDataKitSort[]) => go({ ...current, page: { ...current.page, number: 1 }, sort }),\n\t\t\t// ** A changed filter always starts again from page 1\n\t\t\tfilter: (filter: Record<string, unknown>) => go({ ...current, page: { ...current.page, number: 1 }, filter: { ...current.filter, ...filter } }),\n\t\t},\n\t\trefresh,\n\t\treset: () => go({ page: { number: 1, size: result.page.size }, sort: [], filter: Object.fromEntries(Object.keys(current.filter).map((name) => [name, undefined])) }),\n\t\titem: {\n\t\t\tpush: (props: Readonly<{ item: TItem; position?: 'start' | 'end' }>) => setResult((value) => ({ ...value, total: value.total + 1, items: props.position === 'end' ? [...value.items, props.item] : [props.item, ...value.items] })),\n\t\t\tupdate: (props: Readonly<{ id: string; data: Partial<TItem> }>) => setResult((value) => ({ ...value, items: value.items.map((item) => (item.id === props.id ? { ...item, ...props.data } : item)) })),\n\t\t\tremove: (props: Readonly<{ id: string }>) => setResult((value) => ({ ...value, total: value.total - 1, items: value.items.filter((item) => item.id !== props.id) })),\n\t\t},\n\t\tselection: {\n\t\t\tids: selected,\n\t\t\thas: (id: string) => selected.includes(id),\n\t\t\ttoggle: (id: string) => setSelected((ids) => (ids.includes(id) ? ids.filter((value) => value !== id) : [...ids, id])),\n\t\t\t// ** Selects every row on this page, or clears them when they're all selected already\n\t\t\tall: () => setSelected((ids) => (result.items.every((item) => ids.includes(item.id)) ? [] : result.items.map((item) => item.id))),\n\t\t\tclear: () => setSelected([]),\n\t\t},\n\t};\n};\n","import type { TDataKitInput } from '../types';\n\n// ** One format for both sides: the hook writes it, kit.parse reads it\n// ** ?page=2&size=20&sort=name.asc,createdAt.desc&search=x — with key \"user\": ?user.page=2&user.sort=…\n\nexport const urlEncode = (props: Readonly<{ input: TDataKitInput; key?: string; search?: string }>) => {\n\t// ** Deconstruct Props\n\tconst { input, key, search } = props;\n\n\tconst prefix = key ? `${key}.` : '';\n\tconst params = new URLSearchParams(search);\n\n\t// ** Drop this kit's old params, keep everything else on the page (other kits, returnUrl, …)\n\t[...params.keys()].filter((name) => (key ? name.startsWith(prefix) : ['page', 'size', 'sort'].includes(name) || name in input.filter)).forEach((name) => params.delete(name));\n\n\tif (input.page.number > 1) params.set(`${prefix}page`, String(input.page.number));\n\tparams.set(`${prefix}size`, String(input.page.size));\n\tif (input.sort.length) params.set(`${prefix}sort`, input.sort.map((sort) => `${sort.field}.${sort.direction}`).join(','));\n\tObject.entries(input.filter).forEach(([name, value]) => {\n\t\tif (value !== undefined && value !== null && value !== '') params.set(`${prefix}${name}`, String(value));\n\t});\n\n\treturn params.toString();\n};\n\n// ** Raw, unvalidated values: kit.schema decides what survives\nexport const urlDecode = (props: Readonly<{ searchParams: URLSearchParams | Record<string, string | string[] | undefined>; key?: string }>) => {\n\t// ** Deconstruct Props\n\tconst { searchParams, key } = props;\n\n\tconst prefix = key ? `${key}.` : '';\n\tconst entries = (searchParams instanceof URLSearchParams ? [...searchParams.entries()] : Object.entries(searchParams).map(([name, value]) => [name, Array.isArray(value) ? value[0] : value] as [string, string | undefined]))\n\t\t.filter((entry): entry is [string, string] => typeof entry[1] === 'string' && entry[0].startsWith(prefix))\n\t\t.map(([name, value]) => [name.slice(prefix.length), value] as const);\n\tconst values = Object.fromEntries(entries);\n\n\treturn {\n\t\tpage: { number: values.page, size: values.size },\n\t\tsort: (values.sort ?? '')\n\t\t\t.split(',')\n\t\t\t.filter(Boolean)\n\t\t\t.map((sort) => ({ field: sort.slice(0, sort.lastIndexOf('.')), direction: sort.slice(sort.lastIndexOf('.') + 1) })),\n\t\tfilter: Object.fromEntries(entries.filter(([name]) => !['page', 'size', 'sort'].includes(name))),\n\t};\n};\n"],"mappings":";;;AAAA,SAAS,WAAW,UAAU,qBAAqB;;;ACK5C,IAAM,YAAY,CAAC,UAA6E;AAEtG,QAAM,EAAE,OAAO,KAAK,OAAO,IAAI;AAE/B,QAAM,SAAS,MAAM,GAAG,GAAG,MAAM;AACjC,QAAM,SAAS,IAAI,gBAAgB,MAAM;AAGzC,GAAC,GAAG,OAAO,KAAK,CAAC,EAAE,OAAO,CAAC,SAAU,MAAM,KAAK,WAAW,MAAM,IAAI,CAAC,QAAQ,QAAQ,MAAM,EAAE,SAAS,IAAI,KAAK,QAAQ,MAAM,MAAO,EAAE,QAAQ,CAAC,SAAS,OAAO,OAAO,IAAI,CAAC;AAE5K,MAAI,MAAM,KAAK,SAAS,EAAG,QAAO,IAAI,GAAG,MAAM,QAAQ,OAAO,MAAM,KAAK,MAAM,CAAC;AAChF,SAAO,IAAI,GAAG,MAAM,QAAQ,OAAO,MAAM,KAAK,IAAI,CAAC;AACnD,MAAI,MAAM,KAAK,OAAQ,QAAO,IAAI,GAAG,MAAM,QAAQ,MAAM,KAAK,IAAI,CAAC,SAAS,GAAG,KAAK,KAAK,IAAI,KAAK,SAAS,EAAE,EAAE,KAAK,GAAG,CAAC;AACxH,SAAO,QAAQ,MAAM,MAAM,EAAE,QAAQ,CAAC,CA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MAAM,IAAI,CAAC,SAAS,KAAK,EAAE,CAAE;AAAA,MAChI,OAAO,MAAM,YAAY,CAAC,CAAC;AAAA,IAC5B;AAAA,EACD;AACD;","names":["current","props"]}
|
|
1
|
+
{"version":3,"sources":["../src/hook/index.ts","../src/url/index.ts"],"sourcesContent":["import { useEffect, useRef, useState, useTransition } from 'react';\nimport type { TDataKitData, TDataKitInput } from '../types';\nimport { urlDecode, urlEncode } from '../url';\n\n// ** One hook for a table's state: page, sort, filters, search, selection and local row edits\n// ** source.navigate: state lives in the URL and the server page renders the next `data` (Next: router.push)\n// ** source.fetch: your own authed action returns the next data (infinite scroll, apps without server rendering)\nexport const useDataKit = <TRow extends { id: string }>(\n\tprops: Readonly<{\n\t\tdata: TDataKitData<TRow>;\n\t\tsource: { navigate: (url: string) => void; refresh?: () => void } | { fetch: (input: unknown) => Promise<TDataKitData<TRow>>; url?: boolean };\n\t\tkey?: string;\n\t\t// ** fetch only: add the next page under the current rows instead of replacing them\n\t\tappend?: boolean;\n\t\trefetch?: { intervalMs: number };\n\t}>,\n) => {\n\t// ** Deconstruct Props\n\tconst { data, source, key, append, refetch } = props;\n\n\tconst [isPending, startTransition] = useTransition();\n\tconst [result, setResult] = useState(data);\n\tconst [previous, setPrevious] = useState(data);\n\tconst [error, setError] = useState<Error | null>(null);\n\tconst [selected, setSelected] = useState<string[]>([]);\n\t// ** Only the latest request may apply its answer (fast typing, slow network)\n\tconst sequence = useRef(0);\n\n\t// ** New server-rendered `data` (navigation, router.refresh) replaces local state\n\tif (data !== previous) {\n\t\tsetPrevious(data);\n\t\tsetResult(data);\n\t\t// ** Rows that are gone (deleted, filtered out) drop out of the selection\n\t\tsetSelected((ids) => ids.filter((id) => data.rows.some((row) => row.id === id)));\n\t}\n\n\tconst current: TDataKitInput = { page: result.page, sort: result.sort, filter: result.filter, ...(result.search && { search: result.search }) };\n\tconst url = (input: TDataKitInput) => `${window.location.pathname}?${urlEncode({ input, key, search: window.location.search, remove: Object.keys(current.filter) })}`;\n\n\tconst go = (input: TDataKitInput, more?: boolean) => {\n\t\tsetError(null);\n\t\tif ('navigate' in source) {\n\t\t\tstartTransition(() => source.navigate(url(input)));\n\t\t\treturn;\n\t\t}\n\t\tconst request = ++sequence.current;\n\t\tstartTransition(async () => {\n\t\t\ttry {\n\t\t\t\tconst next = await source.fetch(input);\n\t\t\t\tif (request !== sequence.current) return;\n\t\t\t\tif (source.url && !more) window.history.pushState(null, '', url(next));\n\t\t\t\tstartTransition(() => setResult((value) => (more ? { ...next, rows: [...value.rows, ...next.rows.filter((row) => !value.rows.some((item) => item.id === row.id))] } : next)));\n\t\t\t} catch (caught) {\n\t\t\t\tif (request === sequence.current) setError(caught instanceof Error ? caught : new Error(String(caught)));\n\t\t\t}\n\t\t});\n\t};\n\n\tconst refresh = () => ('navigate' in source ? source.refresh?.() : go(current));\n\n\t// ** fetch + url: back / forward re-reads the URL\n\tuseEffect(() => {\n\t\tif ('navigate' in source || !source.url) return;\n\t\tconst listener = () => go(urlDecode({ searchParams: new URLSearchParams(window.location.search), key }) as unknown as TDataKitInput);\n\t\twindow.addEventListener('popstate', listener);\n\t\treturn () => window.removeEventListener('popstate', listener);\n\t});\n\n\tuseEffect(() => {\n\t\tif (!refetch) return;\n\t\tconst interval = setInterval(refresh, refetch.intervalMs);\n\t\treturn () => clearInterval(interval);\n\t});\n\n\t// ** Without a count, there's a next page whenever this one is full\n\tconst count = result.total === null ? null : Math.max(1, Math.ceil(result.total / result.page.size));\n\tconst next = result.total === null ? result.rows.length >= result.page.size : result.page.number < (count ?? 1);\n\n\treturn {\n\t\tkey,\n\t\trows: result.rows,\n\t\ttotal: result.total,\n\t\tmeta: result.meta,\n\t\tpage: { number: result.page.number, size: result.page.size, count, next },\n\t\tsort: result.sort,\n\t\tfilter: result.filter,\n\t\tsearch: result.search ?? '',\n\t\tstate: { isPending, error },\n\t\tinput: current,\n\t\turl,\n\t\tset: {\n\t\t\tpage: (number: number) => go({ ...current, page: { ...current.page, number } }, append && number === current.page.number + 1),\n\t\t\tsize: (size: number) => go({ ...current, page: { number: 1, size } }),\n\t\t\tsort: (sort: TDataKitInput['sort']) => go({ ...current, page: { ...current.page, number: 1 }, sort }),\n\t\t\t// ** A changed filter or search always starts again from page 1; undefined or \"\" clears it\n\t\t\tfilter: (filter: Record<string, string | undefined>) =>\n\t\t\t\tgo({ ...current, page: { ...current.page, number: 1 }, filter: Object.fromEntries(Object.entries({ ...current.filter, ...filter }).filter((entry): entry is [string, string] => Boolean(entry[1]))) }),\n\t\t\tsearch: (search: string) => go({ ...current, page: { ...current.page, number: 1 }, ...(search.trim() ? { search: search.trim() } : { search: undefined }) }),\n\t\t},\n\t\trefresh,\n\t\treset: () => go({ page: { number: 1, size: result.page.size }, sort: [], filter: {} }),\n\t\trow: {\n\t\t\tpush: (props: Readonly<{ row: TRow; position?: 'start' | 'end' }>) => setResult((value) => ({ ...value, total: value.total === null ? null : value.total + 1, rows: props.position === 'end' ? [...value.rows, props.row] : [props.row, ...value.rows] })),\n\t\t\tupdate: (props: Readonly<{ id: string; data: Partial<TRow> }>) => setResult((value) => ({ ...value, rows: value.rows.map((row) => (row.id === props.id ? { ...row, ...props.data } : row)) })),\n\t\t\tremove: (props: Readonly<{ id: string }>) => setResult((value) => ({ ...value, total: value.total === null ? null : value.total - 1, rows: value.rows.filter((row) => row.id !== props.id) })),\n\t\t},\n\t\tselection: {\n\t\t\tids: selected,\n\t\t\tset: setSelected,\n\t\t\tclear: () => setSelected([]),\n\t\t},\n\t};\n};\n","import type { TDataKitInput } from '../types';\n\n// ** One format for both sides: the hook writes it, tableX.query reads it\n// ** ?page=2&size=20&sort=name.asc&search=ada&role=admin,user&age=18-30&createdAt=7d — with key \"user\": ?user.page=2…\n// ** Filter values are already their URL strings (the toolbar builds them), so this only moves strings around\n\nconst reserved = ['page', 'size', 'sort', 'search'];\n\n// ** `remove`: filter names the previous state had, so a filter that was cleared leaves the URL too\nexport const urlEncode = (props: Readonly<{ input: TDataKitInput; key?: string; search?: string; remove?: string[] }>) => {\n\t// ** Deconstruct Props\n\tconst { input, key, search, remove = [] } = props;\n\n\tconst prefix = key ? `${key}.` : '';\n\tconst params = new URLSearchParams(search);\n\n\t// ** Drop this table's old params, keep everything else on the page (other tables, returnUrl, …)\n\t[...params.keys()].filter((name) => (key ? name.startsWith(prefix) : reserved.includes(name) || name in input.filter || remove.includes(name))).forEach((name) => params.delete(name));\n\n\tif (input.page.number > 1) params.set(`${prefix}page`, String(input.page.number));\n\tparams.set(`${prefix}size`, String(input.page.size));\n\tif (input.sort.length) params.set(`${prefix}sort`, input.sort.map((sort) => `${sort.column}.${sort.direction}`).join(','));\n\tif (input.search) params.set(`${prefix}search`, input.search);\n\tObject.entries(input.filter).forEach(([name, value]) => {\n\t\tif (value) params.set(`${prefix}${name}`, value);\n\t});\n\n\treturn params.toString();\n};\n\n// ** Raw strings, unvalidated: the table's schema decides what survives\nexport const urlDecode = (props: Readonly<{ searchParams: URLSearchParams | Record<string, string | string[] | undefined>; key?: string }>) => {\n\t// ** Deconstruct Props\n\tconst { searchParams, key } = props;\n\n\tconst prefix = key ? `${key}.` : '';\n\tconst entries = (searchParams instanceof URLSearchParams ? [...searchParams.entries()] : Object.entries(searchParams).map(([name, value]) => [name, Array.isArray(value) ? value[0] : value] as [string, string | undefined]))\n\t\t.filter((entry): entry is [string, string] => typeof entry[1] === 'string' && entry[0].startsWith(prefix))\n\t\t.map(([name, value]) => [name.slice(prefix.length), value] as const);\n\tconst values = Object.fromEntries(entries);\n\n\treturn {\n\t\tpage: { number: values.page, size: values.size },\n\t\tsort: (values.sort ?? '')\n\t\t\t.split(',')\n\t\t\t.filter(Boolean)\n\t\t\t.map((sort) => ({ column: sort.slice(0, sort.lastIndexOf('.')), direction: sort.slice(sort.lastIndexOf('.') + 1) })),\n\t\tsearch: values.search,\n\t\tfilter: Object.fromEntries(entries.filter(([name]) => !reserved.includes(name))),\n\t};\n};\n"],"mappings":";;;AAAA,SAAS,WAAW,QAAQ,UAAU,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,GAAG,MAAM,MAAM,KAAK,OAAO,CAAC,QAAQ,IAAI,OAAOA,OAAM,EAAE,EAAE,EAAE;AAAA,IAC9L;AAAA,IACA,WAAW;AAAA,MACV,KAAK;AAAA,MACL,KAAK;AAAA,MACL,OAAO,MAAM,YAAY,CAAC,CAAC;AAAA,IAC5B;AAAA,EACD;AACD;","names":["next","props"]}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { a as TDataKitSource } from '../source--l-z9HHB.js';
|
|
2
|
+
import { Table } from 'drizzle-orm';
|
|
3
|
+
|
|
4
|
+
declare const sourceDrizzle: <TTable extends Table>(props: Readonly<{
|
|
5
|
+
db: any;
|
|
6
|
+
table: TTable;
|
|
7
|
+
id?: string;
|
|
8
|
+
dialect?: "pg" | "mysql" | "sqlite";
|
|
9
|
+
}>) => TDataKitSource<TTable["$inferSelect"]>;
|
|
10
|
+
|
|
11
|
+
export { sourceDrizzle };
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { sourceDefine } from '../chunk-5D747NEB.js';
|
|
2
|
+
import { getTableColumns, or, and, isNull, isNotNull, notInArray, inArray, gte, gt, lte, lt, ne, eq, asc, desc, sql } from 'drizzle-orm';
|
|
3
|
+
|
|
4
|
+
var sourceDrizzle = (props) => {
|
|
5
|
+
const { db, table, id = "id", dialect = "pg" } = props;
|
|
6
|
+
const columns = getTableColumns(table);
|
|
7
|
+
const column = (field) => {
|
|
8
|
+
if (!columns[field]) throw new Error(`[next-data-kit] "${field}" isn't a column of this table.`);
|
|
9
|
+
return columns[field];
|
|
10
|
+
};
|
|
11
|
+
return sourceDefine({
|
|
12
|
+
operator: {
|
|
13
|
+
eq: (props2) => eq(column(props2.field), props2.value),
|
|
14
|
+
ne: (props2) => ne(column(props2.field), props2.value),
|
|
15
|
+
lt: (props2) => lt(column(props2.field), props2.value),
|
|
16
|
+
lte: (props2) => lte(column(props2.field), props2.value),
|
|
17
|
+
gt: (props2) => gt(column(props2.field), props2.value),
|
|
18
|
+
gte: (props2) => gte(column(props2.field), props2.value),
|
|
19
|
+
in: (props2) => inArray(column(props2.field), props2.value),
|
|
20
|
+
nin: (props2) => notInArray(column(props2.field), props2.value),
|
|
21
|
+
// ** % and _ are escaped, so the text is literal; the value always goes as a parameter
|
|
22
|
+
contains: (props2) => sql`${column(props2.field)} ${dialect === "pg" ? sql`ilike` : sql`like`} ${`%${String(props2.value).replace(/[\\%_]/g, "\\$&")}%`} escape '\\'`,
|
|
23
|
+
between: (props2) => and(gte(column(props2.field), props2.value[0]), lte(column(props2.field), props2.value[1])),
|
|
24
|
+
null: (props2) => props2.value ? isNull(column(props2.field)) : isNotNull(column(props2.field))
|
|
25
|
+
},
|
|
26
|
+
and: (list) => and(...list),
|
|
27
|
+
or: (list) => or(...list),
|
|
28
|
+
list: async (props2) => {
|
|
29
|
+
const { where, sort, page } = props2;
|
|
30
|
+
const order = [...sort.map((entry) => (entry.direction === "asc" ? asc : desc)(column(entry.field))), ...sort.some((entry) => entry.field === id) ? [] : [asc(column(id))]];
|
|
31
|
+
const [rows, total] = await Promise.all([db.select().from(table).where(where).orderBy(...order).limit(page.limit).offset(page.offset), page.count ? db.$count(table, where) : null]);
|
|
32
|
+
return { rows, total: total === null ? null : Number(total) };
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
export { sourceDrizzle };
|
|
38
|
+
//# sourceMappingURL=drizzle.js.map
|
|
39
|
+
//# sourceMappingURL=drizzle.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/server/source/drizzle.ts"],"names":["props"],"mappings":";;;AAMO,IAAM,aAAA,GAAgB,CAAuB,KAAA,KAAkG;AAErJ,EAAA,MAAM,EAAE,EAAA,EAAI,KAAA,EAAO,KAAK,IAAA,EAAM,OAAA,GAAU,MAAK,GAAI,KAAA;AAEjD,EAAA,MAAM,OAAA,GAAU,gBAAgB,KAAK,CAAA;AACrC,EAAA,MAAM,MAAA,GAAS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A,CAAK,CAAC,KAAA,KAAU,KAAA,CAAM,UAAU,EAAE,CAAA,GAAI,EAAC,GAAI,CAAC,GAAA,CAAI,MAAA,CAAO,EAAE,CAAC,CAAC,CAAE,CAAA;AAC5K,MAAA,MAAM,CAAC,IAAA,EAAM,KAAK,CAAA,GAAI,MAAM,QAAQ,GAAA,CAAI,CAAC,EAAA,CAAG,MAAA,GAAS,IAAA,CAAK,KAAK,CAAA,CAAE,KAAA,CAAM,KAAK,CAAA,CAAE,OAAA,CAAQ,GAAG,KAAK,EAAE,KAAA,CAAM,IAAA,CAAK,KAAK,CAAA,CAAE,OAAO,IAAA,CAAK,MAAM,CAAA,EAAG,IAAA,CAAK,QAAQ,EAAA,CAAG,MAAA,CAAO,OAAO,KAAK,CAAA,GAAI,IAAI,CAAC,CAAA;AACnL,MAAA,OAAO,EAAE,MAAM,KAAA,EAAO,KAAA,KAAU,OAAO,IAAA,GAAO,MAAA,CAAO,KAAK,CAAA,EAAE;AAAA,IAC7D;AAAA,GACA,CAAA;AACF","file":"drizzle.js","sourcesContent":["import { and, asc, desc, eq, getTableColumns, gt, gte, inArray, isNotNull, isNull, lt, lte, ne, notInArray, or, sql, type SQL, type Table } from 'drizzle-orm';\nimport { sourceDefine } from './define';\n\n// ** A Drizzle table on any dialect: fields resolve to the table's own columns, so a name never becomes raw SQL\n// ** `dialect: 'pg'` searches with ilike; MySQL and SQLite use like (case-insensitive by collation)\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport const sourceDrizzle = <TTable extends Table>(props: Readonly<{ db: any; table: TTable; id?: string; dialect?: 'pg' | 'mysql' | 'sqlite' }>) => {\n\t// ** Deconstruct Props\n\tconst { db, table, id = 'id', dialect = 'pg' } = props;\n\n\tconst columns = getTableColumns(table) as Record<string, any>;\n\tconst column = (field: string) => {\n\t\tif (!columns[field]) throw new Error(`[next-data-kit] \"${field}\" isn't a column of this table.`);\n\t\treturn columns[field];\n\t};\n\n\treturn sourceDefine<TTable['$inferSelect'], SQL>({\n\t\toperator: {\n\t\t\teq: (props) => eq(column(props.field), props.value),\n\t\t\tne: (props) => ne(column(props.field), props.value),\n\t\t\tlt: (props) => lt(column(props.field), props.value),\n\t\t\tlte: (props) => lte(column(props.field), props.value),\n\t\t\tgt: (props) => gt(column(props.field), props.value),\n\t\t\tgte: (props) => gte(column(props.field), props.value),\n\t\t\tin: (props) => inArray(column(props.field), props.value),\n\t\t\tnin: (props) => notInArray(column(props.field), props.value),\n\t\t\t// ** % and _ are escaped, so the text is literal; the value always goes as a parameter\n\t\t\tcontains: (props) => sql`${column(props.field)} ${dialect === 'pg' ? sql`ilike` : sql`like`} ${`%${String(props.value).replace(/[\\\\%_]/g, '\\\\$&')}%`} escape '\\\\'`,\n\t\t\tbetween: (props) => and(gte(column(props.field), props.value[0]), lte(column(props.field), props.value[1]))!,\n\t\t\tnull: (props) => (props.value ? isNull(column(props.field)) : isNotNull(column(props.field))),\n\t\t},\n\t\tand: (list) => and(...list)!,\n\t\tor: (list) => or(...list)!,\n\t\tlist: async (props) => {\n\t\t\t// ** Deconstruct Props\n\t\t\tconst { where, sort, page } = props;\n\n\t\t\t// ** The id last keeps the order stable when sorted values tie\n\t\t\tconst order = [...sort.map((entry) => (entry.direction === 'asc' ? asc : desc)(column(entry.field))), ...(sort.some((entry) => entry.field === id) ? [] : [asc(column(id))])];\n\t\t\tconst [rows, total] = await Promise.all([db.select().from(table).where(where).orderBy(...order).limit(page.limit).offset(page.offset), page.count ? db.$count(table, where) : null]);\n\t\t\treturn { rows, total: total === null ? null : Number(total) };\n\t\t},\n\t});\n};\n"]}
|