@sincpro/web-framework 3.4.0 → 3.6.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 (46) hide show
  1. package/README.md +2 -0
  2. package/dist/core/command.d.ts +16 -0
  3. package/dist/core/command.js +17 -0
  4. package/dist/core/copy.d.ts +16 -0
  5. package/dist/core/copy.js +26 -0
  6. package/dist/core/history.d.ts +16 -4
  7. package/dist/core/history.js +20 -17
  8. package/dist/core/index.d.ts +4 -3
  9. package/dist/core/index.js +3 -2
  10. package/dist/core/list.d.ts +51 -2
  11. package/dist/core/list.js +58 -1
  12. package/dist/core/present.d.ts +12 -0
  13. package/dist/core/present.js +39 -0
  14. package/dist/react/index.d.ts +2 -0
  15. package/dist/react/index.js +2 -0
  16. package/dist/react/useBatchCommand.d.ts +50 -0
  17. package/dist/react/useBatchCommand.js +124 -0
  18. package/dist/react/useCommand.js +3 -4
  19. package/dist/react/useListing.d.ts +7 -1
  20. package/dist/react/useListing.js +9 -21
  21. package/dist/react/useSelection.d.ts +37 -0
  22. package/dist/react/useSelection.js +40 -0
  23. package/dist/react/useServiceReading.d.ts +8 -0
  24. package/dist/react/useServiceReading.js +16 -1
  25. package/dist/web/index.d.ts +2 -0
  26. package/dist/web/index.js +2 -0
  27. package/dist/web/list/BatchProgress.d.ts +16 -0
  28. package/dist/web/list/BatchProgress.js +40 -0
  29. package/dist/web/list/EntityList.d.ts +12 -6
  30. package/dist/web/list/EntityList.js +37 -22
  31. package/dist/web/list/EntitySearchBar.d.ts +9 -0
  32. package/dist/web/list/EntitySearchBar.js +15 -5
  33. package/dist/web/list/pivot.d.ts +5 -1
  34. package/dist/web/list/pivot.js +28 -11
  35. package/dist/web/list/records.d.ts +100 -0
  36. package/dist/web/list/records.js +219 -0
  37. package/dist/web/list/search.d.ts +0 -17
  38. package/dist/web/list/search.js +33 -5
  39. package/dist/web/record/EntityTags.d.ts +5 -2
  40. package/dist/web/record/EntityTags.js +34 -12
  41. package/dist/web/record/opening.d.ts +6 -2
  42. package/dist/web/workspace/SincproApp.js +13 -2
  43. package/dist/web/workspace/composer.d.ts +1 -1
  44. package/dist/web/workspace/composer.js +23 -25
  45. package/dist/web/workspace/record.d.ts +1 -1
  46. package/package.json +9 -9
@@ -0,0 +1,124 @@
1
+ "use client";
2
+ import { keysOf, listRoute, retryKeys, runBatch, } from "@sincpro/client-framework";
3
+ import { sendRoute } from "../core/command.js";
4
+ import { useFramework } from "./context.js";
5
+ import { useCallback, useEffect, useRef, useState } from "react";
6
+ /** The most records a Command runs on at once from a screen, unless the screen says otherwise. */
7
+ export const BATCH_LIMIT = 200;
8
+ /**
9
+ * One Command of an entity, run once per record of a selection — «Confirmar» on the invoices
10
+ * ticked, «Aprobar» on every payment a filter shows —, one outcome per record.
11
+ *
12
+ * const confirm = useBatchCommand(invoices, "confirm");
13
+ * <Button onPress={() => confirm.run(chosen.selection)}>Confirmar</Button>
14
+ * <BatchProgress batch={confirm} /> // «2 de 3», then «2 hechos · 1 falló: F-7 — …»
15
+ *
16
+ * Context: `for rec in self` from a screen. The keys come from the selection (`keysOf`: in
17
+ * hand, or read once as references — never more than `limit`); each record is the Command sent
18
+ * through the screens' transport — a use case of its own, traced — with an idempotency key of
19
+ * its own, kept while it goes unanswered (`retryKeys`): a retry after a dropped request is the
20
+ * same confirmation, never a second one. A failure is that record's (`runBatch`); the lists
21
+ * follow every write as they do for one.
22
+ *
23
+ * In order, one at a time, by default: a server is not asked for two hundred writes at once
24
+ * because a person ticked them. `concurrency` changes that.
25
+ *
26
+ * Not here: a batch the server runs in one request («everything matching» as a criteria) —
27
+ * sincpro_framework#185.
28
+ */
29
+ export function useBatchCommand(entity, name, options = {}) {
30
+ const route = entity.commands[name];
31
+ if (route === undefined)
32
+ throw new Error(`${entity.key} declares no command "${name}"`);
33
+ const { limit = BATCH_LIMIT, concurrency = 1 } = options;
34
+ const { transport, metas } = useFramework();
35
+ const [running, setRunning] = useState(false);
36
+ const [progress, setProgress] = useState(null);
37
+ const [result, setResult] = useState(null);
38
+ const [error, setError] = useState(null);
39
+ // The answers must not land on a screen that left; the Commands themselves go on.
40
+ const mounted = useRef(true);
41
+ useEffect(() => {
42
+ mounted.current = true;
43
+ return () => void (mounted.current = false);
44
+ }, []);
45
+ /** One gesture per record, kept across a retry: what went unanswered keeps its key. */
46
+ const gestures = useRef(new Map());
47
+ const last = useRef(null);
48
+ const stopping = useRef(null);
49
+ const execute = useCallback(async (keys, body) => {
50
+ const stopper = new AbortController();
51
+ stopping.current = stopper;
52
+ last.current = { body };
53
+ setRunning(true);
54
+ setResult(null);
55
+ setProgress({ settled: 0, total: keys.length });
56
+ const done = await runBatch(keys, async (key) => {
57
+ const gesture = gestures.current.get(key) ?? retryKeys();
58
+ gestures.current.set(key, gesture);
59
+ try {
60
+ const answer = await sendRoute(transport, route, key, body, {
61
+ idempotencyKey: gesture.keyFor({ id: key, body }),
62
+ });
63
+ gesture.settle(null);
64
+ return answer;
65
+ }
66
+ catch (failure) {
67
+ gesture.settle(failure);
68
+ throw failure;
69
+ }
70
+ }, {
71
+ concurrency,
72
+ // Never handed to the send: a Command sent is not taken back, only the next ones.
73
+ signal: stopper.signal,
74
+ onOutcome: (_, now) => {
75
+ if (mounted.current)
76
+ setProgress(now);
77
+ },
78
+ });
79
+ if (mounted.current) {
80
+ setResult(done);
81
+ setRunning(false);
82
+ }
83
+ return done;
84
+ }, [transport, route, concurrency]);
85
+ return {
86
+ run: async (selection, body) => {
87
+ setError(null);
88
+ const meta = metas.get(entity.key);
89
+ let keys;
90
+ try {
91
+ keys = await keysOf(selection, {
92
+ transport,
93
+ route: listRoute(entity.list),
94
+ identity: meta?.get_id || meta?.identity || "id",
95
+ limit,
96
+ });
97
+ }
98
+ catch (failure) {
99
+ if (mounted.current)
100
+ setError(failure);
101
+ return undefined;
102
+ }
103
+ return execute(keys, body ?? {});
104
+ },
105
+ retry: async () => {
106
+ const failed = (result?.outcomes ?? [])
107
+ .filter((one) => one.status !== "done")
108
+ .map((one) => one.item);
109
+ if (failed.length === 0 || last.current === null)
110
+ return undefined;
111
+ return execute(failed, last.current.body);
112
+ },
113
+ stop: () => stopping.current?.abort(),
114
+ running,
115
+ progress,
116
+ result,
117
+ error,
118
+ reset: () => {
119
+ setResult(null);
120
+ setError(null);
121
+ setProgress(null);
122
+ },
123
+ };
124
+ }
@@ -1,5 +1,6 @@
1
1
  "use client";
2
- import { bodyFor, pathFor, retryKeys, } from "@sincpro/client-framework";
2
+ import { retryKeys, } from "@sincpro/client-framework";
3
+ import { sendRoute } from "../core/command.js";
3
4
  import { useFramework } from "./context.js";
4
5
  import { useCallback, useEffect, useRef, useState } from "react";
5
6
  export function useCommand(entity, name) {
@@ -35,10 +36,8 @@ export function useRouteCommand(route, owner) {
35
36
  setBusy(true);
36
37
  setError(null);
37
38
  const idempotencyKey = gesture.keyFor({ id, body });
38
- // A Command whose body names its record (`target`) gets the id there.
39
- const sent = bodyFor(route, id, body);
40
39
  try {
41
- const answer = await transport.send(route.method, pathFor(route, id, sent), sent, undefined, { idempotencyKey });
40
+ const answer = await sendRoute(transport, route, id, body, { idempotencyKey });
42
41
  gesture.settle(null);
43
42
  return answer;
44
43
  }
@@ -1,5 +1,5 @@
1
1
  import { type CommandBodies, type Entity } from "@sincpro/client-framework";
2
- import { type AnyRecord, type Count, type Criteria, type Dropped, type Expression, type Meta, type ReadingStatus, type Sort } from "@sincpro/criteria";
2
+ import { type AnyRecord, type Count, type Criteria, type Dropped, type Expression, type Meta, type Page, type ReadingStatus, type Sort } from "@sincpro/criteria";
3
3
  import { type ListDefinition } from "../core/list.js";
4
4
  /**
5
5
  * N records of an entity, live: what a list draws and the gestures that drive it.
@@ -94,5 +94,11 @@ export type ListingOptions<T> = {
94
94
  pageSize?: number;
95
95
  /** `more` mode: the most rows ever on screen. 500 by default. */
96
96
  maxRows?: number;
97
+ /**
98
+ * The first page already read — on the server, by `readListing` with this same list and
99
+ * these same options. The listing starts `ready` with it, renders its rows there, and in the
100
+ * browser keeps it instead of asking again. Without it, the listing reads on mount (a SPA).
101
+ */
102
+ page?: Page<T>;
97
103
  };
98
104
  export declare function useListing<T extends AnyRecord, C extends CommandBodies = CommandBodies>(given: Entity<T, C> | ListDefinition<T>, own?: ListingOptions<T>): Listing<T, C>;
@@ -1,8 +1,8 @@
1
1
  "use client";
2
- import { listRoute } from "@sincpro/client-framework";
2
+ import {} from "@sincpro/client-framework";
3
3
  import { merge, resource, resumingFrom, searchOver, } from "@sincpro/criteria";
4
4
  import { useReading } from "@sincpro/criteria-react";
5
- import { isList, scopeOf } from "../core/list.js";
5
+ import { isList, listingAsk } from "../core/list.js";
6
6
  import { useFramework } from "./context.js";
7
7
  import { useListScope } from "./scope.js";
8
8
  import { useWrites } from "./useWrites.js";
@@ -17,30 +17,18 @@ export function useListing(given, own = {}) {
17
17
  const entity = (definition?.entity ?? given);
18
18
  // The screen's cut for this entity (a chooser's, `ListScopeProvider`) ANDs like a scope.
19
19
  const cut = useListScope(entity.key);
20
- const scopes = [
21
- ...(definition === undefined ? [] : [scopeOf(definition)]),
22
- ...(cut === undefined ? [] : [{ selection: cut }]),
23
- ];
24
- const options = scopes.length === 0
25
- ? own
26
- : {
27
- ...own,
28
- criteria: [...scopes, ...(own.criteria === undefined ? [] : [own.criteria])].reduce((all, one) => merge(all, one)),
29
- };
30
- const route = listRoute(entity.list, options.params);
20
+ // The first page's question — the list's scope, the cut, the caller's criteria, the page
21
+ // size —: the same `readListing` asks on a server, so a page read there is this one.
22
+ const { route, criteria: asked } = listingAsk(given, own, cut);
31
23
  const source = useMemo(() => resource((criteria, signal) => transport.list(route, criteria, signal)), [transport, route]);
32
24
  // A definition already known draws the columns before the first page arrives; the one the
33
25
  // transport reads from the discovery document comes with it.
34
26
  const [preloaded] = useState(() => metas.get(entity.key));
35
- const paging = options.paging ?? "pages";
36
- const size = options.pageSize ?? options.criteria?.pagination?.limit ?? 50;
37
- const maxRows = options.maxRows ?? 500;
38
- const asked = {
39
- ...options.criteria,
40
- pagination: { ...options.criteria?.pagination, limit: size },
41
- };
27
+ const paging = own.paging ?? "pages";
28
+ const size = asked.pagination?.limit ?? 50;
29
+ const maxRows = own.maxRows ?? 500;
42
30
  const base = asked;
43
- const reading = useReading(source, base);
31
+ const reading = useReading(source, base, own.page === undefined ? {} : { page: own.page });
44
32
  // `pages` mode: the cursor that opens each page walked so far — page 0 opens with none.
45
33
  const [cursors, setCursors] = useState([null]);
46
34
  // The definition is kept across refinements: a refine in flight must not blank the columns.
@@ -0,0 +1,37 @@
1
+ import { type Selection } from "@sincpro/client-framework";
2
+ import type { AnyRecord } from "@sincpro/criteria";
3
+ import type { Listing } from "./useListing.js";
4
+ /**
5
+ * What is chosen in a list, and how a screen changes it — one state, reachable from outside the
6
+ * list: a bulk action reads it, a screen sets it, a chooser answers it.
7
+ */
8
+ export type ListSelection<T extends AnyRecord = AnyRecord> = {
9
+ /** The value (@sincpro/client-framework's `Selection`): these keys, or every record the
10
+ * list's question matches but some. */
11
+ selection: Selection<T>;
12
+ /** How many are chosen; `null` when «all that match» has no exact count. */
13
+ size: number | null;
14
+ isChosen: (key: string) => boolean;
15
+ toggle: (key: string) => void;
16
+ /** Every record the list's question matches, as the server counted them. */
17
+ chooseAllMatching: () => void;
18
+ clear: () => void;
19
+ set: (selection: Selection<T>) => void;
20
+ };
21
+ /**
22
+ * The selection of a list: ticking chooses keys, «Elegir los 187 que coinciden» chooses the
23
+ * list's question — its scope, search and filter — with the total the server counted.
24
+ *
25
+ * const listing = useListing(invoices);
26
+ * const chosen = useSelection(listing);
27
+ * <EntityList listing={listing} selectable selection={chosen} />
28
+ * <ConfirmAll selection={chosen.selection} />
29
+ *
30
+ * Context: `EntityList` kept what was ticked in its own state — the page's keys, reachable by
31
+ * nothing outside it. The value is client-framework's, the same a phone or a script holds; this
32
+ * is only where a screen keeps it.
33
+ *
34
+ * Another question is another set: a selection made under one filter is forgotten when the
35
+ * list's question changes — what was chosen is not among what is on screen anymore.
36
+ */
37
+ export declare function useSelection<T extends AnyRecord>(listing: Listing<T>): ListSelection<T>;
@@ -0,0 +1,40 @@
1
+ "use client";
2
+ import { allMatching, isChosen, NOTHING_CHOSEN, sizeOf, toggled, } from "@sincpro/client-framework";
3
+ import { useCallback, useMemo, useState } from "react";
4
+ /**
5
+ * The selection of a list: ticking chooses keys, «Elegir los 187 que coinciden» chooses the
6
+ * list's question — its scope, search and filter — with the total the server counted.
7
+ *
8
+ * const listing = useListing(invoices);
9
+ * const chosen = useSelection(listing);
10
+ * <EntityList listing={listing} selectable selection={chosen} />
11
+ * <ConfirmAll selection={chosen.selection} />
12
+ *
13
+ * Context: `EntityList` kept what was ticked in its own state — the page's keys, reachable by
14
+ * nothing outside it. The value is client-framework's, the same a phone or a script holds; this
15
+ * is only where a screen keeps it.
16
+ *
17
+ * Another question is another set: a selection made under one filter is forgotten when the
18
+ * list's question changes — what was chosen is not among what is on screen anymore.
19
+ */
20
+ export function useSelection(listing) {
21
+ const asked = listing.question.selection;
22
+ const question = useMemo(() => JSON.stringify(asked ?? null), [asked]);
23
+ const [held, setHeld] = useState({
24
+ question,
25
+ selection: NOTHING_CHOSEN,
26
+ });
27
+ // Held under the question it was made for: under another one, nothing is chosen.
28
+ const selection = held.question === question ? held.selection : NOTHING_CHOSEN;
29
+ const set = useCallback((next) => setHeld({ question, selection: next }), [question]);
30
+ const total = listing.count?.exact === true ? listing.count.value : null;
31
+ return {
32
+ selection,
33
+ size: sizeOf(selection),
34
+ isChosen: (key) => isChosen(selection, key),
35
+ toggle: (key) => set(toggled(selection, key)),
36
+ chooseAllMatching: () => set(allMatching(asked, total)),
37
+ clear: () => set(NOTHING_CHOSEN),
38
+ set,
39
+ };
40
+ }
@@ -28,8 +28,16 @@ type UseCase<A extends unknown[], R> = (...args: A) => R | Promise<R>;
28
28
  * screen until the new one lands. The last question wins: an answer to arguments no longer on
29
29
  * screen is dropped. The use case is the latest the screen gave (a bounded context answers a new
30
30
  * function per `scoped(…)`); its trace and report are the service's, never this hook's.
31
+ *
32
+ * `initial` is the answer to these same arguments already read — on the server that renders the
33
+ * screen, in a route's loader, by calling the same use case. The reading starts `ready` with it,
34
+ * renders it there, and in the browser keeps it on mount instead of reading again; a change of
35
+ * arguments, a followed write or `reload()` read as always.
36
+ *
37
+ * const portada = useServiceReading(sitio.portada, [], { initial: loaderData.portada });
31
38
  */
32
39
  export declare function useServiceReading<A extends unknown[], R>(useCase: UseCase<A, R>, args: A, options?: {
33
40
  follows?: readonly Entity[];
41
+ initial?: Awaited<R>;
34
42
  }): ServiceReading<Awaited<R>>;
35
43
  export {};
@@ -30,13 +30,24 @@ function routeOf(entity) {
30
30
  * screen until the new one lands. The last question wins: an answer to arguments no longer on
31
31
  * screen is dropped. The use case is the latest the screen gave (a bounded context answers a new
32
32
  * function per `scoped(…)`); its trace and report are the service's, never this hook's.
33
+ *
34
+ * `initial` is the answer to these same arguments already read — on the server that renders the
35
+ * screen, in a route's loader, by calling the same use case. The reading starts `ready` with it,
36
+ * renders it there, and in the browser keeps it on mount instead of reading again; a change of
37
+ * arguments, a followed write or `reload()` read as always.
38
+ *
39
+ * const portada = useServiceReading(sitio.portada, [], { initial: loaderData.portada });
33
40
  */
34
41
  export function useServiceReading(useCase, args, options = {}) {
35
42
  const { context, changes, entities } = useFramework();
36
43
  const key = JSON.stringify(args);
37
44
  const latest = useRef({ useCase, args });
38
45
  latest.current = { useCase, args };
39
- const [answered, setAnswered] = useState(null);
46
+ const [answered, setAnswered] = useState(() => options.initial === undefined
47
+ ? null
48
+ : { key, status: "ready", answer: options.initial, error: null });
49
+ // Born answered: the first read on mount is the one the server already made.
50
+ const seeded = useRef(options.initial !== undefined);
40
51
  const [again, setAgain] = useState(0);
41
52
  // A write anyone sends — a save, another use case, a panel beside — to what it follows.
42
53
  const followed = (options.follows ?? [])
@@ -53,6 +64,10 @@ export function useServiceReading(useCase, args, options = {}) {
53
64
  });
54
65
  }, [changes, entities, followed]);
55
66
  useEffect(() => {
67
+ if (seeded.current) {
68
+ seeded.current = false;
69
+ return;
70
+ }
56
71
  let current = true;
57
72
  const { useCase: read, args: now } = latest.current;
58
73
  // Through the promise: a use case that throws before it answers is a failure like any other.
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * The web bindings: what draws a `Listing` and a record with `@sincpro/web-ui`.
3
3
  */
4
+ export { BatchProgress } from "./list/BatchProgress.js";
4
5
  export { aggregateOf, type ColumnOptions, columnsOf, } from "./list/columns.js";
5
6
  export { type EntityFace, EntityList, type EntityListProps, type View, } from "./list/EntityList.js";
6
7
  export { EntitySearchBar } from "./list/EntitySearchBar.js";
@@ -8,6 +9,7 @@ export { groupableOf, pilesOf } from "./list/groups.js";
8
9
  export { OpenInMenu } from "./list/openIn.js";
9
10
  export { pivotOf } from "./list/pivot.js";
10
11
  export { type CardLook, type ChoiceTones, type OptionLook, type PartLook, partLookOf, type PartLooks, type PartOf, type Presentation, presentationOf, type Presented, presented, type RowLook, tonesOver, } from "./list/presentation.js";
12
+ export { type Choice, type Chooser, findChoices, type FrameworkReads, modelLoader, recordsBrowser, RecordsBrowserProvider, recordsSearch, refusalNotice, useLoadModel, useRecordsBrowser, useSearchRecords, } from "./list/records.js";
11
13
  export { type RowCommand, type RowCommands, useRowCommands, } from "./list/rowCommands.js";
12
14
  export { facetsOf, modelOf } from "./list/search.js";
13
15
  export { type ActionDialog, type Asked, } from "./record/ActionButton.js";
package/dist/web/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * The web bindings: what draws a `Listing` and a record with `@sincpro/web-ui`.
3
3
  */
4
+ export { BatchProgress } from "./list/BatchProgress.js";
4
5
  export { aggregateOf, columnsOf, } from "./list/columns.js";
5
6
  export { EntityList, } from "./list/EntityList.js";
6
7
  export { EntitySearchBar } from "./list/EntitySearchBar.js";
@@ -8,6 +9,7 @@ export { groupableOf, pilesOf } from "./list/groups.js";
8
9
  export { OpenInMenu } from "./list/openIn.js";
9
10
  export { pivotOf } from "./list/pivot.js";
10
11
  export { partLookOf, presentationOf, presented, tonesOver, } from "./list/presentation.js";
12
+ export { findChoices, modelLoader, recordsBrowser, RecordsBrowserProvider, recordsSearch, refusalNotice, useLoadModel, useRecordsBrowser, useSearchRecords, } from "./list/records.js";
11
13
  export { useRowCommands, } from "./list/rowCommands.js";
12
14
  export { facetsOf, modelOf } from "./list/search.js";
13
15
  export {} from "./record/ActionButton.js";
@@ -0,0 +1,16 @@
1
+ import type { BatchCommandState } from "../../react/useBatchCommand.js";
2
+ /**
3
+ * A Command running once per record, drawn: how far it is while it runs, then what became of
4
+ * each — «2 hechos · 1 falló», every failure named by its record and its reason, «Reintentar los
5
+ * que fallaron». Before it starts, why it did not: too many chosen.
6
+ *
7
+ * const confirm = useBatchCommand(invoices, "confirm");
8
+ * <BatchProgress batch={confirm} />
9
+ *
10
+ * Context: a batch's result is one outcome per record, and a person needs the ones that failed —
11
+ * by name, with the server's reason —, not a count. web-ui draws (`ProgressBar`, `Callout`); the
12
+ * words are the framework's copy, the reasons the server's (`explain`).
13
+ */
14
+ export declare function BatchProgress<R>({ batch, }: {
15
+ batch: Pick<BatchCommandState<R>, "running" | "progress" | "result" | "error" | "retry" | "stop" | "reset">;
16
+ }): import("react").JSX.Element | null;
@@ -0,0 +1,40 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { SelectionTooLarge } from "@sincpro/client-framework";
4
+ import { frameworkCopy } from "../../core/copy.js";
5
+ import { explain } from "../../core/explain.js";
6
+ import { Button, Callout, ProgressBar } from "@sincpro/web-ui";
7
+ /**
8
+ * A Command running once per record, drawn: how far it is while it runs, then what became of
9
+ * each — «2 hechos · 1 falló», every failure named by its record and its reason, «Reintentar los
10
+ * que fallaron». Before it starts, why it did not: too many chosen.
11
+ *
12
+ * const confirm = useBatchCommand(invoices, "confirm");
13
+ * <BatchProgress batch={confirm} />
14
+ *
15
+ * Context: a batch's result is one outcome per record, and a person needs the ones that failed —
16
+ * by name, with the server's reason —, not a count. web-ui draws (`ProgressBar`, `Callout`); the
17
+ * words are the framework's copy, the reasons the server's (`explain`).
18
+ */
19
+ export function BatchProgress({ batch, }) {
20
+ const copy = frameworkCopy().batch;
21
+ const { running, progress, result, error } = batch;
22
+ if (running && progress !== null)
23
+ return (_jsxs("div", { className: "flex items-center gap-3", children: [_jsx(ProgressBar, { label: copy.running, value: progress.settled, maxValue: progress.total, valueLabel: copy.progress(progress.settled, progress.total), tone: "brand" }), _jsx(Button, { role: "ghost", size: "sm", onClick: batch.stop, children: copy.stop })] }));
24
+ if (error instanceof SelectionTooLarge)
25
+ return (_jsx(Callout, { tone: "warn", onDismiss: batch.reset, children: copy.tooMany(error.size, error.limit) }));
26
+ if (error !== null && error !== undefined) {
27
+ const { heading, sentence } = explain(error);
28
+ return (_jsx(Callout, { tone: "bad", title: heading, onDismiss: batch.reset, children: sentence }));
29
+ }
30
+ if (result === null || result.outcomes.length === 0)
31
+ return null;
32
+ const left = result.outcomes.filter((one) => one.status !== "done");
33
+ return (_jsx(Callout, { tone: left.length === 0 ? "good" : result.done === 0 ? "bad" : "warn", title: copy.outcome(result.done, result.failed, result.skipped), onDismiss: batch.reset, ...(left.length === 0
34
+ ? {}
35
+ : {
36
+ action: (_jsx(Button, { role: "secondary", size: "sm", onClick: () => void batch.retry(), children: copy.retry })),
37
+ }), children: left.length === 0 ? null : (_jsx("ul", { className: "flex flex-col gap-1", children: left
38
+ .filter((one) => one.status === "failed")
39
+ .map((one) => (_jsxs("li", { children: [_jsx("span", { className: "font-medium", children: one.item }), " — ", explain(one.error).sentence] }, one.item))) })) }));
40
+ }
@@ -1,8 +1,9 @@
1
1
  import { type CommandBodies } from "@sincpro/client-framework";
2
2
  import { type AnyRecord } from "@sincpro/criteria";
3
3
  import { type WorkspaceApi } from "@sincpro/web-composer";
4
- import type { GroupLevel, NamedFilter } from "../../core/list.js";
4
+ import { type GroupLevel, type NamedFilter } from "../../core/list.js";
5
5
  import type { Listing } from "../../react/useListing.js";
6
+ import { type ListSelection } from "../../react/useSelection.js";
6
7
  import { type RowCommand } from "./rowCommands.js";
7
8
  import { type ListCrumb, type ListPresentProps, type ListSet, type OpenTarget, type RowAction } from "@sincpro/web-ui";
8
9
  import { type ReactNode } from "react";
@@ -96,12 +97,17 @@ export type EntityListProps<T extends AnyRecord, C extends CommandBodies = Comma
96
97
  * Without it, the list definition's, else every one the model does. */
97
98
  groupable?: readonly string[];
98
99
  /**
99
- * Rows can be ticked. With `api`, what is ticked is PUBLISHED to the workspace
100
- * (`api.select`): a panel beside it follows the selection without knowing this list.
100
+ * Rows can be ticked — and, past the page, «Elegir los 187 que coinciden». With `api`, what is
101
+ * chosen is PUBLISHED to the workspace (`api.select`): a panel beside it follows the selection
102
+ * without knowing this list.
101
103
  */
102
104
  selectable?: boolean;
103
- /** What to do with what is ticked: drawn in the bar while something is. */
104
- selectionActions?: ReactNode;
105
+ /** The selection, held by the screen (`useSelection(listing)`): read and set from outside the
106
+ * list. Without it the list holds its own. */
107
+ selection?: ListSelection<T>;
108
+ /** What to do with what is chosen, drawn in the bar while something is — handed the selection
109
+ * to act on it (`useBatchCommand`). */
110
+ selectionActions?: ReactNode | ((selection: ListSelection<T>) => ReactNode);
105
111
  /** The list is a FIELD of a record — its lines, its members — and not a screen. */
106
112
  embedded?: boolean;
107
113
  /**
@@ -135,4 +141,4 @@ export type EntityFace<T> = {
135
141
  render: (set: ListSet<T>) => ReactNode;
136
142
  };
137
143
  export type View = "table" | "rows" | "board" | "sheet" | "pivot";
138
- export declare function EntityList<T extends AnyRecord, C extends CommandBodies = CommandBodies>({ listing, api, columns: askedColumns, cells, views: askedViews, title: askedTitle, description: askedDescription, crumbs, actions, onOpen, onPeek, openTargets, onOpenIn, pivot: pivotAsked, empty, search, sums, filters: askedFilters, facets: askedFacets, groupable: askedGroupable, selectable, selectionActions, embedded, create, commands, rowActions: askedRowActions, faces, }: EntityListProps<T, C>): import("react").JSX.Element;
144
+ export declare function EntityList<T extends AnyRecord, C extends CommandBodies = CommandBodies>({ listing, api, columns: askedColumns, cells, views: askedViews, title: askedTitle, description: askedDescription, crumbs, actions, onOpen, onPeek, openTargets, onOpenIn, pivot: pivotAsked, empty, search, sums, filters: askedFilters, facets: askedFacets, groupable: askedGroupable, selectable, selection: held, selectionActions, embedded, create, commands, rowActions: askedRowActions, faces, }: EntityListProps<T, C>): import("react").JSX.Element;
@@ -5,11 +5,13 @@ import { nameOf } from "@sincpro/criteria";
5
5
  import { RecordLink, useCrumbs, usePhone } from "@sincpro/web-composer";
6
6
  import { frameworkCopy } from "../../core/copy.js";
7
7
  import { explain } from "../../core/explain.js";
8
+ import { choosesMany, } from "../../core/list.js";
8
9
  import { textOf, viewOf } from "../../core/present.js";
9
10
  import { summaryFieldsOf } from "../../core/summary.js";
10
11
  import { useFramework } from "../../react/context.js";
11
12
  import { useGroups } from "../../react/useGroups.js";
12
13
  import { usePivot } from "../../react/usePivot.js";
14
+ import { useSelection } from "../../react/useSelection.js";
13
15
  import { columnsOf } from "./columns.js";
14
16
  import { EntitySearchBar } from "./EntitySearchBar.js";
15
17
  import { pilesOf } from "./groups.js";
@@ -33,7 +35,7 @@ const TRAILS = 50;
33
35
  const NO_COMMANDS = [];
34
36
  /** What a list offers when nobody said: every face that needs no configuration. */
35
37
  const EVERY_VIEW = ["table", "rows", "board", "sheet"];
36
- export function EntityList({ listing, api, columns: askedColumns, cells, views: askedViews, title: askedTitle, description: askedDescription, crumbs, actions, onOpen, onPeek, openTargets, onOpenIn, pivot: pivotAsked, empty, search = "bar", sums, filters: askedFilters, facets: askedFacets, groupable: askedGroupable, selectable = false, selectionActions, embedded = false, create = true, commands = NO_COMMANDS, rowActions: askedRowActions, faces, }) {
38
+ export function EntityList({ listing, api, columns: askedColumns, cells, views: askedViews, title: askedTitle, description: askedDescription, crumbs, actions, onOpen, onPeek, openTargets, onOpenIn, pivot: pivotAsked, empty, search = "bar", sums, filters: askedFilters, facets: askedFacets, groupable: askedGroupable, selectable = false, selection: held, selectionActions, embedded = false, create = true, commands = NO_COMMANDS, rowActions: askedRowActions, faces, }) {
37
39
  // A named list (`defineList`) brings its own columns, filters, faces and words; what the
38
40
  // screen passes wins.
39
41
  const definition = listing.definition;
@@ -67,6 +69,12 @@ export function EntityList({ listing, api, columns: askedColumns, cells, views:
67
69
  }, []);
68
70
  // Opened by `api.pick` (`entity.chooserRef()`): a row ANSWERS whoever asked, it does not open.
69
71
  const choosing = api?.self.params?.[PICK_PARAM] !== undefined;
72
+ // Asked for SEVERAL (`CHOOSE_MANY`, a many2many's «Buscar más…»): a row press ticks it, and
73
+ // «Agregar (N)» answers what was chosen — the keys, or every record the list matches.
74
+ const choosingMany = choosing && choosesMany(api?.choosing?.question);
75
+ const own = useSelection(listing);
76
+ const chosen = held ?? own;
77
+ const ticking = selectable || choosingMany;
70
78
  // The record opened from a row knows the page it came from: «3 / 64» and its neighbours.
71
79
  const { trails, dateStyle } = useFramework();
72
80
  const trailKey = `trail:${useId()}`;
@@ -114,9 +122,11 @@ export function EntityList({ listing, api, columns: askedColumns, cells, views:
114
122
  const opening = onOpen ??
115
123
  (api === undefined
116
124
  ? undefined
117
- : choosing
118
- ? (row) => api.answer(listing.entity.ref(idOf(row)))
119
- : openWithTrail);
125
+ : choosingMany
126
+ ? (row) => chosen.toggle(idOf(row))
127
+ : choosing
128
+ ? (row) => api.answer(listing.entity.ref(idOf(row)))
129
+ : openWithTrail);
120
130
  const creating = create &&
121
131
  api !== undefined &&
122
132
  !choosing &&
@@ -163,25 +173,30 @@ export function EntityList({ listing, api, columns: askedColumns, cells, views:
163
173
  const following = useCrumbs(api ?? NO_WORKSPACE);
164
174
  usePhone(api ?? NO_WORKSPACE); // where a row opens follows the mode (`targetsFor`)
165
175
  const trail = crumbs ?? (embedded || api === undefined ? undefined : following);
166
- const [ticked, setTicked] = useState(() => new Set());
167
- const tick = (next) => {
168
- setTicked(next);
169
- api?.select([...next].map((id) => listing.entity.ref(id)));
170
- };
171
- const selection = selectable
176
+ // The workspace hears what is chosen: the keys, or — «all that match» — the ones on screen.
177
+ const published = (chosen.selection.by === "keys"
178
+ ? chosen.selection.keys
179
+ : listing.rows.map((row) => idOf(row)).filter((id) => chosen.isChosen(id))).join("\u0000");
180
+ const heard = useRef(published);
181
+ useEffect(() => {
182
+ if (!ticking || heard.current === published)
183
+ return;
184
+ heard.current = published;
185
+ api?.select(published === "" ? [] : published.split("\u0000").map((id) => listing.entity.ref(id)));
186
+ }, [api, ticking, published, listing.entity]);
187
+ // «Elegir los 187 que coinciden» only past the page, and only with the server's exact count.
188
+ const total = listing.count?.exact === true ? listing.count.value : null;
189
+ const onChosen = choosingMany ? (_jsx(Button, { role: "primary", size: "sm", onClick: () => api?.answer(chosen.selection), children: frameworkCopy().picker.addChosen(chosen.size) })) : typeof selectionActions === "function" ? (selectionActions(chosen)) : (selectionActions);
190
+ const selection = ticking
172
191
  ? {
173
- has: (id) => ticked.has(id),
174
- toggle: (id) => {
175
- const next = new Set(ticked);
176
- if (next.has(id))
177
- next.delete(id);
178
- else
179
- next.add(id);
180
- tick(next);
181
- },
182
- count: ticked.size,
183
- clear: () => tick(new Set()),
184
- ...(selectionActions === undefined ? {} : { actions: selectionActions }),
192
+ has: chosen.isChosen,
193
+ toggle: chosen.toggle,
194
+ count: chosen.size ?? 0,
195
+ clear: chosen.clear,
196
+ ...(total !== null && total > listing.rows.length
197
+ ? { matching: { total, onSelect: chosen.chooseAllMatching } }
198
+ : {}),
199
+ ...(onChosen === undefined ? {} : { actions: onChosen }),
185
200
  }
186
201
  : undefined;
187
202
  // Rebuilt only when what it reads changes: a new set of columns on every render redraws
@@ -15,6 +15,15 @@ import type { Listing } from "../../react/useListing.js";
15
15
  * - «search by name»: facets are the fields the screen names (`facets`), else the ones the
16
16
  * entity's search template names — never every text field;
17
17
  * - a typed question («total > 5000») is checked against each field's operators;
18
+ * - a relation unfolds into its RECORDS that match what was typed — «andres» → the customers
19
+ * —, chosen by key and read by name («Cliente: Andrés Pérez»), and an enum into its words
20
+ * («Estado: Pagada», sent as `paid`): the related entity's literal search
21
+ * (`useSearchRecords`), unless the application put its own in a web-ui `SearchProvider`;
22
+ * inside a workspace, «Buscar más…» under them opens the entity's list to choose
23
+ * (`useRecordsBrowser`) — the bar's, never the builder's: the builder is a modal dialog, and
24
+ * what opens outside one cannot be used;
25
+ * - the builder walks relations — «Cliente › País» — through the models along the path
26
+ * (`useLoadModel`), and picks the related records themselves;
18
27
  * - a named filter is one click; the builder writes what nobody foresaw (all/any/not);
19
28
  * - everything put becomes ONE `selection` the SERVER answers (`listing.filter`) — web-ui
20
29
  * writes it in criteria's own shape, a filter through a relation included;