@jsb188/react 1.1.11 → 1.1.13

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 jsb188
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,65 @@
1
+ /*
2
+ * Split the readable filter grammar into fields and values, respecting JSON-quoted strings.
3
+ */
4
+ export function tokenizePageFilters(input: string): string[][] {
5
+ const fields: string[][] = [];
6
+ let values: string[] = [];
7
+ let index = 0;
8
+ while (index < input.length) {
9
+ let value = '';
10
+ if (input[index] === '"') {
11
+ const start = index++;
12
+ let closed = false;
13
+ while (index < input.length) {
14
+ if (input[index] === '\\') {
15
+ index += 2;
16
+ } else if (input[index++] === '"') {
17
+ closed = true;
18
+ break;
19
+ }
20
+ }
21
+ if (!closed) throw new Error('Unclosed filter value');
22
+ value = JSON.parse(input.slice(start, index));
23
+ } else {
24
+ const start = index;
25
+ while (
26
+ index < input.length &&
27
+ input[index] !== ',' &&
28
+ input[index] !== '|'
29
+ )
30
+ index++;
31
+ value = input.slice(start, index);
32
+ if (!value || /["\\]/.test(value))
33
+ throw new Error('Invalid filter token');
34
+ }
35
+ values.push(value);
36
+ const separator = input[index++];
37
+ if (separator !== undefined && separator !== ',' && separator !== '|')
38
+ throw new Error('Invalid filter separator');
39
+ if (separator !== ',') {
40
+ fields.push(values);
41
+ values = [];
42
+ }
43
+ if (separator && index === input.length)
44
+ throw new Error('Missing filter value');
45
+ }
46
+ return fields;
47
+ }
48
+
49
+ /*
50
+ * Quote only values that would otherwise collide with the filter grammar.
51
+ */
52
+ export function quotePageFilterValue(value: string | number | boolean): string {
53
+ const text = String(value);
54
+ return !text || /[,|"\\\s]/.test(text) ? JSON.stringify(text) : text;
55
+ }
56
+
57
+ /*
58
+ * Encode URL values safely while keeping filter field and selection separators readable.
59
+ */
60
+ export function stringifyPageSearchParams(params: URLSearchParams): string {
61
+ return Array.from(params, ([name, value]) => {
62
+ const encoded = encodeURIComponent(value);
63
+ return `${encodeURIComponent(name)}=${name === 'filter' ? encoded.replace(/%2C/gi, ',').replace(/%7C/gi, '|') : encoded}`;
64
+ }).join('&');
65
+ }
@@ -0,0 +1,223 @@
1
+ import { quotePageFilterValue, stringifyPageSearchParams, tokenizePageFilters } from './page-filters.helpers.ts';
2
+
3
+ export { stringifyPageSearchParams } from './page-filters.helpers.ts';
4
+ export type PageFilterScalar = string | number | boolean;
5
+ export type PageFilterValue = PageFilterScalar | readonly PageFilterScalar[];
6
+ export type PageFilterValues = Record<string, PageFilterValue | undefined>;
7
+
8
+ type ScalarDefinition =
9
+ | { type: 'string'; values?: readonly string[]; pattern?: RegExp }
10
+ | { type: 'date'; min?: string; max?: string }
11
+ | {
12
+ type: 'number';
13
+ values?: readonly number[];
14
+ integer?: boolean;
15
+ min?: number;
16
+ max?: number;
17
+ }
18
+ | { type: 'boolean' };
19
+
20
+ type ScalarValue<T> = T extends { type: 'boolean' } ? boolean : T extends { type: 'number' } ? number : string;
21
+ type FieldDefinitions = {
22
+ [T in ScalarDefinition['type']]: Extract<ScalarDefinition, { type: T }> & {
23
+ default?: ScalarValue<{ type: T }>;
24
+ };
25
+ }[ScalarDefinition['type']];
26
+
27
+ export type PageFilterField = (
28
+ | FieldDefinitions
29
+ | {
30
+ type: 'array';
31
+ items: ScalarDefinition;
32
+ default?: readonly PageFilterScalar[];
33
+ }
34
+ ) & { alias?: string };
35
+
36
+ export interface PageFilterSchema {
37
+ filter: Record<string, PageFilterField>;
38
+ sort?: { values: readonly string[]; default?: string };
39
+ validate?: (filter: PageFilterValues) => boolean;
40
+ }
41
+
42
+ type FieldValue<F> = F extends { type: 'array'; items: infer I } ? readonly ScalarValue<I>[] : ScalarValue<F>;
43
+ export type InferPageFilters<S extends PageFilterSchema> = {
44
+ [K in keyof S['filter']]?: FieldValue<S['filter'][K]>;
45
+ };
46
+
47
+ /*
48
+ * Declare a page schema and reject ambiguous URL aliases or invalid defaults before it is used.
49
+ */
50
+ export function definePageFilterSchema<const S extends PageFilterSchema>(schema: S): S {
51
+ const names = new Set<string>();
52
+ for (const [field, definition] of Object.entries(schema.filter)) {
53
+ const name = definition.alias ?? field;
54
+ if (!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(name) || names.has(name)) throw new Error(`Invalid or duplicate filter name: ${name}`);
55
+ names.add(name);
56
+ if (definition.default !== undefined) normalizePageFilterValue(definition, definition.default);
57
+ }
58
+ if (schema.sort?.default !== undefined && !schema.sort.values.includes(schema.sort.default)) throw new Error('Invalid default sort');
59
+ if (schema.validate && !schema.validate(getPageFilterDefaults(schema))) throw new Error('Invalid default filter combination');
60
+ return schema;
61
+ }
62
+
63
+ /*
64
+ * Validate a calendar date without timezone conversion or permissive JavaScript date normalization.
65
+ */
66
+ function isPageFilterDate(value: string): boolean {
67
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
68
+ const date = new Date(`${value}T00:00:00.000Z`);
69
+ return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value;
70
+ }
71
+
72
+ /*
73
+ * Parse one scalar using its schema, preserving string IDs and enforcing strict booleans and numbers.
74
+ */
75
+ function parseScalar(definition: ScalarDefinition, value: string): PageFilterScalar {
76
+ if (definition.type === 'boolean') {
77
+ if (value !== 'true' && value !== 'false') throw new Error('Invalid boolean');
78
+ return value === 'true';
79
+ }
80
+ if (definition.type === 'number') {
81
+ if (!/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(value)) throw new Error('Invalid number');
82
+ const number = Number(value);
83
+ if (
84
+ !Number.isFinite(number) ||
85
+ (definition.integer && !Number.isSafeInteger(number)) ||
86
+ (definition.min !== undefined && number < definition.min) ||
87
+ (definition.max !== undefined && number > definition.max) ||
88
+ (definition.values && !definition.values.includes(number))
89
+ )
90
+ throw new Error('Number outside schema');
91
+ return number;
92
+ }
93
+ if (definition.type === 'date') {
94
+ if (!isPageFilterDate(value) || (definition.min && value < definition.min) || (definition.max && value > definition.max))
95
+ throw new Error('Invalid date');
96
+ } else if (
97
+ (definition.values && !definition.values.includes(value)) ||
98
+ (definition.pattern && !new RegExp(definition.pattern.source, definition.pattern.flags.replace(/[gy]/g, '')).test(value))
99
+ ) {
100
+ throw new Error('String outside schema');
101
+ }
102
+ return value;
103
+ }
104
+
105
+ /*
106
+ * Normalize typed control values through the same validation used for URL values.
107
+ */
108
+ export function normalizePageFilterValue(definition: PageFilterField, value: PageFilterValue): PageFilterValue {
109
+ if (definition.type === 'array') {
110
+ if (!Array.isArray(value)) throw new Error('Expected an array');
111
+ return Array.from(new Set(value.map((item) => parseScalar(definition.items, String(item))))).sort();
112
+ }
113
+ if (Array.isArray(value)) throw new Error('Expected a scalar');
114
+ return parseScalar(definition, String(value));
115
+ }
116
+
117
+ /*
118
+ * Resolve defaults independently from URL input so invalid filters never reach a table query.
119
+ */
120
+ export function getPageFilterDefaults(schema: PageFilterSchema): PageFilterValues {
121
+ return Object.fromEntries(
122
+ Object.entries(schema.filter).flatMap(([field, definition]) =>
123
+ definition.default === undefined ? [] : [[field, normalizePageFilterValue(definition, definition.default)]],
124
+ ),
125
+ );
126
+ }
127
+
128
+ /*
129
+ * Parse both reserved parameters atomically; any invalid entry invalidates filter and sort together.
130
+ */
131
+ export function parsePageFilters<S extends PageFilterSchema>(schema: S, params: URLSearchParams, scope = '') {
132
+ const filterParam = scope ? `${scope}.filter` : 'filter';
133
+ const sortParam = scope ? `${scope}.sort` : 'sort';
134
+ const defaults = getPageFilterDefaults(schema);
135
+ const defaultSort = schema.sort?.default;
136
+ try {
137
+ if (params.getAll(filterParam).length > 1 || params.getAll(sortParam).length > 1) throw new Error('Duplicate reserved parameter');
138
+ const filter = { ...defaults };
139
+ const input = params.get(filterParam);
140
+ if (input === '') throw new Error('Empty filter');
141
+ const definitions = new Map(
142
+ Object.entries(schema.filter).map(([field, definition]) => [definition.alias ?? field, { field, definition }]),
143
+ );
144
+ const seen = new Set<string>();
145
+ for (const [name, ...values] of input === null ? [] : tokenizePageFilters(input)) {
146
+ const entry = definitions.get(name);
147
+ if (!entry || seen.has(name)) throw new Error('Unknown or duplicate filter');
148
+ seen.add(name);
149
+ const { field, definition } = entry;
150
+ if (definition.type !== 'array' && values.length !== 1) throw new Error('Invalid scalar arity');
151
+ filter[field] = definition.type === 'array' ? normalizePageFilterValue(definition, values) : parseScalar(definition, values[0]);
152
+ }
153
+ const sort = params.get(sortParam) ?? defaultSort;
154
+ if (sort !== undefined && !schema.sort?.values.includes(sort)) throw new Error('Invalid sort');
155
+ if (schema.validate && !schema.validate(filter)) throw new Error('Invalid filter combination');
156
+ const orderedFilter = Object.fromEntries(
157
+ Object.keys(schema.filter).flatMap((field) => (filter[field] === undefined ? [] : [[field, filter[field]]])),
158
+ );
159
+ return { filter: orderedFilter as InferPageFilters<S>, sort, valid: true };
160
+ } catch {
161
+ return {
162
+ filter: defaults as InferPageFilters<S>,
163
+ sort: defaultSort,
164
+ valid: false,
165
+ };
166
+ }
167
+ }
168
+
169
+ /*
170
+ * Serialize canonical field names through URL aliases, omitting defaults while retaining explicit empty arrays.
171
+ */
172
+ export function serializePageFilters(schema: PageFilterSchema, filter: PageFilterValues): string {
173
+ const fields: string[] = [];
174
+ for (const name of Object.keys(filter)) {
175
+ if (!Object.hasOwn(schema.filter, name)) throw new Error(`Unknown filter field: ${name}`);
176
+ }
177
+ for (const [field, definition] of Object.entries(schema.filter)) {
178
+ const value = filter[field];
179
+ if (value === undefined) continue;
180
+ const normalized = normalizePageFilterValue(definition, value);
181
+ if (
182
+ definition.default !== undefined &&
183
+ JSON.stringify(normalized) === JSON.stringify(normalizePageFilterValue(definition, definition.default))
184
+ )
185
+ continue;
186
+ fields.push(
187
+ [definition.alias ?? field, ...(Array.isArray(normalized) ? normalized : [normalized]).map(quotePageFilterValue)].join(','),
188
+ );
189
+ }
190
+ return fields.join('|');
191
+ }
192
+
193
+ /*
194
+ * Update only reserved parameters, preserving the page selector and unrelated URL state.
195
+ */
196
+ export function updatePageFilterSearch(
197
+ schema: PageFilterSchema,
198
+ params: URLSearchParams,
199
+ filter: PageFilterValues,
200
+ sort?: string,
201
+ scope = '',
202
+ ): string {
203
+ const next = new URLSearchParams(params);
204
+ const filterParam = scope ? `${scope}.filter` : 'filter';
205
+ const sortParam = scope ? `${scope}.sort` : 'sort';
206
+ next.delete(filterParam);
207
+ next.delete(sortParam);
208
+ const encoded = serializePageFilters(schema, filter);
209
+ if (encoded) next.set(filterParam, encoded);
210
+ if (sort !== undefined && sort !== schema.sort?.default) next.set(sortParam, sort);
211
+ if (!parsePageFilters(schema, next, scope).valid) throw new Error('Invalid page filter update');
212
+ return stringifyPageSearchParams(next);
213
+ }
214
+
215
+ /*
216
+ * Remove both invalid reserved parameters without changing other page navigation state.
217
+ */
218
+ export function clearPageFilterSearch(params: URLSearchParams, scope = ''): string {
219
+ const next = new URLSearchParams(params);
220
+ next.delete(scope ? `${scope}.filter` : 'filter');
221
+ next.delete(scope ? `${scope}.sort` : 'sort');
222
+ return stringifyPageSearchParams(next);
223
+ }
@@ -0,0 +1,168 @@
1
+ import {
2
+ clearPageFilterSearch,
3
+ getPageFilterDefaults,
4
+ parsePageFilters,
5
+ updatePageFilterSearch,
6
+ type PageFilterSchema,
7
+ type PageFilterValues,
8
+ type InferPageFilters,
9
+ } from './page-filters.ts';
10
+ import { createContext, useContext, useCallback, useEffect, useMemo, useRef } from 'react';
11
+ import { useLocation, useNavigate } from 'react-router';
12
+
13
+ interface PageLocation {
14
+ pathname: string;
15
+ search: string;
16
+ hash?: string;
17
+ }
18
+
19
+ export interface ControlledPageLocation extends PageLocation {
20
+ onSearchChange: (search: string) => void;
21
+ }
22
+
23
+ // Routes that treat their search string as one unit can reset it on an invalid filter.
24
+ export const ResetInvalidPageSearchContext = createContext(false);
25
+
26
+ const committedLocations = new WeakMap<PageLocation, PageLocation>();
27
+
28
+ export interface PageFilterController {
29
+ schema: PageFilterSchema;
30
+ filter: PageFilterValues;
31
+ sort?: string;
32
+ ready: boolean;
33
+ valid: boolean;
34
+ queryKey: string;
35
+ setFilter: (update: PageFilterValues) => void;
36
+ setSort: (sort?: string) => void;
37
+ reset: () => void;
38
+ getFilterTo: (update: PageFilterValues) => string;
39
+ }
40
+
41
+ /*
42
+ * Own URL-derived filter state, atomic invalid-input redirects, and updates shared by a page's toolbar and query.
43
+ */
44
+ export function usePageFilters<S extends PageFilterSchema>(
45
+ schema: S,
46
+ ready = true,
47
+ scope = '',
48
+ controlled?: ControlledPageLocation | null,
49
+ ) {
50
+ const resetInvalidSearch = useContext(ResetInvalidPageSearchContext);
51
+ const routerLocation = useLocation();
52
+ const location = controlled ?? routerLocation;
53
+ const onSearchChange = controlled?.onSearchChange;
54
+ const navigate = useNavigate();
55
+ const parsed = useMemo(
56
+ () => parsePageFilters(schema, new URLSearchParams(location.search), scope),
57
+ [schema, location.search, scope],
58
+ );
59
+ const current = useRef({ schema, location, ready, scope });
60
+ current.current = { schema, location, ready: ready && parsed.valid, scope };
61
+
62
+ /*
63
+ * Publish the latest location before another control can read it, then update its owner.
64
+ */
65
+ const commitLocation = useCallback(
66
+ (next: PageLocation, replace = false) => {
67
+ committedLocations.set(current.current.location, next);
68
+ if (onSearchChange) onSearchChange(next.search);
69
+ else navigate(next, { replace, preventScrollReset: true });
70
+ },
71
+ [navigate, onSearchChange],
72
+ );
73
+
74
+ useEffect(() => {
75
+ return () => {
76
+ committedLocations.delete(location);
77
+ };
78
+ }, [location]);
79
+
80
+ useEffect(() => {
81
+ if (!ready || parsed.valid) return;
82
+ const latest = committedLocations.get(location) ?? location;
83
+ const search = resetInvalidSearch ? '' : clearPageFilterSearch(new URLSearchParams(latest.search), scope);
84
+ const next = { ...latest, search: search ? `?${search}` : '' };
85
+ commitLocation(next, true);
86
+ }, [location.pathname, location.search, location.hash, commitLocation, parsed.valid, ready, resetInvalidSearch, scope]);
87
+
88
+ /*
89
+ * Merge one control's committed changes against the latest URL, never a stale render snapshot.
90
+ */
91
+ const getNextLocation = useCallback((update: PageFilterValues, sortUpdate?: { value?: string }) => {
92
+ const { schema, scope } = current.current;
93
+ const location = committedLocations.get(current.current.location) ?? current.current.location;
94
+ const params = new URLSearchParams(location.search);
95
+ const state = parsePageFilters(schema, params, scope);
96
+ const search = updatePageFilterSearch(
97
+ schema,
98
+ params,
99
+ { ...state.filter, ...update },
100
+ sortUpdate ? sortUpdate.value : state.sort,
101
+ scope,
102
+ );
103
+ return {
104
+ pathname: location.pathname,
105
+ search: search ? `?${search}` : '',
106
+ hash: location.hash,
107
+ };
108
+ }, []);
109
+
110
+ /*
111
+ * Apply a filter patch with one navigation and preserve all unrelated search parameters.
112
+ */
113
+ const setFilter = useCallback(
114
+ (update: PageFilterValues) => {
115
+ if (current.current.ready) commitLocation(getNextLocation(update));
116
+ },
117
+ [getNextLocation, commitLocation],
118
+ );
119
+
120
+ /*
121
+ * Apply the selected sort while retaining all committed filter values.
122
+ */
123
+ const setSort = useCallback(
124
+ (value?: string) => {
125
+ if (current.current.ready) commitLocation(getNextLocation({}, { value }));
126
+ },
127
+ [getNextLocation, commitLocation],
128
+ );
129
+
130
+ /*
131
+ * Reset the reserved parameters to the page's declared defaults.
132
+ */
133
+ const reset = useCallback(() => {
134
+ if (!current.current.ready) return;
135
+ const { schema, scope } = current.current;
136
+ const location = committedLocations.get(current.current.location) ?? current.current.location;
137
+ const search = updatePageFilterSearch(
138
+ schema,
139
+ new URLSearchParams(location.search),
140
+ getPageFilterDefaults(schema),
141
+ schema.sort?.default,
142
+ scope,
143
+ );
144
+ commitLocation({ ...location, search: search ? `?${search}` : '' });
145
+ }, [commitLocation]);
146
+
147
+ /*
148
+ * Build a link that performs the same validated patch as a toolbar action.
149
+ */
150
+ const getFilterTo = useCallback(
151
+ (update: PageFilterValues) => {
152
+ const next = getNextLocation(update);
153
+ return `${next.pathname}${next.search}${next.hash || ''}`;
154
+ },
155
+ [getNextLocation],
156
+ );
157
+
158
+ return {
159
+ schema,
160
+ ...parsed,
161
+ ready: ready && parsed.valid,
162
+ queryKey: JSON.stringify([parsed.filter, parsed.sort]),
163
+ setFilter: setFilter as (update: Partial<InferPageFilters<S>>) => void,
164
+ setSort,
165
+ reset,
166
+ getFilterTo,
167
+ };
168
+ }
package/package.json CHANGED
@@ -1,22 +1,37 @@
1
1
  {
2
2
  "name": "@jsb188/react",
3
- "version": "1.1.11",
3
+ "version": "1.1.13",
4
4
  "description": "Contains react (and DOM) related utils and hooks.",
5
- "license": "ISC",
5
+ "license": "MIT",
6
6
  "author": "jsb188",
7
7
  "type": "module",
8
8
  "exports": {
9
+ "./libs/page-filters": "./libs/page-filters.ts",
10
+ "./libs/use-page-filters": "./libs/use-page-filters.ts",
9
11
  "./states": "./states/index.ts",
12
+ "./states/keyboardLayer": "./states/keyboardLayer.ts",
10
13
  "./hooks": "./utils/hooks.ts",
11
- "./schema": "./utils/schema.ts",
14
+ "./utils/lazy": "./utils/lazy.ts",
12
15
  "./types/PopOver.d": "./types/PopOver.d.ts"
13
16
  },
14
17
  "peerDependencies": {
15
- "@jsb188/app": "1.1.11",
18
+ "@jsb188/app": "1.1.13",
16
19
  "jotai": "^2.20.2",
17
- "react": "^19.2.8"
20
+ "react": "^19.3.0",
21
+ "react-router": "^8.4.0"
18
22
  },
19
23
  "scripts": {
20
24
  "test": "echo \"Error: no test specified\" && exit 1"
21
- }
25
+ },
26
+ "files": [
27
+ "libs/**/*.{ts,tsx,css,svg}",
28
+ "states/**/*.{ts,tsx,css,svg}",
29
+ "types/**/*.{ts,tsx,css,svg}",
30
+ "utils/**/*.{ts,tsx,css,svg}",
31
+ "!**/*.test.*",
32
+ "!**/*.spec.*",
33
+ "!**/tests/**",
34
+ "!**/*.md",
35
+ "!**/.DS_Store"
36
+ ]
22
37
  }