@coding_doc/sveltedt 0.0.0 → 0.1.0-rehearsal.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +52 -0
  3. package/README.md +618 -2
  4. package/dist/DataTable.svelte +313 -0
  5. package/dist/DataTable.svelte.d.ts +26 -0
  6. package/dist/Pagination.svelte +125 -0
  7. package/dist/Pagination.svelte.d.ts +5 -0
  8. package/dist/checks.d.ts +5 -0
  9. package/dist/checks.js +7 -0
  10. package/dist/connection/answer.d.ts +6 -0
  11. package/dist/connection/answer.js +47 -0
  12. package/dist/connection/connection.svelte.d.ts +16 -0
  13. package/dist/connection/connection.svelte.js +214 -0
  14. package/dist/connection/index.d.ts +8 -0
  15. package/dist/connection/index.js +7 -0
  16. package/dist/connection/request.d.ts +4 -0
  17. package/dist/connection/request.js +71 -0
  18. package/dist/connection/types.d.ts +182 -0
  19. package/dist/connection/types.js +1 -0
  20. package/dist/faults.d.ts +6 -0
  21. package/dist/faults.js +64 -0
  22. package/dist/filters.d.ts +23 -0
  23. package/dist/filters.js +65 -0
  24. package/dist/index.d.ts +9 -0
  25. package/dist/index.js +8 -0
  26. package/dist/messages.d.ts +4 -0
  27. package/dist/messages.js +62 -0
  28. package/dist/pager.d.ts +19 -0
  29. package/dist/pager.js +80 -0
  30. package/dist/parts/ColumnFilter.svelte +213 -0
  31. package/dist/parts/ColumnFilter.svelte.d.ts +11 -0
  32. package/dist/parts/HeaderCell.svelte +90 -0
  33. package/dist/parts/HeaderCell.svelte.d.ts +34 -0
  34. package/dist/parts/Search.svelte +79 -0
  35. package/dist/parts/Search.svelte.d.ts +9 -0
  36. package/dist/parts/Toolbar.svelte +70 -0
  37. package/dist/parts/Toolbar.svelte.d.ts +29 -0
  38. package/dist/picks.svelte.d.ts +6 -0
  39. package/dist/picks.svelte.js +42 -0
  40. package/dist/search.svelte.d.ts +15 -0
  41. package/dist/search.svelte.js +76 -0
  42. package/dist/sort.d.ts +6 -0
  43. package/dist/sort.js +32 -0
  44. package/dist/styles.css +230 -0
  45. package/dist/types.d.ts +323 -0
  46. package/dist/types.js +1 -0
  47. package/dist/validate.d.ts +5 -0
  48. package/dist/validate.js +201 -0
  49. package/dist/view.svelte.d.ts +7 -0
  50. package/dist/view.svelte.js +75 -0
  51. package/package.json +83 -3
@@ -0,0 +1,313 @@
1
+ <!--
2
+ @component
3
+ The data table. Its props are {@link DataTableProps}.
4
+ -->
5
+ <script lang="ts" generics="Row">
6
+ import { untrack } from "svelte";
7
+ import { faultLine } from "./faults.js";
8
+ import { defaultMessages, mergeMessages } from "./messages.js";
9
+ import HeaderCell from "./parts/HeaderCell.svelte";
10
+ import Search from "./parts/Search.svelte";
11
+ import Toolbar from "./parts/Toolbar.svelte";
12
+ import { nextOrder, sortState } from "./sort.js";
13
+ import type { DataTableColumn, DataTableProps } from "./types.js";
14
+ import { validateTable } from "./validate.js";
15
+ import { TableView } from "./view.svelte.js";
16
+
17
+ const {
18
+ rows,
19
+ columns,
20
+ getRowId,
21
+ caption,
22
+ regionLabel,
23
+ status = "ready",
24
+ busy = false,
25
+ messages,
26
+ sort,
27
+ onsort,
28
+ oncancel,
29
+ onretry,
30
+ filters,
31
+ onfilter,
32
+ onclearfilter,
33
+ onclearfilters,
34
+ onreset,
35
+ criteria,
36
+ onsearch,
37
+ search,
38
+ searchDelay,
39
+ searchOnEnter,
40
+ maxLength,
41
+ heading,
42
+ actions,
43
+ panels,
44
+ }: DataTableProps<Row> = $props();
45
+ // The caption text and the hint (SORT-28) are one name: Svelte trims a bare space beside a tag, so it is a value
46
+ const SPACE = " ";
47
+ // Ties each sort button to its description, unique per table on the page
48
+ const uid = $props.id();
49
+ // Shift held at the Enter or Space keydown (null: no such key pending) decides the next click with no pointer,
50
+ // whatever Shift that click carries or another key changes; the click or a blur clears it
51
+ let keyShift: boolean | null = null;
52
+ function sortKey(event: KeyboardEvent): void {
53
+ if (event.key === "Enter" || event.key === " ") keyShift = event.shiftKey;
54
+ }
55
+ function shiftOf(event: MouseEvent): boolean {
56
+ const shift =
57
+ event.detail === 0 && keyShift !== null ? keyShift : event.shiftKey;
58
+ keyShift = null;
59
+ return shift;
60
+ }
61
+ // A sort button's press focuses it, without scrolling, also where a click does not (A11Y-19, A11Y-17), before the
62
+ // callback so an application that moves focus itself keeps its choice; then it emits the next order (SORT-12). A sort
63
+ // button exists only for a sortable column, and the table has an onsort whenever a column is sortable (RND-05), so
64
+ // neither fallback below can be reached
65
+ function press(column: DataTableColumn<Row>, event: MouseEvent): void {
66
+ (event.currentTarget as HTMLElement).focus({ preventScroll: true });
67
+ // Stryker disable OptionalChaining,ArrayDeclaration: unreachable fallbacks, see above
68
+ onsort?.(
69
+ nextOrder(order, column.id, column.sortable ?? [], shiftOf(event)),
70
+ );
71
+ }
72
+ // Stryker restore OptionalChaining,ArrayDeclaration
73
+ // The text of a cell without a snippet; RND-05 refuses a column with neither, so its value is there
74
+ // Stryker disable OptionalChaining: unreachable, see above
75
+ const textOf = (column: DataTableColumn<Row>, row: Row) =>
76
+ column.value?.({ row });
77
+ // Stryker restore OptionalChaining
78
+ // The given words over the English defaults (RND-06)
79
+ const words = $derived(mergeMessages(defaultMessages, messages));
80
+ // null is no order (SORT-15)
81
+ const order = $derived(sort ?? []);
82
+ const fault = $derived(
83
+ validateTable({
84
+ rows,
85
+ columns,
86
+ getRowId,
87
+ caption,
88
+ regionLabel,
89
+ status,
90
+ sort,
91
+ onsort,
92
+ filters,
93
+ onfilter,
94
+ onclearfilter,
95
+ onclearfilters,
96
+ search,
97
+ searchDelay,
98
+ maxLength,
99
+ emptyOption: words.emptyOption,
100
+ }),
101
+ );
102
+ // The cause of a fault goes to the developer (RND-17). `fault` is a derived code, so the effect runs again only when
103
+ // it changes: once for each change, and never on the server
104
+ $effect(() => {
105
+ if (fault !== null) console.error(faultLine(fault));
106
+ });
107
+ // Counted only while the rows shown are the answer (A11Y-05)
108
+ const count = $derived(
109
+ fault === null && status === "ready" && !busy
110
+ ? words.rowCount(rows.length)
111
+ : "",
112
+ );
113
+ // Loading or busy, with valid input: what the slow-load feedback waits on (STATE-09)
114
+ const pending = $derived(fault === null && (status === "loading" || busy));
115
+ // The slow-load state of PRD-B2; its first effect keeps focus off a Cancel that is about to go (A11Y-28; why it is
116
+ // there: see TableView)
117
+ const view = new TableView(
118
+ () => pending,
119
+ () => keepFocus(cancelButton),
120
+ () => region,
121
+ );
122
+ // The callback of "Cancel" while it is shown (STATE-17), nothing otherwise; the markup and the focus hand-off read it
123
+ const cancel = $derived(view.still ? oncancel : undefined);
124
+ // The callback of "Try again" while it is shown (STATE-23), nothing otherwise
125
+ const retry = $derived(
126
+ status === "stopped" || status === "failed" ? onretry : undefined,
127
+ );
128
+ // For the focus hand-off and the region's Tab stop: bind:this sets them, and nulls them when their element goes.
129
+ // State, because a variable that bind:this sets inside an {#if} must be declared with $state(...) (the compiler warns
130
+ // otherwise)
131
+ let region = $state<HTMLDivElement | null>(null);
132
+ let table = $state<HTMLTableElement | null>(null);
133
+ let cancelButton = $state<HTMLButtonElement | null>(null);
134
+ let retryButton = $state<HTMLButtonElement | null>(null);
135
+ // A focused button about to go hands focus to the table, which takes it without scrolling (A11Y-28, A11Y-30). The
136
+ // tabindex is set only for this focus and goes with the table's `onblur`. With invalid
137
+ // input there is no table. It must run before the button leaves the DOM
138
+ function keepFocus(button: HTMLElement | null): void {
139
+ if (table && button?.matches(":focus")) {
140
+ table.tabIndex = -1;
141
+ table.focus({ preventScroll: true });
142
+ }
143
+ }
144
+ // A pressed badge goes, so focus moves to its column's filter button, not to the page body (FILT-24). Before the
145
+ // callback, so an application that moves focus itself keeps its choice. A badge shows only while no fault does
146
+ // (FILT-08), and FILT-32 refuses a filter on a column without one and a column filter without onclearfilter, so the
147
+ // table, the button and the callback are there
148
+ function clearFilter(change: Readonly<{ id: string }>): void {
149
+ // Stryker disable OptionalChaining: unreachable fallbacks, see above
150
+ const index = columns.findIndex((column) => column.id === change.id);
151
+ table
152
+ ?.querySelector<HTMLElement>(
153
+ `thead th:nth-child(${String(index + 1)}) button[popovertarget]`,
154
+ )
155
+ ?.focus();
156
+ onclearfilter?.(change);
157
+ // Stryker restore OptionalChaining
158
+ }
159
+ // A button goes with the props: a props flush, where a pre-effect runs before the DOM update. Both are read, so
160
+ // either going reruns it
161
+ $effect.pre(() => {
162
+ const goneCancel = !cancel;
163
+ const goneRetry = !retry;
164
+ untrack(() => {
165
+ if (goneCancel) keepFocus(cancelButton);
166
+ if (goneRetry) keepFocus(retryButton);
167
+ });
168
+ });
169
+ </script>
170
+
171
+ <div class="sdt">
172
+ {@render heading?.()}
173
+ {@render actions?.()}
174
+ {#if onsearch && fault === null}<Search
175
+ label={words.searchLabel}
176
+ {words}
177
+ {search}
178
+ {searchDelay}
179
+ {searchOnEnter}
180
+ {maxLength}
181
+ {onsearch}
182
+ />{/if}
183
+ <Toolbar
184
+ {fault}
185
+ {columns}
186
+ {filters}
187
+ {words}
188
+ {criteria}
189
+ onclearfilter={clearFilter}
190
+ {onclearfilters}
191
+ {onreset}
192
+ />
193
+ {#if panels !== undefined}{@render panels()}{/if}
194
+ <!-- The status line: the status region, "Cancel" beside it and the progress indicator at its foot. It keeps its room
195
+ from the first load or refetch until unmount (STATE-15, STATE-29; `started` is set in view.svelte.ts). The status
196
+ region and the live count stay in the document in every state, the invalid-input alert's included, so a change of
197
+ their text is announced. The indicator is not drawn beside the alert (RND-13): `shown` outlasts a fault for up to
198
+ its 500 ms minimum -->
199
+ <div class={[(pending || view.started) && "sdt-status"]}>
200
+ <div role="status" aria-atomic="false">
201
+ {fault === null && status === "loading" ? words.loading : ""}
202
+ {#if view.still}<span>{words.stillLoading}</span>{/if}
203
+ {#if fault === null && status === "stopped"}<div class="sdt-stopped">
204
+ {words.stopped}
205
+ </div>{/if}
206
+ </div>
207
+ {#if cancel}<button
208
+ class="sdt-button"
209
+ bind:this={cancelButton}
210
+ type="button"
211
+ onclick={() => cancel()}
212
+ >
213
+ {words.cancel}
214
+ </button>{/if}
215
+ {#if view.shown && fault === null}<div
216
+ class="sdt-progress"
217
+ data-sdt-progress
218
+ aria-hidden="true"
219
+ ></div>{/if}
220
+ </div>
221
+ <div class="sdt-sr-only" aria-live="polite">{count}</div>
222
+ {#if fault !== null}
223
+ <div role="alert">{words.invalidInput}</div>
224
+ {:else}
225
+ {#if status === "failed"}
226
+ <div role="alert">{words.failed}</div>
227
+ {/if}
228
+ <div
229
+ bind:this={region}
230
+ class="sdt-region"
231
+ role="region"
232
+ aria-label={regionLabel}
233
+ >
234
+ <table
235
+ bind:this={table}
236
+ class="sdt-table"
237
+ aria-busy={busy || status === "loading"}
238
+ onblur={(event) => event.currentTarget.removeAttribute("tabindex")}
239
+ >
240
+ <caption class="sdt-caption">
241
+ {caption}{#if columns.some((column) => column.sortable)}{SPACE}<span>
242
+ {words.sortableHint}
243
+ </span>{/if}
244
+ </caption>
245
+ <thead>
246
+ <tr class="sdt-head-row">
247
+ {#each columns as column, index (column.id)}
248
+ <HeaderCell
249
+ {column}
250
+ {order}
251
+ describedBy={`${uid}-sort-${index}`}
252
+ {words}
253
+ onkeydown={sortKey}
254
+ onblur={() => (keyShift = null)}
255
+ onpress={(event: MouseEvent) => press(column, event)}
256
+ applied={filters?.[column.id]}
257
+ {searchDelay}
258
+ {searchOnEnter}
259
+ {maxLength}
260
+ {onfilter}
261
+ />
262
+ {/each}
263
+ </tr>
264
+ </thead>
265
+ <tbody>
266
+ <!-- STATE-20: stopped shows one spanning cell and no rows; loading and failed leave the body empty and
267
+ show their message outside the table (STATE-01, STATE-02, STATE-06, STATE-07) -->
268
+ {#if status === "stopped"}
269
+ <tr>
270
+ <td class="sdt-cell" colspan={columns.length}>{words.stopped}</td>
271
+ </tr>
272
+ {:else if status === "ready"}
273
+ {#each rows as row (getRowId({ row }))}
274
+ <tr class="sdt-row">
275
+ {#each columns as column (column.id)}
276
+ <td class="sdt-cell">
277
+ {#if typeof column.cell === "function"}{@render column.cell(
278
+ { row, column },
279
+ )}{:else}{textOf(column, row)}{/if}
280
+ </td>
281
+ {/each}
282
+ </tr>
283
+ {:else}
284
+ <tr>
285
+ <td class="sdt-cell sdt-empty" colspan={columns.length}>
286
+ {words.empty}
287
+ </td>
288
+ </tr>
289
+ {/each}
290
+ {/if}
291
+ </tbody>
292
+ </table>
293
+ </div>
294
+ {#if retry}<button
295
+ class="sdt-button"
296
+ bind:this={retryButton}
297
+ type="button"
298
+ onclick={() => retry()}
299
+ >
300
+ {words.retry}
301
+ </button>{/if}
302
+ <!-- The sort buttons' descriptions, outside the table so they are no header text -->
303
+ <div hidden>
304
+ {#each columns as column, index (column.id)}
305
+ {#if column.sortable}
306
+ <span id={`${uid}-sort-${index}`}>
307
+ {words.sortDescription(sortState(order, column.id))}
308
+ </span>
309
+ {/if}
310
+ {/each}
311
+ </div>
312
+ {/if}
313
+ </div>
@@ -0,0 +1,26 @@
1
+ import type { DataTableProps } from "./types.js";
2
+ declare function $$render<Row>(): {
3
+ props: DataTableProps<Row>;
4
+ exports: {};
5
+ bindings: "";
6
+ slots: {};
7
+ events: {};
8
+ };
9
+ declare class __sveltets_Render<Row> {
10
+ props(): ReturnType<typeof $$render<Row>>['props'];
11
+ events(): ReturnType<typeof $$render<Row>>['events'];
12
+ slots(): ReturnType<typeof $$render<Row>>['slots'];
13
+ bindings(): "";
14
+ exports(): {};
15
+ }
16
+ interface $$IsomorphicComponent {
17
+ new <Row>(options: import('svelte').ComponentConstructorOptions<ReturnType<__sveltets_Render<Row>['props']>>): import('svelte').SvelteComponent<ReturnType<__sveltets_Render<Row>['props']>, ReturnType<__sveltets_Render<Row>['events']>, ReturnType<__sveltets_Render<Row>['slots']>> & {
18
+ $$bindings?: ReturnType<__sveltets_Render<Row>['bindings']>;
19
+ } & ReturnType<__sveltets_Render<Row>['exports']>;
20
+ <Row>(internal: unknown, props: ReturnType<__sveltets_Render<Row>['props']> & {}): ReturnType<__sveltets_Render<Row>['exports']>;
21
+ z_$$bindings?: ReturnType<__sveltets_Render<any>['bindings']>;
22
+ }
23
+ /** The data table. Its props are {@link DataTableProps}. */
24
+ declare const DataTable: $$IsomorphicComponent;
25
+ type DataTable<Row> = InstanceType<typeof DataTable<Row>>;
26
+ export default DataTable;
@@ -0,0 +1,125 @@
1
+ <!-- Adapted from ontoprism, frontend/src/lib/components/Pagination.svelte (Apache License 2.0, the owner's own
2
+ project): the nav, the aria-disabled step buttons, the keyed number row and its gaps. -->
3
+ <!--
4
+ @component
5
+ The pager. Its props are {@link PaginationProps}.
6
+ -->
7
+ <script lang="ts">
8
+ import { faultLine } from "./faults.js";
9
+ import { defaultPagerMessages, mergeMessages } from "./messages.js";
10
+ import { pageNumbers, pagerState, validatePager } from "./pager.js";
11
+ import type { PaginationProps } from "./types.js";
12
+
13
+ const props: PaginationProps = $props();
14
+ const words = $derived(mergeMessages(defaultPagerMessages, props.messages));
15
+ const fault = $derived(validatePager(props));
16
+ // The cause of a fault goes to the developer (PAGE-41), as the table's does (RND-17): once for each change of the
17
+ // derived code, and never on the server
18
+ $effect(() => {
19
+ if (fault !== null) console.error(faultLine(fault));
20
+ });
21
+ const state = $derived(pagerState(props.offset, props.limit, props.total));
22
+ const items = $derived(pageNumbers(state.page - 1, state.pages));
23
+ const sizes = $derived(props.sizes ?? []);
24
+ // The information line; the unfiltered total follows only when it differs (PAGE-37, PAGE-38)
25
+ const info = $derived(
26
+ words.info({
27
+ first: state.firstRow,
28
+ last: state.lastRow,
29
+ total: props.total,
30
+ }) +
31
+ (props.unfilteredTotal != null && props.unfilteredTotal !== props.total
32
+ ? ` ${words.infoFiltered(props.unfilteredTotal)}`
33
+ : ""),
34
+ );
35
+
36
+ // A pressed button takes focus, without scrolling, also where a click does not give it (A11Y-19, A11Y-17), before the
37
+ // callback so an application that moves focus itself keeps its choice. A step that cannot move stays a focusable
38
+ // button and emits nothing (PAGE-05, PAGE-13)
39
+ function step(event: MouseEvent, can: boolean, offset: number): void {
40
+ (event.currentTarget as HTMLElement).focus({ preventScroll: true });
41
+ if (can) props.onpage(offset);
42
+ }
43
+
44
+ // The select shows `limit` again until the consumer passes a new one (PAGE-22)
45
+ function choose(event: Event & { currentTarget: HTMLSelectElement }): void {
46
+ const size = Number(event.currentTarget.value);
47
+ event.currentTarget.value = String(props.limit);
48
+ props.onsize?.(size);
49
+ }
50
+ </script>
51
+
52
+ {#if fault !== null}
53
+ <div role="alert">{words.invalidInput}</div>
54
+ {:else}
55
+ <nav class="sdt-pager" aria-label={props.label}>
56
+ {#if sizes.length > 0}
57
+ <label>
58
+ {words.sizeLabel}
59
+ <select class="sdt-field" value={props.limit} onchange={choose}>
60
+ {#each sizes as size (size)}
61
+ <option value={size}>{words.sizeOption(size)}</option>
62
+ {/each}
63
+ </select>
64
+ </label>
65
+ {/if}
66
+ <span>{info}</span>
67
+ <button
68
+ class="sdt-button"
69
+ type="button"
70
+ aria-label={words.firstPage}
71
+ aria-disabled={!state.canPrevious}
72
+ onclick={(event) => step(event, state.canPrevious, 0)}
73
+ >
74
+ <span aria-hidden="true">«</span>
75
+ </button>
76
+ <button
77
+ class="sdt-button"
78
+ type="button"
79
+ aria-label={words.previousPage}
80
+ aria-disabled={!state.canPrevious}
81
+ onclick={(event) => step(event, state.canPrevious, state.previous)}
82
+ >
83
+ <span aria-hidden="true">‹</span>
84
+ </button>
85
+ {#each items as item (item)}
86
+ {#if typeof item === "number"}
87
+ <!-- The current page emits only when `offset` is off its own grid offset (PAGE-12, PAGE-27) -->
88
+ <button
89
+ class="sdt-button"
90
+ type="button"
91
+ aria-label={words.pageLabel(item + 1)}
92
+ aria-current={item + 1 === state.current ? "page" : undefined}
93
+ onclick={(event) =>
94
+ step(
95
+ event,
96
+ item * props.limit !== props.offset,
97
+ item * props.limit,
98
+ )}
99
+ >
100
+ {words.pageNumber(item + 1)}
101
+ </button>
102
+ {:else}
103
+ <span aria-hidden="true">…</span>
104
+ {/if}
105
+ {/each}
106
+ <button
107
+ class="sdt-button"
108
+ type="button"
109
+ aria-label={words.nextPage}
110
+ aria-disabled={!state.canNext}
111
+ onclick={(event) => step(event, state.canNext, state.next)}
112
+ >
113
+ <span aria-hidden="true">›</span>
114
+ </button>
115
+ <button
116
+ class="sdt-button"
117
+ type="button"
118
+ aria-label={words.lastPage}
119
+ aria-disabled={!state.canNext}
120
+ onclick={(event) => step(event, state.canNext, state.last)}
121
+ >
122
+ <span aria-hidden="true">»</span>
123
+ </button>
124
+ </nav>
125
+ {/if}
@@ -0,0 +1,5 @@
1
+ import type { PaginationProps } from "./types.js";
2
+ /** The pager. Its props are {@link PaginationProps}. */
3
+ declare const Pagination: import("svelte").Component<PaginationProps, {}, "">;
4
+ type Pagination = ReturnType<typeof Pagination>;
5
+ export default Pagination;
@@ -0,0 +1,5 @@
1
+ type Check<Fault> = readonly [Fault, () => boolean];
2
+ export declare const firstFault: <Fault>(table: readonly Check<Fault>[]) => Fault | null;
3
+ export declare const hasDuplicate: (values: readonly unknown[]) => boolean;
4
+ export declare const isEmpty: (text: unknown) => boolean;
5
+ export {};
package/dist/checks.js ADDED
@@ -0,0 +1,7 @@
1
+ // The fault tables of validate.ts and pager.ts: each lists its rows in the order of its spec table (RND-05, SORT-15,
2
+ // FILT-32, PAGE-16), and the first row whose test holds names the fault.
3
+ // The fault of the first row whose test holds, in the table's order, or null when none does
4
+ export const firstFault = (table) => table.find(([, holds]) => holds())?.[0] ?? null;
5
+ export const hasDuplicate = (values) => new Set(values).size !== values.length;
6
+ // A text that is not a string counts as empty: callers the type does not reach can pass one (RND-05, PAGE-16)
7
+ export const isEmpty = (text) => typeof text !== "string" || text.trim() === "";
@@ -0,0 +1,6 @@
1
+ export interface Answer<Row> {
2
+ readonly rows: readonly Row[];
3
+ readonly total: number;
4
+ readonly unfilteredTotal: number;
5
+ }
6
+ export declare function readAnswer<Row>(body: unknown, sent: number): Answer<Row> | Error;
@@ -0,0 +1,47 @@
1
+ import { isCount } from "../pager.js";
2
+ // A count given as a number or as its decimal text (digits only), read as a number; `undefined` for anything else
3
+ function readCount(value) {
4
+ const count = typeof value === "string" && /^\d+$/.test(value) ? Number(value) : value;
5
+ return isCount(count) ? count : undefined;
6
+ }
7
+ const MISMATCH = "The answer does not match the request";
8
+ // The Error of a refused answer. The message is fixed words, never text from the answer; `code` is the answer's
9
+ // `errorCode` when it is a string, else `null`.
10
+ const failure = (message, code) => Object.assign(new Error(message), {
11
+ code: typeof code === "string" ? code : null,
12
+ });
13
+ const mismatch = (reason, code = null) => failure(`${MISMATCH}: ${reason}.`, code);
14
+ function read(body, sent) {
15
+ if (typeof body !== "object" || body === null)
16
+ return mismatch("it is not an object");
17
+ const { data, draw, error, errorCode, recordsFiltered, recordsTotal } = body;
18
+ if (error)
19
+ return failure("The answer reports an error.", errorCode);
20
+ if (!Array.isArray(data))
21
+ return mismatch("data is not a list", errorCode);
22
+ return counted(data, { draw, recordsFiltered, recordsTotal }, sent, errorCode);
23
+ }
24
+ // The answer, or the mismatch when a count is not a count or a `draw` that is given is not the one `sent`
25
+ function counted(rows, counts, sent, code) {
26
+ const { draw, recordsFiltered, recordsTotal } = counts;
27
+ const total = readCount(recordsFiltered);
28
+ if (total === undefined)
29
+ return mismatch("recordsFiltered is not a count", code);
30
+ const unfilteredTotal = readCount(recordsTotal);
31
+ if (unfilteredTotal === undefined)
32
+ return mismatch("recordsTotal is not a count", code);
33
+ if (draw !== undefined && readCount(draw) !== sent)
34
+ return mismatch("draw is not the one sent", code);
35
+ return { rows, total, unfilteredTotal };
36
+ }
37
+ // An answer body read as given: its `data` is the rows, the list itself, each count is read by `readCount`, and a
38
+ // `draw` that is given must read to `sent`, the draw of the request answered. An `Error` when the answer's `error` is
39
+ // truthy, when a check fails, naming the first one, or when a property of the body throws when read.
40
+ export function readAnswer(body, sent) {
41
+ try {
42
+ return read(body, sent);
43
+ }
44
+ catch {
45
+ return mismatch("it cannot be read");
46
+ }
47
+ }
@@ -0,0 +1,16 @@
1
+ import type { Connection, ConnectionOptions } from "./types.js";
2
+ /**
3
+ * Connects `DataTable` and `Pagination` to a server that speaks the DataTables server-side protocol.
4
+ *
5
+ * Call it in a component's script: it registers an `onMount`, which must run while that component initialises, and
6
+ * Svelte does not run it on the server. It sends one request on mount and one more for each `pager.onpage`,
7
+ * `pager.onsize`, `table.onsort`, `table.onfilter`, `table.onclearfilter`, `table.onclearfilters`, `table.onsearch`,
8
+ * `table.onreset`, `table.onretry` and `reload()` (none when a sort or a filter is refused), and maps each answer; a
9
+ * later request, `table.oncancel` and unmounting abort the one still running. It reads `options` when it builds each
10
+ * request, except the query: it is read once, at creation, and then held by the helper.
11
+ *
12
+ * Read `pager` from the returned object, never destructured from it: it is a getter, so a copy would hold the value it
13
+ * had when it was copied. `table` is a plain object, so `const { table } = connection` is fine; read `table.rows`,
14
+ * `table.status`, `table.busy`, `table.sort`, `table.filters` and `table.search` from it, not destructured.
15
+ */
16
+ export declare function createConnection<Row = unknown>(options: ConnectionOptions): Connection<Row>;