@jsb188/react 1.0.4 → 1.1.2
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/libs/README.md +75 -0
- package/libs/page-filters.helpers.ts +65 -0
- package/libs/page-filters.ts +223 -0
- package/libs/use-page-filters.ts +147 -0
- package/package.json +24 -22
- package/states/apiData.ts +18 -14
- package/states/appContext.ts +424 -0
- package/states/connected.ts +135 -11
- package/states/index.ts +5 -0
- package/states/keyDown.ts +167 -0
- package/states/keyboardLayer.ts +57 -0
- package/states/modal.ts +403 -240
- package/states/popOver.ts +381 -233
- package/states/reactiveEvents.ts +99 -0
- package/states/uploads.ts +70 -0
- package/types/PopOver.d.ts +680 -0
- package/utils/hooks.ts +399 -251
- package/utils/lazy.ts +183 -0
- package/icons/Icon.tsx +0 -207
- package/icons/IconSVGs.tsx +0 -1486
- package/types/dom.d.ts +0 -7
- package/utils/dom.ts +0 -303
- package/utils/priorityTimeout.ts +0 -57
package/libs/README.md
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# Page filters
|
|
2
|
+
|
|
3
|
+
The pure schema/codec and React Router hook are independent of toolbars, tables, GraphQL, and app context.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { definePageFilterSchema, parsePageFilters } from '@jsb188/react/libs/page-filters';
|
|
7
|
+
import { usePageFilters } from '@jsb188/react/libs/use-page-filters';
|
|
8
|
+
|
|
9
|
+
const schema = definePageFilterSchema({
|
|
10
|
+
filter: {
|
|
11
|
+
status: { type: 'array', items: { type: 'string', values: ['ACTIVE', 'CLOSED'] } },
|
|
12
|
+
archived: { type: 'boolean', default: false },
|
|
13
|
+
minimumThreshold: { type: 'number', alias: 'mr', integer: true, min: 0 },
|
|
14
|
+
startDate: { type: 'date' },
|
|
15
|
+
query: { type: 'string' },
|
|
16
|
+
},
|
|
17
|
+
sort: { values: ['CREATED_AT_DESC', 'UPDATED_AT_DESC'], default: 'CREATED_AT_DESC' },
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
// Also works in a loader, server, CLI, or other non-React consumer.
|
|
21
|
+
const parsed = parsePageFilters(schema, new URL(request.url).searchParams);
|
|
22
|
+
|
|
23
|
+
/*
|
|
24
|
+
* Drive a query and any custom controls from one committed URL snapshot.
|
|
25
|
+
*/
|
|
26
|
+
const Page = () => {
|
|
27
|
+
const state = usePageFilters(schema);
|
|
28
|
+
const query = useYourQuery({ filter: state.filter, sort: state.sort }, { skip: !state.ready });
|
|
29
|
+
// state.setFilter({ minimumThreshold: 123 });
|
|
30
|
+
// state.setFilter({ status: ['ACTIVE'], archived: true });
|
|
31
|
+
// state.setFilter({ startDate: undefined }); // reset one field to its default
|
|
32
|
+
// state.setSort('UPDATED_AT_DESC');
|
|
33
|
+
// state.reset(); // remove filter and sort; retain page and unrelated params
|
|
34
|
+
return renderYourContent(query, state);
|
|
35
|
+
};
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## URL contract
|
|
39
|
+
|
|
40
|
+
`?page=campaigns&filter=status,ACTIVE,CLOSED|archived,true|mr,123&sort=UPDATED_AT_DESC`
|
|
41
|
+
|
|
42
|
+
- `filter` and `sort` are reserved. A filter group starts with its field name, followed by comma-separated values. Pipes separate groups.
|
|
43
|
+
- Aliases are URL-only. `mr,123` produces `minimumThreshold: 123`; the full name is not accepted in the URL when an alias is configured. Controls and query adapters always use canonical field names.
|
|
44
|
+
- Scalars accept one value. Booleans are exactly `true` or `false`; numbers must be finite; dates are real calendar dates in `YYYY-MM-DD` form. Strings can declare `values` and/or a `pattern`; numbers can declare `values`, `integer`, `min`, and `max`; dates can declare `min` and `max`.
|
|
45
|
+
- Arrays use the `items` schema, and have set semantics: duplicates are removed and values are sorted deterministically. `status` represents an explicit empty array; `query,""` represents an empty string.
|
|
46
|
+
- Values containing commas, pipes, quotes, backslashes, or whitespace are JSON-quoted **within the readable grammar**. For example, `filter=query,"north,south|west"` is one string, not extra filters. The serializer handles quoting and URL encoding; callers should not concatenate URL values by hand.
|
|
47
|
+
- Default values are omitted when writing URLs and restored when reading. `undefined` resets a field to its declared default. A schema-level `validate(filter)` can reject invalid combinations such as reversed date ranges; its defaults must also be valid.
|
|
48
|
+
- Unknown fields, invalid values, duplicate groups/reserved parameters, malformed grammar, and invalid sorts invalidate **both** parameters. `parsePageFilters` returns `valid: false` with defaults, never partial input. Pure callers decide how to redirect; the hook replaces the URL with both reserved parameters removed while retaining pathname, unrelated params, and hash.
|
|
49
|
+
- Consumers must use `state.ready` to gate queries. Invalid input is never ready before the replacement URL renders. For dynamic choices, pass `usePageFilters(schema, optionsLoaded)` so incoming IDs are not discarded while options load. Handle option-loading errors/retries in the page's data layer.
|
|
50
|
+
- Changes create browser history entries; invalid-URL corrections replace history. Browser Back/Forward immediately restores committed state. `queryKey` identifies normalized filter/sort values, independent of unrelated URL parameters.
|
|
51
|
+
- Independent sections can pass a third argument: `usePageFilters(templateSchema, optionsLoaded, 'templates')` owns `templates.filter` and `templates.sort`. The default controller continues to own `filter` and `sort`. Each section validates and resets only its own pair, and consecutive changes from different sections preserve each other before the router renders. The pure parse/clear helpers accept a trailing scope argument; the update helper accepts it after `sort`.
|
|
52
|
+
|
|
53
|
+
## Optional toolbar adapter
|
|
54
|
+
|
|
55
|
+
`@jsb188/react-web/modules/ToolbarFilters` exports `makePageToolbarFilters(controller, definitions)` and `PageToolbarFilter<typeof schema>`. Presentation definitions choose controls and labels; selectable values come directly from the schema so validation, selections, and query values agree.
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
const controls = [
|
|
59
|
+
{ control: 'checklist', field: 'status', label: i18n.t('c.status') },
|
|
60
|
+
{ control: 'toggle', field: 'archived', label: i18n.t('campaign.status_archived') },
|
|
61
|
+
{ control: 'date', field: 'startDate', label: i18n.t('c.start') },
|
|
62
|
+
{ control: 'sort', label: i18n.t('c.sort_by') },
|
|
63
|
+
] satisfies PageToolbarFilter<typeof schema>[];
|
|
64
|
+
const options = makePageToolbarFilters(state, controls);
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Built-in controls are `toggle`, `select`, `checklist`, `date`, `dateRange`, and `sort`. A date range maps two schema fields in a single update. Share schema field definitions and presentation definitions by importing them across pages. `ToolbarItems` also accepts typed actions, links, or `{ type: 'custom', id, content }` for arbitrary React controls, including free-text and numeric inputs using `state.setFilter`.
|
|
68
|
+
|
|
69
|
+
## Table-route integration
|
|
70
|
+
|
|
71
|
+
Marketday's `TableRoute.filters.ts` contains page-specific schemas, reusable log/campaign/date configurations, asynchronous option sources, and API mappings. `FilteredTableRoute`, `StandardTableRoute`, and `TableRoute` apply this controller automatically. A page that owns a custom toolbar can pass its existing `pageFilterState` into `TableRoute` so it parses only once. The embedded template-campaign page shares the same campaign schema and adapter.
|
|
72
|
+
|
|
73
|
+
Fixed scopes such as organization, template ID, campaign kind, or a route-specific activity group stay outside editable URL fields. Initial queries and pagination use the same mapped filter/sort values. The recent-weeks log preset defaults on only when no explicit dates/location/search are present; incompatible explicit combinations are invalid.
|
|
74
|
+
|
|
75
|
+
Existing toolbar/table consumers use this contract throughout. Legacy standalone filter parameters and numeric sort indexes are no longer interpreted; unrelated search parameters remain untouched.
|
|
@@ -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,147 @@
|
|
|
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 { useCallback, useEffect, useMemo, useRef } from 'react';
|
|
11
|
+
import { useLocation, useNavigate, type Location } from 'react-router';
|
|
12
|
+
|
|
13
|
+
const committedLocations = new WeakMap<Location, Location>();
|
|
14
|
+
|
|
15
|
+
export interface PageFilterController {
|
|
16
|
+
schema: PageFilterSchema;
|
|
17
|
+
filter: PageFilterValues;
|
|
18
|
+
sort?: string;
|
|
19
|
+
ready: boolean;
|
|
20
|
+
valid: boolean;
|
|
21
|
+
queryKey: string;
|
|
22
|
+
setFilter: (update: PageFilterValues) => void;
|
|
23
|
+
setSort: (sort?: string) => void;
|
|
24
|
+
reset: () => void;
|
|
25
|
+
getFilterTo: (update: PageFilterValues) => string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/*
|
|
29
|
+
* Own URL-derived filter state, atomic invalid-input redirects, and updates shared by a page's toolbar and query.
|
|
30
|
+
*/
|
|
31
|
+
export function usePageFilters<S extends PageFilterSchema>(schema: S, ready = true, scope = '') {
|
|
32
|
+
const location = useLocation();
|
|
33
|
+
const navigate = useNavigate();
|
|
34
|
+
const parsed = useMemo(
|
|
35
|
+
() => parsePageFilters(schema, new URLSearchParams(location.search), scope),
|
|
36
|
+
[schema, location.search, scope],
|
|
37
|
+
);
|
|
38
|
+
const current = useRef({ schema, location, ready, scope });
|
|
39
|
+
current.current = { schema, location, ready: ready && parsed.valid, scope };
|
|
40
|
+
|
|
41
|
+
useEffect(() => {
|
|
42
|
+
return () => {
|
|
43
|
+
committedLocations.delete(location);
|
|
44
|
+
};
|
|
45
|
+
}, [location]);
|
|
46
|
+
|
|
47
|
+
useEffect(() => {
|
|
48
|
+
if (!ready || parsed.valid) return;
|
|
49
|
+
const latest = committedLocations.get(location) ?? location;
|
|
50
|
+
const search = clearPageFilterSearch(new URLSearchParams(latest.search), scope);
|
|
51
|
+
const next = { ...latest, search: search ? `?${search}` : '' };
|
|
52
|
+
committedLocations.set(location, next);
|
|
53
|
+
navigate(next, { replace: true, preventScrollReset: true });
|
|
54
|
+
}, [location.pathname, location.search, location.hash, navigate, parsed.valid, ready, scope]);
|
|
55
|
+
|
|
56
|
+
/*
|
|
57
|
+
* Merge one control's committed changes against the latest URL, never a stale render snapshot.
|
|
58
|
+
*/
|
|
59
|
+
const getNextLocation = useCallback((update: PageFilterValues, sortUpdate?: { value?: string }) => {
|
|
60
|
+
const { schema, scope } = current.current;
|
|
61
|
+
const location = committedLocations.get(current.current.location) ?? current.current.location;
|
|
62
|
+
const params = new URLSearchParams(location.search);
|
|
63
|
+
const state = parsePageFilters(schema, params, scope);
|
|
64
|
+
const search = updatePageFilterSearch(
|
|
65
|
+
schema,
|
|
66
|
+
params,
|
|
67
|
+
{ ...state.filter, ...update },
|
|
68
|
+
sortUpdate ? sortUpdate.value : state.sort,
|
|
69
|
+
scope,
|
|
70
|
+
);
|
|
71
|
+
return {
|
|
72
|
+
pathname: location.pathname,
|
|
73
|
+
search: search ? `?${search}` : '',
|
|
74
|
+
hash: location.hash,
|
|
75
|
+
};
|
|
76
|
+
}, []);
|
|
77
|
+
|
|
78
|
+
/*
|
|
79
|
+
* Retain consecutive changes across independently scoped controls before the router publishes its next render.
|
|
80
|
+
*/
|
|
81
|
+
const commitLocation = useCallback(
|
|
82
|
+
(next: Pick<typeof location, 'pathname' | 'search' | 'hash'>) => {
|
|
83
|
+
committedLocations.set(current.current.location, { ...current.current.location, ...next });
|
|
84
|
+
navigate(next, { preventScrollReset: true });
|
|
85
|
+
},
|
|
86
|
+
[navigate],
|
|
87
|
+
);
|
|
88
|
+
|
|
89
|
+
/*
|
|
90
|
+
* Apply a filter patch with one navigation and preserve all unrelated search parameters.
|
|
91
|
+
*/
|
|
92
|
+
const setFilter = useCallback(
|
|
93
|
+
(update: PageFilterValues) => {
|
|
94
|
+
if (current.current.ready) commitLocation(getNextLocation(update));
|
|
95
|
+
},
|
|
96
|
+
[getNextLocation, commitLocation],
|
|
97
|
+
);
|
|
98
|
+
|
|
99
|
+
/*
|
|
100
|
+
* Apply the selected sort while retaining all committed filter values.
|
|
101
|
+
*/
|
|
102
|
+
const setSort = useCallback(
|
|
103
|
+
(value?: string) => {
|
|
104
|
+
if (current.current.ready) commitLocation(getNextLocation({}, { value }));
|
|
105
|
+
},
|
|
106
|
+
[getNextLocation, commitLocation],
|
|
107
|
+
);
|
|
108
|
+
|
|
109
|
+
/*
|
|
110
|
+
* Reset the reserved parameters to the page's declared defaults.
|
|
111
|
+
*/
|
|
112
|
+
const reset = useCallback(() => {
|
|
113
|
+
if (!current.current.ready) return;
|
|
114
|
+
const { schema, scope } = current.current;
|
|
115
|
+
const location = committedLocations.get(current.current.location) ?? current.current.location;
|
|
116
|
+
const search = updatePageFilterSearch(
|
|
117
|
+
schema,
|
|
118
|
+
new URLSearchParams(location.search),
|
|
119
|
+
getPageFilterDefaults(schema),
|
|
120
|
+
schema.sort?.default,
|
|
121
|
+
scope,
|
|
122
|
+
);
|
|
123
|
+
commitLocation({ ...location, search: search ? `?${search}` : '' });
|
|
124
|
+
}, [commitLocation]);
|
|
125
|
+
|
|
126
|
+
/*
|
|
127
|
+
* Build a link that performs the same validated patch as a toolbar action.
|
|
128
|
+
*/
|
|
129
|
+
const getFilterTo = useCallback(
|
|
130
|
+
(update: PageFilterValues) => {
|
|
131
|
+
const next = getNextLocation(update);
|
|
132
|
+
return `${next.pathname}${next.search}${next.hash}`;
|
|
133
|
+
},
|
|
134
|
+
[getNextLocation],
|
|
135
|
+
);
|
|
136
|
+
|
|
137
|
+
return {
|
|
138
|
+
schema,
|
|
139
|
+
...parsed,
|
|
140
|
+
ready: ready && parsed.valid,
|
|
141
|
+
queryKey: JSON.stringify([parsed.filter, parsed.sort]),
|
|
142
|
+
setFilter: setFilter as (update: Partial<InferPageFilters<S>>) => void,
|
|
143
|
+
setSort,
|
|
144
|
+
reset,
|
|
145
|
+
getFilterTo,
|
|
146
|
+
};
|
|
147
|
+
}
|
package/package.json
CHANGED
|
@@ -1,24 +1,26 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
2
|
+
"name": "@jsb188/react",
|
|
3
|
+
"version": "1.1.2",
|
|
4
|
+
"description": "Contains react (and DOM) related utils and hooks.",
|
|
5
|
+
"license": "ISC",
|
|
6
|
+
"author": "jsb188",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"exports": {
|
|
9
|
+
"./libs/page-filters": "./libs/page-filters.ts",
|
|
10
|
+
"./libs/use-page-filters": "./libs/use-page-filters.ts",
|
|
11
|
+
"./states": "./states/index.ts",
|
|
12
|
+
"./states/keyboardLayer": "./states/keyboardLayer.ts",
|
|
13
|
+
"./hooks": "./utils/hooks.ts",
|
|
14
|
+
"./utils/lazy": "./utils/lazy.ts",
|
|
15
|
+
"./types/PopOver.d": "./types/PopOver.d.ts"
|
|
16
|
+
},
|
|
17
|
+
"peerDependencies": {
|
|
18
|
+
"@jsb188/app": "1.1.2",
|
|
19
|
+
"jotai": "^2.20.2",
|
|
20
|
+
"react": "^19.3.0",
|
|
21
|
+
"react-router": "^8.4.0"
|
|
22
|
+
},
|
|
23
|
+
"scripts": {
|
|
24
|
+
"test": "echo \"Error: no test specified\" && exit 1"
|
|
25
|
+
}
|
|
24
26
|
}
|
package/states/apiData.ts
CHANGED
|
@@ -5,14 +5,16 @@ import { atom, useAtomValue, useSetAtom } from 'jotai';
|
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
7
|
type QueryObserverObj = {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
8
|
+
count: number;
|
|
9
|
+
eventSequence: number;
|
|
10
|
+
name: string;
|
|
11
|
+
forceRefetch: boolean;
|
|
12
|
+
resetOnly: boolean;
|
|
11
13
|
};
|
|
12
14
|
|
|
13
15
|
type FragmentObserverObj = {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
+
count: number;
|
|
17
|
+
list: string[];
|
|
16
18
|
};
|
|
17
19
|
|
|
18
20
|
/**
|
|
@@ -20,9 +22,11 @@ type FragmentObserverObj = {
|
|
|
20
22
|
*/
|
|
21
23
|
|
|
22
24
|
const queryObserverState = atom<QueryObserverObj>({
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
25
|
+
count: 0,
|
|
26
|
+
eventSequence: 0,
|
|
27
|
+
name: '',
|
|
28
|
+
forceRefetch: false,
|
|
29
|
+
resetOnly: false,
|
|
26
30
|
});
|
|
27
31
|
|
|
28
32
|
/**
|
|
@@ -30,8 +34,8 @@ const queryObserverState = atom<QueryObserverObj>({
|
|
|
30
34
|
*/
|
|
31
35
|
|
|
32
36
|
const fragmentObserverState = atom<FragmentObserverObj>({
|
|
33
|
-
|
|
34
|
-
|
|
37
|
+
count: 0,
|
|
38
|
+
list: [],
|
|
35
39
|
});
|
|
36
40
|
|
|
37
41
|
/**
|
|
@@ -39,7 +43,7 @@ const fragmentObserverState = atom<FragmentObserverObj>({
|
|
|
39
43
|
*/
|
|
40
44
|
|
|
41
45
|
export function useQueryObserverValue() {
|
|
42
|
-
|
|
46
|
+
return useAtomValue(queryObserverState);
|
|
43
47
|
}
|
|
44
48
|
|
|
45
49
|
/**
|
|
@@ -47,7 +51,7 @@ export function useQueryObserverValue() {
|
|
|
47
51
|
*/
|
|
48
52
|
|
|
49
53
|
export function useSetQueryObserver() {
|
|
50
|
-
|
|
54
|
+
return useSetAtom(queryObserverState);
|
|
51
55
|
}
|
|
52
56
|
|
|
53
57
|
/**
|
|
@@ -55,7 +59,7 @@ export function useSetQueryObserver() {
|
|
|
55
59
|
*/
|
|
56
60
|
|
|
57
61
|
export function useSetFragmentObserver() {
|
|
58
|
-
|
|
62
|
+
return useSetAtom(fragmentObserverState);
|
|
59
63
|
}
|
|
60
64
|
|
|
61
65
|
/**
|
|
@@ -63,5 +67,5 @@ export function useSetFragmentObserver() {
|
|
|
63
67
|
*/
|
|
64
68
|
|
|
65
69
|
export function useFragmentObserverValue() {
|
|
66
|
-
|
|
70
|
+
return useAtomValue(fragmentObserverState);
|
|
67
71
|
}
|