@cahyo-dimas/freeday 3.23.0 → 3.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 CHANGED
@@ -9,6 +9,64 @@ benar. Perubahan seperti itu ditulis di bawah `### Changed: BREAKING (types)`
9
9
  lama → tipe baru, dan cara menyempitkannya — bukan di bawah `### Added`, betapapun aditifnya dari
10
10
  sisi kit.
11
11
 
12
+ ## [3.24.0] - 2026-11-27
13
+
14
+ **Satu keadaan, satu pintu.** Audit state machine implisit di kit (dan di app ronda yang memakainya)
15
+ menemukan keadaan yang disimpan sebagai beberapa variabel terpisah, yang bisa saling bertentangan.
16
+ Rilis ini menambah `useLoad` untuk app, dan menutup sembilan cacat kit dari kelas yang sama
17
+ (`#123`). Setiap cacat direproduksi di peramban atau bUnit dulu, dan ujinya terbukti merah pada kode
18
+ lama.
19
+
20
+ ### Added
21
+ - **`useLoad`** di Vue dan React (`/vue`, `/react`). Satu muatan data sebagai satu nilai:
22
+ `idle`, `loading` (dengan `previous`), `ready` (dengan `data`), atau `error` (dengan `error` dan
23
+ `previous`), sesuai keadaan yang `docs/screen-states.md` sebut untuk area data. `load()`
24
+ membatalkan permintaan sebelumnya lewat `AbortSignal` dan membuang jawaban yang datang sesudah
25
+ muatan yang lebih baru dimulai. Data lama hanya bisa diambil lewat nama `previous`, jadi menampilkan
26
+ data basi selalu keputusan yang terlihat di template. Tipe `LoadState<T>` ikut diekspor.
27
+
28
+ ### Fixed
29
+ - **`FdyCfl` tidak lagi mencampur baris dua kueri**, di Vue, React dan Blazor. "Load more" di dalam
30
+ jeda debounce membaca kotak pencarian yang sudah berisi ketikan baru, lalu menambahkan halaman 1
31
+ kueri baru di bawah halaman 0 kueri lama. Kini ia meminta halaman berikut untuk kueri baris yang
32
+ tampil. Pencarian baru yang gagal tidak meninggalkan baris kueri lama di bawah teks baru, dan
33
+ "Try again" mengulang permintaan yang gagal beserta kuerinya.
34
+ - **`FdyCfl` Blazor saat dibuka ulang dan ditutup.** Membuka ulang tidak lagi menampilkan baris
35
+ pencarian terakhir sampai halaman baru tiba. Menutup membatalkan permintaan yang sedang berjalan
36
+ dan pencarian yang menunggu debounce. "Try again" mengulang halaman yang gagal, sama seperti Vue
37
+ dan React, alih-alih memuat ulang halaman 0.
38
+ - **`FdyTable` tidak lagi berputar me-render tanpa henti** saat induk menyimpan hasil `onProcess` /
39
+ `Process` ke state-nya. React: tabel mode server tanpa prop `filters` membuat objek filter baru
40
+ setiap render, dan literal `columns`/`page` di induk berbuat sama; terukur 8.625 laporan dalam
41
+ setengah detik. Blazor: render queue meluap sampai stack overflow. Kini laporan hanya dikirim saat
42
+ baris di halaman atau totalnya berubah, di kedua stack. Vue sudah aman dan kini ikut dijaga uji.
43
+ - **`FdyModal` dan `FdyDrawer`: `open` tidak lagi menyimpang dari `<dialog>`**, di Vue, React dan
44
+ Blazor. Chrome menghormati `cancel` yang dicegah hanya sekali per aktivasi pengguna, jadi Escape
45
+ kedua menutup dialog sementara app masih memegang `open=true`, dan tidak bisa membukanya lagi.
46
+ Kini yang `dismissible` melaporkan penutupan itu, dan yang tidak dibuka kembali.
47
+ - **Datepicker: Escape menutup panel dari mana pun di dalamnya**, di ketiga stack. Sebelumnya hanya
48
+ dari grid, jadi fokus di panah bulan membuat Escape tidak berbuat apa-apa. Di jalur mentah panah
49
+ yang dibangun ulang kini mempertahankan fokus, dan panel menutup saat fokus keluar dari field,
50
+ sama dengan Vue dan React (sekaligus membuang setengah rentang yang tertunda).
51
+ - **Stepper: selama penjaga `waitFor` memutuskan, tidak ada navigasi yang lolos.** Klik header
52
+ langkah dulu lolos, dan saat penjaga menjawab, Next bergerak dari posisi yang baru: perpindahan
53
+ yang tidak pernah ditanyakan ke penjaga, sementara yang disetujui hilang.
54
+ - **Upload:** `setProgress` sesudah `done()`/`fail()` mengembalikan baris ke keadaan mengunggah,
55
+ bukan bilah progres di bawah tulisan "Uploaded". Sorotan `is-dragover` hilang saat seretan keluar
56
+ dari zona lewat elemen anak atau dibatalkan dengan Escape.
57
+ - **Form:** tombol `<button type="reset">` milik form kini menghapus pesan galat dan status
58
+ "sudah dikirim", seperti `api.reset()`.
59
+ - **Tabel mentah:** Escape yang menutup panel filter tidak lagi ikut menutup modal di belakangnya.
60
+
61
+ ### Catatan
62
+ - **Belum dikerjakan, dicatat di `NEXT-UP.md`:** pembungkus Blazor `FdyAutocomplete`,
63
+ `FdyDatepicker` dan `FdyDateRange` tidak mendorong `Value`/`From`/`To` atau `Options` yang
64
+ berubah sesudah hidrasi (butuh API `setValue` di enhancer, jadi dirancang terpisah); opsi
65
+ autocomplete mentah yang ditambahkan belakangan; dan carousel (indeks ditimpa saat gulir halus,
66
+ autoplay saat fokus di dalam), yang baru dilacak di kode.
67
+ - `FdyModal`/`FdyDrawer` Blazor diperbaiki di jembatan JS, jadi tidak tercakup bUnit; jalurnya sama
68
+ dengan Vue dan React yang diuji di peramban.
69
+
12
70
  ## [3.23.0] - 2026-11-26
13
71
 
14
72
  **Empat catatan dari app ronda (`CATATAN-FREEDAY.md` §29 sampai §31, dan satu temuan di §26).**
package/COMPONENTS.md CHANGED
@@ -1874,6 +1874,33 @@ replaces.
1874
1874
  rather than rendering zero: a widget that shows 0 for a request that failed reads as "nothing to
1875
1875
  do", the opposite of what happened.
1876
1876
 
1877
+ **Which state to render: `useLoad`** (Vue and React, from the same import path). One data load as
1878
+ one value, so a screen cannot be loading and failed at once, show its empty state beside its error,
1879
+ or show a form filled with defaults after the load meant to fill it failed:
1880
+
1881
+ | `state.status` | Also holds | Render |
1882
+ |---|---|---|
1883
+ | `'idle'` | nothing | nothing yet |
1884
+ | `'loading'` | `previous`: the last good data, or `null` | skeleton or `FdyTable`'s `loading` |
1885
+ | `'error'` | `error`, `previous` | `.fdy-state--danger` with Try again. Never the empty state. |
1886
+ | `'ready'` | `data` | the data, or one of the three empty states when it has none |
1887
+
1888
+ ```js
1889
+ const { state, load } = useLoad((signal) => fetchInvoices(month.value, signal));
1890
+ onMounted(load);
1891
+ watch(month, load);
1892
+ ```
1893
+
1894
+ - `load()` aborts the request before it (the fetcher receives an `AbortSignal`) and discards any
1895
+ answer that arrives after a newer load started, so a quick change of filter never leaves the
1896
+ older result on screen. Unmounting aborts what is in flight.
1897
+ - It returns a promise that settles when that load does and never rejects; the error is in `state`.
1898
+ - Data from an earlier load is reachable only as `previous`, so showing stale rows while reloading,
1899
+ or beside an error, is a decision visible in the template. A form that edits loaded data renders
1900
+ only under `'ready'`.
1901
+ - In React `load` is stable and calls the latest fetcher, so `useEffect(() => { void load(); },
1902
+ [month, load])` is enough.
1903
+
1877
1904
  ## Charts — `data-fdy-chart`
1878
1905
  > **Typed wrapper: `<FdyChart>`**. data props in all three (`type` + `values` / `series`); it repaints on data change, so `FreedayChart.update(el)` is only for the raw path below. It paints through the enhancer: on Vue and React it needs `import '@cahyo-dimas/freeday'` once at app entry, the one typed wrapper that does. Without it the slot content stays and no chart is drawn.
1879
1906
 
package/README.id.md CHANGED
@@ -5,7 +5,7 @@
5
5
  > **Lebih banyak _free day_ buat dev. UI kit-nya sudah siap pakai.**
6
6
 
7
7
  [![Live docs](https://img.shields.io/badge/docs-live-2050d8?style=flat-square)](https://cahyo-dimas.github.io/freeday-ui-kit/)
8
- [![Release](https://img.shields.io/badge/release-v3.23.0-0078d4?style=flat-square)](https://github.com/cahyo-dimas/freeday-ui-kit/tree/v3.23.0)
8
+ [![Release](https://img.shields.io/badge/release-v3.24.0-0078d4?style=flat-square)](https://github.com/cahyo-dimas/freeday-ui-kit/tree/v3.24.0)
9
9
 
10
10
  UI KIT yang token-driven & framework-agnostic. Satu sumber kebenaran untuk warna, tipografi,
11
11
  spasi, dan komponen. Blueprint: `docs/superpowers/specs/2026-07-21-freeday-ui-kit-design.md`.
package/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
  > **More free days for devs. The UI kit is ready to use.**
6
6
 
7
7
  [![Live docs](https://img.shields.io/badge/docs-live-2050d8?style=flat-square)](https://cahyo-dimas.github.io/freeday-ui-kit/)
8
- [![Release](https://img.shields.io/badge/release-v3.23.0-0078d4?style=flat-square)](https://github.com/cahyo-dimas/freeday-ui-kit/tree/v3.23.0)
8
+ [![Release](https://img.shields.io/badge/release-v3.24.0-0078d4?style=flat-square)](https://github.com/cahyo-dimas/freeday-ui-kit/tree/v3.24.0)
9
9
 
10
10
  A token-driven, framework-agnostic UI kit. One source of truth for color, typography,
11
11
  spacing, and components. Blueprint: `docs/superpowers/specs/2026-07-21-freeday-ui-kit-design.md`.
@@ -97,6 +97,13 @@ public partial class FdyCfl<TRow>
97
97
  private string? _error;
98
98
  private int _reqSeq; // out-of-order response guard
99
99
  private int _debounceSeq; // supersedes stale debounced searches
100
+ /* The query the rows on screen came from, which is not always _query: during the debounce the
101
+ box holds a search not yet sent, and "Load more" appends to the ROWS (#123). */
102
+ private string _shownQuery = string.Empty;
103
+ /* The request that last ran, so Try again repeats it: the page that failed, with its query,
104
+ the same as the Vue and React pickers. It used to reload page 0, dropping appended pages. */
105
+ private string _lastQuery = string.Empty;
106
+ private bool _lastReset = true;
100
107
 
101
108
  private string DisplayValue => Value is null ? string.Empty : Display(Value);
102
109
  /* The live value on the group, as every value-bearing kit control mirrors it: the picked keys. */
@@ -121,11 +128,18 @@ public partial class FdyCfl<TRow>
121
128
  if (Disabled || Readonly || _open) return;
122
129
  _open = true;
123
130
  _query = string.Empty;
131
+ /* Nothing from the last opening survives into this one: its rows answered another search,
132
+ and showing them under an empty box until the new page lands reads as this search's
133
+ results, or stays on screen beside the error if that page fails. */
134
+ _rows.Clear();
135
+ _error = null;
136
+ _hasMore = false;
137
+ _page = 0;
124
138
  /* Re-seeded per open, so Cancel really is a cancel: the ticks start as whatever the caller holds. */
125
139
  _picked.Clear();
126
140
  if (Multiple && Values is not null) _picked.AddRange(Values);
127
141
  await JS.InvokeVoidAsync("FreedayBlazor.dialogShow", Root);
128
- await LoadAsync(reset: true);
142
+ await LoadAsync(_query, reset: true);
129
143
  }
130
144
 
131
145
  /// <summary>Close the picker without committing, the same path Esc and the footer button take.</summary>
@@ -133,6 +147,12 @@ public partial class FdyCfl<TRow>
133
147
  {
134
148
  if (!_open) return;
135
149
  _open = false;
150
+ /* A response in flight, or a search still waiting out its debounce, belongs to the dialog
151
+ that just closed. Bumping both counters drops them; without it a search typed just before
152
+ closing was still sent, and its rows landed in the next opening. */
153
+ ++_reqSeq;
154
+ ++_debounceSeq;
155
+ _loading = false;
136
156
  await JS.InvokeVoidAsync("FreedayBlazor.dialogClose", Root);
137
157
  }
138
158
 
@@ -148,27 +168,43 @@ public partial class FdyCfl<TRow>
148
168
  await Task.Delay(SearchDebounceMs);
149
169
  if (seq != _debounceSeq) return; // a newer keystroke superseded this one
150
170
  }
151
- await LoadAsync(reset: true);
171
+ await LoadAsync(_query, reset: true);
152
172
  }
153
173
 
154
- private async Task LoadAsync(bool reset)
174
+ private async Task LoadAsync(string query, bool reset)
155
175
  {
176
+ _lastQuery = query;
177
+ _lastReset = reset;
156
178
  _loading = true;
157
179
  _error = null;
158
180
  StateHasChanged();
159
181
  int seq = ++_reqSeq;
160
182
  try
161
183
  {
162
- CflPage<TRow> result = await LoadPage(_query, reset ? 0 : _page);
184
+ CflPage<TRow> result = await LoadPage(query, reset ? 0 : _page);
163
185
  if (seq != _reqSeq) return; // a newer request superseded this response
164
- if (reset) _rows.Clear();
186
+ if (reset)
187
+ {
188
+ _rows.Clear();
189
+ _shownQuery = query;
190
+ }
165
191
  _rows.AddRange(result.Rows);
166
192
  _hasMore = result.HasMore;
167
193
  _page = reset ? 1 : _page + 1;
168
194
  }
169
195
  catch (Exception ex)
170
196
  {
171
- if (seq == _reqSeq) _error = string.IsNullOrEmpty(ex.Message) ? ErrorText : ex.Message;
197
+ if (seq == _reqSeq)
198
+ {
199
+ /* A failed new search leaves no rows from the old one under the new text. A failed
200
+ next page keeps the rows it was adding to, which still answer their own query. */
201
+ if (reset)
202
+ {
203
+ _rows.Clear();
204
+ _hasMore = false;
205
+ }
206
+ _error = string.IsNullOrEmpty(ex.Message) ? ErrorText : ex.Message;
207
+ }
172
208
  }
173
209
  finally
174
210
  {
@@ -180,9 +216,9 @@ public partial class FdyCfl<TRow>
180
216
  }
181
217
  }
182
218
 
183
- private Task LoadMoreAsync() => _hasMore && !_loading ? LoadAsync(reset: false) : Task.CompletedTask;
219
+ private Task LoadMoreAsync() => _hasMore && !_loading ? LoadAsync(_shownQuery, reset: false) : Task.CompletedTask;
184
220
 
185
- private Task RetryAsync() => LoadAsync(reset: true);
221
+ private Task RetryAsync() => LoadAsync(_lastQuery, _lastReset);
186
222
 
187
223
  /// <summary>Unset the value. Not "choosing nothing": the dialog is not involved, so this neither
188
224
  /// opens nor closes it.</summary>
@@ -159,6 +159,12 @@ public partial class FdyTable<TRow>
159
159
  // Both notifications are therefore queued here and flushed in OnAfterRenderAsync.
160
160
  private int? _pendingClamp;
161
161
  private bool _processDirty;
162
+ /* What was last reported through Process. Every parent render re-sets this component's
163
+ parameters, Recompute runs, and the page comes out as a new list of the same rows; reporting
164
+ that again made a parent that stores the report render the table again, until the render queue
165
+ overflowed the stack. A report goes out when the rows on the page or the total change. */
166
+ private IReadOnlyList<TRow>? _reportedRows;
167
+ private int _reportedTotal = -1;
162
168
 
163
169
  private static readonly IReadOnlyDictionary<string, FdyColumnFilter> EmptyFilters = new Dictionary<string, FdyColumnFilter>();
164
170
 
@@ -240,7 +246,23 @@ public partial class FdyTable<TRow>
240
246
  _displayRows = filteredSorted;
241
247
  }
242
248
 
243
- _processDirty = true;
249
+ if (_reportedRows is null || _reportedTotal != _totalCount || !SameRows(_reportedRows, _displayRows))
250
+ {
251
+ _reportedRows = _displayRows;
252
+ _reportedTotal = _totalCount;
253
+ _processDirty = true;
254
+ }
255
+ }
256
+
257
+ /// <summary>The same rows in the same order: one page, compared element by element.</summary>
258
+ private static bool SameRows(IReadOnlyList<TRow> a, IReadOnlyList<TRow> b)
259
+ {
260
+ if (a.Count != b.Count) return false;
261
+ for (int i = 0; i < a.Count; i++)
262
+ {
263
+ if (!EqualityComparer<TRow>.Default.Equals(a[i], b[i])) return false;
264
+ }
265
+ return true;
244
266
  }
245
267
 
246
268
  private FdyColumnFilter? GetFilter(string key) => EffectiveFilters.TryGetValue(key, out FdyColumnFilter? f) ? f : null;
@@ -144,10 +144,20 @@
144
144
  // itself (not its content) is a backdrop click.
145
145
  if (dismissible && e.target === dialog) dotNetRef.invokeMethodAsync(dismissMethod);
146
146
  };
147
+ /* A close nobody here asked for: Chrome honours a prevented `cancel` once per user activation,
148
+ so a second Escape closes the dialog regardless, while .NET still holds Open=true and cannot
149
+ reopen it. dialogClose marks its own closes; any other one is reported when dismissible, and
150
+ undone when not, because that is what Dismissible=false promises. */
151
+ var onClose = function () {
152
+ if (dialog._fdyClosing) { dialog._fdyClosing = false; return; }
153
+ if (dismissible) dotNetRef.invokeMethodAsync(dismissMethod);
154
+ else if (typeof dialog.showModal === 'function') dialog.showModal();
155
+ };
147
156
  dialog.addEventListener('cancel', onCancel);
148
157
  dialog.addEventListener('click', onClick);
158
+ dialog.addEventListener('close', onClose);
149
159
  var token = ++dialogSeq;
150
- dialogSubs[token] = { el: dialog, cancel: onCancel, click: onClick };
160
+ dialogSubs[token] = { el: dialog, cancel: onCancel, click: onClick, close: onClose };
151
161
  return token;
152
162
  }
153
163
 
@@ -156,7 +166,10 @@
156
166
  }
157
167
 
158
168
  function dialogClose(dialog) {
159
- if (dialog && dialog.open) dialog.close();
169
+ if (dialog && dialog.open) {
170
+ dialog._fdyClosing = true;
171
+ dialog.close();
172
+ }
160
173
  }
161
174
 
162
175
  function dialogDispose(token) {
@@ -164,6 +177,7 @@
164
177
  if (s) {
165
178
  s.el.removeEventListener('cancel', s.cancel);
166
179
  s.el.removeEventListener('click', s.click);
180
+ s.el.removeEventListener('close', s.close);
167
181
  delete dialogSubs[token];
168
182
  }
169
183
  }
@@ -0,0 +1,17 @@
1
+ // Types for the load state (adapters/core/load-state.js), shared by useLoad in Vue and React.
2
+
3
+ /**
4
+ * One data load. `previous` is what an earlier load returned, kept through a reload or a failure so a
5
+ * screen can choose to show it; it is never mixed into `data`, which only a successful load sets.
6
+ */
7
+ export type LoadState<T> =
8
+ | { readonly status: 'idle' }
9
+ | { readonly status: 'loading'; readonly previous: T | null }
10
+ | { readonly status: 'ready'; readonly data: T }
11
+ | { readonly status: 'error'; readonly error: Error; readonly previous: T | null };
12
+
13
+ export declare const IDLE: LoadState<never>;
14
+ export declare function dataOf<T>(state: LoadState<T>): T | null;
15
+ export declare function loadingFrom<T>(state: LoadState<T>): LoadState<T>;
16
+ export declare function readyWith<T>(data: T): LoadState<T>;
17
+ export declare function failedFrom<T>(state: LoadState<T>, error: Error): LoadState<T>;
@@ -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
+ }