@sincpro/web-framework 0.1.0 → 0.3.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 (97) hide show
  1. package/README.md +298 -40
  2. package/dist/core/cache.js +2 -2
  3. package/dist/core/copy.d.ts +26 -0
  4. package/dist/core/copy.js +32 -0
  5. package/dist/core/edit.d.ts +48 -3
  6. package/dist/core/edit.js +79 -5
  7. package/dist/core/entity.d.ts +46 -0
  8. package/dist/core/entity.js +57 -0
  9. package/dist/core/form.d.ts +21 -0
  10. package/dist/core/form.js +30 -0
  11. package/dist/core/index.d.ts +11 -3
  12. package/dist/core/index.js +10 -2
  13. package/dist/core/lines.d.ts +53 -0
  14. package/dist/core/lines.js +120 -0
  15. package/dist/core/list.d.ts +64 -0
  16. package/dist/core/list.js +22 -0
  17. package/dist/core/lookup.d.ts +7 -2
  18. package/dist/core/lookup.js +8 -2
  19. package/dist/core/measure.d.ts +16 -0
  20. package/dist/core/measure.js +38 -0
  21. package/dist/core/memory.js +18 -4
  22. package/dist/core/relation.d.ts +28 -0
  23. package/dist/core/relation.js +30 -0
  24. package/dist/core/rest.d.ts +5 -9
  25. package/dist/core/rest.js +25 -7
  26. package/dist/core/retry.d.ts +24 -0
  27. package/dist/core/retry.js +25 -0
  28. package/dist/core/summary.d.ts +50 -0
  29. package/dist/core/summary.js +54 -0
  30. package/dist/core/trail.d.ts +44 -0
  31. package/dist/core/trail.js +70 -0
  32. package/dist/core/transport.d.ts +22 -2
  33. package/dist/react/context.d.ts +20 -1
  34. package/dist/react/context.js +10 -2
  35. package/dist/react/index.d.ts +5 -2
  36. package/dist/react/index.js +4 -1
  37. package/dist/react/useCommand.d.ts +3 -1
  38. package/dist/react/useCommand.js +12 -4
  39. package/dist/react/useGroups.d.ts +52 -0
  40. package/dist/react/useGroups.js +110 -0
  41. package/dist/react/useListing.d.ts +29 -7
  42. package/dist/react/useListing.js +49 -8
  43. package/dist/react/useLookup.d.ts +30 -5
  44. package/dist/react/useLookup.js +56 -3
  45. package/dist/react/usePivot.d.ts +33 -0
  46. package/dist/react/usePivot.js +59 -0
  47. package/dist/react/useRecord.d.ts +28 -9
  48. package/dist/react/useRecord.js +156 -18
  49. package/dist/react/useSummary.d.ts +15 -0
  50. package/dist/react/useSummary.js +22 -0
  51. package/dist/web/index.d.ts +15 -3
  52. package/dist/web/index.js +14 -2
  53. package/dist/web/list/EntityList.d.ts +69 -7
  54. package/dist/web/list/EntityList.js +281 -23
  55. package/dist/web/list/EntitySearchBar.d.ts +16 -8
  56. package/dist/web/list/EntitySearchBar.js +52 -4
  57. package/dist/web/list/columns.d.ts +0 -13
  58. package/dist/web/list/columns.js +20 -1
  59. package/dist/web/list/groups.d.ts +17 -0
  60. package/dist/web/list/groups.js +80 -0
  61. package/dist/web/list/openIn.d.ts +41 -0
  62. package/dist/web/list/openIn.js +55 -0
  63. package/dist/web/list/pivot.d.ts +23 -0
  64. package/dist/web/list/pivot.js +64 -0
  65. package/dist/web/list/presentation.d.ts +51 -0
  66. package/dist/web/list/presentation.js +20 -0
  67. package/dist/web/list/rowCommands.d.ts +41 -0
  68. package/dist/web/list/rowCommands.js +56 -0
  69. package/dist/web/record/EntityPicker.d.ts +45 -14
  70. package/dist/web/record/EntityPicker.js +64 -20
  71. package/dist/web/record/EntityTags.d.ts +38 -0
  72. package/dist/web/record/EntityTags.js +52 -0
  73. package/dist/web/record/RelatedList.d.ts +8 -1
  74. package/dist/web/record/RelatedList.js +37 -3
  75. package/dist/web/record/control.d.ts +42 -0
  76. package/dist/web/record/control.js +60 -0
  77. package/dist/web/record/edit.d.ts +27 -12
  78. package/dist/web/record/edit.js +92 -25
  79. package/dist/web/record/lines.d.ts +84 -0
  80. package/dist/web/record/lines.js +190 -0
  81. package/dist/web/record/opening.d.ts +34 -0
  82. package/dist/web/record/opening.js +10 -0
  83. package/dist/web/record/summary.d.ts +22 -0
  84. package/dist/web/record/summary.js +63 -0
  85. package/dist/web/workspace/SincproApp.d.ts +4 -1
  86. package/dist/web/workspace/SincproApp.js +2 -2
  87. package/dist/web/workspace/composer.d.ts +27 -4
  88. package/dist/web/workspace/composer.js +75 -7
  89. package/dist/web/workspace/open.d.ts +49 -0
  90. package/dist/web/workspace/open.js +51 -0
  91. package/dist/web/workspace/record.d.ts +30 -0
  92. package/dist/web/workspace/record.js +83 -0
  93. package/dist/web/workspace/skin.d.ts +0 -9
  94. package/dist/web/workspace/skin.js +25 -13
  95. package/dist/web/workspace/workspace.d.ts +33 -3
  96. package/dist/web/workspace/workspace.js +63 -4
  97. package/package.json +9 -9
@@ -1,5 +1,7 @@
1
1
  import type { Meta } from "@sincpro/criteria";
2
+ import type { Entity } from "../core/entity.js";
2
3
  import { type MetaStore } from "../core/metas.js";
4
+ import type { Trail } from "../core/trail.js";
3
5
  import type { Transport } from "../core/transport.js";
4
6
  import { type ReactNode } from "react";
5
7
  /**
@@ -9,19 +11,36 @@ import { type ReactNode } from "react";
9
11
  * Context: a view receives its record reference and nothing else — the composer hands it no
10
12
  * client on purpose — so the transport reaches it through context, set once where the
11
13
  * application starts.
14
+ *
15
+ * This is the GLOBAL part, and only that. What an OPENING carries is the composer's, and it
16
+ * already has it: `params` on the reference (a company, a filter, a default — survives a reload
17
+ * and a link), `api.over` (in a modal, the record it covers), `pick(…, { question })` +
18
+ * `api.choosing` (what a chooser was asked, in memory) and `api.context` (what the user is on,
19
+ * what is selected). Read `~/dev/sincpro_web_composer/README.md` before writing a second one
20
+ * here. A value the backend must see on every request (the active company) goes in the
21
+ * transport's `headers` — the backend's `sincpro-context` header is read by every entrance.
12
22
  */
13
23
  type FrameworkContextValue = {
14
24
  transport: Transport;
15
25
  locale: string | undefined;
16
26
  metas: MetaStore;
27
+ /** The application's entities: what a relation of a model is resolved to. */
28
+ entities: readonly Entity[];
29
+ /** Where each open record came from (`Trail`), by the key its reference carries. */
30
+ trails: Map<string, Trail>;
17
31
  };
18
- export declare function FrameworkProvider({ transport, locale, metas: seed, children, }: {
32
+ export declare function FrameworkProvider({ transport, locale, metas: seed, entities, children, }: {
19
33
  transport: Transport;
20
34
  /** The language labels and values are read in (`"es"`); the model's `default` without it. */
21
35
  locale?: string;
22
36
  /** Definitions known before any request, by entity key: the preload. */
23
37
  metas?: Readonly<Record<string, Meta>>;
38
+ /** The entities of the application: a form draws a many2one as a picker of the one its
39
+ * model points at (`relation: "Cliente"`) without being told. */
40
+ entities?: readonly Entity[];
24
41
  children: ReactNode;
25
42
  }): import("react").JSX.Element;
26
43
  export declare function useFramework(): FrameworkContextValue;
44
+ /** The declared entity a relation points at (`"Cliente"`), or `undefined`. */
45
+ export declare function useEntityFor(target: string | undefined): Entity | undefined;
27
46
  export {};
@@ -1,18 +1,26 @@
1
1
  "use client";
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
3
  import { metaStore } from "../core/metas.js";
4
+ import { entityFor } from "../core/relation.js";
4
5
  import { createContext, useContext, useMemo, useState } from "react";
5
6
  const FrameworkContext = createContext(null);
6
- export function FrameworkProvider({ transport, locale, metas: seed, children, }) {
7
+ export function FrameworkProvider({ transport, locale, metas: seed, entities = NO_ENTITIES, children, }) {
7
8
  // One store for the provider's life: a new seed object on a re-render must not forget what
8
9
  // the screens already learned.
9
10
  const [metas] = useState(() => metaStore(seed));
10
- const value = useMemo(() => ({ transport, locale, metas }), [transport, locale, metas]);
11
+ const [trails] = useState(() => new Map());
12
+ const value = useMemo(() => ({ transport, locale, metas, entities, trails }), [transport, locale, metas, entities, trails]);
11
13
  return _jsx(FrameworkContext.Provider, { value: value, children: children });
12
14
  }
15
+ const NO_ENTITIES = [];
13
16
  export function useFramework() {
14
17
  const value = useContext(FrameworkContext);
15
18
  if (value === null)
16
19
  throw new Error("useFramework outside a FrameworkProvider");
17
20
  return value;
18
21
  }
22
+ /** The declared entity a relation points at (`"Cliente"`), or `undefined`. */
23
+ export function useEntityFor(target) {
24
+ const { entities, metas } = useFramework();
25
+ return target === undefined ? undefined : entityFor(entities, target, metas.get);
26
+ }
@@ -3,10 +3,13 @@
3
3
  * DOM, no design system — so a screen can drop `EntityList` and still keep it. `make doctor`
4
4
  * keeps it that way.
5
5
  */
6
- export { FrameworkProvider, useFramework } from "./context.js";
6
+ export { FrameworkProvider, useEntityFor, useFramework, } from "./context.js";
7
7
  export { type CommandState, type Rehearsal, useCommand, } from "./useCommand.js";
8
+ export { type Groups, useGroups } from "./useGroups.js";
8
9
  export { useHistory } from "./useHistory.js";
9
10
  export { type Listing, type ListingOptions, type Paging, useListing, } from "./useListing.js";
10
11
  export { type Lookup, useLookup } from "./useLookup.js";
11
- export { type Advice, type Editing, type RecordReading, type RecordState, useRecord, } from "./useRecord.js";
12
+ export { type PivotAxes, type PivotReading, usePivot, } from "./usePivot.js";
13
+ export { type Editing, type RecordReading, type RecordState, useRecord, } from "./useRecord.js";
12
14
  export { useRelated } from "./useRelated.js";
15
+ export { useSummaryOf } from "./useSummary.js";
@@ -3,10 +3,13 @@
3
3
  * DOM, no design system — so a screen can drop `EntityList` and still keep it. `make doctor`
4
4
  * keeps it that way.
5
5
  */
6
- export { FrameworkProvider, useFramework } from "./context.js";
6
+ export { FrameworkProvider, useEntityFor, useFramework, } from "./context.js";
7
7
  export { useCommand, } from "./useCommand.js";
8
+ export { useGroups } from "./useGroups.js";
8
9
  export { useHistory } from "./useHistory.js";
9
10
  export { useListing, } from "./useListing.js";
10
11
  export { useLookup } from "./useLookup.js";
12
+ export { usePivot, } from "./usePivot.js";
11
13
  export { useRecord, } from "./useRecord.js";
12
14
  export { useRelated } from "./useRelated.js";
15
+ export { useSummaryOf } from "./useSummary.js";
@@ -9,7 +9,9 @@ import { type Entity } from "../core/entity.js";
9
9
  * destructive action deserves: not «are you sure?», but what is about to happen. forge's
10
10
  * console had the backend for it and no screen that asked.
11
11
  *
12
- * One at a time: `busy` turns the button off, because a payment sent twice is two payments.
12
+ * One at a time: `busy` turns the button off, because a payment sent twice is two payments. And
13
+ * once sent, the same gesture keeps its `Idempotency-Key` until the server answers: a retry
14
+ * after a dropped request is the same payment, never a second one (`retryKeys`).
13
15
  */
14
16
  export type Rehearsal = {
15
17
  text: string;
@@ -1,5 +1,6 @@
1
1
  "use client";
2
2
  import { pathFor } from "../core/entity.js";
3
+ import { retryKeys } from "../core/retry.js";
3
4
  import { useFramework } from "./context.js";
4
5
  import { useCallback, useEffect, useRef, useState } from "react";
5
6
  export function useCommand(entity, name) {
@@ -17,13 +18,20 @@ export function useCommand(entity, name) {
17
18
  mounted.current = true;
18
19
  return () => void (mounted.current = false);
19
20
  }, []);
20
- const send = useCallback(async (id, body) => {
21
+ // One key per gesture, kept while it goes unanswered: «retry» after a dropped request must
22
+ // not run it twice. A dry run touches nothing, so each one gets a key of its own.
23
+ const keys = useRef(retryKeys());
24
+ const send = useCallback(async (id, body, gesture) => {
21
25
  setBusy(true);
22
26
  setError(null);
27
+ const idempotencyKey = gesture.keyFor({ id, body });
23
28
  try {
24
- return await transport.send(route.method, pathFor(route, id), body);
29
+ const answer = await transport.send(route.method, pathFor(route, id), body, undefined, { idempotencyKey });
30
+ gesture.settle(null);
31
+ return answer;
25
32
  }
26
33
  catch (failure) {
34
+ gesture.settle(failure);
27
35
  if (mounted.current)
28
36
  setError(failure);
29
37
  return undefined;
@@ -34,9 +42,9 @@ export function useCommand(entity, name) {
34
42
  }
35
43
  }, [transport, route]);
36
44
  return {
37
- run: (id, body = {}) => send(id, body),
45
+ run: (id, body = {}) => send(id, body, keys.current),
38
46
  rehearse: async (id, body = {}) => {
39
- const answer = await send(id, { ...body, dry_run: true });
47
+ const answer = await send(id, { ...body, dry_run: true }, retryKeys());
40
48
  if (answer !== undefined && mounted.current)
41
49
  setRehearsal(answer);
42
50
  return answer;
@@ -0,0 +1,52 @@
1
+ import { type AnyRecord, type Bucket } from "@sincpro/criteria";
2
+ import type { GroupLevel } from "../core/list.js";
3
+ import type { Listing } from "./useListing.js";
4
+ /**
5
+ * The set of a list, split into groups — counted by the SERVER over every row that matches.
6
+ *
7
+ * Context: grouping is the same question as filtering («which part of this am I looking at»),
8
+ * and it obeys the same rule: never on the page. Twelve rows on screen cannot say «187 paid»;
9
+ * whoever keeps the set can. So the listing's own question (scope, search, filter) goes to the
10
+ * server with `group_by`, and what comes back is the groups: their value, their real count, the
11
+ * level below, and the criteria that opens each one (sincpro_framework's aggregation; the
12
+ * in-memory server answers the same with criteria's engine). A group's rows are read when it is
13
+ * opened, with that criteria — nobody rebuilds a filter here.
14
+ *
15
+ * const groups = useGroups(listing);
16
+ * groups.group([{ field: "state" }, { field: "invoice_date", grain: "month" }]);
17
+ * groups.buckets // [{ field: "state", value: "paid", count: 187, groups: [...] }, ...]
18
+ * groups.open(bucket); groups.rowsOf(bucket) // its first page of rows
19
+ */
20
+ export type { GroupLevel };
21
+ export type Groups<T> = {
22
+ levels: readonly GroupLevel[];
23
+ /** Split by these levels, outermost first; none is no grouping. */
24
+ group: (levels: readonly GroupLevel[]) => void;
25
+ status: "idle" | "loading" | "ready" | "failed";
26
+ buckets: readonly Bucket<T>[];
27
+ error: unknown;
28
+ /** More groups exist than the ceiling shows: narrow the set instead. */
29
+ capped: boolean;
30
+ /** Read the rows of a group — its first page. */
31
+ open: (bucket: Bucket<T>) => void;
32
+ /** The rows of a group once read; `undefined` while it was never opened or is loading. */
33
+ rowsOf: (bucket: Bucket<T>) => readonly T[] | undefined;
34
+ /** Read the group's next page and append it — on the server's cursor, like the list's «load
35
+ * more». Nothing when it has no more, is already reading, or reached the ceiling. */
36
+ more: (bucket: Bucket<T>) => void;
37
+ /** The group has rows past those read, under the ceiling: «Show N more» makes sense. */
38
+ hasMore: (bucket: Bucket<T>) => boolean;
39
+ /** What the next `more` brings: a number of rows, `false` when it brings none (the server
40
+ * has no next page, or the ceiling was reached), `undefined` while the group is unread.
41
+ * web-ui's `Pile.more`: «Show 50 more of 49,950», or «Showing 500 of 49,950». */
42
+ brings: (bucket: Bucket<T>) => number | false | undefined;
43
+ };
44
+ export declare function useGroups<T extends AnyRecord>(listing: Listing<T>, options?: {
45
+ pageSize?: number;
46
+ /** The fields each group adds up, over every row of it (`detailOf` reads them). Without
47
+ * it, the figures the model computes (`sumsOf`); `[]` adds nothing up. */
48
+ sums?: readonly string[];
49
+ /** The most rows ONE group grows to with «more» — 500, the list's ceiling. Past it a group
50
+ * is narrowed with the search, as a list is. */
51
+ maxRows?: number;
52
+ }): Groups<T>;
@@ -0,0 +1,110 @@
1
+ "use client";
2
+ import { resumingFrom } from "@sincpro/criteria";
3
+ import { measuresOf, sumsOf } from "../core/measure.js";
4
+ import { useFramework } from "./context.js";
5
+ import { useCallback, useEffect, useRef, useState } from "react";
6
+ /** The most groups a level answers: a split into ten thousand groups is a list, not a split. */
7
+ const MAX_GROUPS = 100;
8
+ /** A group is known by its criteria: unique per group, and stable across renders. */
9
+ const keyOf = (bucket) => JSON.stringify(bucket.criteria);
10
+ export function useGroups(listing, options = {}) {
11
+ const { transport } = useFramework();
12
+ // A named list may open grouped (`groupBy`); a person regroups from there.
13
+ const [levels, setLevels] = useState(() => listing.definition?.groupBy ?? []);
14
+ const [state, setState] = useState({ status: "idle", buckets: [], error: null });
15
+ const [rows, setRows] = useState(new Map());
16
+ // A group being read: a second «more» before the first answer would ask for the same page.
17
+ const reading = useRef(new Set());
18
+ const pageSize = options.pageSize ?? 50;
19
+ const maxRows = options.maxRows ?? 500;
20
+ // The question without what pages it: a cursor or a limit of rows has no meaning for groups.
21
+ const { pagination: _page, ...asked } = listing.question;
22
+ const question = JSON.stringify(asked);
23
+ const route = listing.route;
24
+ const sums = (options.sums ?? sumsOf(listing.meta)).join(",");
25
+ // What adds up by default is read from the model: without it yet, asking now and again when
26
+ // it arrives would be two questions — and the groups on screen replaced under the pointer.
27
+ const waiting = options.sums === undefined && listing.meta === null;
28
+ useEffect(() => {
29
+ setRows(new Map());
30
+ reading.current.clear();
31
+ if (levels.length === 0) {
32
+ setState({ status: "idle", buckets: [], error: null });
33
+ return;
34
+ }
35
+ const aborter = new AbortController();
36
+ setState((now) => ({ ...now, status: "loading", error: null }));
37
+ if (waiting)
38
+ return () => aborter.abort();
39
+ const criteria = {
40
+ ...JSON.parse(question),
41
+ meta: false,
42
+ grouping: {
43
+ group_by: levels.map((level) => ({ ...level })),
44
+ ...(sums === "" ? {} : { measures: measuresOf(sums.split(",")) }),
45
+ pagination: { limit: MAX_GROUPS },
46
+ },
47
+ // One id per group is the least a grouped answer carries; the rows come on opening.
48
+ pagination: { limit: 1 },
49
+ };
50
+ transport.list(route, criteria, aborter.signal).then((page) => {
51
+ if (!aborter.signal.aborted)
52
+ setState({ status: "ready", buckets: page.rows, error: null });
53
+ }, (error) => {
54
+ if (!aborter.signal.aborted)
55
+ setState({ status: "failed", buckets: [], error });
56
+ });
57
+ return () => aborter.abort();
58
+ }, [transport, route, question, levels, sums, waiting]);
59
+ /** One page of a group: the first (`after` null) or the one the cursor points at. */
60
+ const read = useCallback((bucket, after) => {
61
+ const key = keyOf(bucket);
62
+ if (reading.current.has(key))
63
+ return;
64
+ reading.current.add(key);
65
+ const { grouping: _grouping, pagination: _pagination, ...own } = bucket.criteria;
66
+ const first = { ...own, meta: false, pagination: { limit: pageSize } };
67
+ void transport.list(route, after === null ? first : resumingFrom(first, after)).then((page) => {
68
+ reading.current.delete(key);
69
+ setRows((now) => {
70
+ const before = after === null ? [] : (now.get(key)?.rows ?? []);
71
+ return new Map(now).set(key, {
72
+ rows: [...before, ...page.rows],
73
+ after: page.cursor,
74
+ });
75
+ });
76
+ }, (error) => {
77
+ reading.current.delete(key);
78
+ setState((now) => ({ ...now, error }));
79
+ });
80
+ }, [transport, route, pageSize]);
81
+ const open = useCallback((bucket) => read(bucket, null), [read]);
82
+ const readOf = (bucket) => rows.get(keyOf(bucket));
83
+ const hasMore = (bucket) => {
84
+ const now = readOf(bucket);
85
+ return now !== undefined && now.after !== null && now.rows.length < maxRows;
86
+ };
87
+ return {
88
+ levels,
89
+ group: setLevels,
90
+ ...state,
91
+ capped: state.buckets.length >= MAX_GROUPS,
92
+ open,
93
+ rowsOf: (bucket) => readOf(bucket)?.rows,
94
+ more: (bucket) => {
95
+ const now = readOf(bucket);
96
+ if (now !== undefined && hasMore(bucket))
97
+ read(bucket, now.after);
98
+ },
99
+ hasMore,
100
+ brings: (bucket) => {
101
+ const now = readOf(bucket);
102
+ if (now === undefined)
103
+ return undefined;
104
+ if (!hasMore(bucket))
105
+ return false;
106
+ const left = Math.min(maxRows, bucket.count) - now.rows.length;
107
+ return Math.max(0, Math.min(pageSize, left));
108
+ },
109
+ };
110
+ }
@@ -1,5 +1,6 @@
1
1
  import { type AnyRecord, type Count, type Criteria, type Dropped, type Expression, type Meta, type ReadingStatus, type Sort } from "@sincpro/criteria";
2
2
  import type { Entity } from "../core/entity.js";
3
+ import { type ListDefinition } from "../core/list.js";
3
4
  /**
4
5
  * N records of an entity, live: what a list draws and the gestures that drive it.
5
6
  *
@@ -10,13 +11,24 @@ import type { Entity } from "../core/entity.js";
10
11
  *
11
12
  * search(text) the entity's own search template (`meta.search`), as the server fills it
12
13
  * filter(where) what a search bar or a criteria builder put — any depth of all/any/negate
13
- * orderBy(sort) the order, asked of the SERVER: a page sorted locally lies about page two
14
+ * orderBy(sort) the order — one field or several —, asked of the SERVER: a page sorted
15
+ * locally lies about page two
14
16
  *
15
17
  * All three refine the same reading instead of starting another. It holds state and draws
16
18
  * nothing: `EntityList` draws it, and a screen that needs another shape draws it itself.
17
19
  */
18
20
  export type Listing<T> = {
19
21
  entity: Entity<T & AnyRecord>;
22
+ /** The named list it reads, when it was handed one (`defineList`): what `EntityList` draws
23
+ * by default — its columns, filters, faces, title — and how `useGroups` starts. */
24
+ definition?: ListDefinition<T & AnyRecord>;
25
+ /** The route this list reads, with its own parameters (`/projects?tenant_id=acme`). */
26
+ route: string;
27
+ /**
28
+ * The question on screen — scope, search, filter and order — without a page: what a grouping
29
+ * of the same set asks with (`useGroups`), so groups and rows never disagree.
30
+ */
31
+ question: Criteria<T>;
20
32
  rows: T[];
21
33
  meta: Meta | null;
22
34
  count: Count | null;
@@ -29,14 +41,20 @@ export type Listing<T> = {
29
41
  reload: () => void;
30
42
  /** What was typed in the search box. */
31
43
  text: string;
32
- /** Debounced: a request per pause, not per keystroke. */
33
- search: (text: string) => void;
44
+ /** Debounced: a request per pause, not per keystroke. `now` asks at once — an explicit
45
+ * Enter does not wait for a pause. */
46
+ search: (text: string, options?: {
47
+ now?: boolean;
48
+ }) => void;
34
49
  /** What the search bar put; `undefined` is nothing. */
35
50
  where: Expression<T> | undefined;
36
51
  filter: (where: Expression<T> | undefined) => void;
37
- /** The order the server was asked for; `null` is the entity's own default. */
38
- order: Sort | null;
39
- orderBy: (order: Sort | null) => void;
52
+ /** The order the server was asked for, by one field then the next; empty is the entity's own
53
+ * default. */
54
+ order: readonly Sort[];
55
+ /** One field, several (`[{ field: "state" }, { field: "amount_total", descending: true }]`),
56
+ * or `null` / `[]` for the entity's default — always a question to the server. */
57
+ orderBy: (order: Sort | readonly Sort[] | null) => void;
40
58
  /** How the set is walked: a page at a time, or «load more» up to a ceiling. */
41
59
  paging: Paging;
42
60
  /** Where the page on screen is — `pages` mode. `from`/`to` count from 1. */
@@ -47,6 +65,10 @@ export type Listing<T> = {
47
65
  to: number;
48
66
  hasPrev: boolean;
49
67
  hasNext: boolean;
68
+ /** The server's cursors that start each page up to this one (`null` is the first) — and
69
+ * the one that starts the next: what a record opened from here walks on (`trailOf`). */
70
+ cursors: readonly (string | null)[];
71
+ after: string | null;
50
72
  };
51
73
  next: () => void;
52
74
  prev: () => void;
@@ -72,4 +94,4 @@ export type ListingOptions<T> = {
72
94
  /** `more` mode: the most rows ever on screen. 500 by default. */
73
95
  maxRows?: number;
74
96
  };
75
- export declare function useListing<T extends AnyRecord>(entity: Entity<T>, options?: ListingOptions<T>): Listing<T>;
97
+ export declare function useListing<T extends AnyRecord>(given: Entity<T> | ListDefinition<T>, own?: ListingOptions<T>): Listing<T>;
@@ -1,6 +1,7 @@
1
1
  "use client";
2
2
  import { merge, resource, resumingFrom, searchOver, } from "@sincpro/criteria";
3
3
  import { useReading } from "@sincpro/criteria-react";
4
+ import { isList, scopeOf } from "../core/list.js";
4
5
  import { useFramework } from "./context.js";
5
6
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
6
7
  /** How long typing has to pause before the search goes out. */
@@ -11,8 +12,19 @@ function routeOf(list, params) {
11
12
  return list;
12
13
  return `${list}${list.includes("?") ? "&" : "?"}${query}`;
13
14
  }
14
- export function useListing(entity, options = {}) {
15
+ export function useListing(given, own = {}) {
15
16
  const { transport, locale, metas } = useFramework();
17
+ // A named list is its entity under a fixed scope: the scope ANDs under the caller's own.
18
+ const definition = isList(given) ? given : undefined;
19
+ const entity = definition?.entity ?? given;
20
+ const options = definition === undefined
21
+ ? own
22
+ : {
23
+ ...own,
24
+ criteria: own.criteria === undefined
25
+ ? scopeOf(definition)
26
+ : merge(scopeOf(definition), own.criteria),
27
+ };
16
28
  const route = routeOf(entity.list, options.params);
17
29
  const source = useMemo(() => resource((criteria, signal) => transport.list(route, criteria, signal)), [transport, route]);
18
30
  // Decided once, at mount: a definition already known means the server is not asked for it
@@ -39,7 +51,7 @@ export function useListing(entity, options = {}) {
39
51
  const [narrowing, setNarrowing] = useState({
40
52
  text: "",
41
53
  where: undefined,
42
- order: null,
54
+ order: [],
43
55
  });
44
56
  const typing = useRef(null);
45
57
  useEffect(() => () => void (typing.current && clearTimeout(typing.current)), []);
@@ -50,8 +62,8 @@ export function useListing(entity, options = {}) {
50
62
  criteria = merge(criteria, { where: found });
51
63
  if (next.where !== undefined)
52
64
  criteria = merge(criteria, { where: next.where });
53
- if (next.order !== null)
54
- criteria = merge(criteria, { order: [next.order] });
65
+ if (next.order.length > 0)
66
+ criteria = merge(criteria, { order: [...next.order] });
55
67
  return criteria;
56
68
  };
57
69
  const refine = useCallback((next) => {
@@ -62,24 +74,51 @@ export function useListing(entity, options = {}) {
62
74
  // `base` is the caller's literal: its identity changes every render, its content does not.
63
75
  // eslint-disable-next-line react-hooks/exhaustive-deps
64
76
  [reading.refine, meta]);
77
+ const latest = useRef(refine);
78
+ latest.current = refine;
79
+ // Typed before the definition arrived: the text had no template to fill, so it asked nothing.
80
+ // The moment the definition is known, the question on screen is asked again — what a person
81
+ // typed is never lost to a slow first answer.
82
+ const typedBeforeModel = useRef(false);
83
+ if (meta === null && narrowing.text !== "")
84
+ typedBeforeModel.current = true;
85
+ useEffect(() => {
86
+ if (meta === null || !typedBeforeModel.current)
87
+ return;
88
+ typedBeforeModel.current = false;
89
+ refine(narrowing);
90
+ // Only the arrival of the definition re-asks; `narrowing` is read as it is then.
91
+ // eslint-disable-next-line react-hooks/exhaustive-deps
92
+ }, [meta]);
65
93
  const index = cursors.length - 1;
66
94
  const turn = (to) => {
67
95
  setCursors(to);
68
96
  void reading.refine(resumingFrom(narrowed(narrowing), to[to.length - 1] ?? null));
69
97
  };
70
98
  const capped = paging === "more" && reading.rows.length >= maxRows;
99
+ // Two changes in one gesture — the builder applies a filter AND an order — must both stand:
100
+ // each starts from the latest, never from the render that made the callback (the second one
101
+ // used to undo the first).
102
+ const now = useRef(narrowing);
103
+ now.current = narrowing;
71
104
  const narrow = (change, debounce) => {
72
- const next = { ...narrowing, ...change };
105
+ const next = { ...now.current, ...change };
106
+ now.current = next;
73
107
  setNarrowing(next);
74
108
  if (typing.current)
75
109
  clearTimeout(typing.current);
110
+ // The pause ends with the refine of THAT moment, not of the keystroke: a model that arrived
111
+ // meanwhile fills the search, instead of a stale refine asking unfiltered (CI found it).
76
112
  if (debounce)
77
- typing.current = setTimeout(() => refine(next), TYPING_PAUSE);
113
+ typing.current = setTimeout(() => latest.current(next), TYPING_PAUSE);
78
114
  else
79
115
  refine(next);
80
116
  };
81
117
  return {
82
118
  entity,
119
+ ...(definition === undefined ? {} : { definition }),
120
+ route,
121
+ question: narrowed(narrowing),
83
122
  rows: reading.rows,
84
123
  meta,
85
124
  count: reading.count,
@@ -94,11 +133,11 @@ export function useListing(entity, options = {}) {
94
133
  },
95
134
  reload: () => void reading.reload(),
96
135
  text: narrowing.text,
97
- search: (text) => narrow({ text }, true),
136
+ search: (text, options) => narrow({ text }, options?.now !== true),
98
137
  where: narrowing.where,
99
138
  filter: (where) => narrow({ where }, false),
100
139
  order: narrowing.order,
101
- orderBy: (order) => narrow({ order }, false),
140
+ orderBy: (order) => narrow({ order: order === null ? [] : Array.isArray(order) ? order : [order] }, false),
102
141
  paging,
103
142
  page: {
104
143
  index,
@@ -107,6 +146,8 @@ export function useListing(entity, options = {}) {
107
146
  to: index * size + reading.rows.length,
108
147
  hasPrev: paging === "pages" && index > 0,
109
148
  hasNext: paging === "pages" && reading.cursor !== null,
149
+ cursors,
150
+ after: reading.cursor,
110
151
  },
111
152
  next: () => {
112
153
  if (paging === "pages" && reading.cursor !== null)
@@ -1,22 +1,47 @@
1
- import type { AnyRecord } from "@sincpro/criteria";
1
+ import type { AnyRecord, Criteria } from "@sincpro/criteria";
2
2
  import type { Entity } from "../core/entity.js";
3
+ import { type ListDefinition } from "../core/list.js";
3
4
  import { type LookupOption } from "../core/lookup.js";
4
5
  /**
5
6
  * The records of an entity as choices — the literal search of a many2one.
6
7
  *
7
8
  * Context: it is a listing like any other — the entity's own search template fills with what
8
- * is typed, debounced, asked of the server — whose rows are read as choices (`lookupOf`). One
9
- * page at a time: a select over ten thousand customers loads the first page and the next on
10
- * demand, never the table.
9
+ * is typed, debounced, asked of the server — whose rows are read as choices (`lookupOf`). It
10
+ * opens on the first TEN in the entity's own order (what Odoo's many2one shows, and what fits
11
+ * a dropdown); typing asks the server, so the record 123 455 of 200 000 is found by its name
12
+ * though it was never among the ten. Never the table.
13
+ *
14
+ * The chosen record usually is NOT on the page on screen — a search narrowed it, or it lies
15
+ * past the first ten — so its name is kept: from the options it was seen among, or asked of
16
+ * the server once by its key (`chosen`).
11
17
  */
12
18
  export type Lookup = {
13
19
  options: LookupOption[];
14
20
  text: string;
15
21
  search: (text: string) => void;
22
+ /** The entity has a literal search template: typing asks the server. Without one the
23
+ * options are filtered where they are. */
24
+ searchable: boolean;
16
25
  loading: boolean;
17
26
  hasMore: boolean;
18
27
  more: () => void;
28
+ /** The chosen record as a choice, whether or not it is among `options`. */
29
+ chosen: LookupOption | undefined;
30
+ /** The chosen records of a many2many (`values`), in their order, each as a choice — those
31
+ * not known yet are asked of the server in one question. */
32
+ chosenAll: LookupOption[];
19
33
  };
20
- export declare function useLookup<T extends AnyRecord>(entity: Entity<T>, options?: {
34
+ export declare function useLookup<T extends AnyRecord>(
35
+ /** The entity, or a named list of it: «active customers» chooses only those. */
36
+ entity: Entity<T> | ListDefinition<T>, options?: {
21
37
  pageSize?: number;
38
+ /**
39
+ * Which records may be chosen at all — the contacts OF the chosen customer, the warehouses
40
+ * OF the branch. The server applies it under whatever is typed; a new scope starts over.
41
+ */
42
+ criteria?: Criteria<T>;
43
+ /** The key of the chosen record, to keep its name (`chosen`). */
44
+ value?: string;
45
+ /** The keys chosen in a many2many, to keep their names (`chosenAll`). */
46
+ values?: readonly string[];
22
47
  }): Lookup;
@@ -1,15 +1,68 @@
1
1
  "use client";
2
+ import { isList } from "../core/list.js";
2
3
  import { lookupOf } from "../core/lookup.js";
4
+ import { useFramework } from "./context.js";
3
5
  import { useListing } from "./useListing.js";
4
- export function useLookup(entity, options = {}) {
6
+ import { useEffect, useRef, useState } from "react";
7
+ /** Ten: what a dropdown shows without scrolling, and what Odoo's many2one asks for. */
8
+ const FIRST = 10;
9
+ export function useLookup(
10
+ /** The entity, or a named list of it: «active customers» chooses only those. */
11
+ entity, options = {}) {
12
+ const { transport } = useFramework();
5
13
  // «More», not pages: a choice list grows downwards, and its ceiling keeps it light.
6
- const listing = useListing(entity, { paging: "more", pageSize: options.pageSize ?? 50 });
14
+ const listing = useListing(entity, {
15
+ paging: "more",
16
+ pageSize: options.pageSize ?? FIRST,
17
+ ...(options.criteria === undefined ? {} : { criteria: options.criteria }),
18
+ });
19
+ const base = isList(entity) ? entity.entity : entity;
20
+ const choices = lookupOf(listing.meta, listing.rows, base.summary);
21
+ // Every choice seen is remembered: the chosen are named even after the page moved on.
22
+ const seen = useRef(new Map());
23
+ for (const one of choices)
24
+ seen.current.set(one.id, one);
25
+ const [, setNamed] = useState(0);
26
+ const value = options.value ?? "";
27
+ const wanted = options.values ?? (value === "" ? [] : [value]);
28
+ const missing = wanted.filter((id) => !seen.current.has(id));
29
+ const missingKey = missing.join("\u0000");
30
+ // Chosen but never seen (a form opened on a saved record): their names, asked ONCE by key.
31
+ const route = base.list;
32
+ const meta = listing.meta;
33
+ useEffect(() => {
34
+ if (missingKey === "" || meta === null)
35
+ return;
36
+ const keys = missingKey.split("\u0000");
37
+ const key = meta.get_id || meta.identity || "id";
38
+ const aborter = new AbortController();
39
+ transport
40
+ .list(route, {
41
+ where: keys.length === 1
42
+ ? { field: key, operator: "=", value: keys[0] ?? "" }
43
+ : { field: key, operator: "in", value: keys },
44
+ pagination: { limit: keys.length },
45
+ meta: false,
46
+ }, aborter.signal)
47
+ .then((page) => {
48
+ for (const one of lookupOf(meta, page.rows, base.summary))
49
+ seen.current.set(one.id, one);
50
+ setNamed((n) => n + 1);
51
+ })
52
+ .catch(() => undefined); // unnamed is not an error: the field shows its key
53
+ return () => aborter.abort();
54
+ }, [transport, route, meta, missingKey, base.summary]);
55
+ const known = value === "" ? undefined : seen.current.get(value);
56
+ const chosenAll = wanted.map((id) => seen.current.get(id) ?? { id, label: id });
7
57
  return {
8
- options: lookupOf(listing.meta, listing.rows),
58
+ options: choices,
9
59
  text: listing.text,
10
60
  search: listing.search,
61
+ searchable: listing.meta?.search != null,
11
62
  loading: listing.status === "loading",
12
63
  hasMore: listing.hasMore,
13
64
  more: listing.more,
65
+ chosen: known,
66
+ chosenAll,
14
67
  };
15
68
  }