@shivaedev/react 0.49.2 → 0.51.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 (151) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +188 -186
  3. package/dist/adapters/permissionGuard.d.ts +4 -3
  4. package/dist/adapters/permissionGuard.d.ts.map +1 -1
  5. package/dist/adapters/permissionGuard.js +3 -4
  6. package/dist/adapters/permissionGuard.js.map +1 -1
  7. package/dist/adapters/signInRedirect.d.ts +4 -0
  8. package/dist/adapters/signInRedirect.d.ts.map +1 -0
  9. package/dist/adapters/signInRedirect.js +6 -0
  10. package/dist/adapters/signInRedirect.js.map +1 -0
  11. package/dist/client/FailureHostContext.d.ts +3 -0
  12. package/dist/client/FailureHostContext.d.ts.map +1 -0
  13. package/dist/client/FailureHostContext.js +3 -0
  14. package/dist/client/FailureHostContext.js.map +1 -0
  15. package/dist/client/NoticeContext.d.ts +1 -1
  16. package/dist/client/QueryView.d.ts +20 -5
  17. package/dist/client/QueryView.d.ts.map +1 -1
  18. package/dist/client/QueryView.js +23 -3
  19. package/dist/client/QueryView.js.map +1 -1
  20. package/dist/client/actionCompletion.d.ts +6 -5
  21. package/dist/client/actionCompletion.d.ts.map +1 -1
  22. package/dist/client/actionCompletion.js +19 -18
  23. package/dist/client/actionCompletion.js.map +1 -1
  24. package/dist/client/adapters/formFields.d.ts +4 -0
  25. package/dist/client/adapters/formFields.d.ts.map +1 -0
  26. package/dist/client/adapters/formFields.js +30 -0
  27. package/dist/client/adapters/formFields.js.map +1 -0
  28. package/dist/client/adapters/operationHooks.d.ts +5 -0
  29. package/dist/client/adapters/operationHooks.d.ts.map +1 -0
  30. package/dist/client/adapters/operationHooks.js +7 -0
  31. package/dist/client/adapters/operationHooks.js.map +1 -0
  32. package/dist/{adapters → client/adapters}/queryRoute.d.ts +12 -5
  33. package/dist/client/adapters/queryRoute.d.ts.map +1 -0
  34. package/dist/{adapters → client/adapters}/queryRoute.js +14 -1
  35. package/dist/client/adapters/queryRoute.js.map +1 -0
  36. package/dist/client/adapters/rowValues.d.ts +7 -0
  37. package/dist/client/adapters/rowValues.d.ts.map +1 -0
  38. package/dist/client/adapters/rowValues.js +17 -0
  39. package/dist/client/adapters/rowValues.js.map +1 -0
  40. package/dist/client/adapters/useFeedback.d.ts +11 -0
  41. package/dist/client/adapters/useFeedback.d.ts.map +1 -0
  42. package/dist/client/adapters/useFeedback.js +38 -0
  43. package/dist/client/adapters/useFeedback.js.map +1 -0
  44. package/dist/client/adapters/useQueryNotice.js +1 -1
  45. package/dist/client/adapters/useQueryNotice.js.map +1 -1
  46. package/dist/client/adapters/useStableRun.js +1 -1
  47. package/dist/client/adapters/useStableRun.js.map +1 -1
  48. package/dist/client/adapters/useSubmissionCallbacks.d.ts +4 -5
  49. package/dist/client/adapters/useSubmissionCallbacks.d.ts.map +1 -1
  50. package/dist/client/adapters/useSubmissionCallbacks.js +37 -17
  51. package/dist/client/adapters/useSubmissionCallbacks.js.map +1 -1
  52. package/dist/client/adapters/useUndoableChange.d.ts +13 -12
  53. package/dist/client/adapters/useUndoableChange.d.ts.map +1 -1
  54. package/dist/client/adapters/useUndoableChange.js +16 -4
  55. package/dist/client/adapters/useUndoableChange.js.map +1 -1
  56. package/dist/client/boundOperation.d.ts +12 -0
  57. package/dist/client/boundOperation.d.ts.map +1 -0
  58. package/dist/client/boundOperation.js +2 -0
  59. package/dist/client/boundOperation.js.map +1 -0
  60. package/dist/client/create.d.ts +15 -11
  61. package/dist/client/create.d.ts.map +1 -1
  62. package/dist/client/create.js +12 -5
  63. package/dist/client/create.js.map +1 -1
  64. package/dist/client/editor.d.ts +25 -18
  65. package/dist/client/editor.d.ts.map +1 -1
  66. package/dist/client/editor.js +14 -8
  67. package/dist/client/editor.js.map +1 -1
  68. package/dist/client/failureDecision.d.ts +16 -0
  69. package/dist/client/failureDecision.d.ts.map +1 -0
  70. package/dist/client/failureDecision.js +49 -0
  71. package/dist/client/failureDecision.js.map +1 -0
  72. package/dist/client/failures.d.ts +45 -0
  73. package/dist/client/failures.d.ts.map +1 -0
  74. package/dist/client/failures.js +2 -0
  75. package/dist/client/failures.js.map +1 -0
  76. package/dist/client/notices.d.ts +9 -4
  77. package/dist/client/notices.d.ts.map +1 -1
  78. package/dist/client/notices.js +22 -3
  79. package/dist/client/notices.js.map +1 -1
  80. package/dist/client/operationForm.d.ts +40 -0
  81. package/dist/client/operationForm.d.ts.map +1 -0
  82. package/dist/client/operationForm.js +2 -0
  83. package/dist/client/operationForm.js.map +1 -0
  84. package/dist/client/pendingCommand.d.ts +6 -9
  85. package/dist/client/pendingCommand.d.ts.map +1 -1
  86. package/dist/client/pendingCommand.js +3 -3
  87. package/dist/client/pendingCommand.js.map +1 -1
  88. package/dist/client/resultState.d.ts +7 -4
  89. package/dist/client/resultState.d.ts.map +1 -1
  90. package/dist/client/resultState.js +6 -3
  91. package/dist/client/resultState.js.map +1 -1
  92. package/dist/client/unexpectedFailure.d.ts +8 -0
  93. package/dist/client/unexpectedFailure.d.ts.map +1 -0
  94. package/dist/client/unexpectedFailure.js +17 -0
  95. package/dist/client/unexpectedFailure.js.map +1 -0
  96. package/dist/client/useDebouncedValue.js +1 -1
  97. package/dist/client/useDebouncedValue.js.map +1 -1
  98. package/dist/client/useDelay.js +1 -1
  99. package/dist/client/useDelay.js.map +1 -1
  100. package/dist/noticeEntry.d.ts +3 -1
  101. package/dist/noticeEntry.d.ts.map +1 -1
  102. package/dist/noticeEntry.js +2 -1
  103. package/dist/noticeEntry.js.map +1 -1
  104. package/dist/noticeStore.d.ts +3 -3
  105. package/dist/noticeStore.d.ts.map +1 -1
  106. package/dist/noticeStore.js +4 -4
  107. package/dist/noticeStore.js.map +1 -1
  108. package/dist/noticeTypes.d.ts +1 -2
  109. package/dist/noticeTypes.d.ts.map +1 -1
  110. package/dist/submission.d.ts +2 -4
  111. package/dist/submission.d.ts.map +1 -1
  112. package/dist/submission.js +1 -3
  113. package/dist/submission.js.map +1 -1
  114. package/package.json +13 -13
  115. package/src/adapters/permissionGuard.ts +6 -5
  116. package/src/adapters/signInRedirect.ts +7 -0
  117. package/src/client/FailureHostContext.ts +4 -0
  118. package/src/client/QueryView.ts +50 -7
  119. package/src/client/actionCompletion.ts +33 -23
  120. package/src/client/adapters/formFields.ts +33 -0
  121. package/src/client/adapters/operationHooks.ts +14 -0
  122. package/src/{adapters → client/adapters}/queryRoute.ts +24 -9
  123. package/src/client/adapters/rowValues.ts +25 -0
  124. package/src/client/adapters/useFeedback.ts +50 -0
  125. package/src/client/adapters/useQueryNotice.ts +1 -1
  126. package/src/client/adapters/useStableRun.ts +1 -1
  127. package/src/client/adapters/useSubmissionCallbacks.ts +44 -21
  128. package/src/client/adapters/useUndoableChange.ts +66 -30
  129. package/src/client/boundOperation.ts +13 -0
  130. package/src/client/create.ts +50 -20
  131. package/src/client/editor.ts +98 -38
  132. package/src/client/failureDecision.ts +70 -0
  133. package/src/client/failures.ts +56 -0
  134. package/src/client/notices.ts +44 -6
  135. package/src/client/operationForm.ts +52 -0
  136. package/src/client/pendingCommand.ts +12 -14
  137. package/src/client/resultState.ts +20 -11
  138. package/src/client/unexpectedFailure.ts +24 -0
  139. package/src/client/useDebouncedValue.ts +1 -1
  140. package/src/client/useDelay.ts +1 -1
  141. package/src/noticeEntry.ts +5 -0
  142. package/src/noticeStore.ts +9 -4
  143. package/src/noticeTypes.ts +1 -2
  144. package/src/submission.ts +4 -6
  145. package/dist/adapters/queryRoute.d.ts.map +0 -1
  146. package/dist/adapters/queryRoute.js.map +0 -1
  147. package/dist/client/adapters/useNoticePublisher.d.ts +0 -4
  148. package/dist/client/adapters/useNoticePublisher.d.ts.map +0 -1
  149. package/dist/client/adapters/useNoticePublisher.js +0 -8
  150. package/dist/client/adapters/useNoticePublisher.js.map +0 -1
  151. package/src/client/adapters/useNoticePublisher.ts +0 -10
@@ -0,0 +1,56 @@
1
+ import type { AppRejection } from "@shivaedev/contract/failureKind.ts";
2
+ import type { FieldRejection } from "@shivaedev/form/fieldRejection.ts";
3
+ import type { Decoded, FieldFailure, Fields, Name } from "@shivaedev/form/shape.ts";
4
+ import type { NoticeDescriptor } from "#client/notices.ts";
5
+
6
+ type Tag<E> = E extends { readonly _tag: infer TTag extends string } ? TTag : never;
7
+ type Tagged<E, TTag> = Extract<E, { readonly _tag: TTag }>;
8
+
9
+ export type FailureChoice<TError, TInput, TOutcome> = "silent" | "message" | ((error: TError, input: TInput) => TOutcome | "silent");
10
+
11
+ export type FailureHandlers<E, TInput, TOutcome> = {
12
+ readonly [TTag in Tag<E>]?: FailureChoice<Tagged<E, TTag>, TInput, TOutcome>;
13
+ };
14
+
15
+ export type Unhandled<E, TRouted = never> = Tag<Exclude<AppRejection<E>, TRouted>>;
16
+
17
+ // tsc prints this alias with the tags it still needs, so a missing handler is named in the error.
18
+ export type HandleAppRejections<TTags extends string, E, TInput, TOutcome> = {
19
+ readonly [TTag in TTags]: FailureChoice<Tagged<E, TTag>, TInput, TOutcome>;
20
+ } & FailureHandlers<E, TInput, TOutcome>;
21
+
22
+ export type FailuresOption<E, TInput, TOutcome, TSilent extends boolean, TRouted = never> = { readonly silent?: TSilent } & (TSilent extends true
23
+ ? { readonly failures?: FailureHandlers<E, TInput, TOutcome> }
24
+ : [Unhandled<E, TRouted>] extends [never]
25
+ ? { readonly failures?: FailureHandlers<E, TInput, TOutcome> }
26
+ : { readonly failures: HandleAppRejections<Unhandled<E, TRouted>, E, TInput, TOutcome> });
27
+
28
+ export type FailuresChecked<E> = [Unhandled<E>] extends [never]
29
+ ? unknown
30
+ : {
31
+ readonly [TTag in Unhandled<E> as `failures.${TTag}`]: `the operation can fail with ${TTag}, a rejection the app declared: say what it shows, for example failures: { ${TTag}: "message" }`;
32
+ };
33
+
34
+ export type FieldRouted<TFields, E> = E extends { readonly _tag: string; readonly field: infer TField extends string; readonly message: string }
35
+ ? string extends TField
36
+ ? never
37
+ : [TField] extends [TFields]
38
+ ? E
39
+ : never
40
+ : never;
41
+
42
+ // A notice carries no `field`, so a handler that names a field the form lacks does not compile.
43
+ export type FormFailureOutcome<TDescriptor, TFields extends Fields> = (TDescriptor & { readonly field?: never }) | FieldRejection<Name<TFields>>;
44
+
45
+ export interface FailureChoices {
46
+ readonly failures?: Readonly<Record<string, unknown>> | undefined;
47
+ readonly silent?: boolean | undefined;
48
+ }
49
+
50
+ export type FormFailuresOption<TFields extends Fields, E, R, TSilent extends boolean> = FailuresOption<
51
+ E,
52
+ Decoded<TFields>,
53
+ FormFailureOutcome<NoticeDescriptor<R>, TFields>,
54
+ TSilent,
55
+ FieldRouted<Name<TFields>, E> | FieldFailure
56
+ >;
@@ -2,10 +2,12 @@ import { RegistryContext, useAtomValue } from "@effect/atom-react";
2
2
  import { Layer } from "effect";
3
3
  import type * as AsyncResult from "effect/reactivity/AsyncResult";
4
4
  import * as Atom from "effect/reactivity/Atom";
5
- import { createElement, Fragment, type ReactNode, useContext, useLayoutEffect, useMemo } from "react";
5
+ import { createElement, Fragment, type ReactNode, useContext, useInsertionEffect, useLayoutEffect, useMemo, useRef } from "react";
6
6
  import { closeInactiveNotice } from "#client/adapters/closeInactiveNotice.ts";
7
+ import { FailureHostContext } from "#client/FailureHostContext.ts";
7
8
  import { NoticeContext } from "#client/NoticeContext.ts";
8
- import type { NoticeClock, NoticeEntry } from "#noticeEntry.ts";
9
+ import type { UnexpectedFailure } from "#client/unexpectedFailure.ts";
10
+ import type { NoticeClock, NoticeEntry, NoticeKind } from "#noticeEntry.ts";
9
11
  import { noticeStore } from "#noticeStore.ts";
10
12
  import type { NoticeDescriptor as SharedNoticeDescriptor, NoticeFeedback as SharedNoticeFeedback } from "#noticeTypes.ts";
11
13
 
@@ -21,15 +23,18 @@ export interface Notice {
21
23
  | undefined;
22
24
  readonly dismiss: () => void;
23
25
  readonly id: number;
26
+ readonly kind: NoticeKind;
24
27
  readonly message: ReactNode;
25
28
  }
26
- export interface NoticeFeedback<TInput, A, E, R = never> extends SharedNoticeFeedback<TInput, A, E, R, ReactNode> {}
29
+ export interface NoticeFeedback<TInput, A, R = never> extends SharedNoticeFeedback<TInput, A, R, ReactNode> {}
30
+ export type FailureNotice = Omit<NoticeDescriptor, "action">;
27
31
  function Entry({ entry, render }: { readonly entry: NoticeEntry<ReactNode>; readonly render: (notice: Notice) => ReactNode }) {
28
32
  const result = useAtomValue(entry.status);
29
33
  return render({
30
34
  action: entry.action === undefined ? undefined : { ...entry.action, pending: result.waiting, result },
31
35
  dismiss: entry.dismiss,
32
36
  id: entry.id,
37
+ kind: entry.kind,
33
38
  message: entry.message,
34
39
  });
35
40
  }
@@ -38,20 +43,53 @@ function Entries({ store, render }: { readonly store: ReturnType<typeof noticeSt
38
43
  return entries.map((entry) => createElement(Entry, { entry, key: entry.id, render }));
39
44
  }
40
45
  const defaultClock = Atom.runtime(Layer.empty);
46
+ export function renderNotice(notice: Notice): ReactNode {
47
+ const action = notice.action;
48
+ return createElement(
49
+ "div",
50
+ { "data-notice": notice.kind, role: notice.kind === "success" ? "status" : "alert" },
51
+ createElement("p", null, notice.message),
52
+ action && createElement("button", { disabled: action.pending, onClick: action.run, type: "button" }, action.label),
53
+ createElement("button", { onClick: notice.dismiss, type: "button" }, "Dismiss"),
54
+ );
55
+ }
56
+ function failureNotice(failure: UnexpectedFailure): FailureNotice {
57
+ return { message: failure.message };
58
+ }
41
59
  export function NoticeHost({
42
60
  children,
43
- render,
61
+ failure = failureNotice,
62
+ render = renderNotice,
44
63
  runtime = defaultClock,
45
64
  }: {
46
65
  readonly children: ReactNode;
47
- readonly render: (notice: Notice) => ReactNode;
66
+ // The one place an application words the failures no screen handles: transport, server outages and defects.
67
+ readonly failure?: ((failure: UnexpectedFailure) => FailureNotice | "silent") | undefined;
68
+ readonly render?: ((notice: Notice) => ReactNode) | undefined;
48
69
  readonly runtime?: NoticeClock | undefined;
49
70
  }): ReactNode {
50
71
  const registry = useContext(RegistryContext);
51
72
  const store = useMemo(() => noticeStore<ReactNode>(registry, runtime), [registry, runtime]);
73
+ const wordingRef = useRef(failure);
74
+ useInsertionEffect(() => {
75
+ wordingRef.current = failure;
76
+ }, [failure]);
77
+ const report = useMemo(
78
+ () => (unexpected: UnexpectedFailure) => {
79
+ const descriptor = wordingRef.current(unexpected);
80
+ if (descriptor !== "silent") {
81
+ store.publish(descriptor, "failure");
82
+ }
83
+ },
84
+ [store],
85
+ );
52
86
  useLayoutEffect(() => {
53
87
  store.active = true;
54
88
  return () => closeInactiveNotice(store);
55
89
  }, [store]);
56
- return createElement(NoticeContext.Provider, { value: store }, createElement(Fragment, null, children, createElement(Entries, { render, store })));
90
+ return createElement(
91
+ NoticeContext.Provider,
92
+ { value: store },
93
+ createElement(FailureHostContext.Provider, { value: report }, createElement(Fragment, null, children, createElement(Entries, { render, store }))),
94
+ );
57
95
  }
@@ -0,0 +1,52 @@
1
+ import type { Schema } from "effect";
2
+ import type { Decoded, Encoded, Fields } from "@shivaedev/form/shape.ts";
3
+
4
+ export type NoFixed = Record<never, never>;
5
+
6
+ type FieldsWithout<TPayload, TFixedKey> =
7
+ TPayload extends Schema.Struct<infer TPayloadFields>
8
+ ? { readonly [TKey in keyof TPayloadFields as TKey extends TFixedKey ? never : TKey]: TPayloadFields[TKey] }
9
+ : never;
10
+
11
+ export type FormFields<TPayload, TFixed, TFields extends Fields> = [TFields] extends [never]
12
+ ? Extract<FieldsWithout<TPayload, keyof TFixed>, Fields>
13
+ : TFields;
14
+
15
+ export type FieldsOption<TPayload, TFields extends Fields> = [TPayload] extends [Schema.Struct<infer _Fields>]
16
+ ? { readonly fields?: Schema.Struct<TFields> }
17
+ : { readonly fields: Schema.Struct<TFields> };
18
+
19
+ type FixedValues<TInput, TFixed, TRequired> = {
20
+ readonly [TKey in keyof TFixed]: TKey extends keyof TInput ? TInput[TKey] : "is not a field of the command's payload";
21
+ } & { readonly [TKey in Extract<TRequired, keyof TInput>]: TInput[TKey] };
22
+
23
+ // `fixed` and the form's fields together give the command its whole payload, so a key missing from both or foreign to the payload fails to compile.
24
+ export type FixedOption<TInput, TFixed, TRequired> = [TRequired] extends [never]
25
+ ? { readonly fixed?: TFixed & FixedValues<TInput, TFixed, never> }
26
+ : { readonly fixed: TFixed & FixedValues<TInput, TFixed, TRequired> };
27
+
28
+ export type Unfixed<TInput, TFields extends Fields, TFixed> = Exclude<keyof TInput, keyof Decoded<TFields> | keyof TFixed>;
29
+
30
+ export type DecodingServicesOption<TFields extends Fields, R> = [Exclude<Schema.Struct.DecodingServices<TFields>, R>] extends [never]
31
+ ? unknown
32
+ : { readonly "the operation's runtime must provide the services its form fields decode with": Exclude<Schema.Struct.DecodingServices<TFields>, R> };
33
+
34
+ type Shared<TRow, TFields extends Fields> = keyof Decoded<TFields> & keyof TRow;
35
+
36
+ export type MissingFromRow<TRow, TFields extends Fields> = Exclude<keyof Decoded<TFields>, keyof TRow>;
37
+
38
+ type RowMatches<TRow, TFields extends Fields> = [Pick<TRow, Shared<TRow, TFields>>] extends [Pick<Decoded<TFields>, Shared<TRow, TFields>>]
39
+ ? [Schema.Struct.EncodingServices<TFields>] extends [never]
40
+ ? true
41
+ : false
42
+ : false;
43
+
44
+ // Without `values`, each form value is the row's value of the same name, encoded by its field; a row that cannot supply them needs `values`.
45
+ export type ValuesOption<TRow, TFields extends Fields, TDerived extends boolean> =
46
+ RowMatches<TRow, TFields> extends true
47
+ ? TDerived extends true
48
+ ? { readonly values?: (row: TRow) => Encoded<TFields> }
49
+ : [MissingFromRow<TRow, TFields>] extends [never]
50
+ ? { readonly values?: (row: TRow) => Encoded<TFields> }
51
+ : { readonly values: (row: TRow) => Encoded<TFields> }
52
+ : { readonly values: (row: TRow) => Encoded<TFields> };
@@ -1,36 +1,34 @@
1
1
  import { RegistryContext, useAtomValue } from "@effect/atom-react";
2
- import { type Effect, Option } from "effect";
2
+ import { Option } from "effect";
3
3
  import * as AsyncResult from "effect/reactivity/AsyncResult";
4
4
  import * as Atom from "effect/reactivity/Atom";
5
5
  import { useContext, useMemo, useState } from "react";
6
6
  import { untilReflected } from "@shivaedev/contract/commandSignal.ts";
7
- import type { AtomServices } from "#AtomServices.ts";
8
- import { type ActionState, useAction } from "#client/resultState.ts";
7
+ import type { BoundOperation } from "#client/boundOperation.ts";
8
+ import type { FailuresOption } from "#client/failures.ts";
9
+ import type { NoticeDescriptor } from "#client/notices.ts";
10
+ import { type ActionState, useActionState } from "#client/resultState.ts";
9
11
 
10
- export interface PendingCommand<TInput, A, E, R, TRuntimeError> {
11
- readonly run: (input: TInput) => Effect.Effect<A, E, AtomServices<R>>;
12
- readonly runtime: Atom.AtomRuntime<R, TRuntimeError>;
13
- }
14
- export interface PendingCommandOptions<TInput, TValue> {
12
+ export type PendingCommandOptions<TInput, TValue, E = never, R = never, TSilent extends boolean = false> = {
15
13
  readonly queries?: readonly Atom.Atom<AsyncResult.AsyncResult<unknown, unknown>>[];
16
14
  readonly value: TValue;
17
15
  readonly wanted: (input: TInput) => TValue;
18
- }
16
+ } & FailuresOption<E, TInput, NoticeDescriptor<R>, TSilent>;
19
17
  export interface PendingCommandState<TInput, A, E, TValue> extends ActionState<TInput, A, E> {
20
18
  readonly value: TValue;
21
19
  }
22
20
 
23
21
  const NO_QUERIES: readonly Atom.Atom<AsyncResult.AsyncResult<unknown, unknown>>[] = [];
24
22
 
25
- export function usePendingCommand<TInput, A, E, R, TRuntimeError, TValue>(
26
- command: PendingCommand<TInput, A, E, R, TRuntimeError>,
27
- options: PendingCommandOptions<NoInfer<TInput>, TValue>,
23
+ export function usePendingCommand<TInput, A, E, R, TRuntimeError, TValue, TSilent extends boolean = false>(
24
+ command: BoundOperation<TInput, A, E, R, TRuntimeError>,
25
+ options: PendingCommandOptions<NoInfer<TInput>, TValue, E, R, TSilent>,
28
26
  ): PendingCommandState<TInput, A, E | TRuntimeError, TValue> {
29
27
  const { run, runtime } = command;
30
- const { queries = NO_QUERIES, value, wanted } = options;
28
+ const { failures, queries = NO_QUERIES, silent, value, wanted } = options;
31
29
  // The reply arrives before the live queries the command changed are updated, so the action ends when the command is reflected.
32
30
  const reflected = useMemo(() => (input: TInput) => untilReflected(run(input)), [run]);
33
- const action = useAction(runtime, reflected);
31
+ const action = useActionState({ run: reflected, runtime }, { failures, silent });
34
32
  const registry = useContext(RegistryContext);
35
33
  const refreshing = useAtomValue(useMemo(() => Atom.make((get) => queries.some((query) => get(query).waiting)), [queries]));
36
34
  const [held, hold] = useState({ reflected, registry, value: Option.none<TValue>() });
@@ -1,15 +1,16 @@
1
1
  import { RegistryContext, useAtomRefresh, useAtomSet, useAtomValue } from "@effect/atom-react";
2
- import { Cause, type Effect, Option, Predicate } from "effect";
2
+ import { Cause, Option, Predicate } from "effect";
3
3
  import * as AsyncResult from "effect/reactivity/AsyncResult";
4
4
  import type * as Atom from "effect/reactivity/Atom";
5
5
  import type * as AtomRegistry from "effect/reactivity/AtomRegistry";
6
6
  import { useContext, useEffect, useState } from "react";
7
7
  import { isUnauthorized } from "@shivaedev/errors/taxonomy.ts";
8
- import type { AtomServices } from "#AtomServices.ts";
9
- import { type ActionOptions, useActionSource } from "#client/actionCompletion.ts";
8
+ import { type ActionOptions, type OperationActionOptions, useActionSource } from "#client/actionCompletion.ts";
10
9
  import { useActionResult } from "#client/adapters/useActionResult.ts";
11
10
  import { usePermissionFailure } from "#client/adapters/usePermissionFailure.ts";
12
11
  import { useQueryNotice } from "#client/adapters/useQueryNotice.ts";
12
+ import type { BoundOperation } from "#client/boundOperation.ts";
13
+ import type { FailureChoices, FailuresChecked } from "#client/failures.ts";
13
14
  import type { NoticeDescriptor } from "#client/notices.ts";
14
15
  import { useSessionRecheck } from "#client/sessionBoundary.ts";
15
16
 
@@ -89,18 +90,26 @@ export interface ActionState<TInput, A, E> extends ResultState<A, E> {
89
90
  readonly dispatch: (input: TInput) => void;
90
91
  }
91
92
  export function useAction<TInput, A, E>(atom: Atom.AtomResultFn<TInput, A, E>): ActionState<TInput, A, E>;
93
+ export function useAction<TInput, A, E, R, TRuntimeError, TSilent extends boolean = false>(
94
+ operation: BoundOperation<TInput, A, E, R, TRuntimeError>,
95
+ options: OperationActionOptions<TInput, A, E, R, TSilent>,
96
+ ): ActionState<TInput, A, E | TRuntimeError>;
97
+ // Declared last so that a call without options reports this overload's error, which names each rejection that needs `failures`.
92
98
  export function useAction<TInput, A, E, R, TRuntimeError>(
93
- runtime: Atom.AtomRuntime<R, TRuntimeError>,
94
- run: (input: TInput) => Effect.Effect<A, E, AtomServices<R>>,
95
- options?: ActionOptions<NoInfer<TInput>, NoInfer<A>, NoInfer<E>, R>,
99
+ operation: BoundOperation<TInput, A, E, R, TRuntimeError> & FailuresChecked<E>,
96
100
  ): ActionState<TInput, A, E | TRuntimeError>;
97
101
  export function useAction<TInput, A, E, R, TRuntimeError>(
98
- source: Atom.AtomResultFn<TInput, A, E> | Atom.AtomRuntime<R, TRuntimeError>,
99
- run?: (input: TInput) => Effect.Effect<A, E, AtomServices<R>>,
100
- options: ActionOptions<TInput, A, E, R> = {},
102
+ source: Atom.AtomResultFn<TInput, A, E> | BoundOperation<TInput, A, E, R, TRuntimeError>,
103
+ options: ActionOptions<TInput, A, E, R> & FailureChoices = {},
104
+ ): ActionState<TInput, A, E | TRuntimeError> {
105
+ return useActionState(source, options);
106
+ }
107
+ export function useActionState<TInput, A, E, R, TRuntimeError>(
108
+ source: Atom.AtomResultFn<TInput, A, E> | BoundOperation<TInput, A, E, R, TRuntimeError>,
109
+ options: ActionOptions<TInput, A, E, R> & FailureChoices = {},
101
110
  ): ActionState<TInput, A, E | TRuntimeError> {
102
- const atom = useActionSource(source, run, options);
111
+ const atom = useActionSource(source, options);
103
112
  const result = useActionResult(atom);
104
- useRecheckOnUnauthorized(result, run === undefined);
113
+ useRecheckOnUnauthorized(result, !("runtime" in source));
105
114
  return { ...state(result), dispatch: useAtomSet(atom) };
106
115
  }
@@ -0,0 +1,24 @@
1
+ import { Cause, Option, Predicate } from "effect";
2
+ import { isAuthUnavailable, isInternalServerError, isServiceUnavailable } from "@shivaedev/errors/taxonomy.ts";
3
+
4
+ // `cause` is for the application's diagnostics; only `message` is meant for the person.
5
+ export interface UnexpectedFailure {
6
+ readonly cause: Cause.Cause<unknown>;
7
+ readonly kind: "connection" | "unavailable" | "unexpected";
8
+ readonly message: string;
9
+ }
10
+
11
+ export function unexpectedFailure(cause: Cause.Cause<unknown>): UnexpectedFailure {
12
+ const error = Option.getOrUndefined(Cause.findErrorOption(cause));
13
+ if (Predicate.isTagged(error, "RpcClientError") || Predicate.isTagged(error, "WebSocketRequired")) {
14
+ return { cause, kind: "connection", message: "Could not reach the server. Check your connection and try again." };
15
+ }
16
+ // These messages come from the server's handler edge, which has already redacted them.
17
+ if (isServiceUnavailable(error) || isAuthUnavailable(error)) {
18
+ return { cause, kind: "unavailable", message: error.message };
19
+ }
20
+ if (isInternalServerError(error)) {
21
+ return { cause, kind: "unexpected", message: error.message };
22
+ }
23
+ return { cause, kind: "unexpected", message: "Something went wrong. Try again." };
24
+ }
@@ -22,7 +22,7 @@ function debounce<A>(value: A, millis: number, runtime: TimerRuntime) {
22
22
 
23
23
  export function useDebouncedValue<A>(value: A, duration: Duration.Input, runtime: TimerRuntime = defaultRuntime): A {
24
24
  const registry = useContext(RegistryContext);
25
- const millis = Duration.toMillis(Duration.fromInputUnsafe(duration));
25
+ const millis = Duration.toMillis(duration);
26
26
  const [held, hold] = useState(() => ({ ...debounce(value, millis, runtime), registry, runtime }));
27
27
  let owner = held;
28
28
  if (held.registry !== registry || held.runtime !== runtime) {
@@ -8,7 +8,7 @@ type TimerRuntime = Pick<Atom.AtomRuntime<never, unknown>, "fn">;
8
8
 
9
9
  export function useDelay(duration: Duration.Input, runtime: TimerRuntime = defaultRuntime) {
10
10
  const registry = useContext(RegistryContext);
11
- const millis = Duration.toMillis(Duration.fromInputUnsafe(duration));
11
+ const millis = Duration.toMillis(duration);
12
12
  const timer = useMemo(
13
13
  () => runtime.fn((complete: () => void) => Effect.andThen(Effect.sleep(millis), Effect.sync(complete))).pipe(Atom.setIdleTTL(0)),
14
14
  [runtime, millis],
@@ -9,10 +9,13 @@ export interface NoticeAction<TMessage = unknown> {
9
9
  readonly label: TMessage;
10
10
  }
11
11
  export type NoticeClock = Pick<Atom.AtomRuntime<never, unknown>, "atom">;
12
+ // A success reports what a command did, a rejection why the server refused it, a failure that the framework could not complete it.
13
+ export type NoticeKind = "failure" | "rejection" | "success";
12
14
  export interface NoticeEntry<TMessage = unknown> {
13
15
  readonly action?: { readonly label: TMessage; readonly run: () => void } | undefined;
14
16
  readonly dismiss: () => void;
15
17
  readonly id: number;
18
+ readonly kind: NoticeKind;
16
19
  readonly message: TMessage;
17
20
  readonly release: () => void;
18
21
  readonly status: Atom.Atom<AsyncResult.AsyncResult<unknown, unknown>>;
@@ -25,6 +28,7 @@ export function noticeEntry<TMessage>(
25
28
  descriptor: Pick<NoticeDescriptor<never, TMessage>, "message" | "expiresIn">,
26
29
  remove: (id: number) => void,
27
30
  action: NoticeAction<TMessage> | undefined,
31
+ kind: NoticeKind,
28
32
  ): NoticeEntry<TMessage> {
29
33
  let active = true;
30
34
  function dismiss() {
@@ -63,6 +67,7 @@ export function noticeEntry<TMessage>(
63
67
  action: action === undefined ? undefined : { label: action.label, run },
64
68
  dismiss,
65
69
  id,
70
+ kind,
66
71
  message: descriptor.message,
67
72
  release,
68
73
  status: action?.atom ?? idle,
@@ -1,6 +1,6 @@
1
1
  import * as Atom from "effect/reactivity/Atom";
2
2
  import type * as AtomRegistry from "effect/reactivity/AtomRegistry";
3
- import { type NoticeAction, type NoticeClock, type NoticeEntry, noticeEntry } from "#noticeEntry.ts";
3
+ import { type NoticeAction, type NoticeClock, type NoticeEntry, type NoticeKind, noticeEntry } from "#noticeEntry.ts";
4
4
  import type { NoticeDescriptor } from "#noticeTypes.ts";
5
5
 
6
6
  export function noticeStore<TMessage = unknown>(registry: AtomRegistry.AtomRegistry, clock: NoticeClock) {
@@ -22,11 +22,11 @@ export function noticeStore<TMessage = unknown>(registry: AtomRegistry.AtomRegis
22
22
  registry.set(entries, []);
23
23
  },
24
24
  entries,
25
- publish: (descriptor: Pick<NoticeDescriptor<never, TMessage>, "message" | "expiresIn">, action?: NoticeAction<TMessage>) => {
25
+ publish: (descriptor: Pick<NoticeDescriptor<never, TMessage>, "message" | "expiresIn">, kind: NoticeKind, action?: NoticeAction<TMessage>) => {
26
26
  if (!store.active) {
27
27
  return;
28
28
  }
29
- const entry = noticeEntry(registry, clock, nextId, descriptor, remove, action);
29
+ const entry = noticeEntry(registry, clock, nextId, descriptor, remove, action, kind);
30
30
  nextId += 1;
31
31
  registry.set(entries, [...registry.get(entries), entry]);
32
32
  },
@@ -37,10 +37,15 @@ export function publishNotice<R, E, TMessage = unknown>(
37
37
  store: ReturnType<typeof noticeStore<TMessage>> | undefined,
38
38
  runtime: Atom.AtomRuntime<R, E>,
39
39
  descriptor: NoticeDescriptor<R, TMessage> | undefined,
40
+ kind: NoticeKind,
40
41
  ) {
41
42
  if (!(store?.active && descriptor)) {
42
43
  return;
43
44
  }
44
45
  const action = descriptor.action;
45
- store.publish(descriptor, action === undefined ? undefined : { atom: runtime.fn(() => action.run).pipe(Atom.setIdleTTL(0)), label: action.label });
46
+ store.publish(
47
+ descriptor,
48
+ kind,
49
+ action === undefined ? undefined : { atom: runtime.fn(() => action.run).pipe(Atom.setIdleTTL(0)), label: action.label },
50
+ );
46
51
  }
@@ -12,7 +12,6 @@ export interface NoticeDescriptor<R = never, TMessage = unknown> {
12
12
  readonly message: TMessage;
13
13
  }
14
14
 
15
- export interface NoticeFeedback<TInput, A, E, R = never, TMessage = unknown> {
16
- readonly onFailure?: (error: E, input: TInput) => NoticeDescriptor<R, TMessage> | undefined;
15
+ export interface NoticeFeedback<TInput, A, R = never, TMessage = unknown> {
17
16
  readonly onSuccess?: (value: A, input: TInput) => NoticeDescriptor<R, TMessage> | undefined;
18
17
  }
package/src/submission.ts CHANGED
@@ -1,9 +1,8 @@
1
1
  import type { Effect, Schema } from "effect";
2
2
  import type * as Atom from "effect/reactivity/Atom";
3
- import { type RejectField, rejecting } from "@shivaedev/form/fieldRejection.ts";
4
3
  import { form } from "@shivaedev/form/form.ts";
5
4
  import type { PersistedDraftConfig } from "@shivaedev/form/persistence.ts";
6
- import type { Config, Decoded, Encoded, FieldFailure, Fields, Form, Services } from "@shivaedev/form/shape.ts";
5
+ import type { Config, Decoded, Encoded, FieldFailure, Fields, Form, Name, Services, Submitter } from "@shivaedev/form/shape.ts";
7
6
  import type { AtomServices } from "#AtomServices.ts";
8
7
  import { actionTrace } from "#actionTrace.ts";
9
8
 
@@ -12,9 +11,9 @@ export interface SubmissionConfig<TFields extends Fields, A, E, R, TRuntimeError
12
11
  readonly fields: Schema.Struct<TFields>;
13
12
  readonly initialValues: Encoded<TFields>;
14
13
  readonly persistedDraft?: PersistedDraftConfig | undefined;
15
- readonly rejectField: RejectField<TFields, E> | undefined;
16
14
  readonly runtime: Atom.AtomRuntime<Services<TFields, R>, TRuntimeError>;
17
- readonly save: (values: Decoded<TFields>) => Effect.Effect<A, E, AtomServices<R>>;
15
+ // The submitter lets a save place a rejection on one of the form's fields.
16
+ readonly save: (values: Decoded<TFields>, submitter: Submitter<Name<TFields>>) => Effect.Effect<A, E | FieldFailure, AtomServices<R>>;
18
17
  readonly savedValues?: (value: A) => Encoded<TFields>;
19
18
  }
20
19
 
@@ -26,8 +25,7 @@ export interface Submission<TFields extends Fields, A, E, TRuntimeError> {
26
25
  export function submission<TFields extends Fields, A, E, R, TRuntimeError>(
27
26
  config: SubmissionConfig<TFields, A, E, R, TRuntimeError>,
28
27
  ): Submission<TFields, A, E, TRuntimeError> {
29
- const { fields, initialValues, runtime } = config;
30
- const save = rejecting(fields, config.save, config.rejectField);
28
+ const { fields, initialValues, runtime, save } = config;
31
29
  let submitted: Encoded<TFields> | undefined;
32
30
  const currentForm: Form<TFields, A, E | FieldFailure, TRuntimeError> = form(fields, {
33
31
  ...(config.arrayKeys === undefined ? {} : { arrayKeys: config.arrayKeys }),
@@ -1 +0,0 @@
1
- {"version":3,"file":"queryRoute.d.ts","sourceRoot":"","sources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AC;AACH,CAAC"}
@@ -1,4 +0,0 @@
1
- import type * as Atom from "effect/reactivity/Atom";
2
- import type { NoticeDescriptor } from "#client/notices.ts";
3
- export declare function useNoticePublisher<R, E>(runtime: Atom.AtomRuntime<R, E>): (descriptor: NoticeDescriptor<R> | undefined) => void;
4
- //# sourceMappingURL=useNoticePublisher.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"useNoticePublisher.d.ts","sourceRoot":"","sources":["../../../src/client/adapters/useNoticePublisher.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,IAAI,MAAM,wBAAwB,CAAC;AAGpD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAG3D,wBAAgB,kBAAkB,CAAC,CAAC,EAAE,CAAC,EAAE,OAAO,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,UAAU,EAAE,gBAAgB,CAAC,CAAC,CAAC,GAAG,SAAS,KAAK,IAAI,CAG/H"}
@@ -1,8 +0,0 @@
1
- import { useContext, useMemo } from "react";
2
- import { NoticeContext } from "#client/NoticeContext.ts";
3
- import { publishNotice } from "#noticeStore.ts";
4
- export function useNoticePublisher(runtime) {
5
- const store = useContext(NoticeContext);
6
- return useMemo(() => (descriptor) => publishNotice(store, runtime, descriptor), [store, runtime]);
7
- }
8
- //# sourceMappingURL=useNoticePublisher.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"useNoticePublisher.js","sourceRoot":"","sources":["../../../src/client/adapters/useNoticePublisher.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAEhD,MAAM,UAAU,kBAAkB,CAAO,OAA+B;IACvE,MAAM,KAAK,GAAG,UAAU,CAAC,aAAa,CAAC,CAAC;IACxC,OAAO,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC,UAA2C,EAAE,EAAE,CAAC,aAAa,CAAC,KAAK,EAAE,OAAO,EAAE,UAAU,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC;AACpI,CAAC"}
@@ -1,10 +0,0 @@
1
- import type * as Atom from "effect/reactivity/Atom";
2
- import { useContext, useMemo } from "react";
3
- import { NoticeContext } from "#client/NoticeContext.ts";
4
- import type { NoticeDescriptor } from "#client/notices.ts";
5
- import { publishNotice } from "#noticeStore.ts";
6
-
7
- export function useNoticePublisher<R, E>(runtime: Atom.AtomRuntime<R, E>): (descriptor: NoticeDescriptor<R> | undefined) => void {
8
- const store = useContext(NoticeContext);
9
- return useMemo(() => (descriptor: NoticeDescriptor<R> | undefined) => publishNotice(store, runtime, descriptor), [store, runtime]);
10
- }