@sincpro/web-framework 0.2.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 (64) hide show
  1. package/README.md +56 -19
  2. package/dist/core/copy.d.ts +2 -0
  3. package/dist/core/copy.js +2 -0
  4. package/dist/core/edit.d.ts +35 -3
  5. package/dist/core/edit.js +49 -5
  6. package/dist/core/entity.d.ts +14 -2
  7. package/dist/core/entity.js +33 -1
  8. package/dist/core/index.d.ts +3 -2
  9. package/dist/core/index.js +3 -2
  10. package/dist/core/lines.d.ts +53 -0
  11. package/dist/core/lines.js +120 -0
  12. package/dist/core/list.d.ts +1 -1
  13. package/dist/core/lookup.d.ts +2 -0
  14. package/dist/core/lookup.js +3 -1
  15. package/dist/core/rest.d.ts +5 -9
  16. package/dist/core/rest.js +14 -6
  17. package/dist/core/transport.d.ts +9 -1
  18. package/dist/react/context.d.ts +8 -0
  19. package/dist/react/index.d.ts +2 -1
  20. package/dist/react/index.js +1 -0
  21. package/dist/react/useGroups.d.ts +13 -1
  22. package/dist/react/useGroups.js +48 -7
  23. package/dist/react/useListing.d.ts +8 -4
  24. package/dist/react/useListing.js +11 -5
  25. package/dist/react/usePivot.d.ts +33 -0
  26. package/dist/react/usePivot.js +59 -0
  27. package/dist/react/useRecord.d.ts +13 -9
  28. package/dist/react/useRecord.js +55 -13
  29. package/dist/web/index.d.ts +7 -1
  30. package/dist/web/index.js +7 -1
  31. package/dist/web/list/EntityList.d.ts +46 -7
  32. package/dist/web/list/EntityList.js +132 -21
  33. package/dist/web/list/EntitySearchBar.js +19 -1
  34. package/dist/web/list/columns.d.ts +0 -13
  35. package/dist/web/list/columns.js +20 -1
  36. package/dist/web/list/groups.d.ts +3 -1
  37. package/dist/web/list/groups.js +8 -1
  38. package/dist/web/list/openIn.d.ts +41 -0
  39. package/dist/web/list/openIn.js +55 -0
  40. package/dist/web/list/pivot.d.ts +23 -0
  41. package/dist/web/list/pivot.js +64 -0
  42. package/dist/web/list/presentation.d.ts +51 -0
  43. package/dist/web/list/presentation.js +20 -0
  44. package/dist/web/record/EntityPicker.d.ts +3 -1
  45. package/dist/web/record/EntityPicker.js +15 -5
  46. package/dist/web/record/EntityTags.js +16 -5
  47. package/dist/web/record/RelatedList.d.ts +6 -0
  48. package/dist/web/record/RelatedList.js +26 -2
  49. package/dist/web/record/control.d.ts +42 -0
  50. package/dist/web/record/control.js +60 -0
  51. package/dist/web/record/edit.d.ts +16 -8
  52. package/dist/web/record/edit.js +57 -49
  53. package/dist/web/record/lines.d.ts +84 -0
  54. package/dist/web/record/lines.js +190 -0
  55. package/dist/web/record/opening.d.ts +8 -0
  56. package/dist/web/record/summary.js +14 -6
  57. package/dist/web/workspace/composer.d.ts +2 -1
  58. package/dist/web/workspace/composer.js +27 -16
  59. package/dist/web/workspace/open.d.ts +2 -14
  60. package/dist/web/workspace/open.js +2 -13
  61. package/dist/web/workspace/record.js +6 -3
  62. package/dist/web/workspace/workspace.d.ts +4 -2
  63. package/dist/web/workspace/workspace.js +10 -4
  64. package/package.json +9 -9
package/dist/core/rest.js CHANGED
@@ -1,4 +1,5 @@
1
- import { pageFrom, plain, readProblem, } from "@sincpro/criteria";
1
+ import { readProblem } from "@sincpro/criteria";
2
+ import { RestError, restSource } from "@sincpro/criteria/rest";
2
3
  import { TransportError, } from "./transport.js";
3
4
  /** The keys of an answer that are not the record: what is left is the record's own field. */
4
5
  const ENVELOPE = new Set(["cursor", "count", "entity_meta_data", "dropped", "draft"]);
@@ -12,15 +13,15 @@ export function urlOf(base, route, criteria) {
12
13
  export function restTransport(options = {}) {
13
14
  const base = options.base ?? "";
14
15
  const doFetch = options.fetch ?? ((input, init) => fetch(input, init));
16
+ const own = () => typeof options.headers === "function" ? options.headers() : (options.headers ?? {});
15
17
  async function get(route, url, signal, write) {
16
- const own = typeof options.headers === "function" ? options.headers() : (options.headers ?? {});
17
18
  const headers = write
18
19
  ? {
19
- ...own,
20
+ ...own(),
20
21
  "Content-Type": "application/json",
21
22
  ...(write.key === undefined ? {} : { "Idempotency-Key": write.key }),
22
23
  }
23
- : own;
24
+ : own();
24
25
  const response = await doFetch(url, {
25
26
  headers,
26
27
  ...(write ? { method: write.method, body: JSON.stringify(write.body) } : {}),
@@ -33,8 +34,15 @@ export function restTransport(options = {}) {
33
34
  }
34
35
  return {
35
36
  async list(route, criteria, signal) {
36
- const answer = await get(route, urlOf(base, route, plain(criteria)), signal);
37
- return pageFrom(answer);
37
+ const source = restSource(`${base}${route}`, { headers: own, fetch: doFetch });
38
+ try {
39
+ return await source.read(criteria, signal);
40
+ }
41
+ catch (error) {
42
+ if (error instanceof RestError)
43
+ throw new TransportError(route, error.status, error.problem, undefined);
44
+ throw error;
45
+ }
38
46
  },
39
47
  async one(route, signal) {
40
48
  const answer = (await get(route, urlOf(base, route), signal));
@@ -41,10 +41,18 @@ export type One<T> = {
41
41
  draft: Draft | null;
42
42
  };
43
43
  /** A kept edit: the values typed, the version of the draft, the record version it started on. */
44
+ /**
45
+ * The caller's draft of a record (sincpro_framework's `DraftState`): the version the next edit
46
+ * names, the stored version it started from, and whether the record moved on since (`stale`).
47
+ * `values` only when a server answers them apart from the record — sincpro_framework answers the
48
+ * record FROM the draft instead.
49
+ */
44
50
  export type Draft = {
45
- values: Record<string, unknown>;
51
+ values?: Record<string, unknown>;
46
52
  version: number;
47
53
  origin_version?: number;
54
+ kept_at?: string;
55
+ stale?: boolean;
48
56
  };
49
57
  /**
50
58
  * A refusal, from any wire. `problem` is what the server said about it (RFC 9457 plus the
@@ -11,6 +11,14 @@ import { type ReactNode } from "react";
11
11
  * Context: a view receives its record reference and nothing else — the composer hands it no
12
12
  * client on purpose — so the transport reaches it through context, set once where the
13
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.
14
22
  */
15
23
  type FrameworkContextValue = {
16
24
  transport: Transport;
@@ -9,6 +9,7 @@ export { type Groups, useGroups } from "./useGroups.js";
9
9
  export { useHistory } from "./useHistory.js";
10
10
  export { type Listing, type ListingOptions, type Paging, useListing, } from "./useListing.js";
11
11
  export { type Lookup, useLookup } from "./useLookup.js";
12
- 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";
13
14
  export { useRelated } from "./useRelated.js";
14
15
  export { useSummaryOf } from "./useSummary.js";
@@ -9,6 +9,7 @@ export { useGroups } from "./useGroups.js";
9
9
  export { useHistory } from "./useHistory.js";
10
10
  export { useListing, } from "./useListing.js";
11
11
  export { useLookup } from "./useLookup.js";
12
+ export { usePivot, } from "./usePivot.js";
12
13
  export { useRecord, } from "./useRecord.js";
13
14
  export { useRelated } from "./useRelated.js";
14
15
  export { useSummaryOf } from "./useSummary.js";
@@ -1,4 +1,4 @@
1
- import type { AnyRecord, Bucket } from "@sincpro/criteria";
1
+ import { type AnyRecord, type Bucket } from "@sincpro/criteria";
2
2
  import type { GroupLevel } from "../core/list.js";
3
3
  import type { Listing } from "./useListing.js";
4
4
  /**
@@ -31,10 +31,22 @@ export type Groups<T> = {
31
31
  open: (bucket: Bucket<T>) => void;
32
32
  /** The rows of a group once read; `undefined` while it was never opened or is loading. */
33
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;
34
43
  };
35
44
  export declare function useGroups<T extends AnyRecord>(listing: Listing<T>, options?: {
36
45
  pageSize?: number;
37
46
  /** The fields each group adds up, over every row of it (`detailOf` reads them). Without
38
47
  * it, the figures the model computes (`sumsOf`); `[]` adds nothing up. */
39
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;
40
52
  }): Groups<T>;
@@ -1,7 +1,8 @@
1
1
  "use client";
2
+ import { resumingFrom } from "@sincpro/criteria";
2
3
  import { measuresOf, sumsOf } from "../core/measure.js";
3
4
  import { useFramework } from "./context.js";
4
- import { useCallback, useEffect, useState } from "react";
5
+ import { useCallback, useEffect, useRef, useState } from "react";
5
6
  /** The most groups a level answers: a split into ten thousand groups is a list, not a split. */
6
7
  const MAX_GROUPS = 100;
7
8
  /** A group is known by its criteria: unique per group, and stable across renders. */
@@ -12,7 +13,10 @@ export function useGroups(listing, options = {}) {
12
13
  const [levels, setLevels] = useState(() => listing.definition?.groupBy ?? []);
13
14
  const [state, setState] = useState({ status: "idle", buckets: [], error: null });
14
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());
15
18
  const pageSize = options.pageSize ?? 50;
19
+ const maxRows = options.maxRows ?? 500;
16
20
  // The question without what pages it: a cursor or a limit of rows has no meaning for groups.
17
21
  const { pagination: _page, ...asked } = listing.question;
18
22
  const question = JSON.stringify(asked);
@@ -23,6 +27,7 @@ export function useGroups(listing, options = {}) {
23
27
  const waiting = options.sums === undefined && listing.meta === null;
24
28
  useEffect(() => {
25
29
  setRows(new Map());
30
+ reading.current.clear();
26
31
  if (levels.length === 0) {
27
32
  setState({ status: "idle", buckets: [], error: null });
28
33
  return;
@@ -51,19 +56,55 @@ export function useGroups(listing, options = {}) {
51
56
  });
52
57
  return () => aborter.abort();
53
58
  }, [transport, route, question, levels, sums, waiting]);
54
- const open = useCallback((bucket) => {
59
+ /** One page of a group: the first (`after` null) or the one the cursor points at. */
60
+ const read = useCallback((bucket, after) => {
55
61
  const key = keyOf(bucket);
56
- const { grouping: _grouping, pagination: _pagination, ...criteria } = bucket.criteria;
57
- void transport
58
- .list(route, { ...criteria, meta: false, pagination: { limit: pageSize } })
59
- .then((page) => setRows((now) => new Map(now).set(key, page.rows)), (error) => setState((now) => ({ ...now, error })));
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
+ });
60
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
+ };
61
87
  return {
62
88
  levels,
63
89
  group: setLevels,
64
90
  ...state,
65
91
  capped: state.buckets.length >= MAX_GROUPS,
66
92
  open,
67
- rowsOf: (bucket) => rows.get(keyOf(bucket)),
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
+ },
68
109
  };
69
110
  }
@@ -11,7 +11,8 @@ import { type ListDefinition } from "../core/list.js";
11
11
  *
12
12
  * search(text) the entity's own search template (`meta.search`), as the server fills it
13
13
  * filter(where) what a search bar or a criteria builder put — any depth of all/any/negate
14
- * 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
15
16
  *
16
17
  * All three refine the same reading instead of starting another. It holds state and draws
17
18
  * nothing: `EntityList` draws it, and a screen that needs another shape draws it itself.
@@ -48,9 +49,12 @@ export type Listing<T> = {
48
49
  /** What the search bar put; `undefined` is nothing. */
49
50
  where: Expression<T> | undefined;
50
51
  filter: (where: Expression<T> | undefined) => void;
51
- /** The order the server was asked for; `null` is the entity's own default. */
52
- order: Sort | null;
53
- 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;
54
58
  /** How the set is walked: a page at a time, or «load more» up to a ceiling. */
55
59
  paging: Paging;
56
60
  /** Where the page on screen is — `pages` mode. `from`/`to` count from 1. */
@@ -51,7 +51,7 @@ export function useListing(given, own = {}) {
51
51
  const [narrowing, setNarrowing] = useState({
52
52
  text: "",
53
53
  where: undefined,
54
- order: null,
54
+ order: [],
55
55
  });
56
56
  const typing = useRef(null);
57
57
  useEffect(() => () => void (typing.current && clearTimeout(typing.current)), []);
@@ -62,8 +62,8 @@ export function useListing(given, own = {}) {
62
62
  criteria = merge(criteria, { where: found });
63
63
  if (next.where !== undefined)
64
64
  criteria = merge(criteria, { where: next.where });
65
- if (next.order !== null)
66
- criteria = merge(criteria, { order: [next.order] });
65
+ if (next.order.length > 0)
66
+ criteria = merge(criteria, { order: [...next.order] });
67
67
  return criteria;
68
68
  };
69
69
  const refine = useCallback((next) => {
@@ -96,8 +96,14 @@ export function useListing(given, own = {}) {
96
96
  void reading.refine(resumingFrom(narrowed(narrowing), to[to.length - 1] ?? null));
97
97
  };
98
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;
99
104
  const narrow = (change, debounce) => {
100
- const next = { ...narrowing, ...change };
105
+ const next = { ...now.current, ...change };
106
+ now.current = next;
101
107
  setNarrowing(next);
102
108
  if (typing.current)
103
109
  clearTimeout(typing.current);
@@ -131,7 +137,7 @@ export function useListing(given, own = {}) {
131
137
  where: narrowing.where,
132
138
  filter: (where) => narrow({ where }, false),
133
139
  order: narrowing.order,
134
- orderBy: (order) => narrow({ order }, false),
140
+ orderBy: (order) => narrow({ order: order === null ? [] : Array.isArray(order) ? order : [order] }, false),
135
141
  paging,
136
142
  page: {
137
143
  index,
@@ -0,0 +1,33 @@
1
+ import type { AnyRecord, Bucket } from "@sincpro/criteria";
2
+ import type { GroupLevel } from "../core/list.js";
3
+ import type { Listing } from "./useListing.js";
4
+ /**
5
+ * A list's set crossed by two fields — state by month, customer by payment — counted and added
6
+ * up by the SERVER over every row that matches, never the page.
7
+ *
8
+ * Context: web-ui draws a pivot two ways: `spec` folds the rows IN HAND, `folded` draws one
9
+ * already folded. Folding the page would answer «12 paid» for a set of 187 — the rule of
10
+ * grouping (`AGENTS.md`). So the listing's question (scope, search, filter) goes to the server
11
+ * twice: grouped by both axes (each crossing, and each row's total in the outer group), and by
12
+ * the columns alone (each column's total). No cell is added up here.
13
+ *
14
+ * const pivot = usePivot(listing, { rows: { field: "state" }, columns: { field: "payment" } });
15
+ * pivot.crossed // [{ value: "paid", count: 187, measures, groups: [{ value: "cash", … }] }]
16
+ * pivot.columns // [{ value: "cash", count: 340, measures }, …]
17
+ */
18
+ export type PivotAxes = {
19
+ rows: GroupLevel;
20
+ columns: GroupLevel;
21
+ /** The fields added up in each crossing. Without it, the figures the model computes. */
22
+ measures?: readonly string[];
23
+ };
24
+ export type PivotReading<T> = {
25
+ status: "idle" | "loading" | "ready" | "failed";
26
+ /** Grouped by rows, then columns: a crossing is a row's group's group. */
27
+ crossed: readonly Bucket<T>[];
28
+ /** Grouped by the columns alone: each column's total. */
29
+ columns: readonly Bucket<T>[];
30
+ measures: readonly string[];
31
+ error: unknown;
32
+ };
33
+ export declare function usePivot<T extends AnyRecord>(listing: Listing<T>, axes: PivotAxes | null): PivotReading<T>;
@@ -0,0 +1,59 @@
1
+ "use client";
2
+ import { measuresOf, sumsOf } from "../core/measure.js";
3
+ import { useFramework } from "./context.js";
4
+ import { useEffect, useState } from "react";
5
+ /** The most groups an axis answers: a pivot of ten thousand rows is a list. */
6
+ const MAX_KEYS = 100;
7
+ export function usePivot(listing, axes) {
8
+ const { transport } = useFramework();
9
+ const [state, setState] = useState({
10
+ status: "idle",
11
+ crossed: [],
12
+ columns: [],
13
+ error: null,
14
+ });
15
+ const { pagination: _page, ...asked } = listing.question;
16
+ const question = JSON.stringify(asked);
17
+ const measures = axes?.measures ?? sumsOf(listing.meta);
18
+ const sums = measures.join(",");
19
+ const shape = axes === null ? "" : JSON.stringify([axes.rows, axes.columns]);
20
+ const waiting = axes !== null && axes.measures === undefined && listing.meta === null;
21
+ useEffect(() => {
22
+ if (shape === "") {
23
+ setState({ status: "idle", crossed: [], columns: [], error: null });
24
+ return;
25
+ }
26
+ const aborter = new AbortController();
27
+ setState((now) => ({ ...now, status: "loading", error: null }));
28
+ if (waiting)
29
+ return () => aborter.abort();
30
+ const [rows, columns] = JSON.parse(shape);
31
+ const grouped = (levels) => ({
32
+ ...JSON.parse(question),
33
+ meta: false,
34
+ grouping: {
35
+ group_by: levels.map((level) => ({ ...level })),
36
+ ...(sums === "" ? {} : { measures: measuresOf(sums.split(",")) }),
37
+ pagination: { limit: MAX_KEYS },
38
+ },
39
+ pagination: { limit: 1 },
40
+ });
41
+ Promise.all([
42
+ transport.list(listing.route, grouped([rows, columns]), aborter.signal),
43
+ transport.list(listing.route, grouped([columns]), aborter.signal),
44
+ ]).then(([crossed, byColumn]) => {
45
+ if (!aborter.signal.aborted)
46
+ setState({
47
+ status: "ready",
48
+ crossed: crossed.rows,
49
+ columns: byColumn.rows,
50
+ error: null,
51
+ });
52
+ }, (error) => {
53
+ if (!aborter.signal.aborted)
54
+ setState({ status: "failed", crossed: [], columns: [], error });
55
+ });
56
+ return () => aborter.abort();
57
+ }, [transport, listing.route, question, shape, sums, waiting]);
58
+ return { ...state, measures };
59
+ }
@@ -1,6 +1,6 @@
1
1
  import type { AnyRecord, Meta } from "@sincpro/criteria";
2
- import { type FieldState } from "../core/edit.js";
3
- import { type Entity } from "../core/entity.js";
2
+ import { type Advice, type FieldState } from "../core/edit.js";
3
+ import { type Entity, type EntityRef } from "../core/entity.js";
4
4
  import { type Draft } from "../core/transport.js";
5
5
  /**
6
6
  * ONE record of an entity, with the definition of its model — read, and edited.
@@ -22,10 +22,13 @@ import { type Draft } from "../core/transport.js";
22
22
  * defaults the model publishes, previews like any other, and `save()` sends it to the
23
23
  * entity's `create` route with an `Idempotency-Key` (a retry never creates two). When the
24
24
  * answer carries the new identity, the hook becomes that record; otherwise `edit.created`
25
- * holds the answer and the screen decides where to go.
25
+ * holds the answer and the screen decides where to go. Given the REFERENCE it was opened
26
+ * with, a new record starts with what the reference carries over the defaults
27
+ * (`newRef(values)`): an invoice created from its customer starts with that customer.
26
28
  *
27
29
  * const invoice = useRecord(invoices, ""); // a new one
28
30
  * const invoice = useRecord(invoices, "F-2026-7"); // an existing one
31
+ * const invoice = useRecord(invoices, resource); // what the workspace opened
29
32
  */
30
33
  export type RecordState<T> = {
31
34
  status: "loading";
@@ -43,10 +46,6 @@ export type RecordState<T> = {
43
46
  meta: Meta | null;
44
47
  error: unknown;
45
48
  };
46
- export type Advice = {
47
- field?: string;
48
- text: string;
49
- };
50
49
  export type Editing = {
51
50
  /** The record as on screen: what was read, what the server computed, what was typed. */
52
51
  values: AnyRecord;
@@ -54,8 +53,13 @@ export type Editing = {
54
53
  dirty: boolean;
55
54
  set: (name: string, value: unknown) => void;
56
55
  state: (name: string) => FieldState;
57
- /** The server's word on fields that did not validate, by field. */
56
+ /** A cell of a list of records — line `index` of `name`, its `field`: the line model's hints
57
+ * over that line, refined by what the server's preview said of it (`items[index]`). */
58
+ cell: (name: string, index: number, field: string) => FieldState;
59
+ /** The server's word on what did not validate, by where it points (`pathOf`): `discount`,
60
+ * `lines/1/qty`. Read a field's — its lines' included — with `errorAt`. */
58
61
  errors: Record<string, string>;
62
+ /** What the server's preview warned about, each with where it points; `adviceAt` places it. */
59
63
  advice: Advice[];
60
64
  /** Required, visible, editable and empty: what blocks a save. */
61
65
  missing: string[];
@@ -86,4 +90,4 @@ export type RecordReading<T> = RecordState<T> & {
86
90
  reload: () => void;
87
91
  edit: Editing;
88
92
  };
89
- export declare function useRecord<T extends AnyRecord>(entity: Entity<T>, given: string): RecordReading<T>;
93
+ export declare function useRecord<T extends AnyRecord>(entity: Entity<T>, opened: string | EntityRef): RecordReading<T>;
@@ -1,14 +1,19 @@
1
1
  "use client";
2
- import { changesOf, creationOf, defaultsOf, errorsByField, fieldStateOf, missingOf, } from "../core/edit.js";
3
- import { pathFor } from "../core/entity.js";
2
+ import { changesOf, creationOf, defaultsOf, errorsByField, fieldStateOf, lineStatesOf, missingOf, } from "../core/edit.js";
3
+ import { pathFor, startingValuesOf, WITH_PARAM, } from "../core/entity.js";
4
+ import { linesAnswered } from "../core/lines.js";
4
5
  import { retryKeys } from "../core/retry.js";
5
6
  import { TransportError } from "../core/transport.js";
6
7
  import { useFramework } from "./context.js";
7
8
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
8
9
  /** How long typing has to pause before the server is asked what the record becomes. */
9
10
  const PREVIEW_PAUSE = 300;
10
- export function useRecord(entity, given) {
11
+ export function useRecord(entity, opened) {
11
12
  const { transport, locale, metas } = useFramework();
13
+ const given = typeof opened === "string" ? opened : (opened.id ?? "");
14
+ // As written in the reference: a text compares by value, so a new render with the same
15
+ // reference is not a new start.
16
+ const start = typeof opened === "string" ? undefined : opened.params?.[WITH_PARAM];
12
17
  // A create that answered its identity turns this into that record — until the screen asks
13
18
  // for another one.
14
19
  const [born, setBorn] = useState(null);
@@ -78,9 +83,10 @@ export function useRecord(entity, given) {
78
83
  forget();
79
84
  setDraft(null);
80
85
  setReadFor(id);
86
+ const starting = start === undefined ? {} : startingValuesOf({ params: { [WITH_PARAM]: start } });
81
87
  setState({
82
88
  status: "ready",
83
- record: defaultsOf(meta),
89
+ record: { ...defaultsOf(meta), ...starting },
84
90
  meta: meta ?? null,
85
91
  error: null,
86
92
  });
@@ -100,7 +106,9 @@ export function useRecord(entity, given) {
100
106
  forget();
101
107
  setReadFor(id);
102
108
  setDraft(answer.draft);
103
- if (answer.draft)
109
+ // A server that answers the record FROM the draft (sincpro_framework) sends no values
110
+ // apart: the record is the draft. One that sends them apart, they are what was typed.
111
+ if (answer.draft?.values)
104
112
  setTyped(answer.draft.values);
105
113
  setState({
106
114
  status: "ready",
@@ -118,7 +126,7 @@ export function useRecord(entity, given) {
118
126
  // `forget` only resets this hook's own state; listing it would reload the record on every
119
127
  // render. What reloads it is the transport, the entity, the id or an explicit `reload()`.
120
128
  // eslint-disable-next-line react-hooks/exhaustive-deps
121
- }, [transport, metas, entity, id, isNew, round]);
129
+ }, [transport, metas, entity, id, isNew, start, round]);
122
130
  useEffect(() => {
123
131
  mounted.current = true;
124
132
  return () => {
@@ -148,9 +156,22 @@ export function useRecord(entity, given) {
148
156
  .then((answer) => {
149
157
  if (aborter.signal.aborted || !mounted.current)
150
158
  return;
151
- setComputed(answer.values ?? {});
152
- setFromServer(answer.fields ?? {});
153
- setAdvice(answer.advice ?? []);
159
+ // A list the form sent (the lines) comes back computed — subtotals — as a whole:
160
+ // it takes the place of what was typed, each line keeping its key by position (a
161
+ // new line has no id to be found by). Typing again cancels an answer in flight, so
162
+ // `next` is still what is on screen.
163
+ const fresh = answer.values ?? {};
164
+ const lists = Object.keys(fresh).filter((key) => Array.isArray(fresh[key]) && Array.isArray(next[key]));
165
+ if (lists.length > 0)
166
+ setTyped((now) => {
167
+ const out = { ...now };
168
+ for (const key of lists)
169
+ out[key] = linesAnswered(next[key], fresh[key]);
170
+ return out;
171
+ });
172
+ setComputed(Object.fromEntries(Object.entries(fresh).filter(([key]) => !lists.includes(key))));
173
+ setFromServer(answer.states ?? {});
174
+ setAdvice(answer.warnings ?? []);
154
175
  }, () => undefined);
155
176
  }, PREVIEW_PAUSE);
156
177
  };
@@ -170,13 +191,20 @@ export function useRecord(entity, given) {
170
191
  ask(next, name);
171
192
  },
172
193
  state: (name) => fieldStateOf(state.meta, name, values, fromServer),
194
+ cell: (name, index, field) => {
195
+ const line = (Array.isArray(values[name]) ? values[name] : [])[index];
196
+ const definition = state.meta?.fields[name]?.definition;
197
+ return fieldStateOf(definition, field, line ?? {}, lineStatesOf(fromServer, name)[index]);
198
+ },
173
199
  errors: failure instanceof TransportError ? errorsByField(failure.problem?.errors) : {},
174
200
  advice,
175
201
  missing: missingOf(state.meta, values, fromServer),
176
202
  saving,
177
203
  failure,
178
204
  conflict,
179
- restored: draft !== null && Object.keys(changed).length > 0,
205
+ // Restored: the draft's values were put back over the record (they came apart), or the
206
+ // record itself was answered from the draft (sincpro_framework: no values apart).
207
+ restored: draft !== null && (draft.values === undefined || Object.keys(changed).length > 0),
180
208
  draft,
181
209
  save: async () => {
182
210
  if (isNew)
@@ -215,12 +243,26 @@ export function useRecord(entity, given) {
215
243
  : {
216
244
  keep: async () => {
217
245
  const route = entity.draft;
246
+ // sincpro_framework's `Edit`: the record as the form holds it, whole; the fields
247
+ // changed; the draft version read (`0`: none) — another tab that kept first wins —,
248
+ // and the stored version the edit started from.
218
249
  try {
219
250
  const kept = await transport.send(route.method, pathFor(route, id), {
220
- values: changed,
221
- expected: draft?.version ?? 0,
251
+ id,
252
+ values,
253
+ changed: Object.keys(changed),
254
+ version: draft?.version ?? 0,
255
+ ...(typeof version === "number" ? { origin_version: version } : {}),
222
256
  });
223
- setDraft(kept);
257
+ const now = kept.draft;
258
+ if (now)
259
+ setDraft({
260
+ values: changed,
261
+ version: now.version,
262
+ ...(now.origin_version === undefined
263
+ ? {}
264
+ : { origin_version: now.origin_version }),
265
+ });
224
266
  }
225
267
  catch (error) {
226
268
  refused(error);
@@ -2,15 +2,21 @@
2
2
  * The web bindings: what draws a `Listing` and a record with `@sincpro/web-ui`.
3
3
  */
4
4
  export { type ColumnOptions, columnsOf } from "./list/columns.js";
5
- export { EntityList, type EntityListProps } from "./list/EntityList.js";
5
+ export { type EntityFace, EntityList, type EntityListProps, type View, } from "./list/EntityList.js";
6
6
  export { EntitySearchBar } from "./list/EntitySearchBar.js";
7
7
  export { groupableOf, pilesOf } from "./list/groups.js";
8
+ export { OpenInMenu } from "./list/openIn.js";
9
+ export { pivotOf } from "./list/pivot.js";
10
+ export { type CardLook, type OptionLook, type Presentation, presentationOf, type Presented, presented, type RowLook, } from "./list/presentation.js";
8
11
  export { type RowCommand, type RowCommands, useRowCommands, } from "./list/rowCommands.js";
9
12
  export { facetsOf, modelOf } from "./list/search.js";
10
13
  export { CommandButton } from "./record/CommandButton.js";
14
+ export { RelationPicker } from "./record/control.js";
11
15
  export { dirtyOf, type FieldControl, RecordField, } from "./record/edit.js";
12
16
  export { EntityPicker } from "./record/EntityPicker.js";
13
17
  export { EntityTags } from "./record/EntityTags.js";
18
+ export { type LineColumn, type LineControl, type LinesLook, RecordLinesEditor, } from "./record/lines.js";
19
+ export { type RecordOpening, RecordOpeningProvider, useRecordOpening, } from "./record/opening.js";
14
20
  export { countOf, factsOf, RecordLines } from "./record/record.js";
15
21
  export { RelatedList } from "./record/RelatedList.js";
16
22
  export { cardOf, relationOf } from "./record/summary.js";
package/dist/web/index.js CHANGED
@@ -2,15 +2,21 @@
2
2
  * The web bindings: what draws a `Listing` and a record with `@sincpro/web-ui`.
3
3
  */
4
4
  export { columnsOf } from "./list/columns.js";
5
- export { EntityList } from "./list/EntityList.js";
5
+ export { EntityList, } from "./list/EntityList.js";
6
6
  export { EntitySearchBar } from "./list/EntitySearchBar.js";
7
7
  export { groupableOf, pilesOf } from "./list/groups.js";
8
+ export { OpenInMenu } from "./list/openIn.js";
9
+ export { pivotOf } from "./list/pivot.js";
10
+ export { presentationOf, presented, } from "./list/presentation.js";
8
11
  export { useRowCommands, } from "./list/rowCommands.js";
9
12
  export { facetsOf, modelOf } from "./list/search.js";
10
13
  export { CommandButton } from "./record/CommandButton.js";
14
+ export { RelationPicker } from "./record/control.js";
11
15
  export { dirtyOf, RecordField, } from "./record/edit.js";
12
16
  export { EntityPicker } from "./record/EntityPicker.js";
13
17
  export { EntityTags } from "./record/EntityTags.js";
18
+ export { RecordLinesEditor, } from "./record/lines.js";
19
+ export { RecordOpeningProvider, useRecordOpening, } from "./record/opening.js";
14
20
  export { countOf, factsOf, RecordLines } from "./record/record.js";
15
21
  export { RelatedList } from "./record/RelatedList.js";
16
22
  export { cardOf, relationOf } from "./record/summary.js";