@sincpro/web-framework 4.0.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +37 -28
  2. package/dist/core/index.d.ts +4 -2
  3. package/dist/core/index.js +4 -2
  4. package/dist/core/models.d.ts +16 -0
  5. package/dist/core/models.js +18 -0
  6. package/dist/core/names.js +2 -1
  7. package/dist/core/queries.d.ts +73 -0
  8. package/dist/core/queries.js +159 -0
  9. package/dist/core/server.d.ts +24 -36
  10. package/dist/core/server.js +36 -36
  11. package/dist/react/context.d.ts +3 -0
  12. package/dist/react/context.js +23 -1
  13. package/dist/react/hydration.d.ts +20 -0
  14. package/dist/react/hydration.js +23 -0
  15. package/dist/react/index.d.ts +4 -2
  16. package/dist/react/index.js +4 -2
  17. package/dist/react/useBatchCommand.js +2 -1
  18. package/dist/react/useHistory.js +2 -1
  19. package/dist/react/useListing.js +3 -2
  20. package/dist/react/useLookup.js +3 -2
  21. package/dist/react/useQueryCache.d.ts +13 -0
  22. package/dist/react/useQueryCache.js +16 -0
  23. package/dist/react/useRecord.js +5 -4
  24. package/dist/react/useRunning.d.ts +32 -0
  25. package/dist/react/{useService.js → useRunning.js} +3 -14
  26. package/dist/react/useServiceCommand.d.ts +42 -0
  27. package/dist/react/useServiceCommand.js +41 -0
  28. package/dist/react/useServiceQuery.d.ts +46 -0
  29. package/dist/react/useServiceQuery.js +79 -0
  30. package/dist/react/useSummary.js +2 -1
  31. package/dist/web/list/records.js +4 -3
  32. package/dist/web/record/ActionButton.d.ts +1 -1
  33. package/dist/web/record/CommandButton.js +2 -1
  34. package/dist/web/record/EntityPicker.js +2 -1
  35. package/dist/web/record/EntityTags.js +3 -2
  36. package/dist/web/record/ServiceButton.d.ts +1 -1
  37. package/dist/web/record/ServiceButton.js +9 -4
  38. package/dist/web/record/choice.js +2 -1
  39. package/dist/web/record/edit.js +2 -1
  40. package/dist/web/record/lines.js +2 -1
  41. package/dist/web/workspace/composer.d.ts +2 -2
  42. package/dist/web/workspace/composer.js +3 -1
  43. package/package.json +3 -3
  44. package/dist/react/useService.d.ts +0 -42
  45. package/dist/react/useServiceReading.d.ts +0 -51
  46. package/dist/react/useServiceReading.js +0 -88
@@ -1,50 +1,50 @@
1
1
  import { describeFailure, logger, outcomeOf, readRecord, screensOperations, } from "@sincpro/client-framework";
2
+ import { queryKeyOf, } from "./queries.js";
2
3
  /**
3
- * A use case's answer read on the server that renders a page, before it is drawn — the very use
4
- * case the page reads with in the browser (`useServiceReading`), so the page arrives with its
5
- * data in the HTML (what a search engine, a crawler and a shared link read) and the browser does
6
- * not ask again.
4
+ * Prefetches, on the server that renders a page, the queries its screens will run — the very
5
+ * Commands they run with `useServiceQuery` —, so the page arrives with its data in the HTML (what
6
+ * a search engine, a crawler and a shared link read) and the browser does not fetch them again.
7
7
  *
8
- * // the server: a route's loader, a Server Component
9
- * const balance = await readOnServer(project.Accounts.balance, [{ member_id }]);
10
- * <Balance member={member_id} initial={balance} />
8
+ * // the server: a route, a Server Component
9
+ * const state = await prefetchQueries([
10
+ * [shopBoundedContext, new CommandReadShowcase()],
11
+ * [coursesBoundedContext, new CommandReadCourse(id)],
12
+ * ]);
13
+ * return <HydrationBoundary state={state}><Showcase /></HydrationBoundary>;
11
14
  *
12
- * // the page, rendered there and hydrated in the browser: the same use case, the same args
13
- * type Props = { member: string; initial?: ServerRead<typeof project.Accounts.balance> };
14
- * function Balance({ member, initial }: Props) {
15
- * const balance = useServiceReading(project.Accounts.balance, [{ member_id: member }], {
16
- * initial,
17
- * });
18
- * }
15
+ * // the screen, rendered there and hydrated in the browser: the same query, no props
16
+ * const showcase = useServiceQuery(shopBoundedContext, new CommandReadShowcase());
19
17
  *
20
18
  * Context: what crosses from the server to the browser is plain JSON — a Client Component is
21
- * handed data, never instances, and a `Date` arrives as its text —, so the answer is written and
22
- * read back as JSON here: a framework that refuses a class instance as a prop never sees one.
19
+ * handed data, never instances, and a `Date` arrives as its text —, so each Response is written
20
+ * and read back as JSON here, keyed by its query (`queryKeyOf`): a screen finds it by running the
21
+ * same Command with the same values.
23
22
  *
24
- * A read that fails never refuses the page: it answers `undefined`, the page is drawn without
25
- * it, and the browser reads it on mount, as a single-page application does. The failure is one
26
- * line on the process's log (client-framework's `logger`, WARN: it always speaks) saying `what`
27
- * was not read — the use case's own name when not given. A use case run through its bounded
28
- * context already traced and reported its failure, so nothing is reported twice here; and, as
29
- * there, a refusal (a 404, a permission) says its type and kind, never its message. A use case
30
- * that answers nothing stays nothing, without a line.
23
+ * A query that fails never refuses the page: it is left out, the page is drawn without it, and the
24
+ * browser fetches it on mount, as a single-page application does. The failure is one line on the
25
+ * process's log (client-framework's `logger`, WARN: it always speaks) naming the Command. A use
26
+ * case run through its bounded context already traced and reported its failure, so nothing is
27
+ * reported twice here; and, as there, a refusal (a 404, a permission) says its type and kind,
28
+ * never its message. A Command that returns nothing is left out, without a line.
31
29
  *
32
30
  * Plain logic, without React or the DOM (`core/`): a route's loader, a Server Component and a
33
31
  * script import it from `@sincpro/web-framework/core` without loading any screen.
34
32
  */
35
- export async function readOnServer(useCase, args, options = {}) {
36
- // A use case, not a hook: the linter reads any call to `use…` as one.
37
- const run = useCase;
38
- try {
39
- const answer = await run(...args);
40
- if (answer === undefined)
33
+ export async function prefetchQueries(queries) {
34
+ const fetched = await Promise.all(queries.map(async ([boundedContext, command]) => {
35
+ const key = queryKeyOf(boundedContext, command);
36
+ try {
37
+ const response = await boundedContext.execute(command);
38
+ if (response === undefined)
39
+ return undefined;
40
+ return [key, JSON.parse(JSON.stringify(response))];
41
+ }
42
+ catch (error) {
43
+ notRead(key.split("|")[1] ?? "a Command", error);
41
44
  return undefined;
42
- return JSON.parse(JSON.stringify(answer));
43
- }
44
- catch (error) {
45
- notRead(options.what ?? (useCase.name || "a use case"), error);
46
- return undefined;
47
- }
45
+ }
46
+ }));
47
+ return Object.fromEntries(fetched.filter((one) => one !== undefined));
48
48
  }
49
49
  /** The one line a read on the server that failed leaves on the process's log (WARN: it always
50
50
  * speaks): what was not read, and the failure's type and kind — a refusal never its message. */
@@ -77,7 +77,7 @@ function notRead(what, error) {
77
77
  * Context: it asks through the screens' use case (`screensOperations`), as `useRecord` and
78
78
  * `readListing` do — traced like the browser's reads, with the process's context — and answers
79
79
  * plain JSON (`RecordRead`): a Client Component is handed data, never instances. A read that
80
- * fails never refuses the page, as `readOnServer`: it answers `undefined` and one WARN line on
80
+ * fails never refuses the page, as `prefetchQueries`: it answers `undefined` and one WARN line on
81
81
  * the process's log — `what` (the entity's key when not given), the failure's type and kind, and
82
82
  * never a refusal's message (a 404, a permission) —, the page is drawn without it and the
83
83
  * browser reads the record on mount, as a single-page application does. A read the caller
@@ -3,6 +3,7 @@ import type { Meta } from "@sincpro/criteria";
3
3
  import type { Uploads } from "../core/files.js";
4
4
  import { type NameBook } from "../core/names.js";
5
5
  import { type DateStyle } from "../core/present.js";
6
+ import { QueryCache } from "../core/queries.js";
6
7
  import type { RichTextSettings } from "../core/richText.js";
7
8
  import type { Trail } from "../core/trail.js";
8
9
  import { type ReactNode } from "react";
@@ -48,6 +49,8 @@ type FrameworkContextValue = {
48
49
  context: Readonly<Record<string, unknown>>;
49
50
  /** Where writes are announced: a reading reads again when one touches it (`useWrites`). */
50
51
  changes: ChangeFeed;
52
+ /** The screens' queries to use cases, cached and shared by query key (`useServiceQuery`). */
53
+ queries: QueryCache;
51
54
  /** The names of records by key, asked one request per entity (`useNameOf`). */
52
55
  names: NameBook;
53
56
  /** How dates are written now — a piece that keeps its texts compares it to know when to
@@ -1,8 +1,10 @@
1
1
  "use client";
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
3
  import { installTimeZone, metaStore, processChanges, processContext, screensOperations, } from "@sincpro/client-framework";
4
+ import { modelsOf } from "../core/models.js";
4
5
  import { nameBook } from "../core/names.js";
5
6
  import { installCurrency, installDateStyle, installRegion, } from "../core/present.js";
7
+ import { QueryCache } from "../core/queries.js";
6
8
  import { entityFor } from "../core/relation.js";
7
9
  import { useContextValues } from "./useContextValues.js";
8
10
  import { createContext, useContext, useEffect, useMemo, useRef, useState, } from "react";
@@ -42,8 +44,10 @@ export function FrameworkProvider({ operations, transport, locale, metas: seed,
42
44
  }
43
45
  // One store for the provider's life: a new seed object on a re-render must not forget what
44
46
  // the screens already learned.
45
- const [metas] = useState(() => metaStore(seed));
47
+ // What the entities carry (a generated entity has its model), under what the app gives.
48
+ const [metas] = useState(() => metaStore({ ...modelsOf(entities), ...seed }));
46
49
  const [trails] = useState(() => new Map());
50
+ const [queries] = useState(() => new QueryCache());
47
51
  // What the screens read and write is a use case of `screens` (`screensOperations`,
48
52
  // client-framework): each call traced, carrying the process's context (the company, the
49
53
  // tenant) read at the moment it is sent, and reported when it failed unexpectedly.
@@ -58,6 +62,14 @@ export function FrameworkProvider({ operations, transport, locale, metas: seed,
58
62
  // eslint-disable-next-line react-hooks/exhaustive-deps
59
63
  [screens, metas, context]);
60
64
  useEffect(() => changes.follow((change) => names.changed(change)), [changes, names]);
65
+ // Another company: every cached Response may be another; the screens fetch again.
66
+ const contextShown = useRef(context);
67
+ useEffect(() => {
68
+ if (contextShown.current === context)
69
+ return;
70
+ contextShown.current = context;
71
+ queries.invalidateAll();
72
+ }, [queries, context]);
61
73
  const value = useMemo(() => ({
62
74
  operations: screens,
63
75
  transport,
@@ -67,6 +79,7 @@ export function FrameworkProvider({ operations, transport, locale, metas: seed,
67
79
  trails,
68
80
  context,
69
81
  changes,
82
+ queries,
70
83
  names,
71
84
  dateStyle,
72
85
  currency,
@@ -83,6 +96,7 @@ export function FrameworkProvider({ operations, transport, locale, metas: seed,
83
96
  trails,
84
97
  context,
85
98
  changes,
99
+ queries,
86
100
  names,
87
101
  dateStyle,
88
102
  currency,
@@ -136,12 +150,20 @@ export function ModelDefinitions({ entities, metas, events, people, children, })
136
150
  const above = useFramework();
137
151
  // Added while rendering, before the screens under it render: they read the store as they draw.
138
152
  const brought = useRef(undefined);
153
+ const carried = useRef(undefined);
139
154
  if (metas !== undefined && brought.current !== metas) {
140
155
  for (const [key, meta] of Object.entries(metas))
141
156
  if (above.metas.get(key) === undefined)
142
157
  above.metas.set(key, meta);
143
158
  brought.current = metas;
144
159
  }
160
+ // The models its entities carry, under what it brought: a face's entities are its models.
161
+ if (entities !== undefined && carried.current !== entities) {
162
+ for (const [key, meta] of Object.entries(modelsOf(entities)))
163
+ if (above.metas.get(key) === undefined)
164
+ above.metas.set(key, meta);
165
+ carried.current = entities;
166
+ }
145
167
  const value = useMemo(() => entities === undefined && events === undefined && people === undefined
146
168
  ? above
147
169
  : {
@@ -0,0 +1,20 @@
1
+ import type { DehydratedState } from "../core/queries.js";
2
+ import { type ReactNode } from "react";
3
+ /**
4
+ * Hydrates the queries prefetched on the server that rendered the page (`prefetchQueries`): a
5
+ * screen under it that runs the same query (`useServiceQuery`) starts with its Response — drawn
6
+ * there, kept in the browser — instead of fetching it again.
7
+ *
8
+ * const state = await prefetchQueries([[shopBoundedContext, new CommandReadShowcase()]]);
9
+ * return <HydrationBoundary state={state}><Showcase /></HydrationBoundary>;
10
+ *
11
+ * Context: a page hands its screens no `initial` prop: what it prefetched travels by query key, so
12
+ * the screen that shows it queries exactly as it would in the browser. One inside another adds its
13
+ * Responses to the outer one's.
14
+ */
15
+ export declare function HydrationBoundary({ state, children, }: {
16
+ state: DehydratedState;
17
+ children: ReactNode;
18
+ }): import("react").JSX.Element;
19
+ /** @internal — the Responses prefetched on the server for the screens under it. */
20
+ export declare const useHydratedState: () => DehydratedState;
@@ -0,0 +1,23 @@
1
+ "use client";
2
+ import { jsx as _jsx } from "react/jsx-runtime";
3
+ import { createContext, useContext, useMemo } from "react";
4
+ const HydrationContext = createContext({});
5
+ /**
6
+ * Hydrates the queries prefetched on the server that rendered the page (`prefetchQueries`): a
7
+ * screen under it that runs the same query (`useServiceQuery`) starts with its Response — drawn
8
+ * there, kept in the browser — instead of fetching it again.
9
+ *
10
+ * const state = await prefetchQueries([[shopBoundedContext, new CommandReadShowcase()]]);
11
+ * return <HydrationBoundary state={state}><Showcase /></HydrationBoundary>;
12
+ *
13
+ * Context: a page hands its screens no `initial` prop: what it prefetched travels by query key, so
14
+ * the screen that shows it queries exactly as it would in the browser. One inside another adds its
15
+ * Responses to the outer one's.
16
+ */
17
+ export function HydrationBoundary({ state, children, }) {
18
+ const outer = useContext(HydrationContext);
19
+ const merged = useMemo(() => ({ ...outer, ...state }), [outer, state]);
20
+ return _jsx(HydrationContext.Provider, { value: merged, children: children });
21
+ }
22
+ /** @internal — the Responses prefetched on the server for the screens under it. */
23
+ export const useHydratedState = () => useContext(HydrationContext);
@@ -4,6 +4,7 @@
4
4
  * keeps it that way.
5
5
  */
6
6
  export { FrameworkProvider, ModelDefinitions, type People, useEntityFor, useFramework, } from "./context.js";
7
+ export { HydrationBoundary } from "./hydration.js";
7
8
  export { type ListScope, ListScopeProvider, useListScope, } from "./scope.js";
8
9
  export { BATCH_LIMIT, type BatchCommandState, useBatchCommand, } from "./useBatchCommand.js";
9
10
  export { type CommandState, type Rehearsal, useCommand, useOperationCommand, } from "./useCommand.js";
@@ -17,12 +18,13 @@ export { excluding, type Lookup, useLookup } from "./useLookup.js";
17
18
  export { useNameOf, useNamesOf } from "./useNameOf.js";
18
19
  export { usePeopleOf } from "./usePeopleOf.js";
19
20
  export { type PivotAxes, type PivotReading, usePivot, } from "./usePivot.js";
21
+ export { useQueryCache } from "./useQueryCache.js";
20
22
  export { type Editing, type RecordReading, type RecordState, useRecord, } from "./useRecord.js";
21
23
  export { type LifecycleAction, type RecordLifecycleActions, useRecordLifecycle, } from "./useRecordLifecycle.js";
22
24
  export { useRelated } from "./useRelated.js";
23
25
  export { type ListSelection, useSelection } from "./useSelection.js";
24
- export { type ServiceState, useService } from "./useService.js";
25
- export { type ServiceReading, useServiceReading, } from "./useServiceReading.js";
26
+ export { type ServiceCommand, useServiceCommand, } from "./useServiceCommand.js";
27
+ export { type ServiceQuery, type ServiceQueryOptions, useServiceQuery, } from "./useServiceQuery.js";
26
28
  export { useSummaryOf } from "./useSummary.js";
27
29
  export { useTextOf, type ValueTexts } from "./useTextOf.js";
28
30
  export { type Upload, useUpload } from "./useUpload.js";
@@ -4,6 +4,7 @@
4
4
  * keeps it that way.
5
5
  */
6
6
  export { FrameworkProvider, ModelDefinitions, useEntityFor, useFramework, } from "./context.js";
7
+ export { HydrationBoundary } from "./hydration.js";
7
8
  export { ListScopeProvider, useListScope, } from "./scope.js";
8
9
  export { BATCH_LIMIT, useBatchCommand, } from "./useBatchCommand.js";
9
10
  export { useCommand, useOperationCommand, } from "./useCommand.js";
@@ -17,12 +18,13 @@ export { excluding, useLookup } from "./useLookup.js";
17
18
  export { useNameOf, useNamesOf } from "./useNameOf.js";
18
19
  export { usePeopleOf } from "./usePeopleOf.js";
19
20
  export { usePivot, } from "./usePivot.js";
21
+ export { useQueryCache } from "./useQueryCache.js";
20
22
  export { useRecord, } from "./useRecord.js";
21
23
  export { useRecordLifecycle, } from "./useRecordLifecycle.js";
22
24
  export { useRelated } from "./useRelated.js";
23
25
  export { useSelection } from "./useSelection.js";
24
- export { useService } from "./useService.js";
25
- export { useServiceReading, } from "./useServiceReading.js";
26
+ export { useServiceCommand, } from "./useServiceCommand.js";
27
+ export { useServiceQuery, } from "./useServiceQuery.js";
26
28
  export { useSummaryOf } from "./useSummary.js";
27
29
  export { useTextOf } from "./useTextOf.js";
28
30
  export { useUpload } from "./useUpload.js";
@@ -1,6 +1,7 @@
1
1
  "use client";
2
2
  import { keysOf, retryKeys, runBatch, } from "@sincpro/client-framework";
3
3
  import { callFor, } from "../core/command.js";
4
+ import { knownModelOf } from "../core/models.js";
4
5
  import { useFramework } from "./context.js";
5
6
  import { useCallback, useEffect, useRef, useState } from "react";
6
7
  /** The most records a Command runs on at once from a screen, unless the screen says otherwise. */
@@ -83,7 +84,7 @@ export function useBatchCommand(entity, name, options = {}) {
83
84
  return {
84
85
  run: async (selection, body) => {
85
86
  setError(null);
86
- const meta = metas.get(entity.key);
87
+ const meta = knownModelOf(metas, entity);
87
88
  let keys;
88
89
  try {
89
90
  keys = await keysOf(selection, {
@@ -1,6 +1,7 @@
1
1
  "use client";
2
2
  import { readHistory } from "@sincpro/client-framework";
3
3
  import { historyOf, } from "../core/history.js";
4
+ import { knownModelOf } from "../core/models.js";
4
5
  import { useFramework } from "./context.js";
5
6
  import { useWrites } from "./useWrites.js";
6
7
  import { useEffect, useState } from "react";
@@ -46,7 +47,7 @@ export function useHistory(entity, id, deps = [], options = {}) {
46
47
  };
47
48
  readHistory(operations, entity, id, criteria, { signal: aborter.signal }).then((page) => aborter.signal.aborted ||
48
49
  setEntries(historyOf(page.rows, page.meta, locale, {
49
- record: metas.get(entity.key),
50
+ record: knownModelOf(metas, entity),
50
51
  events,
51
52
  tones,
52
53
  })), () => aborter.signal.aborted || setEntries(undefined));
@@ -3,6 +3,7 @@ import { readPage, } from "@sincpro/client-framework";
3
3
  import { merge, resource, resumingFrom, searchOver, } from "@sincpro/criteria";
4
4
  import { useReading } from "@sincpro/criteria-react";
5
5
  import { isList, listingAsk } from "../core/list.js";
6
+ import { knownModelOf } from "../core/models.js";
6
7
  import { useFramework } from "./context.js";
7
8
  import { useListScope } from "./scope.js";
8
9
  import { useWrites } from "./useWrites.js";
@@ -25,14 +26,14 @@ export function useListing(given, own = {}) {
25
26
  signal,
26
27
  input,
27
28
  // Read when asked: a definition a face brought later (`ModelDefinitions`) counts.
28
- meta: metas.get(entity.key) ?? null,
29
+ meta: knownModelOf(metas, entity) ?? null,
29
30
  })),
30
31
  // `input` is the caller's literal: its content is what counts.
31
32
  // eslint-disable-next-line react-hooks/exhaustive-deps
32
33
  [operations, entity, metas, inputKey]);
33
34
  // A definition already known — the contract's, a face's — draws the columns before the first
34
35
  // page arrives.
35
- const [preloaded] = useState(() => metas.get(entity.key));
36
+ const [preloaded] = useState(() => knownModelOf(metas, entity));
36
37
  const paging = own.paging ?? "pages";
37
38
  const size = asked.pagination?.limit ?? 50;
38
39
  const maxRows = own.maxRows ?? 500;
@@ -3,6 +3,7 @@ import { readPage } from "@sincpro/client-framework";
3
3
  import { merge } from "@sincpro/criteria";
4
4
  import { isList } from "../core/list.js";
5
5
  import { lookupOf } from "../core/lookup.js";
6
+ import { knownModelOf } from "../core/models.js";
6
7
  import { useFramework } from "./context.js";
7
8
  import { useListing } from "./useListing.js";
8
9
  import { useEffect, useRef, useState } from "react";
@@ -30,9 +31,9 @@ entity, options = {}) {
30
31
  // answer — then this renders again and the reading starts over without the excluded.
31
32
  const [definition, setDefinition] = useState(() => ({
32
33
  key: base.key,
33
- meta: metas.get(base.key),
34
+ meta: knownModelOf(metas, base),
34
35
  }));
35
- const keyed = definition.key === base.key ? definition.meta : metas.get(base.key);
36
+ const keyed = definition.key === base.key ? definition.meta : knownModelOf(metas, base);
36
37
  const scope = excluding(options.criteria, options.exclude, keyed);
37
38
  // «More», not pages: a choice list grows downwards, and its ceiling keeps it light.
38
39
  const listing = useListing(entity, {
@@ -0,0 +1,13 @@
1
+ import type { QueryCache } from "../core/queries.js";
2
+ /**
3
+ * The provider's `QueryCache` — for what only the application knows: another person signed in.
4
+ *
5
+ * const queryCache = useQueryCache();
6
+ * function signOut() { endSession(); queryCache.clear(); }
7
+ *
8
+ * Context: a company the process's context names invalidates every query by itself; who is
9
+ * signed in is the application's (its session is not the process's context), so it clears the
10
+ * cache when that changes — a query that names nobody («my orders») must never show the last
11
+ * person's Response to the next.
12
+ */
13
+ export declare function useQueryCache(): QueryCache;
@@ -0,0 +1,16 @@
1
+ "use client";
2
+ import { useFramework } from "./context.js";
3
+ /**
4
+ * The provider's `QueryCache` — for what only the application knows: another person signed in.
5
+ *
6
+ * const queryCache = useQueryCache();
7
+ * function signOut() { endSession(); queryCache.clear(); }
8
+ *
9
+ * Context: a company the process's context names invalidates every query by itself; who is
10
+ * signed in is the application's (its session is not the process's context), so it clears the
11
+ * cache when that changes — a query that names nobody («my orders») must never show the last
12
+ * person's Response to the next.
13
+ */
14
+ export function useQueryCache() {
15
+ return useFramework().queries;
16
+ }
@@ -2,6 +2,7 @@
2
2
  import { newEntityId, readRecord, retryKeys, startingValuesOf, TransportError, WITH_PARAM, } from "@sincpro/client-framework";
3
3
  import { canCreate, changesOf, computedLocally, creationOf, defaultsOf, editedOf, errorsByField, fieldStateOf, lineStatesOf, missingOf, needsPreview, withTargetsOf, } from "../core/edit.js";
4
4
  import { linesAnswered } from "../core/lines.js";
5
+ import { knownModelOf } from "../core/models.js";
5
6
  import { useFramework } from "./context.js";
6
7
  import { useWrites } from "./useWrites.js";
7
8
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -28,7 +29,7 @@ export function useRecord(entity, opened, options = {}) {
28
29
  const startedFrom = (read) => {
29
30
  if (read.meta)
30
31
  metas.set(entity.key, read.meta);
31
- const meta = read.meta ?? metas.get(entity.key) ?? null;
32
+ const meta = read.meta ?? knownModelOf(metas, entity) ?? null;
32
33
  const starting = start === undefined ? {} : startingValuesOf({ params: { [WITH_PARAM]: start } });
33
34
  return {
34
35
  status: "ready",
@@ -109,7 +110,7 @@ export function useRecord(entity, opened, options = {}) {
109
110
  setState((now) => ({ status: "loading", record: null, meta: now.meta, error: null }));
110
111
  if (isNew) {
111
112
  // Nothing to read but the model: the contract's, or a face's (`ModelDefinitions`).
112
- Promise.resolve(metas.get(entity.key) ?? null).then((meta) => {
113
+ Promise.resolve(knownModelOf(metas, entity) ?? null).then((meta) => {
113
114
  if (meta)
114
115
  metas.set(entity.key, meta);
115
116
  if (aborter.signal.aborted)
@@ -134,7 +135,7 @@ export function useRecord(entity, opened, options = {}) {
134
135
  }
135
136
  readRecord(operations, entity, id, {
136
137
  signal: aborter.signal,
137
- meta: metas.get(entity.key) ?? null,
138
+ meta: knownModelOf(metas, entity) ?? null,
138
139
  }).then((answer) => {
139
140
  if (answer.meta)
140
141
  metas.set(entity.key, answer.meta);
@@ -150,7 +151,7 @@ export function useRecord(entity, opened, options = {}) {
150
151
  setState({
151
152
  status: "ready",
152
153
  record: answer.record,
153
- meta: answer.meta ?? metas.get(entity.key) ?? null,
154
+ meta: answer.meta ?? knownModelOf(metas, entity) ?? null,
154
155
  error: null,
155
156
  });
156
157
  }, (error) => {
@@ -0,0 +1,32 @@
1
+ /**
2
+ * @internal — what a screen keeps of running something on a gesture: `useServiceCommand`'s state,
3
+ * and `ServiceButton`'s, whose `run` is the app's own function.
4
+ *
5
+ * `run` answers what the use case answered, or `undefined` when it failed — the failure is in
6
+ * `error`, for the screen to say (`explain`, `Refused`); it never throws at the screen. So a use
7
+ * case that answers nothing answers `null`, never `undefined`: a `DELETE` the server answers
8
+ * with 204 resolves `null` through the transport, and a Feature hands that on instead of typing
9
+ * itself `void` — or «done» and «failed» look the same to the screen
10
+ * (Sincpro-SRL/sincpro_client_framework#51).
11
+ */
12
+ export type Running<A extends unknown[], R> = {
13
+ run: (...args: A) => Promise<R | undefined>;
14
+ /** A run is on its way. */
15
+ busy: boolean;
16
+ /** What the last run answered, until another one starts or `reset`. */
17
+ answer: R | undefined;
18
+ error: unknown;
19
+ reset: () => void;
20
+ };
21
+ /** What is run: a use case reached through its bounded context. */
22
+ type Run<A extends unknown[], R> = (...args: A) => R | Promise<R>;
23
+ /**
24
+ * @internal — runs `useCase` on a gesture and keeps its state: busy, the answer, the failure.
25
+ *
26
+ * Context: the span and the report are the use case's: this hook neither opens one nor reports.
27
+ * The last run wins: an answer that arrives after a newer run started is dropped, so a slow first
28
+ * click never overwrites the second. A run is never aborted — the server may have done it — but
29
+ * its answer does not land on a screen that left.
30
+ */
31
+ export declare function useRunning<A extends unknown[], R>(useCase: Run<A, R>): Running<A, Awaited<R>>;
32
+ export {};
@@ -1,25 +1,14 @@
1
1
  "use client";
2
2
  import { useCallback, useEffect, useRef, useState } from "react";
3
3
  /**
4
- * One of the application's use cases, run from a screen.
5
- *
6
- * const close = useService(project.Issues.close);
7
- * <Button disabled={close.busy} onPress={() => close.run({ issue_id })}>Cerrar</Button>
8
- * {close.error ? <Refused error={close.error} /> : null}
9
- *
10
- * Context: all of an application's logic lives in its services (@sincpro/client-framework's
11
- * `Feature` and `ApplicationService`, reached through their bounded context), traced and reported
12
- * by its interceptors; what a screen adds is the state of running one — busy, the answer, the
13
- * failure. Written by hand, that state is the 300-line context every mobile screen repeats; here
14
- * it is one hook, the same for every use case. The span and the report are the service's: this
15
- * hook neither opens one nor reports. A bounded context answers the same function every time a
16
- * method is read, so `project.Issues.close` can be handed as it is.
4
+ * @internal — runs `useCase` on a gesture and keeps its state: busy, the answer, the failure.
17
5
  *
6
+ * Context: the span and the report are the use case's: this hook neither opens one nor reports.
18
7
  * The last run wins: an answer that arrives after a newer run started is dropped, so a slow first
19
8
  * click never overwrites the second. A run is never aborted — the server may have done it — but
20
9
  * its answer does not land on a screen that left.
21
10
  */
22
- export function useService(useCase) {
11
+ export function useRunning(useCase) {
23
12
  const [busy, setBusy] = useState(false);
24
13
  const [answer, setAnswer] = useState(undefined);
25
14
  const [error, setError] = useState(null);
@@ -0,0 +1,42 @@
1
+ import type { Command } from "@sincpro/client-framework";
2
+ import type { QueryBoundedContext, ResponseOf } from "../core/queries.js";
3
+ /**
4
+ * What a screen keeps of executing a Command on a gesture.
5
+ *
6
+ * `execute` returns the use case's Response, or `undefined` when it failed — the failure is in
7
+ * `error`, for the screen to say (`explain`, `Refused`); it never throws at the screen. So a use
8
+ * case that returns nothing returns `null`, never `undefined`: a `DELETE` the server answers
9
+ * with 204 resolves `null` through the transport, and a Feature hands that on instead of typing
10
+ * itself `void` — or «done» and «failed» look the same to the screen
11
+ * (Sincpro-SRL/sincpro_client_framework#51).
12
+ */
13
+ export type ServiceCommand<C, R> = {
14
+ execute: (command: C) => Promise<R | undefined>;
15
+ /** One is on its way. */
16
+ busy: boolean;
17
+ /** The last one's Response, until another starts or `reset`. */
18
+ response: R | undefined;
19
+ error: unknown;
20
+ reset: () => void;
21
+ };
22
+ /**
23
+ * A Command of the application executed on a gesture — a press, a submit —, never on mount.
24
+ *
25
+ * const order = useServiceCommand(shopBoundedContext, CommandOrder);
26
+ * <Button disabled={order.busy} onPress={() => order.execute(new CommandOrder(id, quantity))}>
27
+ * Pedir
28
+ * </Button>
29
+ * {order.error ? <Refused error={order.error} /> : null}
30
+ *
31
+ * Context: all of an application's logic lives in its services (client-framework's `Feature` and
32
+ * `ApplicationService`, reached through their bounded context), traced and reported there; what a
33
+ * screen adds is the state of executing one — busy, the Response, the failure. The class says
34
+ * which Command this is, so the Response is typed by it and executing another is refused; the
35
+ * values are the ones of the moment it is executed. What it changed every screen hears by itself
36
+ * (the operations announce their writes): refetching is never this hook's.
37
+ *
38
+ * The last one wins: a Response that arrives after a newer one started is dropped, so a slow
39
+ * first click never overwrites the second. None is aborted — the server may have done it — but
40
+ * its Response does not land on a screen that left.
41
+ */
42
+ export declare function useServiceCommand<C extends Command<unknown>>(boundedContext: QueryBoundedContext, command: abstract new (...args: never[]) => C): ServiceCommand<C, ResponseOf<C>>;
@@ -0,0 +1,41 @@
1
+ "use client";
2
+ import { useRunning } from "./useRunning.js";
3
+ import { useCallback, useRef } from "react";
4
+ /**
5
+ * A Command of the application executed on a gesture — a press, a submit —, never on mount.
6
+ *
7
+ * const order = useServiceCommand(shopBoundedContext, CommandOrder);
8
+ * <Button disabled={order.busy} onPress={() => order.execute(new CommandOrder(id, quantity))}>
9
+ * Pedir
10
+ * </Button>
11
+ * {order.error ? <Refused error={order.error} /> : null}
12
+ *
13
+ * Context: all of an application's logic lives in its services (client-framework's `Feature` and
14
+ * `ApplicationService`, reached through their bounded context), traced and reported there; what a
15
+ * screen adds is the state of executing one — busy, the Response, the failure. The class says
16
+ * which Command this is, so the Response is typed by it and executing another is refused; the
17
+ * values are the ones of the moment it is executed. What it changed every screen hears by itself
18
+ * (the operations announce their writes): refetching is never this hook's.
19
+ *
20
+ * The last one wins: a Response that arrives after a newer one started is dropped, so a slow
21
+ * first click never overwrites the second. None is aborted — the server may have done it — but
22
+ * its Response does not land on a screen that left.
23
+ */
24
+ export function useServiceCommand(boundedContext, command) {
25
+ const latest = useRef(boundedContext);
26
+ latest.current = boundedContext;
27
+ const running = useRunning(async (given) => {
28
+ if (!(given instanceof command))
29
+ throw new TypeError(`This screen executes ${command.name}; it was handed another Command`);
30
+ return (await latest.current.execute(given));
31
+ });
32
+ const { run } = running;
33
+ const execute = useCallback((given) => run(given), [run]);
34
+ return {
35
+ execute,
36
+ busy: running.busy,
37
+ response: running.answer,
38
+ error: running.error,
39
+ reset: running.reset,
40
+ };
41
+ }
@@ -0,0 +1,46 @@
1
+ import type { Command, Entity } from "@sincpro/client-framework";
2
+ import { type QueryBoundedContext, type ResponseOf } from "../core/queries.js";
3
+ /** What a screen shows of a query: the Response to the Command it runs NOW. */
4
+ export type ServiceQuery<R> = {
5
+ /** `loading` until the Response to this query arrives — never another query's. */
6
+ status: "loading" | "ready" | "failed";
7
+ response: R | undefined;
8
+ error: unknown;
9
+ /** Fetch it again; the Response stays on screen until the new one lands. */
10
+ refetch: () => void;
11
+ };
12
+ export type ServiceQueryOptions = {
13
+ /** Fetch again when a write touches any of these — whoever sent it. */
14
+ follows?: readonly Entity[];
15
+ /** `false`: nothing to query yet (nobody signed in, a key still unknown) — it stays `loading`
16
+ * and fetches nothing, until it is enabled. `true` by default. */
17
+ enabled?: boolean;
18
+ };
19
+ /**
20
+ * A query to one of the application's use cases: a Command that READS, executed when the screen
21
+ * shows it — again when its values change, when the process's context changes (another company)
22
+ * and when a write touches an entity it follows.
23
+ *
24
+ * const showcase = useServiceQuery(shopBoundedContext, new CommandReadShowcase());
25
+ * const profile = useServiceQuery(membersBoundedContext, new CommandMyProfile(user), {
26
+ * enabled: user !== "",
27
+ * follows: [members],
28
+ * });
29
+ * profile.status === "ready" ? <Profile of={profile.response} /> : <Skeleton />
30
+ *
31
+ * Context: the Command is the query — its bounded context, its identity and its values are its
32
+ * key (`queryKeyOf`) —, so a screen writes `new CommandX(...)` as it executes it anywhere and
33
+ * nothing else: no function wrapped around it, no list of arguments beside it. Other values are
34
+ * another query: it starts `loading`, never with the previous Response. Two screens that run the
35
+ * same query share one request and one Response, the provider's `QueryCache`; refetching keeps
36
+ * the Response on screen until the new one lands. The trace and the report are the use case's,
37
+ * never this hook's.
38
+ *
39
+ * A Response prefetched on the server that rendered the page (`prefetchQueries`,
40
+ * `<HydrationBoundary>`) is this query's from the start: drawn there, kept in the browser instead
41
+ * of fetched again.
42
+ *
43
+ * `enabled: false` is a query that cannot run yet. Never return a pending promise from the use
44
+ * case to hold it back: the screen would wait on a request nobody sent.
45
+ */
46
+ export declare function useServiceQuery<C extends Command<unknown>>(boundedContext: QueryBoundedContext, command: C, options?: ServiceQueryOptions): ServiceQuery<ResponseOf<C>>;