firstly 0.5.1 → 0.6.1

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 (40) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/esm/core/FF_Filter.d.ts +2 -2
  3. package/esm/core/FF_Filter.js +2 -2
  4. package/esm/core/FF_Validators.d.ts +2 -0
  5. package/esm/core/FF_Validators.js +8 -10
  6. package/esm/core/containsWords.d.ts +2 -2
  7. package/esm/core/containsWords.js +2 -2
  8. package/esm/core/tailwind.d.ts +3 -4
  9. package/esm/core/tailwind.js +3 -4
  10. package/esm/svelte/DemoForm.svelte +121 -0
  11. package/esm/svelte/DemoForm.svelte.d.ts +42 -0
  12. package/esm/svelte/DemoGrid.svelte +146 -55
  13. package/esm/svelte/DemoGrid.svelte.d.ts +10 -1
  14. package/esm/svelte/DialogOpenTest.svelte +10 -0
  15. package/esm/svelte/DialogOpenTest.svelte.d.ts +8 -0
  16. package/esm/svelte/FF_Config.svelte +13 -0
  17. package/esm/svelte/FF_Config.svelte.d.ts +3 -0
  18. package/esm/svelte/FF_Config.svelte.js +38 -0
  19. package/esm/svelte/FF_DialogManager.svelte +251 -0
  20. package/esm/svelte/FF_DialogManager.svelte.d.ts +13 -0
  21. package/esm/svelte/FF_PromptDefault.svelte +85 -0
  22. package/esm/svelte/FF_PromptDefault.svelte.d.ts +9 -0
  23. package/esm/svelte/FF_ToastHtml.svelte +9 -0
  24. package/esm/svelte/FF_ToastHtml.svelte.d.ts +6 -0
  25. package/esm/svelte/FF_ToastManager.svelte +22 -0
  26. package/esm/svelte/FF_ToastManager.svelte.d.ts +4 -0
  27. package/esm/svelte/dialog.svelte.d.ts +209 -0
  28. package/esm/svelte/dialog.svelte.js +243 -0
  29. package/esm/svelte/ff.svelte.d.ts +357 -0
  30. package/esm/svelte/ff.svelte.js +679 -0
  31. package/esm/svelte/index.d.ts +13 -2
  32. package/esm/svelte/index.js +8 -1
  33. package/esm/svelte/infiniteScroll.d.ts +1 -1
  34. package/esm/svelte/infiniteScroll.js +1 -1
  35. package/esm/svelte/toast.d.ts +59 -0
  36. package/esm/svelte/toast.js +92 -0
  37. package/esm/virtual/StateDemoEnum.js +1 -1
  38. package/package.json +2 -1
  39. package/esm/svelte/FF_Repo.svelte.d.ts +0 -198
  40. package/esm/svelte/FF_Repo.svelte.js +0 -305
@@ -0,0 +1,679 @@
1
+ import { repo as remultRepo, } from 'remult';
2
+ import { dialog } from './dialog.svelte.js';
3
+ /** Classify a thrown read error into an {@link FF_Issue} (best-effort status sniffing). */
4
+ function toIssue(e) {
5
+ const err = e;
6
+ const status = err?.httpStatusCode ?? err?.status;
7
+ const message = e instanceof Error ? e.message : typeof e === 'string' ? e : err?.message;
8
+ const kind = status === 403 ? 'forbidden' : status === 404 ? 'notFound' : 'error';
9
+ return { kind, status, message };
10
+ }
11
+ /**
12
+ * The reactive handle implementation (internal). `ff().one()` returns an Omit'd view of this
13
+ * (`FF_One`); `ff().many()` wraps a list handle + a `.syncs`-linked one in `FF_ManyHandle`
14
+ * (exposed as `FF_Many`). The per-mode aliases below stay internal to this module.
15
+ */
16
+ class FF_RepoHandle {
17
+ #repo;
18
+ #opts;
19
+ #mode;
20
+ #defaultOrderBy;
21
+ #paginator;
22
+ #seq = 0;
23
+ #syncTargets = [];
24
+ #onItemCbs = [];
25
+ #onItemsCbs = [];
26
+ #onIssueCbs = [];
27
+ items = $state([]);
28
+ /** Single-record slot: the loaded row in `one` mode, or a create/edit draft (see `create`). */
29
+ item = $state(undefined);
30
+ loading = $state({
31
+ init: true,
32
+ fetching: false,
33
+ more: false,
34
+ saving: false,
35
+ deleting: false,
36
+ });
37
+ error = $state(undefined);
38
+ hasNextPage = $state(false);
39
+ /** Aggregations for the whole query (paginate mode). `aggregates.$count` is the total row count. */
40
+ aggregates = $state(undefined);
41
+ /** Any read or write currently in flight (init/fetching/more/saving/deleting). */
42
+ get isBusy() {
43
+ const l = this.loading;
44
+ return l.init || l.fetching || l.more || l.saving || l.deleting;
45
+ }
46
+ /** A write (insert/update/delete) in flight. */
47
+ get isWriting() {
48
+ return this.loading.saving || this.loading.deleting;
49
+ }
50
+ constructor(r, opts, mode) {
51
+ this.#repo = r;
52
+ this.#opts = opts;
53
+ this.#mode = mode;
54
+ this.#defaultOrderBy = r.metadata.options.defaultOrderBy;
55
+ $effect(() => {
56
+ const o = this.#resolve();
57
+ if (o.enabled === false) {
58
+ this.loading.init = false;
59
+ return;
60
+ }
61
+ if (mode === 'live') {
62
+ // Pass orderBy so liveQuery re-sorts incrementally-added rows too;
63
+ // without it a freshly inserted row is appended and `items[0]` (the latest) goes stale.
64
+ const unsub = this.#repo
65
+ .liveQuery({ where: o.where, orderBy: o.orderBy, limit: o.limit, include: o.include })
66
+ .subscribe({
67
+ next: (info) => {
68
+ this.items = info.items;
69
+ this.loading.init = false;
70
+ this.#fireItems();
71
+ },
72
+ error: (e) => {
73
+ this.error = e instanceof Error ? e.message : String(e);
74
+ this.loading.init = false;
75
+ this.#fireIssue(toIssue(e));
76
+ },
77
+ });
78
+ return () => unsub();
79
+ }
80
+ // load | paginate | one: (re)fetch; a newer opts() invalidates older responses.
81
+ void this.#load(o, ++this.#seq);
82
+ });
83
+ }
84
+ #resolve() {
85
+ const o = this.#opts();
86
+ return { ...o, orderBy: o.orderBy ?? this.#defaultOrderBy };
87
+ }
88
+ async #load(o, seq, keepCount) {
89
+ this.loading.fetching = true;
90
+ this.error = undefined;
91
+ try {
92
+ if (this.#mode === 'paginate') {
93
+ // One request returns the page AND the aggregates ($count always, plus any
94
+ // requested): on the client REST proxy remult fetches both together. It sets
95
+ // `hasNextPage` from whether a full page came back (no count probe); `more()`
96
+ // then fetches the next page via a keyset cursor (orderBy + PK).
97
+ const p = await this.#repo
98
+ .query({
99
+ where: o.where,
100
+ orderBy: o.orderBy,
101
+ pageSize: keepCount ?? o.pageSize ?? 25,
102
+ include: o.include,
103
+ aggregate: { ...o.aggregate },
104
+ })
105
+ .paginator();
106
+ if (seq !== this.#seq)
107
+ return;
108
+ this.#paginator = p;
109
+ this.items = p.items;
110
+ this.hasNextPage = p.hasNextPage;
111
+ // `aggregates` is only on the paginator type when the aggregate is non-empty,
112
+ // but remult returns `$count` for the empty case too - so read it through a cast.
113
+ this.aggregates = p.aggregates;
114
+ this.#fireItems();
115
+ }
116
+ else if (this.#mode === 'one') {
117
+ // `id` -> findId (by primary key, no sort/limit); otherwise `where` -> findFirst.
118
+ const found = o.id != null
119
+ ? await this.#repo.findId(o.id, { include: o.include })
120
+ : await this.#repo.findFirst(o.where, { orderBy: o.orderBy, include: o.include });
121
+ if (seq !== this.#seq)
122
+ return;
123
+ this.item = found ?? undefined;
124
+ this.items = found ? [found] : [];
125
+ // Found -> onItem; not found -> onIssue (a row was deleted, the id is wrong, or a
126
+ // prefilter hid it) so callers can redirect/404 instead of sitting on an empty record.
127
+ if (found)
128
+ this.#fireItem(found);
129
+ else
130
+ this.#fireIssue({ kind: 'notFound', status: 404 });
131
+ }
132
+ else {
133
+ const items = await this.#repo.find({
134
+ where: o.where,
135
+ orderBy: o.orderBy,
136
+ limit: o.limit,
137
+ include: o.include,
138
+ });
139
+ if (seq !== this.#seq)
140
+ return;
141
+ this.items = items;
142
+ this.#fireItems();
143
+ }
144
+ }
145
+ catch (e) {
146
+ if (seq === this.#seq) {
147
+ this.error = e instanceof Error ? e.message : String(e);
148
+ this.#fireIssue(toIssue(e));
149
+ }
150
+ }
151
+ finally {
152
+ if (seq === this.#seq) {
153
+ this.loading.init = false;
154
+ this.loading.fetching = false;
155
+ }
156
+ }
157
+ }
158
+ /** Re-run the current query (load/paginate/one), back to the first page. */
159
+ async refresh() {
160
+ if (this.#mode === 'live')
161
+ throw new Error('FF_Repo: refresh() is not available in live mode');
162
+ await this.#load(this.#resolve(), ++this.#seq);
163
+ }
164
+ /** Load and append the next page (paginate mode). */
165
+ async more() {
166
+ if (this.#mode !== 'paginate')
167
+ throw new Error('FF_Repo: more() requires paginate mode');
168
+ if (!this.#paginator || this.loading.more || !this.hasNextPage)
169
+ return;
170
+ const seq = this.#seq;
171
+ this.loading.more = true;
172
+ try {
173
+ const next = await this.#paginator.nextPage();
174
+ // A newer query (where/orderBy/pageSize changed) ran while this page was in flight:
175
+ // drop the stale page rather than appending it to the new result.
176
+ if (seq !== this.#seq)
177
+ return;
178
+ this.#paginator = next;
179
+ this.items = [...this.items, ...next.items];
180
+ this.hasNextPage = next.hasNextPage;
181
+ }
182
+ finally {
183
+ this.loading.more = false;
184
+ }
185
+ }
186
+ /**
187
+ * Run `fn` once - the first time a row exists (`items[0]`).
188
+ *
189
+ * The point: seed editable UI state from the latest row WITHOUT a live query
190
+ * clobbering in-progress edits. It fires a single time, on the first non-empty
191
+ * result, and never again - later ticks (an edit, a delete, a re-sort) are
192
+ * ignored. Empty snapshots are skipped (a liveQuery often emits one before the
193
+ * data lands; there is nothing to seed from an empty result).
194
+ *
195
+ * For pure derived state prefer `$derived`; reach for `onFirst` only when the
196
+ * seed must become independently editable (a draft the user then mutates).
197
+ *
198
+ * ```svelte
199
+ * const list = ff(Plan).many(() => ({ where: { ownerDid } }), 'listen')
200
+ * let draft = $state({ title: '' })
201
+ * list.onFirst((latest) => (draft.title = latest.title)) // seed once, then edit freely
202
+ * ```
203
+ */
204
+ onFirst(fn) {
205
+ let done = false;
206
+ $effect(() => {
207
+ if (done)
208
+ return;
209
+ const latest = this.items[0];
210
+ if (latest == null)
211
+ return;
212
+ fn(latest);
213
+ done = true;
214
+ });
215
+ return this;
216
+ }
217
+ #fireItem(item) {
218
+ for (const fn of this.#onItemCbs)
219
+ fn(item);
220
+ }
221
+ #fireItems() {
222
+ for (const fn of this.#onItemsCbs)
223
+ fn(this.items);
224
+ }
225
+ #fireIssue(issue) {
226
+ for (const fn of this.#onIssueCbs)
227
+ fn(issue);
228
+ }
229
+ /**
230
+ * `one` mode only. Run `fn` with the record after EVERY fetch that finds one (a
231
+ * not-found goes to `onIssue` instead). Mirrors the handle's `.item`. Unlike
232
+ * `onFirst` (once, on the first row), this fires on each load / refresh. Chainable.
233
+ */
234
+ onItem(fn) {
235
+ this.#onItemCbs.push(fn);
236
+ return this;
237
+ }
238
+ /**
239
+ * List modes only. Run `fn` with the fresh `items` after EVERY read (mimics the old
240
+ * `storeList` `onNewData`). Fires on each load / refresh / paginate page / live tick.
241
+ * Mirrors the handle's `.items`. Chainable.
242
+ */
243
+ onItems(fn) {
244
+ this.#onItemsCbs.push(fn);
245
+ return this;
246
+ }
247
+ /**
248
+ * Run `fn` when a read doesn't yield the expected data: a `one` query with no row
249
+ * (`notFound`), a rejected read (`forbidden`, 403), or any other failure (`error`).
250
+ * The arg is an `FF_Issue` ({@link FF_Issue}) - switch on `issue.kind` to react,
251
+ * e.g. redirect on not-found. Chainable.
252
+ *
253
+ * ```svelte
254
+ * const site = ff(Site).one(() => ({ where: { id } }))
255
+ * .onIssue((i) => { if (i.kind === 'notFound') goto('/app/sites') })
256
+ * ```
257
+ */
258
+ onIssue(fn) {
259
+ this.#onIssueCbs.push(fn);
260
+ return this;
261
+ }
262
+ /** Create a new unsaved entity into the `item` slot (for an edit form). */
263
+ create(...args) {
264
+ this.item = this.#repo.create(...args);
265
+ return this.item;
266
+ }
267
+ // Mutations: run `op`, then the post-write sync on SUCCESS only (a failed write
268
+ // leaves the result untouched). On failure we fill `error` AND re-throw - the
269
+ // caller still gets the rejection (not silenced); `error` is for a reactive
270
+ // UI that wants it. `finally` only flips `loading` (no `await`, which would
271
+ // mask the original error).
272
+ async #write(flag, op, after) {
273
+ this.loading[flag] = true;
274
+ for (const t of this.#syncTargets)
275
+ t.loading[flag] = true;
276
+ this.error = undefined;
277
+ try {
278
+ const res = await op();
279
+ await after();
280
+ return res;
281
+ }
282
+ catch (e) {
283
+ this.error = e instanceof Error ? e.message : String(e);
284
+ throw e;
285
+ }
286
+ finally {
287
+ this.loading[flag] = false;
288
+ for (const t of this.#syncTargets)
289
+ t.loading[flag] = false;
290
+ }
291
+ }
292
+ /** Save the current `item` (from `one` / `create()`). To save a specific row, use remult `repo(E).save(row)`. */
293
+ async save() {
294
+ const saved = await this.#write('saving', () => this.#repo.save(this.#requireItem()), () => this.#resync());
295
+ this.item = saved;
296
+ for (const t of this.#syncTargets)
297
+ t.reconcile(saved);
298
+ return saved;
299
+ }
300
+ /** Delete the current `item`. To delete a specific row/id, use remult `repo(E).delete(idOrRow)`. */
301
+ async delete() {
302
+ const target = this.#requireItem();
303
+ const res = await this.#write('deleting', () => this.#repo.delete(target), () => {
304
+ // live: liveQuery removes it. one: re-fetch (likely empty now).
305
+ // load/paginate: drop it locally (no refetch).
306
+ if (this.#mode === 'live')
307
+ return;
308
+ if (this.#mode === 'one')
309
+ return this.#resync();
310
+ this.#removeLocal(target);
311
+ });
312
+ for (const t of this.#syncTargets)
313
+ t.removeItem(target);
314
+ return res;
315
+ }
316
+ /**
317
+ * Save a specific `row` through this list handle's loading/error machinery (mirrors the
318
+ * argless `save()`), then reconcile the list (sorted upsert / paginate refresh). Used by
319
+ * `FF_ManyHandle.save(target)` so a targeted write flips `loading.saving` and fills `error`.
320
+ */
321
+ async saveRow(row) {
322
+ let saved;
323
+ await this.#write('saving', async () => (saved = await this.#repo.save(row)), () => this.reconcile(saved));
324
+ return saved;
325
+ }
326
+ /**
327
+ * Delete a specific `row` through this list handle's loading/error machinery (mirrors the
328
+ * argless `delete()`), then drop it from the list. Used by `FF_ManyHandle.remove(target)`.
329
+ */
330
+ async deleteRow(row) {
331
+ await this.#write('deleting', () => this.#repo.delete(row), () => this.removeItem(row));
332
+ }
333
+ /**
334
+ * Link this record handle (`one`) to one or more list handles. On `save()` /
335
+ * `delete()` the lists are reconciled (sorted upsert / remove) and share the
336
+ * write-loading flag, so the list area shows "busy" during the write too. A live
337
+ * list reconcile is a no-op (its liveQuery already syncs). Returns `this`.
338
+ */
339
+ syncs(...targets) {
340
+ this.#syncTargets = targets;
341
+ return this;
342
+ }
343
+ /** The current `item` (or throw) - backs the argless `save()`/`delete()`. */
344
+ #requireItem() {
345
+ if (this.item === undefined)
346
+ throw new Error('FF_Repo: no `item` to save/delete - load one first (`one` mode or `create()`), or write a specific row through remult `repo(E)`.');
347
+ return this.item;
348
+ }
349
+ // Client-side list reconcilers (no server I/O) - reflect a change you made
350
+ // elsewhere (e.g. via remult `repo(E)`) in the reactive `items`. `load`/`paginate` only;
351
+ // `listen` reconciles itself via the liveQuery. `add`/`remove` also adjust
352
+ // `aggregates.$count` (not the other aggregates). For authoritative state, call
353
+ // `refresh()` (it re-pulls and, for paginate, resets to the first page).
354
+ /** Insert into `items` at `top` (default) / `bottom` / an index (`-1` = last). +1 to `$count`. */
355
+ addItem(item, options) {
356
+ const at = options?.at ?? 'top';
357
+ const list = this.items;
358
+ const idx = at === 'top'
359
+ ? 0
360
+ : at === 'bottom'
361
+ ? list.length
362
+ : at < 0
363
+ ? Math.max(0, list.length + at + 1)
364
+ : Math.min(at, list.length);
365
+ this.items = [...list.slice(0, idx), item, ...list.slice(idx)];
366
+ if (this.aggregates)
367
+ this.aggregates.$count += 1;
368
+ }
369
+ /** Replace the row whose id matches `item`'s id (no `$count` change). */
370
+ updateItem(item) {
371
+ const id = this.#repo.metadata.idMetadata.getId(item);
372
+ this.items = this.items.map((x) => (this.#repo.metadata.idMetadata.getId(x) === id ? item : x));
373
+ }
374
+ /** Drop the matching row (pass an id or the item). -1 to `$count`. */
375
+ removeItem(idOrItem) {
376
+ if (this.#mode === 'live')
377
+ return;
378
+ this.#removeLocal(idOrItem);
379
+ }
380
+ /**
381
+ * Insert-or-update `item` at its SORTED position (load mode), recomputing the index
382
+ * from this handle's `orderBy` plus the entity id as tiebreak. Paginate re-fetches
383
+ * (a row may belong to an unloaded page); live is a no-op (the liveQuery syncs).
384
+ */
385
+ reconcile(item) {
386
+ if (this.#mode === 'live')
387
+ return;
388
+ if (this.#mode === 'paginate') {
389
+ void this.refresh();
390
+ return;
391
+ }
392
+ const id = this.#repo.metadata.idMetadata.getId(item);
393
+ const without = this.items.filter((x) => this.#repo.metadata.idMetadata.getId(x) !== id);
394
+ const cmp = this.#comparator(this.#resolve().orderBy);
395
+ let idx = without.findIndex((x) => cmp(item, x) < 0);
396
+ if (idx < 0)
397
+ idx = without.length;
398
+ this.items = [...without.slice(0, idx), item, ...without.slice(idx)];
399
+ }
400
+ // A comparator from an EntityOrderBy, with the entity id appended as a stable
401
+ // tiebreak (remult does the same so keyset paging is deterministic).
402
+ #comparator(orderBy) {
403
+ const entries = Object.entries(orderBy ?? {});
404
+ const idOf = (e) => this.#repo.metadata.idMetadata.getId(e);
405
+ return (a, b) => {
406
+ for (const [field, dir] of entries) {
407
+ const av = a[field];
408
+ const bv = b[field];
409
+ if (av < bv)
410
+ return dir === 'desc' ? 1 : -1;
411
+ if (av > bv)
412
+ return dir === 'desc' ? -1 : 1;
413
+ }
414
+ const ai = idOf(a);
415
+ const bi = idOf(b);
416
+ return ai < bi ? -1 : ai > bi ? 1 : 0;
417
+ };
418
+ }
419
+ #removeLocal(idOrItem) {
420
+ const id = idOrItem != null && typeof idOrItem === 'object'
421
+ ? this.#repo.metadata.idMetadata.getId(idOrItem)
422
+ : idOrItem;
423
+ this.items = this.items.filter((i) => this.#repo.metadata.idMetadata.getId(i) !== id);
424
+ if (this.aggregates)
425
+ this.aggregates.$count = Math.max(0, this.aggregates.$count - 1);
426
+ }
427
+ /** After insert/update (or a `one` delete) in a non-live mode, re-fetch keeping the current count. */
428
+ async #resync() {
429
+ if (this.#mode === 'live')
430
+ return;
431
+ const keepCount = this.#mode === 'paginate' ? this.items.length || undefined : undefined;
432
+ await this.#load(this.#resolve(), ++this.#seq, keepCount);
433
+ }
434
+ /**
435
+ * The entity's remult metadata - the single escape hatch for everything not on
436
+ * this handle: permissions (`apiInsertAllowed()`, `apiUpdateAllowed(item)`,
437
+ * `apiDeleteAllowed(item)`, `apiReadAllowed`), `fields`, `idMetadata`, `options`,
438
+ * `key`. Reflects the current `remult.user`.
439
+ */
440
+ get meta() {
441
+ return this.#repo.metadata;
442
+ }
443
+ /** Escape hatch to the underlying repo (count, findId, upsert, projections, ...). */
444
+ get repo() {
445
+ return this.#repo;
446
+ }
447
+ }
448
+ /**
449
+ * Style 1 - unified composite. One handle owning a list (load/listen/paginate) AND
450
+ * the current editing `draft`, pre-wired: the draft handle `.syncs(list)`, so saving
451
+ * or deleting reconciles the list (sorted upsert / remove) and loading/error are
452
+ * merged across both. Proves the styles share internals: this is just a list handle
453
+ * plus a `.syncs()`-linked `one` handle.
454
+ *
455
+ * const t = ff(Task).many(() => ({ where }), 'load')
456
+ * t.edit(row) / t.create() / t.save() / t.remove(row) / t.cancel()
457
+ * markup reads t.items, t.draft, t.loading, t.isBusy, t.error
458
+ */
459
+ class FF_ManyHandle {
460
+ #repo;
461
+ #idKey;
462
+ #list;
463
+ #editor;
464
+ #editingId = $state(null);
465
+ constructor(r, opts, strategy) {
466
+ this.#repo = r;
467
+ this.#idKey = r.metadata.idMetadata.field.key;
468
+ this.#list = new FF_RepoHandle(r, opts, strategy === 'listen' ? 'live' : strategy);
469
+ this.#editor = new FF_RepoHandle(r, (() => ({
470
+ where: { [this.#idKey]: this.#editingId ?? '' },
471
+ enabled: this.#editingId !== null,
472
+ })), 'one');
473
+ this.#editor.syncs(this.#list);
474
+ }
475
+ get items() {
476
+ return this.#list.items;
477
+ }
478
+ get draft() {
479
+ return this.#editor.item;
480
+ }
481
+ set draft(v) {
482
+ this.#editor.item = v;
483
+ }
484
+ get error() {
485
+ return this.#editor.error ?? this.#list.error;
486
+ }
487
+ get hasNextPage() {
488
+ return this.#list.hasNextPage;
489
+ }
490
+ get aggregates() {
491
+ return this.#list.aggregates;
492
+ }
493
+ /** Merged loading: list reads + draft writes. */
494
+ get loading() {
495
+ const l = this.#list.loading;
496
+ const e = this.#editor.loading;
497
+ return {
498
+ init: l.init,
499
+ fetching: l.fetching || e.fetching,
500
+ more: l.more,
501
+ // Targeted writes (`save(row)`/`remove(row)`) flip the list flags; argless draft
502
+ // writes flip the editor flags (and propagate to the list via `.syncs`). Merge both.
503
+ saving: e.saving || l.saving,
504
+ deleting: e.deleting || l.deleting,
505
+ };
506
+ }
507
+ get isBusy() {
508
+ const l = this.loading;
509
+ return l.init || l.fetching || l.more || l.saving || l.deleting;
510
+ }
511
+ get isWriting() {
512
+ return this.loading.saving || this.loading.deleting;
513
+ }
514
+ /**
515
+ * Load `row` into `draft` for editing. Pass the row itself (works with any PK,
516
+ * single or composite - the id is read off it).
517
+ *
518
+ * Default (no fetch): edits an isolated **clone** of `row` - instant, no flicker,
519
+ * and saving updates the original (the clone keeps remult's existing-row state).
520
+ * Cancelling just drops the clone, so the list row is untouched until save.
521
+ *
522
+ * `{ refetch: true }`: optimistic - put `row`'s structure into `draft` **immediately**
523
+ * (so a form renders at full size, no open-then-grow flicker), then re-read the row
524
+ * fresh from the data source and swap it in. The optimistic draft is marked as an
525
+ * **existing** row (rebuilt via json), so it works whether `row` is a tracked entity,
526
+ * a plain spread/`$state` object, or an id-only stub - and saving updates, never inserts.
527
+ * Use it when the list row may be stale or you only hold its id.
528
+ */
529
+ edit(row, opts) {
530
+ if (opts?.refetch) {
531
+ this.#editor.item = this.#repo.fromJson(this.#repo.toJson(this.#repo.create(row)), false);
532
+ this.#editingId = this.#repo.metadata.idMetadata.getId(row);
533
+ }
534
+ else {
535
+ this.#editingId = null; // keep the editor's query disabled; the clone is the draft
536
+ this.#editor.item = this.#repo.getEntityRef(row).clone();
537
+ }
538
+ }
539
+ /** Start a blank `draft` (insert). */
540
+ create(...args) {
541
+ this.#editingId = null;
542
+ return this.#editor.create(...args);
543
+ }
544
+ /** Drop the draft / stop editing, and clear any pending error. */
545
+ cancel() {
546
+ this.#editingId = null;
547
+ this.#editor.item = undefined;
548
+ this.#editor.error = undefined;
549
+ }
550
+ /** Save `target` (any row) or, argless, the current `draft`; reconciles the list. */
551
+ async save(target) {
552
+ if (target !== undefined) {
553
+ // Route through the list handle's loading/error machinery (same as the argless path),
554
+ // then reconcile - so a targeted save flips `loading.saving` and fills/clears `error`.
555
+ return this.#list.saveRow(target);
556
+ }
557
+ const saved = await this.#editor.save();
558
+ this.cancel();
559
+ return saved;
560
+ }
561
+ /** Delete `target` (any row) or, argless, the current `draft`; reconciles the list. */
562
+ async remove(target) {
563
+ if (target !== undefined) {
564
+ // Route through the list handle's loading/error machinery (same as the argless path),
565
+ // then drop the row - so a targeted remove flips `loading.deleting` and fills/clears `error`.
566
+ await this.#list.deleteRow(target);
567
+ return;
568
+ }
569
+ await this.#editor.delete();
570
+ this.cancel();
571
+ }
572
+ /**
573
+ * Confirm, then remove `row`. Resolves `{ ok: true }` when removed, `{ ok: false }` when the
574
+ * user cancels OR the delete fails (a failure also fills `error` and, unless `toast: false`,
575
+ * shows `toast.fromError`). Never re-throws - safe for `onclick={() => list.confirmRemove(row)}`.
576
+ */
577
+ async confirmRemove(row, opts) {
578
+ const c = await dialog.confirm(opts?.message ?? 'Delete this item?', {
579
+ title: opts?.title,
580
+ confirmLabel: opts?.confirmLabel,
581
+ cancelLabel: opts?.cancelLabel,
582
+ danger: opts?.danger ?? true,
583
+ });
584
+ if (!c.ok)
585
+ return { ok: false };
586
+ try {
587
+ await this.remove(row);
588
+ return { ok: true, data: undefined };
589
+ }
590
+ catch (e) {
591
+ if (opts?.toast !== false) {
592
+ // Lazy import keeps `ff` users who never toast from pulling svelte-sonner.
593
+ const { toast } = await import('./toast.js');
594
+ toast.fromError(e);
595
+ }
596
+ return { ok: false };
597
+ }
598
+ }
599
+ /**
600
+ * Edit `row` in a dialog: seed `draft` (a clone, or `{ refetch: true }` to re-read fresh),
601
+ * open `body`, and always `cancel()` on close. The `body` snippet binds `draft` and calls
602
+ * `save()` itself (so a failed/validation save keeps the dialog open via `error`); this method
603
+ * owns only the seed + cleanup. Resolves the dialog's `DialogResult`.
604
+ */
605
+ async editInDialog(row, body, opts) {
606
+ this.edit(row, { refetch: opts?.refetch });
607
+ try {
608
+ return await dialog.show(body, opts);
609
+ }
610
+ finally {
611
+ this.cancel();
612
+ }
613
+ }
614
+ /**
615
+ * Create in a dialog: start a blank `draft` (optionally seeded with `defaults`), open `body`,
616
+ * and always `cancel()` on close. The `body` binds `draft` and calls `save()` itself.
617
+ */
618
+ async createInDialog(body, opts) {
619
+ this.create(opts?.defaults);
620
+ try {
621
+ return await dialog.show(body, opts);
622
+ }
623
+ finally {
624
+ this.cancel();
625
+ }
626
+ }
627
+ more() {
628
+ return this.#list.more();
629
+ }
630
+ refresh() {
631
+ return this.#list.refresh();
632
+ }
633
+ /**
634
+ * Seed editable state once, from the latest row (`items[0]`), the first time one
635
+ * lands - then never again, so a later live tick can't clobber an in-progress edit.
636
+ * Use it when the seed must become independently editable (a separate `$state` /
637
+ * `$bindable` the user then mutates), not the draft; for pure display prefer
638
+ * `$derived(handle.items[0])`. Delegates to the list handle (see `onFirst` there).
639
+ */
640
+ onFirst(fn) {
641
+ this.#list.onFirst(fn);
642
+ return this;
643
+ }
644
+ /** Run `fn` after every successful list read, with the fresh `items`. Delegates to the list handle. Chainable. */
645
+ onItems(fn) {
646
+ this.#list.onItems(fn);
647
+ return this;
648
+ }
649
+ /** Run `fn` when a list read fails (`forbidden`/`error`). Delegates to the list handle. Chainable. */
650
+ onIssue(fn) {
651
+ this.#list.onIssue(fn);
652
+ return this;
653
+ }
654
+ get meta() {
655
+ return this.#repo.metadata;
656
+ }
657
+ get repo() {
658
+ return this.#repo;
659
+ }
660
+ }
661
+ /**
662
+ * `ff(E)` - the firstly reactive layer. `ff(E).many(getter, strategy?)` for a list+edit
663
+ * composite, `ff(E).one(getter)` for a single record. Everything imperative stays on
664
+ * remult's `repo(E)`.
665
+ */
666
+ export function ff(entity) {
667
+ const r = remultRepo(entity);
668
+ return {
669
+ many(o, strategy) {
670
+ return new FF_ManyHandle(r, o, strategy ?? 'paginate');
671
+ },
672
+ one(o) {
673
+ return new FF_RepoHandle(r, o, 'one');
674
+ },
675
+ get meta() {
676
+ return r.metadata;
677
+ },
678
+ };
679
+ }