@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
@@ -0,0 +1,79 @@
1
+ "use client";
2
+ import { touches } from "../core/changes.js";
3
+ import { queryKeyOf, } from "../core/queries.js";
4
+ import { useFramework } from "./context.js";
5
+ import { useHydratedState } from "./hydration.js";
6
+ import { useCallback, useEffect, useRef, useSyncExternalStore } from "react";
7
+ /**
8
+ * A query to one of the application's use cases: a Command that READS, executed when the screen
9
+ * shows it — again when its values change, when the process's context changes (another company)
10
+ * and when a write touches an entity it follows.
11
+ *
12
+ * const showcase = useServiceQuery(shopBoundedContext, new CommandReadShowcase());
13
+ * const profile = useServiceQuery(membersBoundedContext, new CommandMyProfile(user), {
14
+ * enabled: user !== "",
15
+ * follows: [members],
16
+ * });
17
+ * profile.status === "ready" ? <Profile of={profile.response} /> : <Skeleton />
18
+ *
19
+ * Context: the Command is the query — its bounded context, its identity and its values are its
20
+ * key (`queryKeyOf`) —, so a screen writes `new CommandX(...)` as it executes it anywhere and
21
+ * nothing else: no function wrapped around it, no list of arguments beside it. Other values are
22
+ * another query: it starts `loading`, never with the previous Response. Two screens that run the
23
+ * same query share one request and one Response, the provider's `QueryCache`; refetching keeps
24
+ * the Response on screen until the new one lands. The trace and the report are the use case's,
25
+ * never this hook's.
26
+ *
27
+ * A Response prefetched on the server that rendered the page (`prefetchQueries`,
28
+ * `<HydrationBoundary>`) is this query's from the start: drawn there, kept in the browser instead
29
+ * of fetched again.
30
+ *
31
+ * `enabled: false` is a query that cannot run yet. Never return a pending promise from the use
32
+ * case to hold it back: the screen would wait on a request nobody sent.
33
+ */
34
+ export function useServiceQuery(boundedContext, command, options = {}) {
35
+ const { queries, changes } = useFramework();
36
+ const key = queryKeyOf(boundedContext, command);
37
+ const enabled = options.enabled ?? true;
38
+ // The query as the latest render wrote it.
39
+ const latest = useRef({ boundedContext, command });
40
+ latest.current = { boundedContext, command };
41
+ // Prefetched on the server: this query's Response from the start, rendered there, kept here.
42
+ const hydrated = useHydratedState();
43
+ const prefetched = Object.hasOwn(hydrated, key) ? hydrated[key] : undefined;
44
+ if (prefetched !== undefined)
45
+ queries.hydrate(key, prefetched);
46
+ useEffect(() => {
47
+ if (prefetched !== undefined)
48
+ queries.setResponse(key, prefetched);
49
+ }, [queries, key, prefetched]);
50
+ const subscribe = useCallback((listener) => queries.subscribe(key, listener), [queries, key]);
51
+ const getState = () => queries.getState(key);
52
+ const state = useSyncExternalStore(subscribe, getState, getState);
53
+ // Each change of where it stands fetches if it must: no Response yet, or a stale one.
54
+ useEffect(() => {
55
+ if (!enabled)
56
+ return;
57
+ queries.fetch(key, () => latest.current.boundedContext.execute(latest.current.command));
58
+ }, [queries, key, enabled, state]);
59
+ // A write anyone sends — a save, another use case, a panel beside — to what it follows.
60
+ const followed = (options.follows ?? []).map((one) => one.model).join("\n");
61
+ useEffect(() => {
62
+ if (followed === "")
63
+ return;
64
+ const models = followed.split("\n");
65
+ return changes.follow((change) => {
66
+ if (models.some((model) => touches(change, { model })))
67
+ queries.invalidate(key);
68
+ });
69
+ }, [queries, changes, followed, key]);
70
+ const refetch = useCallback(() => queries.invalidate(key), [queries, key]);
71
+ if (state === undefined || state.status === "loading")
72
+ return { status: "loading", response: undefined, error: null, refetch };
73
+ return {
74
+ status: state.status,
75
+ response: state.response,
76
+ error: state.error,
77
+ refetch,
78
+ };
79
+ }
@@ -1,5 +1,6 @@
1
1
  "use client";
2
2
  import {} from "@sincpro/client-framework";
3
+ import { knownModelOf } from "../core/models.js";
3
4
  import { summaryOf } from "../core/summary.js";
4
5
  import { useFramework } from "./context.js";
5
6
  import { useCallback } from "react";
@@ -16,7 +17,7 @@ import { useCallback } from "react";
16
17
  */
17
18
  export function useSummaryOf(entity) {
18
19
  const { metas, locale } = useFramework();
19
- return useCallback((record, meta) => summaryOf(meta ?? metas.get(entity.key) ?? null, record, {
20
+ return useCallback((record, meta) => summaryOf(meta ?? knownModelOf(metas, entity) ?? null, record, {
20
21
  fields: entity.summary,
21
22
  ...(locale === undefined ? {} : { locale }),
22
23
  }), [metas, entity, locale]);
@@ -5,6 +5,7 @@ import { matching } from "@sincpro/criteria";
5
5
  import { frameworkCopy } from "../../core/copy.js";
6
6
  import { explain } from "../../core/explain.js";
7
7
  import { lookupOf } from "../../core/lookup.js";
8
+ import { knownModelOf } from "../../core/models.js";
8
9
  import { searchedAlone } from "../../core/names.js";
9
10
  import { entityFor } from "../../core/relation.js";
10
11
  import { summaryOf } from "../../core/summary.js";
@@ -70,7 +71,7 @@ export function recordsSearch(framework, locale) {
70
71
  })));
71
72
  if (!searchedAlone(entity))
72
73
  return [];
73
- const meta = framework.metas.get(entity.key);
74
+ const meta = knownModelOf(framework.metas, entity);
74
75
  if (meta === undefined)
75
76
  return [];
76
77
  const choices = await findChoices(framework.operations, entity, meta, text, locale, {
@@ -112,7 +113,7 @@ export function modelLoader(framework, root, locale) {
112
113
  const entity = typeof field.relation === "string"
113
114
  ? entityFor(framework.entities, field.relation, framework.metas.get)
114
115
  : undefined;
115
- return entity === undefined ? undefined : framework.metas.get(entity.key);
116
+ return entity === undefined ? undefined : knownModelOf(framework.metas, entity);
116
117
  };
117
118
  return async (path) => {
118
119
  let meta = root;
@@ -149,7 +150,7 @@ export function recordsBrowser(framework, open, names, refused) {
149
150
  const entity = entityFor(framework.entities, browse.relation, framework.metas.get);
150
151
  if (entity === undefined)
151
152
  return;
152
- const meta = framework.metas.get(entity.key);
153
+ const meta = knownModelOf(framework.metas, entity);
153
154
  const identity = meta?.get_id || meta?.identity || "id";
154
155
  const chosen = browse.chosen.map((one) => String(one.id));
155
156
  const scope = chosen.length === 0
@@ -12,7 +12,7 @@ export type ActionDialog = {
12
12
  };
13
13
  /**
14
14
  * What a button needs of an action to draw it — whatever runs behind: an entity's Command
15
- * (`useCommand`) or one of the application's use cases (`useService`).
15
+ * (`useCommand`) or one of the application's use cases (`useServiceCommand`).
16
16
  */
17
17
  export type ButtonAction<R> = {
18
18
  /** Does it — with what was asked, when it asks —; `undefined` when it failed: the failure is
@@ -1,6 +1,7 @@
1
1
  "use client";
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
3
  import {} from "@sincpro/client-framework";
4
+ import { knownModelOf } from "../../core/models.js";
4
5
  import { entityFor } from "../../core/relation.js";
5
6
  import { useFramework } from "../../react/context.js";
6
7
  import { useCommand } from "../../react/useCommand.js";
@@ -49,7 +50,7 @@ function useCommandBehind({ entity, command, id, body, destructive = false, ask,
49
50
  const form = ask === undefined
50
51
  ? undefined
51
52
  : askFormOf(ask, {
52
- meta: metas.get(entity.key),
53
+ meta: knownModelOf(metas, entity),
53
54
  locale,
54
55
  record,
55
56
  entityFor: (target) => entityFor(entities, target, metas.get),
@@ -4,6 +4,7 @@ import {} from "@sincpro/client-framework";
4
4
  import { nameOf } from "@sincpro/criteria";
5
5
  import { frameworkCopy } from "../../core/copy.js";
6
6
  import { isList } from "../../core/list.js";
7
+ import { knownModelOf } from "../../core/models.js";
7
8
  import { useFramework } from "../../react/context.js";
8
9
  import { useListing } from "../../react/useListing.js";
9
10
  import { excluding, useLookup } from "../../react/useLookup.js";
@@ -63,7 +64,7 @@ export function EntityPicker({ entity, value, onChange, onOpen, openTargets, onB
63
64
  ...(exclude === undefined ? {} : { exclude }),
64
65
  });
65
66
  // The chooser opens after the picker read the definition: it excludes from its first page.
66
- const scope = excluding(criteria, exclude, metas.get(base.key));
67
+ const scope = excluding(criteria, exclude, knownModelOf(metas, base));
67
68
  const person = base.summary.person === true;
68
69
  const nothing = none === undefined || none === false || lookup.text !== ""
69
70
  ? []
@@ -2,6 +2,7 @@
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
3
  import { keysOf } from "@sincpro/client-framework";
4
4
  import { isList } from "../../core/list.js";
5
+ import { knownModelOf } from "../../core/models.js";
5
6
  import { useFramework } from "../../react/context.js";
6
7
  import { BATCH_LIMIT } from "../../react/useBatchCommand.js";
7
8
  import { excluding, useLookup } from "../../react/useLookup.js";
@@ -52,7 +53,7 @@ export function EntityTags({ entity, value, onChange, criteria, onOpen, openTarg
52
53
  };
53
54
  /** The keys of what a chooser of several answered — in hand, or read once with a ceiling. */
54
55
  const addChosen = (selection) => {
55
- const meta = metas.get(base.key);
56
+ const meta = knownModelOf(metas, base);
56
57
  keysOf(selection, {
57
58
  transport: operations,
58
59
  entity: base,
@@ -60,7 +61,7 @@ export function EntityTags({ entity, value, onChange, criteria, onOpen, openTarg
60
61
  limit: BATCH_LIMIT,
61
62
  }).then(add, (failure) => toast?.show(refusalNotice(failure)));
62
63
  };
63
- const scope = () => chooserScopeOf(entity, excluding(criteria, value, metas.get(base.key)));
64
+ const scope = () => chooserScopeOf(entity, excluding(criteria, value, knownModelOf(metas, base)));
64
65
  const { choose, chooseMany } = opening ?? {};
65
66
  const browseAll = onBrowseAll ??
66
67
  (chooseMany !== undefined
@@ -16,7 +16,7 @@ import { type ActionLook, type DockedAction } from "./dock.js";
16
16
  *
17
17
  * Context: an action of an application is a use case — its logic, its composition, its span
18
18
  * `<context>/<Service>`, its request carrying the run's trace to the server —, never a request a
19
- * screen sends; what the screen adds is the state of running it (`useService`). The gesture is
19
+ * screen sends; what the screen adds is the state of running it. The gesture is
20
20
  * `CommandButton`'s, drawn once by `ActionButton`: run on the click, off while it runs, a refusal
21
21
  * where it happened; and an action that destroys asks first (`rehearse`, the use case run dry)
22
22
  * and shows what it would do. What it changed, every screen hears by itself: the use case's
@@ -1,8 +1,9 @@
1
1
  "use client";
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
+ import { knownModelOf } from "../../core/models.js";
3
4
  import { entityFor } from "../../core/relation.js";
4
5
  import { useFrameworkIfAny } from "../../react/context.js";
5
- import { useService } from "../../react/useService.js";
6
+ import { useRunning } from "../../react/useRunning.js";
6
7
  import { ActionButton, useActionGesture, } from "./ActionButton.js";
7
8
  import { askFormOf, } from "./ask.js";
8
9
  import { dockedOf, } from "./dock.js";
@@ -40,14 +41,18 @@ export function useServiceAction({ icon, primary, danger, tucked, shortcut, hint
40
41
  }
41
42
  /** What runs behind a use case's button or dock action: the run, its dry run, what it asks. */
42
43
  function useServiceBehind({ run, rehearse, ask, entity, record }) {
43
- const running = useService((asked) => run(asked ?? NOTHING_ASKED));
44
- const rehearsing = useService((asked) => (rehearse ?? NO_REHEARSAL)(asked ?? NOTHING_ASKED));
44
+ const running = useRunning((asked) => run(asked ?? NOTHING_ASKED));
45
+ const rehearsing = useRunning((asked) => (rehearse ?? NO_REHEARSAL)(asked ?? NOTHING_ASKED));
45
46
  // Outside a provider it still runs: the asked fields are then drawn by what `ask` says.
46
47
  const framework = useFrameworkIfAny();
47
48
  const form = ask === undefined
48
49
  ? undefined
49
50
  : askFormOf(ask, {
50
- meta: entity === undefined ? undefined : framework?.metas.get(entity.key),
51
+ meta: entity === undefined
52
+ ? undefined
53
+ : framework === null
54
+ ? undefined
55
+ : knownModelOf(framework.metas, entity),
51
56
  locale: framework?.locale,
52
57
  record,
53
58
  ...(framework === null
@@ -1,5 +1,6 @@
1
1
  "use client";
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
+ import { knownModelOf } from "../../core/models.js";
3
4
  import { textOf } from "../../core/present.js";
4
5
  import { useFrameworkIfAny } from "../../react/context.js";
5
6
  import { presentationOf } from "../list/presentation.js";
@@ -30,7 +31,7 @@ export function choiceTagOf(entity, meta, field, value, locale) {
30
31
  */
31
32
  export function ChoiceTag({ entity, field, value, meta, }) {
32
33
  const framework = useFrameworkIfAny();
33
- const model = meta ?? framework?.metas.get(entity.key) ?? null;
34
+ const model = meta ?? (framework === null ? undefined : knownModelOf(framework.metas, entity)) ?? null;
34
35
  const look = choiceTagOf(entity, model, field, value, framework?.locale);
35
36
  return _jsx(Tag, { tone: look.tone, children: look.label });
36
37
  }
@@ -20,6 +20,7 @@ import { isPersonEntity, PersonValue } from "./person.js";
20
20
  import { RecordLines } from "./record.js";
21
21
  import { RelatedList } from "./RelatedList.js";
22
22
  import { RichTextControl } from "./richText.js";
23
+ import { knownModelOf } from "../../core/models.js";
23
24
  import { Checkbox, Field, FileValue, FormSection, ReadValue, RelationValue, useFormStyle, } from "@sincpro/web-ui";
24
25
  import { useId } from "react";
25
26
  /** `value` with `path` (`numero`, or `emisor.nit`) set to `next` — a new object, the rest kept. */
@@ -152,7 +153,7 @@ export function RecordField({ record, name, as, bare = false, lines: look, list:
152
153
  ? {}
153
154
  : (() => {
154
155
  const refOf = (row) => {
155
- const known = metas.get(target.key);
156
+ const known = knownModelOf(metas, target);
156
157
  const key = known?.get_id || known?.identity || "id";
157
158
  return target.ref(String(row[key]));
158
159
  };
@@ -5,6 +5,7 @@ import { choicesOf } from "@sincpro/criteria";
5
5
  import { frameworkCopy } from "../../core/copy.js";
6
6
  import { adviceAt, defaultsOf, errorAt, linePlacesOf, pathOf, } from "../../core/edit.js";
7
7
  import { addingOf, addManyOf, blankLine, lineFields, lineKey, moved, sameLine, writtenInCell, } from "../../core/lines.js";
8
+ import { knownModelOf } from "../../core/models.js";
8
9
  import { textOf, viewOf } from "../../core/present.js";
9
10
  import { entityFor, relationFieldOf, } from "../../core/relation.js";
10
11
  import { useEntityFor, useFramework } from "../../react/context.js";
@@ -175,7 +176,7 @@ export function RecordLinesEditor({ record, name, lines, look = {}, }) {
175
176
  const addMany = manyKey === undefined || manyEntity === undefined || chooseMany === undefined
176
177
  ? undefined
177
178
  : () => chooseMany(manyEntity, (selection) => {
178
- const meta = metas.get(manyEntity.key);
179
+ const meta = knownModelOf(metas, manyEntity);
179
180
  keysOf(selection, {
180
181
  transport: operations,
181
182
  entity: manyEntity,
@@ -21,8 +21,8 @@ import { type ComponentType } from "react";
21
21
  * ⌘K asks the server with `matching` — 8 records — the same question a many2one asks. Each hit
22
22
  * says what it is (`noun`, composer's) and, beside it, what tells it apart: the entity's own
23
23
  * `option` look, else its summary's description or type — never its key, which tells a person
24
- * nothing a UUID long («María Fernanda Apaza Quispe 01a1ebd4…»). Its model is `meta`, else the workspace's
25
- * (`SincproApp`: the contract's, `metasOf`); without one, ⌘K finds nothing of it. A search that answers a SCOPE by a field of its input (forge's projects
24
+ * nothing a UUID long («María Fernanda Apaza Quispe 01a1ebd4…»). Its model is `meta`, else the
25
+ * workspace's, else the one the entity carries (a generated entity always does). A search that answers a SCOPE by a field of its input (forge's projects
26
26
  * without `tenant_id` are the projects with NO tenant) is searched in the one ⌘K should see:
27
27
  * `search: { input }`.
28
28
  *
@@ -4,6 +4,7 @@ import { isEntityId, NEW_PARAM, processContext, scopeNameOf, scopeOfRef, screens
4
4
  import { nameOf } from "@sincpro/criteria";
5
5
  import { usePhone, } from "@sincpro/web-composer";
6
6
  import { CHOOSE_MANY } from "../../core/list.js";
7
+ import { knownModelOf } from "../../core/models.js";
7
8
  import { useFramework } from "../../react/context.js";
8
9
  import { ListScopeProvider } from "../../react/scope.js";
9
10
  import { useListing } from "../../react/useListing.js";
@@ -134,7 +135,8 @@ export function entityView(entity, options) {
134
135
  search: async (query) => {
135
136
  if (query.trim() === "")
136
137
  return [];
137
- meta ??= mounted.metas?.get(entity.key) ?? null;
138
+ meta ??=
139
+ (mounted.metas === null ? entity.meta : knownModelOf(mounted.metas, entity)) ?? null;
138
140
  if (meta?.search == null)
139
141
  return [];
140
142
  // A hit reads as a choice anywhere a record is picked by name: its name and what tells it
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sincpro/web-framework",
3
- "version": "4.0.0",
3
+ "version": "5.0.0",
4
4
  "description": "The web client of sincpro_framework: entities, lists and records bound to the metadata the server publishes, drawn with @sincpro/web-ui and arranged with @sincpro/web-composer.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -51,7 +51,7 @@
51
51
  "@opentelemetry/sdk-trace": "^3.1.0",
52
52
  "@sentry/browser": "^11.11.0",
53
53
  "@sentry/core": "^11.11.0",
54
- "@sincpro/client-framework": "^3.1.0",
54
+ "@sincpro/client-framework": "^3.2.0",
55
55
  "@sincpro/criteria": "^2.6.0",
56
56
  "@sincpro/criteria-react": "^2.5.1",
57
57
  "@sincpro/web-composer": "^1.7.0",
@@ -95,7 +95,7 @@
95
95
  "@opentelemetry/sdk-trace": "3.1.0",
96
96
  "@sentry/browser": "11.11.0",
97
97
  "@sentry/core": "11.11.0",
98
- "@sincpro/client-framework": "^3.1.0",
98
+ "@sincpro/client-framework": "^3.2.0",
99
99
  "@sincpro/criteria": "^2.6.0",
100
100
  "@sincpro/criteria-react": "^2.5.1",
101
101
  "@sincpro/web-composer": "^1.9.0",
@@ -1,42 +0,0 @@
1
- /**
2
- * What a screen keeps of running one of the application's use cases.
3
- *
4
- * `run` answers what the use case answered, or `undefined` when it failed — the failure is in
5
- * `error`, for the screen to say (`explain`, `Refused`); it never throws at the screen. So a use
6
- * case that answers nothing answers `null`, never `undefined`: a `DELETE` the server answers
7
- * with 204 resolves `null` through the transport, and a Feature hands that on instead of typing
8
- * itself `void` — or «done» and «failed» look the same to the screen
9
- * (Sincpro-SRL/sincpro_client_framework#51).
10
- */
11
- export type ServiceState<A extends unknown[], R> = {
12
- run: (...args: A) => Promise<R | undefined>;
13
- /** A run is on its way. */
14
- busy: boolean;
15
- /** What the last run answered, until another one starts or `reset`. */
16
- answer: R | undefined;
17
- error: unknown;
18
- reset: () => void;
19
- };
20
- /** A use case as a screen runs it: a method of a service, read from its bounded context. */
21
- type UseCase<A extends unknown[], R> = (...args: A) => R | Promise<R>;
22
- /**
23
- * One of the application's use cases, run from a screen.
24
- *
25
- * const close = useService(project.Issues.close);
26
- * <Button disabled={close.busy} onPress={() => close.run({ issue_id })}>Cerrar</Button>
27
- * {close.error ? <Refused error={close.error} /> : null}
28
- *
29
- * Context: all of an application's logic lives in its services (@sincpro/client-framework's
30
- * `Feature` and `ApplicationService`, reached through their bounded context), traced and reported
31
- * by its interceptors; what a screen adds is the state of running one — busy, the answer, the
32
- * failure. Written by hand, that state is the 300-line context every mobile screen repeats; here
33
- * it is one hook, the same for every use case. The span and the report are the service's: this
34
- * hook neither opens one nor reports. A bounded context answers the same function every time a
35
- * method is read, so `project.Issues.close` can be handed as it is.
36
- *
37
- * The last run wins: an answer that arrives after a newer run started is dropped, so a slow first
38
- * click never overwrites the second. A run is never aborted — the server may have done it — but
39
- * its answer does not land on a screen that left.
40
- */
41
- export declare function useService<A extends unknown[], R>(useCase: UseCase<A, R>): ServiceState<A, Awaited<R>>;
42
- export {};
@@ -1,51 +0,0 @@
1
- import { type Entity } from "@sincpro/client-framework";
2
- /** What a screen shows of a use case that reads: the answer to the arguments it asks with NOW. */
3
- export type ServiceReading<R> = {
4
- /** `loading` until the answer to these arguments arrives — never another's answer. */
5
- status: "loading" | "ready" | "failed";
6
- answer: R | undefined;
7
- error: unknown;
8
- /** Read again with the same arguments; the answer stays on screen until the new one. */
9
- reload: () => void;
10
- };
11
- /** A use case as a screen reads with it: a method of a service, read from its bounded context. */
12
- type UseCase<A extends unknown[], R> = (...args: A) => R | Promise<R>;
13
- /**
14
- * A use case that READS, run by the screen that shows it: on mount, again whenever its
15
- * arguments change, when the process's context changes (another company), and when a write
16
- * touches an entity it follows.
17
- *
18
- * const balance = useServiceReading(members.Accounts.balance, [{ member_id }], {
19
- * follows: [payments],
20
- * });
21
- * balance.status === "ready" ? <Stat value={text.money(balance.answer)} /> : <Skeleton />
22
- *
23
- * Context: `useService` is an ACTION's — it runs when a person presses, never on mount — and a
24
- * screen that read with it re-ran it by hand when a route param changed: easy to miss, and the
25
- * screen kept showing the answer of the tab it left. Here a reading is keyed by its arguments
26
- * (as JSON): the answer of other arguments is never shown — another member starts as `loading`,
27
- * as `useRecord` does for another id — while reading the same ones again keeps the answer on
28
- * screen until the new one lands. The last question wins: an answer to arguments no longer on
29
- * screen is dropped. The use case is the latest the screen gave (a bounded context answers a new
30
- * function per `scoped(…)`); its trace and report are the service's, never this hook's.
31
- *
32
- * `initial` is the answer to these same arguments already read — on the server that renders the
33
- * screen, in a route's loader, by calling the same use case. The reading starts `ready` with it,
34
- * renders it there, and in the browser keeps it on mount instead of reading again; a change of
35
- * arguments, a followed write or `reload()` read as always.
36
- *
37
- * const portada = useServiceReading(sitio.portada, [], { initial: loaderData.portada });
38
- *
39
- * `enabled: false` is a reading that cannot ask yet — nobody signed in, a key still unknown: it
40
- * stays `loading` and asks nothing, and reads as soon as it is enabled. Never answer a pending
41
- * promise from the use case to hold it back: the reading would wait on a question nobody asked.
42
- *
43
- * const perfil = useServiceReading(cuentas.perfil, [usuario], { enabled: usuario !== "" });
44
- */
45
- export declare function useServiceReading<A extends unknown[], R>(useCase: UseCase<A, R>, args: A, options?: {
46
- follows?: readonly Entity[];
47
- initial?: Awaited<R>;
48
- /** `false`: nothing to ask yet — it stays `loading` and asks nothing. `true` by default. */
49
- enabled?: boolean;
50
- }): ServiceReading<Awaited<R>>;
51
- export {};
@@ -1,88 +0,0 @@
1
- "use client";
2
- import {} from "@sincpro/client-framework";
3
- import { touches } from "../core/changes.js";
4
- import { useFramework } from "./context.js";
5
- import { useCallback, useEffect, useRef, useState } from "react";
6
- /**
7
- * A use case that READS, run by the screen that shows it: on mount, again whenever its
8
- * arguments change, when the process's context changes (another company), and when a write
9
- * touches an entity it follows.
10
- *
11
- * const balance = useServiceReading(members.Accounts.balance, [{ member_id }], {
12
- * follows: [payments],
13
- * });
14
- * balance.status === "ready" ? <Stat value={text.money(balance.answer)} /> : <Skeleton />
15
- *
16
- * Context: `useService` is an ACTION's — it runs when a person presses, never on mount — and a
17
- * screen that read with it re-ran it by hand when a route param changed: easy to miss, and the
18
- * screen kept showing the answer of the tab it left. Here a reading is keyed by its arguments
19
- * (as JSON): the answer of other arguments is never shown — another member starts as `loading`,
20
- * as `useRecord` does for another id — while reading the same ones again keeps the answer on
21
- * screen until the new one lands. The last question wins: an answer to arguments no longer on
22
- * screen is dropped. The use case is the latest the screen gave (a bounded context answers a new
23
- * function per `scoped(…)`); its trace and report are the service's, never this hook's.
24
- *
25
- * `initial` is the answer to these same arguments already read — on the server that renders the
26
- * screen, in a route's loader, by calling the same use case. The reading starts `ready` with it,
27
- * renders it there, and in the browser keeps it on mount instead of reading again; a change of
28
- * arguments, a followed write or `reload()` read as always.
29
- *
30
- * const portada = useServiceReading(sitio.portada, [], { initial: loaderData.portada });
31
- *
32
- * `enabled: false` is a reading that cannot ask yet — nobody signed in, a key still unknown: it
33
- * stays `loading` and asks nothing, and reads as soon as it is enabled. Never answer a pending
34
- * promise from the use case to hold it back: the reading would wait on a question nobody asked.
35
- *
36
- * const perfil = useServiceReading(cuentas.perfil, [usuario], { enabled: usuario !== "" });
37
- */
38
- export function useServiceReading(useCase, args, options = {}) {
39
- const { context, changes } = useFramework();
40
- const key = JSON.stringify(args);
41
- const latest = useRef({ useCase, args });
42
- latest.current = { useCase, args };
43
- const [answered, setAnswered] = useState(() => options.initial === undefined
44
- ? null
45
- : { key, status: "ready", answer: options.initial, error: null });
46
- // Born answered: the first read on mount is the one the server already made.
47
- const seeded = useRef(options.initial !== undefined);
48
- const [again, setAgain] = useState(0);
49
- const enabled = options.enabled ?? true;
50
- // A write anyone sends — a save, another use case, a panel beside — to what it follows.
51
- const followed = (options.follows ?? []).map((one) => one.model).join("\n");
52
- useEffect(() => {
53
- if (followed === "")
54
- return;
55
- const models = followed.split("\n");
56
- return changes.follow((change) => {
57
- if (models.some((model) => touches(change, { model })))
58
- setAgain((n) => n + 1);
59
- });
60
- }, [changes, followed]);
61
- useEffect(() => {
62
- if (!enabled)
63
- return;
64
- if (seeded.current) {
65
- seeded.current = false;
66
- return;
67
- }
68
- let current = true;
69
- const { useCase: read, args: now } = latest.current;
70
- // Through the promise: a use case that throws before it answers is a failure like any other.
71
- Promise.resolve()
72
- .then(() => read(...now))
73
- .then((answer) => {
74
- if (current)
75
- setAnswered({ key, status: "ready", answer: answer, error: null });
76
- }, (error) => {
77
- if (current)
78
- setAnswered({ key, status: "failed", answer: undefined, error });
79
- });
80
- return () => void (current = false);
81
- // `context` and `again` read again: another company, a followed write, a `reload()`; and
82
- // being enabled reads what had to wait.
83
- }, [key, context, again, enabled]);
84
- const reload = useCallback(() => setAgain((n) => n + 1), []);
85
- if (answered === null || answered.key !== key)
86
- return { status: "loading", answer: undefined, error: null, reload };
87
- return { status: answered.status, answer: answered.answer, error: answered.error, reload };
88
- }