@selfhelp/shared 1.23.0 → 1.24.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/CHANGELOG.md +107 -0
- package/dist/index.d.mts +300 -100
- package/dist/index.d.ts +300 -100
- package/dist/index.js +519 -3
- package/dist/index.mjs +495 -3
- package/dist/plugin-sdk/index.d.mts +1 -1
- package/dist/plugin-sdk/index.d.ts +1 -1
- package/dist/plugin-sdk/index.js +3 -1
- package/dist/plugin-sdk/index.mjs +3 -1
- package/dist/registry/index.d.mts +2 -2
- package/dist/registry/index.d.ts +2 -2
- package/dist/registry/index.js +3 -1
- package/dist/registry/index.mjs +3 -1
- package/dist/{styles.registry-BBd9T2Ox.d.ts → styles.registry-BKWoDg7q.d.ts} +701 -2
- package/dist/{styles.registry-IjDTff8P.d.mts → styles.registry-aopb3vsI.d.mts} +701 -2
- package/package.json +1 -1
- package/src/api/__tests__/endpoints.test.ts +45 -0
- package/src/api/__tests__/formListErrors.test.ts +143 -0
- package/src/api/endpoints.ts +41 -0
- package/src/api/formListErrors.ts +134 -0
- package/src/api/index.ts +1 -0
- package/src/content/__tests__/formListState.test.ts +448 -0
- package/src/content/__tests__/formRecordPrefill.test.ts +120 -0
- package/src/content/formListState.ts +559 -0
- package/src/content/formRecordPrefill.ts +108 -5
- package/src/content/index.ts +1 -0
- package/src/registry/__tests__/platform.test.ts +15 -6
- package/src/registry/styles.registry.ts +2 -0
- package/src/types/api/__tests__/formWrites.test.ts +84 -0
- package/src/types/api/form-lists.ts +469 -0
- package/src/types/api/forms.ts +149 -4
- package/src/types/api/index.ts +1 -0
- package/src/types/styles/composite.ts +13 -0
- package/src/types/styles/forms.ts +84 -0
- package/src/types/styles/unknown.ts +5 -1
|
@@ -0,0 +1,559 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* SPDX-FileCopyrightText: 2026 Humdek, University of Bern
|
|
3
|
+
* SPDX-License-Identifier: MPL-2.0
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The URL grammar of a list (`entry-form-list` / `data-view`), shared by the web
|
|
8
|
+
* frontend and the mobile app so a link, a bookmark and a cache key mean the same
|
|
9
|
+
* thing on both and on the server.
|
|
10
|
+
*
|
|
11
|
+
* <key>.page=2 <key>.q=anna <key>.sort=title:asc,entry_date:desc
|
|
12
|
+
* <key>.f.<id>=value <key>.record=17 <key>.mode=view|edit|create
|
|
13
|
+
*
|
|
14
|
+
* The parser mirrors the backend `FormListUrlStateParser` rule for rule: it is
|
|
15
|
+
* strict, so a parameter in the list's namespace that is unknown, repeated,
|
|
16
|
+
* written as an array or malformed is refused instead of silently ignored. The
|
|
17
|
+
* server is the authority (it knows the list's sortable columns, controls and
|
|
18
|
+
* operations); pass them as {@link IFormListUrlRules} to refuse early what it
|
|
19
|
+
* would refuse. Parameters outside the namespace (the page, the language, other
|
|
20
|
+
* lists, anything unrelated) are never touched and always survive a change of
|
|
21
|
+
* list state.
|
|
22
|
+
*
|
|
23
|
+
* The state names choices only. It never carries a table, a column filter, an
|
|
24
|
+
* operation or a permission, and no draft form value or credential belongs in a
|
|
25
|
+
* URL.
|
|
26
|
+
*/
|
|
27
|
+
import type { IFormListSort, TFormListMode } from '../types/api/form-lists';
|
|
28
|
+
|
|
29
|
+
export const FORM_LIST_MODES: readonly TFormListMode[] = ['view', 'edit', 'create', 'history'];
|
|
30
|
+
/** The largest page number a URL may name. */
|
|
31
|
+
export const FORM_LIST_MAX_PAGE = 1_000_000;
|
|
32
|
+
/** A parameter value is at most this many bytes (UTF-8). */
|
|
33
|
+
export const FORM_LIST_MAX_VALUE_BYTES = 1000;
|
|
34
|
+
export const FORM_LIST_SEARCH_MIN_LENGTH = 2;
|
|
35
|
+
export const FORM_LIST_SEARCH_MAX_LENGTH = 100;
|
|
36
|
+
export const FORM_LIST_MAX_SORTS = 3;
|
|
37
|
+
|
|
38
|
+
/** How many route parameters a list state request carries at most (the server refuses more). */
|
|
39
|
+
export const FORM_LIST_MAX_ROUTE_PARAMS = 8;
|
|
40
|
+
|
|
41
|
+
/** The longest value of a route parameter the server accepts. */
|
|
42
|
+
export const FORM_LIST_MAX_ROUTE_VALUE_LENGTH = 255;
|
|
43
|
+
|
|
44
|
+
/** What a visitor changed in a list, as it travels in the page URL. */
|
|
45
|
+
export interface IFormListUrlState {
|
|
46
|
+
/** 1-based. A page past the end is served as the last page. */
|
|
47
|
+
page: number;
|
|
48
|
+
/** The visitor's search text, trimmed; null = no search. */
|
|
49
|
+
q: string | null;
|
|
50
|
+
/** The visitor's sort keys; empty = the list's own default order. */
|
|
51
|
+
sort: IFormListSort[];
|
|
52
|
+
/** Control id to the control's raw value (a control without a value is absent). */
|
|
53
|
+
filters: Record<string, string>;
|
|
54
|
+
/** The record that is open. */
|
|
55
|
+
record: number | null;
|
|
56
|
+
/** `view`, `edit` or `create`; null = the list only. */
|
|
57
|
+
mode: TFormListMode | null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* What the list offers, to refuse early what the server would refuse. Every
|
|
62
|
+
* rule is optional: without it only the grammar is checked.
|
|
63
|
+
*/
|
|
64
|
+
export interface IFormListUrlRules {
|
|
65
|
+
/** Fields the list can be sorted by (columns marked sortable, `entry_date`). */
|
|
66
|
+
sortable?: readonly string[];
|
|
67
|
+
/** Ids of the list's controls. */
|
|
68
|
+
controls?: readonly string[];
|
|
69
|
+
/** Default true. False on a list that does not allow new entries (and for a guest on an own-entries list). */
|
|
70
|
+
allowCreate?: boolean;
|
|
71
|
+
/** Default true. False on a list that does not allow editing, and on a data view. */
|
|
72
|
+
allowUpdate?: boolean;
|
|
73
|
+
/** Default true. False when `show_history` is off (or on a data view). */
|
|
74
|
+
showHistory?: boolean;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export type TFormListUrlErrorReason =
|
|
78
|
+
| 'invalid_list_parameter'
|
|
79
|
+
| 'unknown_list_parameter'
|
|
80
|
+
| 'duplicate_list_parameter'
|
|
81
|
+
| 'operation_disabled'
|
|
82
|
+
| 'history_disabled';
|
|
83
|
+
|
|
84
|
+
/** Why a URL cannot be a list state. `parameter` names the parameter a client may drop and retry. */
|
|
85
|
+
export interface IFormListUrlError {
|
|
86
|
+
/** 400 for a malformed or unknown parameter, 403 for a mode the list does not offer. */
|
|
87
|
+
status: 400 | 403;
|
|
88
|
+
reason: TFormListUrlErrorReason;
|
|
89
|
+
parameter: string;
|
|
90
|
+
message: string;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export type TFormListUrlParse =
|
|
94
|
+
| { ok: true; state: IFormListUrlState }
|
|
95
|
+
| { ok: false; error: IFormListUrlError };
|
|
96
|
+
|
|
97
|
+
/** A change of the list state a visitor can make; see {@link applyFormListUrlChange}. */
|
|
98
|
+
export type TFormListUrlChange =
|
|
99
|
+
| { type: 'page'; page: number }
|
|
100
|
+
| { type: 'search'; q: string | null }
|
|
101
|
+
| { type: 'sort'; sort: readonly IFormListSort[] }
|
|
102
|
+
| { type: 'filter'; id: string; value: string | null }
|
|
103
|
+
| { type: 'reset' }
|
|
104
|
+
| { type: 'open'; record: number; mode?: 'view' | 'edit' | 'history' }
|
|
105
|
+
| { type: 'create' }
|
|
106
|
+
| { type: 'close' };
|
|
107
|
+
|
|
108
|
+
const POSITIVE_INT = /^[1-9][0-9]{0,8}$/;
|
|
109
|
+
const SORT_ITEM = /^([A-Za-z][A-Za-z0-9_]{0,63}):(asc|desc)$/;
|
|
110
|
+
const CONTROL_ID = /^[a-z][a-z0-9_]{0,31}$/;
|
|
111
|
+
const LIST_KEY = /^[a-z][a-z0-9_]{0,31}$/;
|
|
112
|
+
/** PHP `trim()`: the server strips exactly these, not every Unicode space. */
|
|
113
|
+
const PHP_TRIM_CHARACTERS = ' \t\n\r\0\x0B';
|
|
114
|
+
|
|
115
|
+
export function emptyFormListUrlState(): IFormListUrlState {
|
|
116
|
+
return { page: 1, q: null, sort: [], filters: {}, record: null, mode: null };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** True when `name` is a parameter of the list called `key` (`<key>.` namespace). */
|
|
120
|
+
export function isFormListParam(name: string, key: string): boolean {
|
|
121
|
+
return name.startsWith(`${key}.`);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Parse the raw query string of a page URL into the state of the list `key`.
|
|
126
|
+
*
|
|
127
|
+
* The raw string is read, not a decoded parameter array: PHP (and many routers)
|
|
128
|
+
* rewrite the dot of `news.q` to `news_q`, which would destroy the namespace.
|
|
129
|
+
*/
|
|
130
|
+
export function parseFormListQuery(
|
|
131
|
+
query: string | URLSearchParams,
|
|
132
|
+
key: string,
|
|
133
|
+
rules: IFormListUrlRules = {},
|
|
134
|
+
): TFormListUrlParse {
|
|
135
|
+
const prefix = `${key}.`;
|
|
136
|
+
const own = new Map<string, string>();
|
|
137
|
+
for (const pair of splitPairs(query)) {
|
|
138
|
+
const equals = pair.indexOf('=');
|
|
139
|
+
const name = lenientDecode(equals === -1 ? pair : pair.slice(0, equals));
|
|
140
|
+
if (!name.startsWith(prefix)) {
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
if (own.has(name)) {
|
|
144
|
+
return refused(400, 'duplicate_list_parameter', name, `The parameter "${name}" is given twice.`);
|
|
145
|
+
}
|
|
146
|
+
own.set(name, lenientDecode(equals === -1 ? '' : pair.slice(equals + 1)));
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
let page = 1;
|
|
150
|
+
let q: string | null = null;
|
|
151
|
+
let sort: IFormListSort[] = [];
|
|
152
|
+
const filters: Record<string, string> = {};
|
|
153
|
+
let record: number | null = null;
|
|
154
|
+
let mode: TFormListMode | null = null;
|
|
155
|
+
|
|
156
|
+
for (const [name, value] of own) {
|
|
157
|
+
const suffix = name.slice(prefix.length);
|
|
158
|
+
if (utf8Length(value) > FORM_LIST_MAX_VALUE_BYTES) {
|
|
159
|
+
return refused(400, 'invalid_list_parameter', name, `The parameter "${name}" is too long.`);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
if (suffix === 'page') {
|
|
163
|
+
const parsed = positiveInt(value);
|
|
164
|
+
if (parsed === null) {
|
|
165
|
+
return refused(400, 'invalid_list_parameter', name, `The parameter "${name}" is a positive whole number.`);
|
|
166
|
+
}
|
|
167
|
+
if (parsed > FORM_LIST_MAX_PAGE) {
|
|
168
|
+
return refused(400, 'invalid_list_parameter', name, `The page in "${name}" is out of range.`);
|
|
169
|
+
}
|
|
170
|
+
page = parsed;
|
|
171
|
+
} else if (suffix === 'q') {
|
|
172
|
+
const term = phpTrim(value);
|
|
173
|
+
if (term === '') {
|
|
174
|
+
q = null;
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
const length = Array.from(term).length;
|
|
178
|
+
if (length < FORM_LIST_SEARCH_MIN_LENGTH || length > FORM_LIST_SEARCH_MAX_LENGTH) {
|
|
179
|
+
return refused(400, 'invalid_list_parameter', name, `A search has ${FORM_LIST_SEARCH_MIN_LENGTH} to ${FORM_LIST_SEARCH_MAX_LENGTH} characters.`);
|
|
180
|
+
}
|
|
181
|
+
q = term;
|
|
182
|
+
} else if (suffix === 'sort') {
|
|
183
|
+
const sorts = parseSort(value, name, rules.sortable);
|
|
184
|
+
if (!Array.isArray(sorts)) {
|
|
185
|
+
return { ok: false, error: sorts };
|
|
186
|
+
}
|
|
187
|
+
sort = sorts;
|
|
188
|
+
} else if (suffix === 'record') {
|
|
189
|
+
const parsed = positiveInt(value);
|
|
190
|
+
if (parsed === null) {
|
|
191
|
+
return refused(400, 'invalid_list_parameter', name, `The parameter "${name}" is a positive whole number.`);
|
|
192
|
+
}
|
|
193
|
+
record = parsed;
|
|
194
|
+
} else if (suffix === 'mode') {
|
|
195
|
+
if (!isMode(value)) {
|
|
196
|
+
return refused(400, 'invalid_list_parameter', name, `The mode in "${name}" is view, edit, create or history.`);
|
|
197
|
+
}
|
|
198
|
+
mode = value;
|
|
199
|
+
} else if (suffix.startsWith('f.')) {
|
|
200
|
+
const controlId = suffix.slice(2);
|
|
201
|
+
const known = rules.controls === undefined ? CONTROL_ID.test(controlId) : rules.controls.includes(controlId);
|
|
202
|
+
if (!known) {
|
|
203
|
+
return refused(400, 'unknown_list_parameter', name, `The list has no filter "${controlId}".`);
|
|
204
|
+
}
|
|
205
|
+
if (value !== '') {
|
|
206
|
+
filters[controlId] = value;
|
|
207
|
+
}
|
|
208
|
+
} else {
|
|
209
|
+
return refused(400, 'unknown_list_parameter', name, `The list has no parameter "${name}".`);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
return withMode({ page, q, sort, filters, record, mode }, key, rules);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* The state as URL parameters, in the order the server echoes them (`page` only
|
|
218
|
+
* above 1, then `q`, `sort`, the filters, `record`, `mode`). Empty state, no
|
|
219
|
+
* parameters.
|
|
220
|
+
*/
|
|
221
|
+
export function encodeFormListQuery(key: string, state: IFormListUrlState): Record<string, string> {
|
|
222
|
+
const query: Record<string, string> = {};
|
|
223
|
+
if (state.page > 1) {
|
|
224
|
+
query[`${key}.page`] = String(state.page);
|
|
225
|
+
}
|
|
226
|
+
if (state.q !== null && state.q !== '') {
|
|
227
|
+
query[`${key}.q`] = state.q;
|
|
228
|
+
}
|
|
229
|
+
if (state.sort.length > 0) {
|
|
230
|
+
query[`${key}.sort`] = state.sort.map((item) => `${item.field}:${item.direction}`).join(',');
|
|
231
|
+
}
|
|
232
|
+
for (const [id, value] of Object.entries(state.filters)) {
|
|
233
|
+
if (value !== '') {
|
|
234
|
+
query[`${key}.f.${id}`] = value;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
if (state.record !== null) {
|
|
238
|
+
query[`${key}.record`] = String(state.record);
|
|
239
|
+
}
|
|
240
|
+
if (state.mode !== null) {
|
|
241
|
+
query[`${key}.mode`] = state.mode;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
return query;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* The query string (no leading `?`) of a link that shows `state` of the list
|
|
249
|
+
* `key` on the page whose current query string is `base`.
|
|
250
|
+
*
|
|
251
|
+
* Every parameter outside the list's namespace is kept exactly as it was, in
|
|
252
|
+
* its place; the list's own parameters are replaced by the encoding of `state`
|
|
253
|
+
* and appended last. Opening a record, paging or searching never drops the
|
|
254
|
+
* language, a preview flag, another list's state or a campaign parameter.
|
|
255
|
+
*/
|
|
256
|
+
export function formListQueryString(base: string | URLSearchParams, key: string, state: IFormListUrlState): string {
|
|
257
|
+
const kept = splitPairs(base).filter((pair) => {
|
|
258
|
+
const equals = pair.indexOf('=');
|
|
259
|
+
return !isFormListParam(lenientDecode(equals === -1 ? pair : pair.slice(0, equals)), key);
|
|
260
|
+
});
|
|
261
|
+
const written = Object.entries(encodeFormListQuery(key, state)).map(
|
|
262
|
+
([name, value]) => `${encodeURIComponent(name)}=${encodeValue(value)}`,
|
|
263
|
+
);
|
|
264
|
+
|
|
265
|
+
return [...kept, ...written].join('&');
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* The next state after a visitor's change. Pure; the URL is then rebuilt with
|
|
270
|
+
* {@link formListQueryString}.
|
|
271
|
+
*
|
|
272
|
+
* Narrowing the list (search, sort, filter, reset) goes back to page 1, because
|
|
273
|
+
* the old page number may no longer exist. The open record is left alone: the
|
|
274
|
+
* server reads it inside the list's dataset and never inside the visitor's
|
|
275
|
+
* filters, so a link to a record keeps working after the visitor narrows the
|
|
276
|
+
* list. Open, create and close change the record and mode and keep the rest.
|
|
277
|
+
*/
|
|
278
|
+
export function applyFormListUrlChange(state: IFormListUrlState, change: TFormListUrlChange): IFormListUrlState {
|
|
279
|
+
switch (change.type) {
|
|
280
|
+
case 'page':
|
|
281
|
+
return { ...state, page: clampPage(change.page) };
|
|
282
|
+
case 'search': {
|
|
283
|
+
const term = change.q === null ? '' : phpTrim(change.q);
|
|
284
|
+
return { ...state, q: term === '' ? null : term, page: 1 };
|
|
285
|
+
}
|
|
286
|
+
case 'sort':
|
|
287
|
+
return { ...state, sort: change.sort.slice(0, FORM_LIST_MAX_SORTS).map((item) => ({ ...item })), page: 1 };
|
|
288
|
+
case 'filter': {
|
|
289
|
+
const filters = { ...state.filters };
|
|
290
|
+
if (change.value === null || change.value === '') {
|
|
291
|
+
delete filters[change.id];
|
|
292
|
+
} else {
|
|
293
|
+
filters[change.id] = change.value;
|
|
294
|
+
}
|
|
295
|
+
return { ...state, filters, page: 1 };
|
|
296
|
+
}
|
|
297
|
+
case 'reset':
|
|
298
|
+
return { ...state, page: 1, q: null, sort: [], filters: {} };
|
|
299
|
+
case 'open':
|
|
300
|
+
return { ...state, record: change.record, mode: change.mode ?? 'view' };
|
|
301
|
+
case 'create':
|
|
302
|
+
return { ...state, record: null, mode: 'create' };
|
|
303
|
+
case 'close':
|
|
304
|
+
return { ...state, record: null, mode: null };
|
|
305
|
+
default: {
|
|
306
|
+
// Compile-time exhaustiveness: a new change type must be handled above.
|
|
307
|
+
const unhandled: never = change;
|
|
308
|
+
throw new Error(`Unknown list state change: ${JSON.stringify(unhandled)}`);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* The sort a click on a column header asks for: none -> ascending -> descending
|
|
315
|
+
* -> none, one key at a time. A click on another column starts that column
|
|
316
|
+
* ascending and drops the others.
|
|
317
|
+
*/
|
|
318
|
+
export function nextSortOnHeaderClick(current: readonly IFormListSort[], field: string): IFormListSort[] {
|
|
319
|
+
const first = current[0];
|
|
320
|
+
if (first === undefined || first.field !== field) {
|
|
321
|
+
return [{ field, direction: 'asc' }];
|
|
322
|
+
}
|
|
323
|
+
if (first.direction === 'asc') {
|
|
324
|
+
return [{ field, direction: 'desc' }];
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
return [];
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* The raw `name=value` pairs of a page URL that can belong to a list: those whose
|
|
332
|
+
* name starts with a list key and a dot. Forward exactly these, unchanged, to
|
|
333
|
+
* `GET /pages/by-keyword/{keyword}` and `GET /pages/resolve` so the server can
|
|
334
|
+
* render the lists of the page. The client does not know the page's list keys
|
|
335
|
+
* before it asks, and the server only reads the namespaces of lists that exist.
|
|
336
|
+
*/
|
|
337
|
+
export function pickFormListQuery(query: string | URLSearchParams): string {
|
|
338
|
+
return splitPairs(query)
|
|
339
|
+
.filter((pair) => {
|
|
340
|
+
const equals = pair.indexOf('=');
|
|
341
|
+
const name = lenientDecode(equals === -1 ? pair : pair.slice(0, equals));
|
|
342
|
+
const dot = name.indexOf('.');
|
|
343
|
+
|
|
344
|
+
return dot > 0 && LIST_KEY.test(name.slice(0, dot));
|
|
345
|
+
})
|
|
346
|
+
.join('&');
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* The route parameters of a page as the list state request names them: `route[record_id]=3`.
|
|
351
|
+
*
|
|
352
|
+
* A page with a route (`/team/{record_id}`) draws the layout of a record with `{{route.record_id}}`, so the
|
|
353
|
+
* state of a list depends on the route as well as on the page. The client repeats the declared parameters
|
|
354
|
+
* of the page it shows (`page.route_params`); the server does not believe them, it checks them against the
|
|
355
|
+
* routes of that page. Names and values are percent-encoded, sorted by name, and a parameter that cannot be a
|
|
356
|
+
* route parameter (a name that is not a placeholder name, an empty value, a value that is too long, or one
|
|
357
|
+
* beyond {@link FORM_LIST_MAX_ROUTE_PARAMS}) is left out. Returns `''` for a page without route parameters.
|
|
358
|
+
*/
|
|
359
|
+
export function formListRouteQuery(route: Readonly<Record<string, string | undefined>> | null | undefined): string {
|
|
360
|
+
if (!route) {
|
|
361
|
+
return '';
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
return Object.entries(route)
|
|
365
|
+
.filter((entry): entry is [string, string] => {
|
|
366
|
+
const [name, value] = entry;
|
|
367
|
+
|
|
368
|
+
return ROUTE_PARAM_NAME.test(name) && typeof value === 'string' && value !== '' && value.length <= FORM_LIST_MAX_ROUTE_VALUE_LENGTH;
|
|
369
|
+
})
|
|
370
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
|
371
|
+
.slice(0, FORM_LIST_MAX_ROUTE_PARAMS)
|
|
372
|
+
.map(([name, value]) => `route%5B${encodeURIComponent(name)}%5D=${encodeURIComponent(value)}`)
|
|
373
|
+
.join('&');
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** What a list's cached state depends on. Log out and a server switch clear every list cache. */
|
|
377
|
+
export interface IFormListCacheScope {
|
|
378
|
+
/** The API base URL of the server the account belongs to. */
|
|
379
|
+
apiBase: string;
|
|
380
|
+
/** The signed-in account's id; null for a guest. */
|
|
381
|
+
account: string | number | null;
|
|
382
|
+
languageId: number;
|
|
383
|
+
platform: 'web' | 'mobile';
|
|
384
|
+
pageId: number;
|
|
385
|
+
sectionId: number;
|
|
386
|
+
/** The list's key in the URL. */
|
|
387
|
+
key: string;
|
|
388
|
+
/**
|
|
389
|
+
* The declared route parameters of the page (`page.route_params`). The layout of a record can read them, so
|
|
390
|
+
* the same page and section with another route is another list state.
|
|
391
|
+
*/
|
|
392
|
+
route?: Readonly<Record<string, string | undefined>> | null;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* A stable client cache key for one list in one state: API base, account (or
|
|
397
|
+
* guest), language, platform, page, section, the declared route of the page and
|
|
398
|
+
* the normalized `<key>.*` parameters (sorted, decoded, so two spellings of
|
|
399
|
+
* one state share an entry). The last part is always the list's own state; every
|
|
400
|
+
* part before it identifies the list itself.
|
|
401
|
+
* Never reuse a key across accounts: the same URL shows different records to
|
|
402
|
+
* different people.
|
|
403
|
+
*/
|
|
404
|
+
export function formListCacheKey(scope: IFormListCacheScope, query: string | URLSearchParams): readonly (string | number)[] {
|
|
405
|
+
const own = splitPairs(query)
|
|
406
|
+
.map((pair): [string, string] => {
|
|
407
|
+
const equals = pair.indexOf('=');
|
|
408
|
+
return [lenientDecode(equals === -1 ? pair : pair.slice(0, equals)), lenientDecode(equals === -1 ? '' : pair.slice(equals + 1))];
|
|
409
|
+
})
|
|
410
|
+
.filter(([name]) => isFormListParam(name, scope.key))
|
|
411
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
|
412
|
+
.map(([name, value]) => `${name}=${value}`)
|
|
413
|
+
.join('&');
|
|
414
|
+
|
|
415
|
+
return [
|
|
416
|
+
'form-list',
|
|
417
|
+
scope.apiBase,
|
|
418
|
+
scope.account === null ? 'guest' : String(scope.account),
|
|
419
|
+
scope.languageId,
|
|
420
|
+
scope.platform,
|
|
421
|
+
scope.pageId,
|
|
422
|
+
scope.sectionId,
|
|
423
|
+
formListRouteQuery(scope.route),
|
|
424
|
+
own,
|
|
425
|
+
];
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
// -- internals ------------------------------------------------------------------------------
|
|
429
|
+
|
|
430
|
+
/** A route placeholder name, as the server's route patterns allow it. */
|
|
431
|
+
const ROUTE_PARAM_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
432
|
+
|
|
433
|
+
function refused(status: 400 | 403, reason: TFormListUrlErrorReason, parameter: string, message: string): TFormListUrlParse {
|
|
434
|
+
return { ok: false, error: { status, reason, parameter, message } };
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/** The record and the mode belong together; a mode the list does not offer is forbidden, not malformed. */
|
|
438
|
+
function withMode(state: IFormListUrlState, key: string, rules: IFormListUrlRules): TFormListUrlParse {
|
|
439
|
+
let mode = state.mode;
|
|
440
|
+
if (mode === null && state.record !== null) {
|
|
441
|
+
mode = 'view';
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
if (mode === 'create') {
|
|
445
|
+
if (state.record !== null) {
|
|
446
|
+
return refused(400, 'invalid_list_parameter', `${key}.record`, 'A new entry has no record.');
|
|
447
|
+
}
|
|
448
|
+
if (rules.allowCreate === false) {
|
|
449
|
+
return refused(403, 'operation_disabled', `${key}.mode`, 'This list does not allow new entries.');
|
|
450
|
+
}
|
|
451
|
+
} else if (mode !== null && state.record === null) {
|
|
452
|
+
return refused(400, 'invalid_list_parameter', `${key}.record`, `The mode "${mode}" needs a record.`);
|
|
453
|
+
}
|
|
454
|
+
if (mode === 'edit' && rules.allowUpdate === false) {
|
|
455
|
+
return refused(403, 'operation_disabled', `${key}.mode`, 'This list does not allow editing.');
|
|
456
|
+
}
|
|
457
|
+
if (mode === 'history' && rules.showHistory === false) {
|
|
458
|
+
return refused(403, 'history_disabled', `${key}.mode`, 'This list does not offer history.');
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
return { ok: true, state: { ...state, mode } };
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
function parseSort(value: string, name: string, sortable: readonly string[] | undefined): IFormListSort[] | IFormListUrlError {
|
|
465
|
+
if (value === '') {
|
|
466
|
+
return [];
|
|
467
|
+
}
|
|
468
|
+
const items = value.split(',');
|
|
469
|
+
const fail = (message: string): IFormListUrlError => ({ status: 400, reason: 'invalid_list_parameter', parameter: name, message });
|
|
470
|
+
if (items.length > FORM_LIST_MAX_SORTS) {
|
|
471
|
+
return fail(`At most ${FORM_LIST_MAX_SORTS} sort keys.`);
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
const sorts: IFormListSort[] = [];
|
|
475
|
+
const seen = new Set<string>();
|
|
476
|
+
for (const item of items) {
|
|
477
|
+
const match = SORT_ITEM.exec(item);
|
|
478
|
+
if (match === null) {
|
|
479
|
+
return fail('A sort key is "column:asc" or "column:desc".');
|
|
480
|
+
}
|
|
481
|
+
const field = match[1] ?? '';
|
|
482
|
+
const direction = match[2] === 'desc' ? 'desc' : 'asc';
|
|
483
|
+
if (sortable !== undefined && !sortable.includes(field)) {
|
|
484
|
+
return fail(`The list cannot be sorted by "${field}".`);
|
|
485
|
+
}
|
|
486
|
+
if (seen.has(field)) {
|
|
487
|
+
return fail(`"${field}" is sorted twice.`);
|
|
488
|
+
}
|
|
489
|
+
seen.add(field);
|
|
490
|
+
sorts.push({ field, direction });
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
return sorts;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/** `trim()` of PHP: strips space, tab, newline, carriage return, NUL and vertical tab, nothing else. */
|
|
497
|
+
function phpTrim(text: string): string {
|
|
498
|
+
let start = 0;
|
|
499
|
+
let end = text.length;
|
|
500
|
+
while (start < end && PHP_TRIM_CHARACTERS.includes(text.charAt(start))) {
|
|
501
|
+
start += 1;
|
|
502
|
+
}
|
|
503
|
+
while (end > start && PHP_TRIM_CHARACTERS.includes(text.charAt(end - 1))) {
|
|
504
|
+
end -= 1;
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
return text.slice(start, end);
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
function positiveInt(value: string): number | null {
|
|
511
|
+
return POSITIVE_INT.test(value) ? Number(value) : null;
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
function isMode(value: string): value is TFormListMode {
|
|
515
|
+
return (FORM_LIST_MODES as readonly string[]).includes(value);
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
function clampPage(page: number): number {
|
|
519
|
+
if (!Number.isFinite(page)) {
|
|
520
|
+
return 1;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
return Math.min(FORM_LIST_MAX_PAGE, Math.max(1, Math.trunc(page)));
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
function splitPairs(query: string | URLSearchParams): string[] {
|
|
527
|
+
const text = typeof query === 'string' ? query : query.toString();
|
|
528
|
+
const trimmed = text.startsWith('?') ? text.slice(1) : text;
|
|
529
|
+
|
|
530
|
+
return trimmed.split('&').filter((pair) => pair !== '');
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/** `rawurldecode(str_replace('+', ' ', ...))` as the server reads it; a malformed escape stays as written. */
|
|
534
|
+
function lenientDecode(text: string): string {
|
|
535
|
+
return text
|
|
536
|
+
.replace(/\+/g, ' ')
|
|
537
|
+
.replace(/(?:%[0-9A-Fa-f]{2})+/g, (run) => {
|
|
538
|
+
try {
|
|
539
|
+
return decodeURIComponent(run);
|
|
540
|
+
} catch {
|
|
541
|
+
return run;
|
|
542
|
+
}
|
|
543
|
+
});
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
/** A value in a link: percent-encoded, with the readable separators of the grammar left as they are. */
|
|
547
|
+
function encodeValue(value: string): string {
|
|
548
|
+
return encodeURIComponent(value).replace(/%3A/g, ':').replace(/%2C/g, ',');
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
function utf8Length(text: string): number {
|
|
552
|
+
let bytes = 0;
|
|
553
|
+
for (const character of text) {
|
|
554
|
+
const code = character.codePointAt(0) ?? 0;
|
|
555
|
+
bytes += code < 0x80 ? 1 : code < 0x800 ? 2 : code < 0x10000 ? 3 : 4;
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
return bytes;
|
|
559
|
+
}
|