@sincpro/web-framework 0.2.0 → 0.4.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 (70) 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 +4 -2
  9. package/dist/core/index.js +4 -2
  10. package/dist/core/lines.d.ts +52 -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/present.js +7 -2
  16. package/dist/core/rest.d.ts +5 -9
  17. package/dist/core/rest.js +14 -6
  18. package/dist/core/transport.d.ts +9 -1
  19. package/dist/core/zone.d.ts +27 -0
  20. package/dist/core/zone.js +75 -0
  21. package/dist/react/context.d.ts +13 -1
  22. package/dist/react/context.js +10 -2
  23. package/dist/react/index.d.ts +2 -1
  24. package/dist/react/index.js +1 -0
  25. package/dist/react/useGroups.d.ts +13 -1
  26. package/dist/react/useGroups.js +48 -7
  27. package/dist/react/useListing.d.ts +8 -4
  28. package/dist/react/useListing.js +11 -5
  29. package/dist/react/usePivot.d.ts +33 -0
  30. package/dist/react/usePivot.js +59 -0
  31. package/dist/react/useRecord.d.ts +13 -9
  32. package/dist/react/useRecord.js +55 -13
  33. package/dist/web/index.d.ts +7 -1
  34. package/dist/web/index.js +7 -1
  35. package/dist/web/list/EntityList.d.ts +46 -7
  36. package/dist/web/list/EntityList.js +132 -21
  37. package/dist/web/list/EntitySearchBar.js +19 -1
  38. package/dist/web/list/columns.d.ts +0 -13
  39. package/dist/web/list/columns.js +20 -1
  40. package/dist/web/list/groups.d.ts +3 -1
  41. package/dist/web/list/groups.js +8 -1
  42. package/dist/web/list/openIn.d.ts +41 -0
  43. package/dist/web/list/openIn.js +55 -0
  44. package/dist/web/list/pivot.d.ts +23 -0
  45. package/dist/web/list/pivot.js +64 -0
  46. package/dist/web/list/presentation.d.ts +51 -0
  47. package/dist/web/list/presentation.js +20 -0
  48. package/dist/web/record/EntityPicker.d.ts +3 -1
  49. package/dist/web/record/EntityPicker.js +15 -5
  50. package/dist/web/record/EntityTags.js +16 -5
  51. package/dist/web/record/RelatedList.d.ts +6 -0
  52. package/dist/web/record/RelatedList.js +26 -2
  53. package/dist/web/record/control.d.ts +43 -0
  54. package/dist/web/record/control.js +67 -0
  55. package/dist/web/record/edit.d.ts +16 -8
  56. package/dist/web/record/edit.js +57 -49
  57. package/dist/web/record/lines.d.ts +84 -0
  58. package/dist/web/record/lines.js +190 -0
  59. package/dist/web/record/opening.d.ts +8 -0
  60. package/dist/web/record/summary.js +14 -6
  61. package/dist/web/workspace/SincproApp.d.ts +4 -1
  62. package/dist/web/workspace/SincproApp.js +2 -2
  63. package/dist/web/workspace/composer.d.ts +2 -1
  64. package/dist/web/workspace/composer.js +27 -16
  65. package/dist/web/workspace/open.d.ts +2 -14
  66. package/dist/web/workspace/open.js +2 -13
  67. package/dist/web/workspace/record.js +6 -3
  68. package/dist/web/workspace/workspace.d.ts +4 -2
  69. package/dist/web/workspace/workspace.js +10 -4
  70. 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
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The time zone a date and time is read and written in — and the two conversions a form needs:
3
+ * the server's instant to the wall clock of that zone, and back.
4
+ *
5
+ * Context: sincpro_framework sends a `datetime` as an instant (`2026-03-12T14:30:00Z`); a person
6
+ * reads and types the wall clock of where the business is (10:30 in La Paz). Which zone that is
7
+ * belongs to whoever is above the screens — the application, the company the user works in —
8
+ * so it is installed once, like the framework's words (`FrameworkProvider timeZone`), and every
9
+ * date and time follows it. Without it, the runtime's. A date with no time (`date`) is a day of
10
+ * the calendar, not an instant: it is never converted.
11
+ */
12
+ /** Install the time zone dates and times are read and written in (IANA: `"America/La_Paz"`);
13
+ * `undefined` goes back to the runtime's. */
14
+ export declare function installTimeZone(timeZone: string | undefined): void;
15
+ /** The time zone in use. */
16
+ export declare function timeZoneNow(): string;
17
+ /** `"2026-03-12T14:30:00Z"` → `"2026-03-12T10:30"` in `America/La_Paz`: the wall clock there,
18
+ * as a date-and-time control reads it. `null` when it is not an instant. */
19
+ export declare function wallTimeOf(instant: string, timeZone: string): string | null;
20
+ /**
21
+ * `"2026-03-12T10:30"` on the wall clock of `timeZone` → the instant, `"2026-03-12T14:30:00.000Z"`.
22
+ * `null` when it is not a wall time.
23
+ *
24
+ * Context: the offset depends on the instant (daylight saving), so it is asked twice: at the
25
+ * first guess, and again at the answer when the guess fell on the other side of a change.
26
+ */
27
+ export declare function instantOf(wall: string, timeZone: string): string | null;
@@ -0,0 +1,75 @@
1
+ /**
2
+ * The time zone a date and time is read and written in — and the two conversions a form needs:
3
+ * the server's instant to the wall clock of that zone, and back.
4
+ *
5
+ * Context: sincpro_framework sends a `datetime` as an instant (`2026-03-12T14:30:00Z`); a person
6
+ * reads and types the wall clock of where the business is (10:30 in La Paz). Which zone that is
7
+ * belongs to whoever is above the screens — the application, the company the user works in —
8
+ * so it is installed once, like the framework's words (`FrameworkProvider timeZone`), and every
9
+ * date and time follows it. Without it, the runtime's. A date with no time (`date`) is a day of
10
+ * the calendar, not an instant: it is never converted.
11
+ */
12
+ let installed;
13
+ /** Install the time zone dates and times are read and written in (IANA: `"America/La_Paz"`);
14
+ * `undefined` goes back to the runtime's. */
15
+ export function installTimeZone(timeZone) {
16
+ installed = timeZone;
17
+ }
18
+ /** The time zone in use. */
19
+ export function timeZoneNow() {
20
+ return installed ?? Intl.DateTimeFormat().resolvedOptions().timeZone;
21
+ }
22
+ const clocks = new Map();
23
+ /** One formatter per zone, kept: building one costs far more than using it. */
24
+ function clockOf(timeZone) {
25
+ let clock = clocks.get(timeZone);
26
+ if (clock === undefined) {
27
+ clock = new Intl.DateTimeFormat("en-US", {
28
+ timeZone,
29
+ hourCycle: "h23",
30
+ year: "numeric",
31
+ month: "2-digit",
32
+ day: "2-digit",
33
+ hour: "2-digit",
34
+ minute: "2-digit",
35
+ second: "2-digit",
36
+ });
37
+ clocks.set(timeZone, clock);
38
+ }
39
+ return clock;
40
+ }
41
+ /** The wall clock of `timeZone` at `at` (ms), as the fields of a UTC date: what to compare. */
42
+ function wallAt(at, timeZone) {
43
+ const parts = Object.fromEntries(clockOf(timeZone)
44
+ .formatToParts(new Date(at))
45
+ .map((part) => [part.type, part.value]));
46
+ return Date.UTC(Number(parts["year"]), Number(parts["month"]) - 1, Number(parts["day"]), Number(parts["hour"]), Number(parts["minute"]), Number(parts["second"]));
47
+ }
48
+ const pad = (n) => String(n).padStart(2, "0");
49
+ /** `"2026-03-12T14:30:00Z"` → `"2026-03-12T10:30"` in `America/La_Paz`: the wall clock there,
50
+ * as a date-and-time control reads it. `null` when it is not an instant. */
51
+ export function wallTimeOf(instant, timeZone) {
52
+ const at = Date.parse(instant);
53
+ if (Number.isNaN(at))
54
+ return null;
55
+ const wall = new Date(wallAt(at, timeZone));
56
+ return (`${wall.getUTCFullYear()}-${pad(wall.getUTCMonth() + 1)}-${pad(wall.getUTCDate())}` +
57
+ `T${pad(wall.getUTCHours())}:${pad(wall.getUTCMinutes())}`);
58
+ }
59
+ /**
60
+ * `"2026-03-12T10:30"` on the wall clock of `timeZone` → the instant, `"2026-03-12T14:30:00.000Z"`.
61
+ * `null` when it is not a wall time.
62
+ *
63
+ * Context: the offset depends on the instant (daylight saving), so it is asked twice: at the
64
+ * first guess, and again at the answer when the guess fell on the other side of a change.
65
+ */
66
+ export function instantOf(wall, timeZone) {
67
+ const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/.exec(wall);
68
+ if (match === null)
69
+ return null;
70
+ const [, year, month, day, hour, minute] = match.map(Number);
71
+ const guess = Date.UTC(year, month - 1, day, hour, minute);
72
+ const first = guess - (wallAt(guess, timeZone) - guess);
73
+ const second = guess - (wallAt(first, timeZone) - first);
74
+ return new Date(second).toISOString();
75
+ }
@@ -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;
@@ -21,7 +29,7 @@ type FrameworkContextValue = {
21
29
  /** Where each open record came from (`Trail`), by the key its reference carries. */
22
30
  trails: Map<string, Trail>;
23
31
  };
24
- export declare function FrameworkProvider({ transport, locale, metas: seed, entities, children, }: {
32
+ export declare function FrameworkProvider({ transport, locale, metas: seed, entities, timeZone, children, }: {
25
33
  transport: Transport;
26
34
  /** The language labels and values are read in (`"es"`); the model's `default` without it. */
27
35
  locale?: string;
@@ -30,6 +38,10 @@ export declare function FrameworkProvider({ transport, locale, metas: seed, enti
30
38
  /** The entities of the application: a form draws a many2one as a picker of the one its
31
39
  * model points at (`relation: "Cliente"`) without being told. */
32
40
  entities?: readonly Entity[];
41
+ /** Where the business is (IANA: `"America/La_Paz"`) — the application's, or the company's
42
+ * the user works in: every date and time reads and is typed on its wall clock. Without it,
43
+ * the browser's. */
44
+ timeZone?: string;
33
45
  children: ReactNode;
34
46
  }): import("react").JSX.Element;
35
47
  export declare function useFramework(): FrameworkContextValue;
@@ -2,9 +2,17 @@
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
3
  import { metaStore } from "../core/metas.js";
4
4
  import { entityFor } from "../core/relation.js";
5
- import { createContext, useContext, useMemo, useState } from "react";
5
+ import { installTimeZone } from "../core/zone.js";
6
+ import { createContext, useContext, useMemo, useRef, useState } from "react";
6
7
  const FrameworkContext = createContext(null);
7
- export function FrameworkProvider({ transport, locale, metas: seed, entities = NO_ENTITIES, children, }) {
8
+ export function FrameworkProvider({ transport, locale, metas: seed, entities = NO_ENTITIES, timeZone, children, }) {
9
+ // Installed before the children draw, and again when it changes (another company): the
10
+ // formatters read it, so it cannot wait for an effect.
11
+ const zoned = useRef(null);
12
+ if (zoned.current !== timeZone) {
13
+ installTimeZone(timeZone);
14
+ zoned.current = timeZone;
15
+ }
8
16
  // One store for the provider's life: a new seed object on a re-render must not forget what
9
17
  // the screens already learned.
10
18
  const [metas] = useState(() => metaStore(seed));
@@ -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>;