@cahyo-dimas/freeday 3.23.0 → 3.25.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 (44) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/COMPONENTS.md +39 -0
  3. package/README.id.md +1 -1
  4. package/README.md +1 -1
  5. package/adapters/blazor/FdyAutocomplete.razor +1 -1
  6. package/adapters/blazor/FdyAutocomplete.razor.cs +34 -1
  7. package/adapters/blazor/FdyCascade.razor.cs +15 -1
  8. package/adapters/blazor/FdyCfl.razor.cs +44 -8
  9. package/adapters/blazor/FdyDateRange.razor +1 -1
  10. package/adapters/blazor/FdyDateRange.razor.cs +25 -1
  11. package/adapters/blazor/FdyDatepicker.razor.cs +15 -1
  12. package/adapters/blazor/FdyMonthpicker.razor.cs +15 -1
  13. package/adapters/blazor/FdyTable.razor.cs +23 -1
  14. package/adapters/blazor/FdyTimepicker.razor.cs +15 -1
  15. package/adapters/blazor/freeday-blazor.js +16 -2
  16. package/adapters/core/load-state.d.ts +17 -0
  17. package/adapters/core/load-state.js +37 -0
  18. package/adapters/react/components/FdyCfl.tsx +20 -5
  19. package/adapters/react/components/FdyDatepicker.tsx +10 -1
  20. package/adapters/react/components/FdyDrawer.tsx +8 -0
  21. package/adapters/react/components/FdyModal.tsx +11 -0
  22. package/adapters/react/components/FdyTable.tsx +28 -5
  23. package/adapters/react/index.d.ts +18 -0
  24. package/adapters/react/index.js +1 -0
  25. package/adapters/react/useLoad.js +53 -0
  26. package/adapters/vue/components/FdyCfl.vue +20 -6
  27. package/adapters/vue/components/FdyDatepicker.vue +10 -1
  28. package/adapters/vue/components/FdyDrawer.vue +10 -0
  29. package/adapters/vue/components/FdyModal.vue +12 -0
  30. package/adapters/vue/index.d.ts +18 -0
  31. package/adapters/vue/index.js +1 -0
  32. package/adapters/vue/useLoad.js +47 -0
  33. package/dist/freeday-autocomplete.js +43 -11
  34. package/dist/freeday-cascade.js +24 -8
  35. package/dist/freeday-datepicker.js +61 -1
  36. package/dist/freeday-form.js +3 -0
  37. package/dist/freeday-stepper.js +14 -5
  38. package/dist/freeday-table.js +5 -1
  39. package/dist/freeday-timepicker.js +12 -1
  40. package/dist/freeday-upload.js +17 -7
  41. package/dist/freeday.js +179 -34
  42. package/docs/getting-started.md +1 -1
  43. package/docs/screen-states.md +3 -0
  44. package/package.json +2 -2
@@ -0,0 +1,37 @@
1
+ // Freeday, the state of one data load, framework-agnostic (pure, zero dependencies).
2
+ //
3
+ // The states docs/screen-states.md names for a data area (loading, load error, ideal), as ONE value
4
+ // instead of a loading flag, an error string and the data held side by side. Three separate values
5
+ // let a screen be "loading" and "failed" at once, render its empty state beside its error, or show a
6
+ // form filled with defaults after the load that should have filled it failed. A union cannot.
7
+ //
8
+ // Data from an earlier load survives a reload and a failure only as `previous`, so showing stale data
9
+ // is always a choice a reader can see in the code, never an accident of what was left in a variable.
10
+ //
11
+ // Shared by useLoad in the Vue and React adapters. Each function returns a new state and never
12
+ // changes the one it is given.
13
+
14
+ /** Nothing asked for yet. */
15
+ export const IDLE = Object.freeze({ status: 'idle' });
16
+
17
+ /** The data a state still holds: the loaded data, or what was there before this load started. */
18
+ export function dataOf(state) {
19
+ if (state.status === 'ready') return state.data;
20
+ if (state.status === 'loading' || state.status === 'error') return state.previous;
21
+ return null;
22
+ }
23
+
24
+ /** A load started; whatever was shown before is kept as `previous`. */
25
+ export function loadingFrom(state) {
26
+ return Object.freeze({ status: 'loading', previous: dataOf(state) });
27
+ }
28
+
29
+ /** A load answered. */
30
+ export function readyWith(data) {
31
+ return Object.freeze({ status: 'ready', data });
32
+ }
33
+
34
+ /** A load failed; the data from before it, if any, is kept as `previous`. */
35
+ export function failedFrom(state, error) {
36
+ return Object.freeze({ status: 'error', error, previous: dataOf(state) });
37
+ }
@@ -138,6 +138,11 @@ function FdyCflInner<Row extends Record<string, unknown>>(
138
138
  const cacheRef = useRef<Map<string, CflPage<Row>>>(new Map<string, CflPage<Row>>());
139
139
  const lastPageRef = useRef<number>(0);
140
140
  const lastAppendRef = useRef<boolean>(false);
141
+ const lastQueryRef = useRef<string>('');
142
+ /* The query the rows on screen came from, which is not always the one in the search box: for 250 ms
143
+ after typing, the box holds a search that has not been sent. "Load more" appends to the ROWS, so
144
+ it asks for their query; reading the box appended page 1 of "ab" under page 0 of "a". */
145
+ const shownQueryRef = useRef<string>('');
141
146
  const searchTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
142
147
 
143
148
  const isDisabled: boolean = props.disabled === true;
@@ -174,6 +179,7 @@ function FdyCflInner<Row extends Record<string, unknown>>(
174
179
 
175
180
  // --- Async engine ----------------------------------------------------------------------
176
181
  async function load(targetQuery: string, targetPage: number, append: boolean): Promise<void> {
182
+ lastQueryRef.current = targetQuery;
177
183
  lastPageRef.current = targetPage;
178
184
  lastAppendRef.current = append;
179
185
  const token: number = ++reqIdRef.current;
@@ -187,27 +193,36 @@ function FdyCflInner<Row extends Record<string, unknown>>(
187
193
  if (cached === undefined) cacheRef.current.set(key, res);
188
194
  const copy: Row[] = res.rows.slice(); // never mutate the caller's array
189
195
  setRows((prev: Row[]): Row[] => (append ? prev.concat(copy) : copy));
196
+ if (!append) shownQueryRef.current = targetQuery;
190
197
  setHasMore(res.hasMore);
191
198
  setPage(targetPage);
192
199
  if (!append) setActiveIndex(copy.length > 0 ? 0 : -1);
193
200
  } catch (err: unknown) {
194
201
  if (token !== reqIdRef.current) return;
202
+ /* A new search that failed leaves no rows behind: the old ones answer a different query, and
203
+ under the new text they would read as its results. A failed NEXT page keeps the rows it was
204
+ adding to, which still belong to the query they say they do. */
205
+ if (!append) {
206
+ setRows([]);
207
+ setHasMore(false);
208
+ setActiveIndex(-1);
209
+ }
195
210
  setError(err instanceof Error ? err : new Error(String(err)));
196
211
  } finally {
197
212
  if (token === reqIdRef.current) setLoading(false);
198
213
  }
199
214
  }
200
215
 
201
- // Mirrors Vue's `retry()`: only `lastPage`/`lastAppend` are frozen from the failed request,
202
- // the query is re-read live so a retry after editing the search box (within the debounce
203
- // window) uses what's currently typed, not a stale snapshot.
216
+ /* Repeats the request that failed, query included. Re-reading the box instead paired a page
217
+ number from one query with the text of another; a newer search, if one was typed, follows on
218
+ its own debounce. */
204
219
  function retry(): void {
205
- void load(query, lastPageRef.current, lastAppendRef.current);
220
+ void load(lastQueryRef.current, lastPageRef.current, lastAppendRef.current);
206
221
  }
207
222
 
208
223
  function loadMore(): void {
209
224
  if (loading || !hasMore) return;
210
- void load(query, page + 1, true);
225
+ void load(shownQueryRef.current, page + 1, true);
211
226
  }
212
227
 
213
228
  function onSearchInput(e: React.ChangeEvent<HTMLInputElement>): void {
@@ -589,6 +589,14 @@ export function FdyDatepicker(props: FdyDatepickerProps): JSX.Element {
589
589
  }
590
590
  }
591
591
 
592
+ /* Escape from anywhere in the panel. The grids handle it first and say so with preventDefault; this
593
+ answers for the arrows and the title, where it used to do nothing. */
594
+ function onPanelKeydown(e: React.KeyboardEvent<HTMLDivElement>): void {
595
+ if (e.key !== 'Escape' || e.defaultPrevented) return;
596
+ e.preventDefault();
597
+ closePanel(true);
598
+ }
599
+
592
600
  // Close when focus leaves the control entirely (e.g. Shift+Tab off the trigger).
593
601
  /* A null relatedTarget means focus fell to <body>, which is what happens when the element the
594
602
  user just pressed is REMOVED by the click it triggered (drilling into the month grid replaces
@@ -655,7 +663,8 @@ export function FdyDatepicker(props: FdyDatepickerProps): JSX.Element {
655
663
  </button>
656
664
  ) : null}
657
665
 
658
- <div ref={panelRef} className="fdy-datepicker__panel" role="dialog" aria-modal="false" aria-labelledby={titleId} hidden={!open}>
666
+ <div ref={panelRef} className="fdy-datepicker__panel" role="dialog" aria-modal="false" aria-labelledby={titleId} hidden={!open}
667
+ onKeyDown={onPanelKeydown}>
659
668
  {/* ONE head for both modes on purpose: swapping it destroys the very button the user just
660
669
  pressed, focus falls to <body>, and the panel's own focusout handler closes it. */}
661
670
  <div className="fdy-cal__head">
@@ -49,6 +49,14 @@ export function FdyDrawer(props: FdyDrawerProps): JSX.Element {
49
49
  onClick={(e): void => {
50
50
  if (dismissible && e.target === dialogRef.current) props.onClose();
51
51
  }}
52
+ onClose={(): void => {
53
+ /* Closed while the app still says open: Chrome honours a prevented `cancel` once per user
54
+ activation. Reported when dismissible, shown again when not; see FdyModal.tsx. */
55
+ const el: HTMLDialogElement | null = dialogRef.current;
56
+ if (!props.open || el === null) return;
57
+ if (dismissible) props.onClose();
58
+ else el.showModal();
59
+ }}
52
60
  >
53
61
  <div className="fdy-drawer__header">
54
62
  <h3 id={titleId} className="fdy-drawer__title">{props.title}</h3>
@@ -46,6 +46,17 @@ export function FdyModal(props: FdyModalProps): JSX.Element {
46
46
  e.preventDefault(); // stop the native close; app state stays the single source of truth
47
47
  if (dismissible) props.onClose();
48
48
  }}
49
+ onClose={(): void => {
50
+ /* The dialog closed while the app still says open. Chrome's close watcher honours a prevented
51
+ `cancel` once per user activation, so a second Escape with no click between closes the
52
+ dialog regardless. Left alone, the app held open=true over a closed dialog and could not
53
+ reopen it, since the value never changed. A dismissible modal reports the close; one that
54
+ may not be dismissed is shown again, because that is what dismissible=false promises. */
55
+ const el: HTMLDialogElement | null = dialogRef.current;
56
+ if (!props.open || el === null) return;
57
+ if (dismissible) props.onClose();
58
+ else el.showModal();
59
+ }}
49
60
  onClick={(e): void => {
50
61
  // The ::backdrop is not a separate element, target === the dialog box means a backdrop click.
51
62
  if (dismissible && e.target === dialogRef.current) props.onClose();
@@ -1,5 +1,5 @@
1
1
  import type { CSSProperties, JSX, ReactNode } from 'react';
2
- import { Fragment, useEffect, useMemo, useState } from 'react';
2
+ import { Fragment, useEffect, useMemo, useRef, useState } from 'react';
3
3
  import {
4
4
  cellValue,
5
5
  cellText,
@@ -154,6 +154,19 @@ export interface FdyTableProps<Row extends object> {
154
154
  pageLabel?: string;
155
155
  }
156
156
 
157
+ /** The same rows in the same order: one page, compared element by element. */
158
+ function sameRows<Row>(a: ReadonlyArray<Row>, b: ReadonlyArray<Row>): boolean {
159
+ if (a.length !== b.length) return false;
160
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
161
+ return true;
162
+ }
163
+
164
+ /* One empty filter map for every render. A server-paged table with no `filters` prop counts as
165
+ filter-controlled and used to read `props.filters ?? {}`: a NEW object each render, which broke
166
+ every memo after it, handed onProcess a new array on every commit, and looped any parent that put
167
+ that array in state (measured 8,625 reports in half a second). */
168
+ const NO_FILTERS: FdyFilterMap = Object.freeze({}) as FdyFilterMap;
169
+
157
170
  export function FdyTable<Row extends object>(props: FdyTableProps<Row>): JSX.Element {
158
171
  const serverPaged: boolean = props.page != null;
159
172
  const sortControlled: boolean = serverPaged || props.sort !== undefined;
@@ -175,7 +188,7 @@ export function FdyTable<Row extends object>(props: FdyTableProps<Row>): JSX.Ele
175
188
  }
176
189
 
177
190
  const effectiveSort: FdySortState | null = sortControlled ? (props.sort ?? null) : internalSort;
178
- const effectiveFilters: FdyFilterMap = filtersControlled ? (props.filters ?? {}) : internalFilters;
191
+ const effectiveFilters: FdyFilterMap = filtersControlled ? (props.filters ?? NO_FILTERS) : internalFilters;
179
192
 
180
193
  // Enum options: explicit (server mode) or distinct values across the current rows (client mode).
181
194
  const enumOptionsMap: Record<string, ReadonlyArray<string>> = useMemo(() => {
@@ -229,10 +242,20 @@ export function FdyTable<Row extends object>(props: FdyTableProps<Row>): JSX.Ele
229
242
 
230
243
  // Surface the processed page + total to the parent (both modes), so the same result can drive a
231
244
  // responsive card list / summary / export without re-implementing filter/sort/paginate.
232
- const onProcess = props.onProcess;
245
+ /* Reported when what the parent would SEE changes: the total, or any row on the page. Identity is
246
+ not that. A parent writing `columns={[...]}` or `page={{...}}` inline hands over new objects on
247
+ every render, the memos above recompute, and the page comes out as a new array of the same rows;
248
+ a parent that stored it in state then rendered again, without end. The callback itself is read
249
+ through a ref for the same reason: an inline arrow is a new function every render. */
250
+ const onProcessRef = useRef(props.onProcess);
251
+ onProcessRef.current = props.onProcess;
252
+ const lastReportRef = useRef<{ rows: Row[]; total: number } | null>(null);
233
253
  useEffect((): void => {
234
- onProcess?.({ rows: displayRows, total: totalCount });
235
- }, [onProcess, displayRows, totalCount]);
254
+ const last = lastReportRef.current;
255
+ if (last !== null && last.total === totalCount && sameRows(last.rows, displayRows)) return;
256
+ lastReportRef.current = { rows: displayRows, total: totalCount };
257
+ onProcessRef.current?.({ rows: displayRows, total: totalCount });
258
+ }, [displayRows, totalCount]);
236
259
 
237
260
  function ariaSortOf(col: FdyTableColumn<Row>): 'ascending' | 'descending' | undefined {
238
261
  if (effectiveSort === null || effectiveSort.key !== col.key) return undefined;
@@ -39,6 +39,24 @@ export interface UseThemeReturn {
39
39
  */
40
40
  export declare function useTheme(rootRef?: RefObject<HTMLElement | null>): UseThemeReturn;
41
41
 
42
+ export type { LoadState } from '../core/load-state';
43
+
44
+ export interface UseLoadReturn<T> {
45
+ /** The load, as one value: 'idle', 'loading' (with `previous`), 'ready' (with `data`) or 'error'
46
+ * (with `error` and `previous`). Narrow on `status` before reading the rest. */
47
+ state: import('../core/load-state').LoadState<T>;
48
+ /** Starts a load, aborting the one before it. Settles when this load does; never rejects. */
49
+ load: () => Promise<void>;
50
+ }
51
+
52
+ /**
53
+ * One data load as one state. The fetcher receives an AbortSignal; a newer `load()` aborts the older
54
+ * request and discards its answer, so a quick change of filter can never leave the older result on
55
+ * screen. Unmounting aborts what is in flight. The states are those docs/screen-states.md lists for a
56
+ * data area: render loading, error and ready from `state.status`, and an error never as empty.
57
+ */
58
+ export declare function useLoad<T>(fetcher: (signal: AbortSignal) => Promise<T>): UseLoadReturn<T>;
59
+
42
60
  /** `event.detail` shapes for the bubbling `fdy-*` CustomEvents. */
43
61
  export interface FdyChangeDetail { value: string }
44
62
  export interface FdyAutocompleteSelectDetail { value: string }
@@ -1,5 +1,6 @@
1
1
  export { useFreeday } from './useFreeday.js';
2
2
  export { useTheme } from './useTheme.js';
3
+ export { useLoad } from './useLoad.js';
3
4
  export { usePopover } from './usePopover.ts';
4
5
  export { FdyCombo } from './components/FdyCombo.tsx';
5
6
  export { FdyDatepicker } from './components/FdyDatepicker.tsx';
@@ -0,0 +1,53 @@
1
+ /* Freeday. useLoad for React: one data load as one state, with superseded requests cancelled.
2
+ *
3
+ * const { state, load } = useLoad((signal) => fetchInvoices(month, signal));
4
+ * useEffect(() => { void load(); }, [month, load]);
5
+ *
6
+ * state.status === 'loading' loading (state.previous: what was shown before)
7
+ * state.status === 'error' load error, never rendered as empty
8
+ * state.status === 'ready' state.data
9
+ *
10
+ * `load` is stable across renders and always calls the LATEST fetcher, so the fetcher may be an
11
+ * inline arrow over current props. It aborts the request before it (the fetcher gets an
12
+ * AbortSignal) and ignores any answer that arrives after a newer load started, so a quick change of
13
+ * filter can never leave the older result on screen. It returns a promise that settles when this
14
+ * load does and never rejects: the error is in `state`. Unmounting aborts whatever is in flight. See
15
+ * adapters/core/load-state.js for why the states are one value.
16
+ */
17
+ import { useCallback, useEffect, useRef, useState } from 'react';
18
+ import { IDLE, failedFrom, loadingFrom, readyWith } from '../core/load-state.js';
19
+
20
+ export function useLoad(fetcher) {
21
+ var pair = useState(IDLE);
22
+ var state = pair[0];
23
+ var setState = pair[1];
24
+ var fetcherRef = useRef(fetcher);
25
+ fetcherRef.current = fetcher;
26
+ var tokenRef = useRef(0);
27
+ var controllerRef = useRef(null);
28
+
29
+ var load = useCallback(function () {
30
+ if (controllerRef.current) controllerRef.current.abort();
31
+ var controller = new AbortController();
32
+ controllerRef.current = controller;
33
+ var mine = ++tokenRef.current;
34
+ setState(function (s) { return loadingFrom(s); });
35
+ return Promise.resolve()
36
+ .then(function () { return fetcherRef.current(controller.signal); })
37
+ .then(function (data) {
38
+ if (mine === tokenRef.current) setState(readyWith(data));
39
+ }, function (err) {
40
+ var error = err instanceof Error ? err : new Error(String(err));
41
+ if (mine === tokenRef.current) setState(function (s) { return failedFrom(s, error); });
42
+ });
43
+ }, []);
44
+
45
+ useEffect(function () {
46
+ return function () {
47
+ tokenRef.current += 1;
48
+ if (controllerRef.current) controllerRef.current.abort();
49
+ };
50
+ }, []);
51
+
52
+ return { state: state, load: load };
53
+ }
@@ -161,10 +161,15 @@ let reqToken: number = 0;
161
161
  const cache: Map<string, CflPage> = new Map<string, CflPage>();
162
162
  let lastPage: number = 0;
163
163
  let lastAppend: boolean = false;
164
+ let lastQuery: string = '';
165
+ /* The query the rows on screen came from, which is not always the one in the search box: for 250 ms
166
+ after typing, the box holds a search that has not been sent. "Load more" appends to the ROWS, so it
167
+ asks for their query; reading the box appended page 1 of "ab" under page 0 of "a". */
168
+ let shownQuery: string = '';
164
169
  let searchTimer: ReturnType<typeof setTimeout> | null = null;
165
170
 
166
- async function loadPage(targetPage: number, append: boolean): Promise<void> {
167
- const q: string = query.value;
171
+ async function loadPage(q: string, targetPage: number, append: boolean): Promise<void> {
172
+ lastQuery = q;
168
173
  lastPage = targetPage;
169
174
  lastAppend = append;
170
175
  const token: number = ++reqToken;
@@ -178,11 +183,20 @@ async function loadPage(targetPage: number, append: boolean): Promise<void> {
178
183
  if (cached === undefined) cache.set(key, res);
179
184
  const copy: Row[] = res.rows.slice(); // never mutate the caller's array
180
185
  rows.value = append ? rows.value.concat(copy) : copy;
186
+ if (!append) shownQuery = q;
181
187
  hasMore.value = res.hasMore;
182
188
  page.value = targetPage;
183
189
  if (!append) activeIndex.value = rows.value.length > 0 ? 0 : -1;
184
190
  } catch (err: unknown) {
185
191
  if (token !== reqToken) return;
192
+ /* A new search that failed leaves no rows behind: the old ones answer a different query, and
193
+ under the new text they would read as its results. A failed NEXT page keeps the rows it was
194
+ adding to, which still belong to the query they say they do. */
195
+ if (!append) {
196
+ rows.value = [];
197
+ hasMore.value = false;
198
+ activeIndex.value = -1;
199
+ }
186
200
  error.value = err instanceof Error ? err : new Error(String(err));
187
201
  } finally {
188
202
  if (token === reqToken) loading.value = false;
@@ -190,19 +204,19 @@ async function loadPage(targetPage: number, append: boolean): Promise<void> {
190
204
  }
191
205
 
192
206
  function retry(): void {
193
- void loadPage(lastPage, lastAppend);
207
+ void loadPage(lastQuery, lastPage, lastAppend);
194
208
  }
195
209
 
196
210
  function loadMore(): void {
197
211
  if (loading.value || !hasMore.value) return;
198
- void loadPage(page.value + 1, true);
212
+ void loadPage(shownQuery, page.value + 1, true);
199
213
  }
200
214
 
201
215
  function onSearchInput(e: Event): void {
202
216
  query.value = (e.target as HTMLInputElement).value;
203
217
  if (searchTimer !== null) clearTimeout(searchTimer);
204
218
  searchTimer = setTimeout((): void => {
205
- void loadPage(0, false);
219
+ void loadPage(query.value, 0, false);
206
220
  }, 250);
207
221
  }
208
222
 
@@ -318,7 +332,7 @@ function openDialog(): void {
318
332
  picked.value = props.multiple === true ? [...currentRows.value] : [];
319
333
  dialogEl.value?.showModal();
320
334
  void nextTick((): void => searchEl.value?.focus());
321
- void loadPage(0, false);
335
+ void loadPage(query.value, 0, false);
322
336
  }
323
337
 
324
338
  function closeDialog(): void {
@@ -586,6 +586,14 @@ function onDocPointerDown(e: MouseEvent): void {
586
586
  * the grid, and with it the cell that had focus). That is not focus leaving the control, and
587
587
  * closing on it made the panel vanish mid-navigation. A pointer that really lands outside is
588
588
  * handled by the mousedown listener, which is the reliable path for that case. */
589
+ /* Escape from anywhere in the panel. The grids handle it first and say so with preventDefault; this
590
+ answers for the arrows and the title, where it used to do nothing. */
591
+ function onPanelKeydown(e: KeyboardEvent): void {
592
+ if (e.key !== 'Escape' || e.defaultPrevented) return;
593
+ e.preventDefault();
594
+ closePanel(true);
595
+ }
596
+
589
597
  function onFocusout(e: FocusEvent): void {
590
598
  const next: EventTarget | null = e.relatedTarget;
591
599
  if (next === null) return;
@@ -642,7 +650,8 @@ onBeforeUnmount((): void => {
642
650
  </svg>
643
651
  </button>
644
652
 
645
- <div ref="panelEl" class="fdy-datepicker__panel" role="dialog" aria-modal="false" popover="manual" :aria-labelledby="titleId" :hidden="!open">
653
+ <div ref="panelEl" class="fdy-datepicker__panel" role="dialog" aria-modal="false" popover="manual" :aria-labelledby="titleId" :hidden="!open"
654
+ @keydown="onPanelKeydown">
646
655
  <!-- ONE head for both modes on purpose: swapping it with v-if destroys the very button the user
647
656
  just pressed, focus falls to <body>, and the panel's own focusout handler closes it. The
648
657
  labels and handlers switch; the elements do not. -->
@@ -50,6 +50,15 @@ function onCancel(): void {
50
50
  function onClick(e: MouseEvent): void {
51
51
  if (dismissible.value && e.target === dialogEl.value) emit('close');
52
52
  }
53
+ /* The dialog closed while the app still says open: Chrome honours a prevented `cancel` once per user
54
+ activation, so a second Escape closes it regardless. Reported when the drawer is dismissible, shown
55
+ again when it is not; see FdyModal.vue. */
56
+ function onClose(): void {
57
+ const el: HTMLDialogElement | null = dialogEl.value;
58
+ if (!props.open || el === null) return;
59
+ if (dismissible.value) emit('close');
60
+ else el.showModal();
61
+ }
53
62
  </script>
54
63
 
55
64
  <template>
@@ -59,6 +68,7 @@ function onClick(e: MouseEvent): void {
59
68
  data-fdy-ignore
60
69
  :aria-labelledby="titleId"
61
70
  @cancel.prevent="onCancel"
71
+ @close="onClose"
62
72
  @click="onClick"
63
73
  >
64
74
  <div class="fdy-drawer__header">
@@ -54,6 +54,17 @@ function onCancel(): void {
54
54
  }
55
55
  // The ::backdrop is not a separate element, a click whose target is the dialog box itself (not its
56
56
  // content) is a backdrop click.
57
+ /* The dialog closed while the app still says open. Chrome's close watcher honours a prevented
58
+ `cancel` once per user activation, so a second Escape with no click between closes the dialog
59
+ regardless. Left alone, the app held open=true over a closed dialog and could not reopen it, since
60
+ the value never changed. A dismissible modal reports the close; one that may not be dismissed is
61
+ shown again, because that is what dismissible=false promises. */
62
+ function onClose(): void {
63
+ const el: HTMLDialogElement | null = dialogEl.value;
64
+ if (!props.open || el === null) return;
65
+ if (dismissible.value) emit('close');
66
+ else el.showModal();
67
+ }
57
68
  function onClick(e: MouseEvent): void {
58
69
  if (dismissible.value && e.target === dialogEl.value) emit('close');
59
70
  }
@@ -65,6 +76,7 @@ function onClick(e: MouseEvent): void {
65
76
  :class="modalClass"
66
77
  :aria-labelledby="titleId"
67
78
  @cancel.prevent="onCancel"
79
+ @close="onClose"
68
80
  @click="onClick"
69
81
  >
70
82
  <div class="fdy-modal__header">
@@ -39,6 +39,24 @@ export interface UseThemeReturn {
39
39
  */
40
40
  export declare function useTheme(rootRef?: Ref<HTMLElement | null>): UseThemeReturn;
41
41
 
42
+ export type { LoadState } from '../core/load-state';
43
+
44
+ export interface UseLoadReturn<T> {
45
+ /** The load, as one value: 'idle', 'loading' (with `previous`), 'ready' (with `data`) or 'error'
46
+ * (with `error` and `previous`). Narrow on `status` before reading the rest. */
47
+ state: Readonly<Ref<import('../core/load-state').LoadState<T>>>;
48
+ /** Starts a load, aborting the one before it. Settles when this load does; never rejects. */
49
+ load: () => Promise<void>;
50
+ }
51
+
52
+ /**
53
+ * One data load as one state. The fetcher receives an AbortSignal; a newer `load()` aborts the older
54
+ * request and discards its answer, so a quick change of filter can never leave the older result on
55
+ * screen. Unmounting aborts what is in flight. The states are those docs/screen-states.md lists for a
56
+ * data area: render loading, error and ready from `state.status`, and an error never as empty.
57
+ */
58
+ export declare function useLoad<T>(fetcher: (signal: AbortSignal) => Promise<T>): UseLoadReturn<T>;
59
+
42
60
  /**
43
61
  * Which of the panel's edges lines up with the trigger's. `'start'` (the default) puts the panel's
44
62
  * LEFT edge on the trigger's left edge, right for an input-shaped dropdown; `'end'` puts its RIGHT
@@ -1,5 +1,6 @@
1
1
  export { useFreeday } from './useFreeday.js';
2
2
  export { useTheme } from './useTheme.js';
3
+ export { useLoad } from './useLoad.js';
3
4
  export { usePopover } from './usePopover.ts';
4
5
  export { default as FdyCombo } from './components/FdyCombo.vue';
5
6
  export { default as FdyDatepicker } from './components/FdyDatepicker.vue';
@@ -0,0 +1,47 @@
1
+ /* Freeday. useLoad for Vue 3: one data load as one state, with superseded requests cancelled.
2
+ *
3
+ * const { state, load } = useLoad((signal) => fetchInvoices(month.value, signal));
4
+ * onMounted(load);
5
+ * watch(month, load);
6
+ *
7
+ * <p v-if="state.status === 'loading'" …> loading (state.previous: what was shown before)
8
+ * <div v-else-if="state.status === 'error'" …> load error, never rendered as empty
9
+ * <ul v-else-if="state.status === 'ready'" …> state.data
10
+ *
11
+ * `load()` aborts the request before it (the fetcher gets an AbortSignal) and ignores any answer
12
+ * that arrives after a newer load started, so a quick change of filter can never leave the older
13
+ * result on screen. It returns a promise that settles when this load does and never rejects: the
14
+ * error is in `state`. Unmounting aborts whatever is in flight. The states are the ones
15
+ * docs/screen-states.md lists for a data area; see adapters/core/load-state.js for why they are one
16
+ * value.
17
+ */
18
+ import { onBeforeUnmount, shallowRef } from 'vue';
19
+ import { IDLE, failedFrom, loadingFrom, readyWith } from '../core/load-state.js';
20
+
21
+ export function useLoad(fetcher) {
22
+ var state = shallowRef(IDLE);
23
+ var controller = null;
24
+ var token = 0;
25
+
26
+ function load() {
27
+ if (controller) controller.abort();
28
+ controller = new AbortController();
29
+ var signal = controller.signal;
30
+ var mine = ++token;
31
+ state.value = loadingFrom(state.value);
32
+ return Promise.resolve()
33
+ .then(function () { return fetcher(signal); })
34
+ .then(function (data) {
35
+ if (mine === token) state.value = readyWith(data);
36
+ }, function (err) {
37
+ if (mine === token) state.value = failedFrom(state.value, err instanceof Error ? err : new Error(String(err)));
38
+ });
39
+ }
40
+
41
+ onBeforeUnmount(function () {
42
+ token += 1;
43
+ if (controller) controller.abort();
44
+ });
45
+
46
+ return { state: state, load: load };
47
+ }
@@ -1,7 +1,9 @@
1
1
  /* Freeday, autocomplete enhancer (optional, zero-dependency).
2
2
  * Editable combobox (WAI-ARIA APG): a text input filters a role="listbox" of role="option"
3
3
  * items as you type; select fills the input. Auto-inits [data-fdy-autocomplete]. Options are
4
- * static markup filtered client-side, in an app, fetch/filter server-side and re-render options.
4
+ * markup filtered client-side and read from the list each time they are used, so an app that
5
+ * re-renders them (after a server-side search) is heard without re-initialising. A host that
6
+ * renders once uses FreedayAutocomplete.setOptions(root, labels).
5
7
  *
6
8
  * Markup: <div data-fdy-autocomplete class="fdy-autocomplete">
7
9
  * <input class="fdy-input" role="combobox" aria-expanded="false" aria-autocomplete="list"
@@ -25,19 +27,24 @@
25
27
  root._fdyInvalid = !!input && input.getAttribute('aria-invalid') === 'true';
26
28
  var listbox = root.querySelector('[role="listbox"]');
27
29
  if (!input || !listbox) return;
28
- var options = Array.prototype.slice.call(listbox.querySelectorAll('[role="option"]'));
29
30
  var emptyEl = listbox.querySelector('.fdy-autocomplete__empty');
30
31
  var active = -1;
31
32
 
32
- options.forEach(function (o) {
33
- if (!o.id) { seq += 1; o.id = 'fdy-ac-opt-' + seq; }
34
- o.dataset.label = o.textContent.trim();
35
- });
33
+ /* Read from the list every time, not captured once at init: options rendered later were never
34
+ seen, and the ready flag refused the re-init that would have found them (#123). */
35
+ function allOptions() {
36
+ return Array.prototype.slice.call(listbox.querySelectorAll('[role="option"]')).map(function (o) {
37
+ if (!o.id) { seq += 1; o.id = 'fdy-ac-opt-' + seq; }
38
+ o.dataset.label = o.textContent.trim();
39
+ return o;
40
+ });
41
+ }
42
+ allOptions();
36
43
  listbox.hidden = true;
37
44
  input.setAttribute('aria-expanded', 'false');
38
45
 
39
- function visible() { return options.filter(function (o) { return !o.hidden; }); }
40
- function clearHighlight() { options.forEach(function (o) { o.classList.remove('is-highlighted'); }); }
46
+ function visible() { return allOptions().filter(function (o) { return !o.hidden; }); }
47
+ function clearHighlight() { allOptions().forEach(function (o) { o.classList.remove('is-highlighted'); }); }
41
48
 
42
49
  var _pop = null;
43
50
  function popCtl() { if (_pop === null && window.FreedayPopover) _pop = window.FreedayPopover.attach(listbox, input); return _pop; }
@@ -76,6 +83,7 @@
76
83
  a saved record) is not a query, and filtering by it opened a one-item list that looked broken
77
84
  (#115). Reset on close, so the arrow keys reopen it whole as well. */
78
85
  function showAll() {
86
+ var options = allOptions();
79
87
  options.forEach(function (o) { o.hidden = false; });
80
88
  if (emptyEl) emptyEl.hidden = options.length !== 0;
81
89
  }
@@ -83,7 +91,7 @@
83
91
  function applyFilter() {
84
92
  var q = input.value.trim().toLowerCase();
85
93
  var shown = 0;
86
- options.forEach(function (o) {
94
+ allOptions().forEach(function (o) {
87
95
  var match = !q || o.dataset.label.toLowerCase().indexOf(q) !== -1;
88
96
  o.hidden = !match;
89
97
  if (match) shown++;
@@ -97,7 +105,7 @@
97
105
 
98
106
  function choose(opt) {
99
107
  input.value = opt.dataset.label;
100
- options.forEach(function (o) { o.setAttribute('aria-selected', o === opt ? 'true' : 'false'); });
108
+ allOptions().forEach(function (o) { o.setAttribute('aria-selected', o === opt ? 'true' : 'false'); });
101
109
  close();
102
110
  root.dispatchEvent(new CustomEvent('fdy-autocomplete-select', { bubbles: true, detail: { value: opt.dataset.label, option: opt } }));
103
111
  }
@@ -137,6 +145,27 @@
137
145
  var opt = e.target.closest('[role="option"]');
138
146
  if (opt && !opt.hidden) choose(opt);
139
147
  });
148
+
149
+ /* For a host that renders its markup once (Blazor): the list and the text are pushed in, silently.
150
+ New options are filtered by what is typed if the list is open, and shown whole otherwise. */
151
+ root._fdyAc = {
152
+ setOptions: function (labels) {
153
+ allOptions().forEach(function (o) { o.remove(); });
154
+ (labels || []).forEach(function (label) {
155
+ var li = document.createElement('li');
156
+ li.className = 'fdy-autocomplete__option';
157
+ li.setAttribute('role', 'option');
158
+ li.textContent = label;
159
+ listbox.insertBefore(li, emptyEl);
160
+ });
161
+ allOptions();
162
+ if (listbox.hidden) showAll(); else applyFilter();
163
+ },
164
+ setValue: function (text) {
165
+ input.value = text || '';
166
+ allOptions().forEach(function (o) { o.setAttribute('aria-selected', o.dataset.label === input.value ? 'true' : 'false'); });
167
+ }
168
+ };
140
169
  }
141
170
 
142
171
  function initAll(context) {
@@ -169,5 +198,8 @@
169
198
  if (state.required != null) input.required = !!state.required;
170
199
  }
171
200
 
172
- window.FreedayAutocomplete = { init: initAutocomplete, initAll: initAll, setState: setState };
201
+ function setValue(root, text) { if (root && root._fdyAc) root._fdyAc.setValue(text); }
202
+ function setOptions(root, labels) { if (root && root._fdyAc) root._fdyAc.setOptions(labels); }
203
+
204
+ window.FreedayAutocomplete = { init: initAutocomplete, initAll: initAll, setState: setState, setValue: setValue, setOptions: setOptions };
173
205
  })();