@sincpro/web-framework 4.1.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.
@@ -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";
@@ -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
+ }
@@ -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>>;
@@ -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
+ }
@@ -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
@@ -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
@@ -3,7 +3,7 @@ import { jsx as _jsx } from "react/jsx-runtime";
3
3
  import { knownModelOf } from "../../core/models.js";
4
4
  import { entityFor } from "../../core/relation.js";
5
5
  import { useFrameworkIfAny } from "../../react/context.js";
6
- import { useService } from "../../react/useService.js";
6
+ import { useRunning } from "../../react/useRunning.js";
7
7
  import { ActionButton, useActionGesture, } from "./ActionButton.js";
8
8
  import { askFormOf, } from "./ask.js";
9
9
  import { dockedOf, } from "./dock.js";
@@ -41,8 +41,8 @@ export function useServiceAction({ icon, primary, danger, tucked, shortcut, hint
41
41
  }
42
42
  /** What runs behind a use case's button or dock action: the run, its dry run, what it asks. */
43
43
  function useServiceBehind({ run, rehearse, ask, entity, record }) {
44
- const running = useService((asked) => run(asked ?? NOTHING_ASKED));
45
- 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));
46
46
  // Outside a provider it still runs: the asked fields are then drawn by what `ask` says.
47
47
  const framework = useFrameworkIfAny();
48
48
  const form = ask === undefined
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sincpro/web-framework",
3
- "version": "4.1.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",
@@ -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
- }