@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
@@ -16,7 +16,7 @@ export function useStableRun(run: unknown) {
16
16
  const changes = seen === committedRef.current ? 1 : seen.changes + 1;
17
17
  if (changes === UNCOMMITTED_CHANGES) {
18
18
  throw new Error(
19
- `useAction received a new \`run\` function on ${UNCOMMITTED_CHANGES} renders in a row. \`run\` is the action's identity and must stay the same function between renders: pass a bound command such as \`api.rename.run\` directly, or wrap your function in \`useCallback\` or \`useMemo\`.`,
19
+ `useAction received a new \`run\` function on ${UNCOMMITTED_CHANGES} renders in a row. \`run\` is the action's identity and must stay the same function between renders: pass a bound command such as \`api.rename\` directly, or wrap your \`run\` in \`useCallback\` or \`useMemo\`.`,
20
20
  );
21
21
  }
22
22
  see({ changes, run });
@@ -1,53 +1,76 @@
1
- import { Effect, type Schema } from "effect";
1
+ import { Cause, Effect, Option, type Schema } from "effect";
2
2
  import type * as Atom from "effect/reactivity/Atom";
3
3
  import { useInsertionEffect, useMemo, useRef } from "react";
4
- import { fieldRejectionOf, type RejectField } from "@shivaedev/form/fieldRejection.ts";
5
- import type { Decoded, Fields } from "@shivaedev/form/shape.ts";
4
+ import { fieldRejectionOf } from "@shivaedev/form/fieldRejection.ts";
5
+ import { type Decoded, FieldFailure, type Fields, type Name, type Submitter } from "@shivaedev/form/shape.ts";
6
6
  import type { AtomServices } from "#AtomServices.ts";
7
- import { useNoticePublisher } from "#client/adapters/useNoticePublisher.ts";
7
+ import { useFeedback } from "#client/adapters/useFeedback.ts";
8
+ import type { Decision } from "#client/failureDecision.ts";
9
+ import type { FailureChoices } from "#client/failures.ts";
8
10
  import type { NoticeFeedback } from "#client/notices.ts";
9
11
 
12
+ function isFieldFailure(cause: Cause.Cause<unknown>) {
13
+ return Option.exists(Cause.findErrorOption(cause), (error) => error instanceof FieldFailure);
14
+ }
15
+
16
+ function placeOnField<TName extends string>(decision: Decision<unknown>, isName: (name: string) => name is TName, submitter: Submitter<TName>) {
17
+ if (decision._tag !== "field") {
18
+ return undefined;
19
+ }
20
+ const { field, message } = decision.rejection;
21
+ const name = typeof field === "string" ? field : field[0];
22
+ if (!isName(name)) {
23
+ return undefined;
24
+ }
25
+ return submitter.fail(typeof field === "string" ? name : [name, ...field.slice(1)], message);
26
+ }
27
+
10
28
  export function useSubmissionCallbacks<TFields extends Fields, A, E, R, TRuntime, TRuntimeError>(
11
29
  fields: Schema.Struct<TFields>,
12
30
  save: (values: Decoded<TFields>) => Effect.Effect<A, E, AtomServices<R>>,
13
- rejectField: RejectField<TFields, E> | undefined,
31
+ choices: FailureChoices,
14
32
  runtime: Atom.AtomRuntime<TRuntime, TRuntimeError>,
15
- notices: NoticeFeedback<Decoded<TFields>, A, E, TRuntime> | undefined,
33
+ notices: NoticeFeedback<Decoded<TFields>, A, TRuntime> | undefined,
16
34
  ) {
17
- const publish = useNoticePublisher(runtime);
18
- const latestRef = useRef({ notices, rejectField, save });
35
+ const feedback = useFeedback(runtime);
36
+ const latestRef = useRef({ choices, notices, save });
19
37
  useInsertionEffect(() => {
20
- latestRef.current = { notices, rejectField, save };
21
- }, [notices, rejectField, save]);
38
+ latestRef.current = { choices, notices, save };
39
+ }, [choices, notices, save]);
22
40
  const callbacks = useMemo(() => {
23
41
  const automatic = fieldRejectionOf(fields);
24
- function rejected(error: E, values: Decoded<TFields>) {
25
- return Effect.sync(() => {
26
- if (callbacks.active) {
27
- publish(latestRef.current.notices?.onFailure?.(error, values));
42
+ function isName(field: string): field is Name<TFields> {
43
+ return Object.hasOwn(fields.fields, field);
44
+ }
45
+ function rejected(cause: Cause.Cause<E>, values: Decoded<TFields>, submitter: Submitter<Name<TFields>>) {
46
+ return Effect.suspend((): Effect.Effect<never, E | FieldFailure> => {
47
+ // A save that already answered with a field failure has placed its own feedback.
48
+ if (!callbacks.active || isFieldFailure(cause)) {
49
+ return Effect.failCause(cause);
28
50
  }
29
- }).pipe(Effect.andThen(Effect.fail(error)));
51
+ const decision = feedback.failed(cause, values, latestRef.current.choices, automatic);
52
+ return placeOnField(decision, isName, submitter) ?? Effect.failCause(cause);
53
+ });
30
54
  }
31
55
  function completed(value: A, values: Decoded<TFields>) {
32
56
  return Effect.sync(() => {
33
57
  if (callbacks.active) {
34
- publish(latestRef.current.notices?.onSuccess?.(value, values));
58
+ feedback.succeeded(latestRef.current.notices?.onSuccess?.(value, values));
35
59
  }
36
60
  return value;
37
61
  });
38
62
  }
39
63
  return {
40
64
  active: false,
41
- rejectField: (error: E) => (latestRef.current.rejectField ?? automatic)(error),
42
- save: (values: Decoded<TFields>): Effect.Effect<A, E, AtomServices<R>> =>
65
+ save: (values: Decoded<TFields>, submitter: Submitter<Name<TFields>>): Effect.Effect<A, E | FieldFailure, AtomServices<R>> =>
43
66
  Effect.suspend(() => latestRef.current.save(values)).pipe(
44
- Effect.matchEffect({
45
- onFailure: (error) => rejected(error, values),
67
+ Effect.matchCauseEffect({
68
+ onFailure: (cause) => rejected(cause, values, submitter),
46
69
  onSuccess: (value) => completed(value, values),
47
70
  }),
48
71
  ),
49
72
  };
50
- }, [fields, publish]);
73
+ }, [feedback, fields]);
51
74
  useInsertionEffect(() => {
52
75
  callbacks.active = true;
53
76
  return () => {
@@ -3,15 +3,13 @@ import { Effect, Option } from "effect";
3
3
  import type * as AsyncResult from "effect/reactivity/AsyncResult";
4
4
  import * as Atom from "effect/reactivity/Atom";
5
5
  import { useContext, useMemo } from "react";
6
- import type { AtomServices } from "#AtomServices.ts";
6
+ import type { BoundOperation } from "#client/boundOperation.ts";
7
7
  import type { deployUpdate } from "#client/deployUpdate.ts";
8
- import { useAction } from "#client/resultState.ts";
8
+ import type { FailureChoices, FailuresOption } from "#client/failures.ts";
9
+ import type { NoticeDescriptor } from "#client/notices.ts";
10
+ import { useActionState } from "#client/resultState.ts";
9
11
 
10
- export interface VersionedChangeCommand<TInput, A, E, R, TRuntimeError> {
11
- readonly run: (input: TInput) => Effect.Effect<A, E, AtomServices<R>>;
12
- readonly runtime: Atom.AtomRuntime<R, TRuntimeError>;
13
- readonly update: Pick<ReturnType<typeof deployUpdate>, "block">;
14
- }
12
+ type DeployUpdate = Pick<ReturnType<typeof deployUpdate>, "block">;
15
13
 
16
14
  export interface UndoableNotice<TInput, A> {
17
15
  readonly input: TInput;
@@ -30,25 +28,55 @@ export interface UndoableChange<TInput, A, E, TInverse extends readonly unknown[
30
28
  readonly undoResult: AsyncResult.AsyncResult<A, E>;
31
29
  }
32
30
 
33
- export function useUndoableChange<TInput, A, E, R, TRuntimeError>(
34
- command: VersionedChangeCommand<TInput, A, E, R, TRuntimeError>,
31
+ function failuresFor<TAction>(choices: FailureChoices, input: (action: TAction) => unknown): FailureChoices {
32
+ const { failures, silent } = choices;
33
+ const handlers =
34
+ failures
35
+ && Object.fromEntries(
36
+ Object.entries(failures).map(([tag, choice]) => [
37
+ tag,
38
+ typeof choice === "function" ? (error: unknown, action: TAction) => choice(error, input(action)) : choice,
39
+ ]),
40
+ );
41
+ return { failures: handlers, silent };
42
+ }
43
+ // A failed removal or Undo hands the change's own input to `failures`.
44
+ type UndoableFailures<TInput, E, R, TSilent extends boolean> = FailuresOption<E, TInput, NoticeDescriptor<R>, TSilent>;
45
+
46
+ export function useUndoableChange<TInput, A, E, R, TRuntimeError, TSilent extends boolean = false>(
47
+ command: BoundOperation<TInput, A, E, R, TRuntimeError>,
35
48
  options: {
36
49
  readonly describe: (value: NoInfer<A>, input: NoInfer<TInput>) => string;
37
50
  readonly undoInput: (value: NoInfer<A>, input: NoInfer<TInput>) => NoInfer<TInput>;
38
- },
51
+ readonly update: DeployUpdate;
52
+ } & UndoableFailures<NoInfer<TInput>, E, R, TSilent>,
39
53
  ): UndoableChange<TInput, A, E | TRuntimeError, []>;
40
- export function useUndoableChange<TInput extends { readonly expectedVersion: number }, A extends { readonly version: number }, E, R, TRuntimeError>(
41
- command: VersionedChangeCommand<TInput, A, E, R, TRuntimeError>,
42
- options: { readonly describe: (value: NoInfer<A>, input: NoInfer<TInput>) => string },
54
+ export function useUndoableChange<
55
+ TInput extends { readonly expectedVersion: number },
56
+ A extends { readonly version: number },
57
+ E,
58
+ R,
59
+ TRuntimeError,
60
+ TSilent extends boolean = false,
61
+ >(
62
+ command: BoundOperation<TInput, A, E, R, TRuntimeError>,
63
+ options: { readonly describe: (value: NoInfer<A>, input: NoInfer<TInput>) => string; readonly update: DeployUpdate } & UndoableFailures<
64
+ NoInfer<TInput>,
65
+ E,
66
+ R,
67
+ TSilent
68
+ >,
43
69
  ): UndoableChange<TInput, A, E | TRuntimeError, [inverse: Omit<TInput, "expectedVersion">]>;
44
70
  export function useUndoableChange<TInput, A extends { readonly version: number }, E, R, TRuntimeError>(
45
- command: VersionedChangeCommand<TInput, A, E, R, TRuntimeError>,
71
+ command: BoundOperation<TInput, A, E, R, TRuntimeError>,
46
72
  options: {
47
73
  readonly describe: (value: A, input: TInput) => string;
48
74
  readonly undoInput?: (value: A, input: TInput) => TInput;
49
- },
75
+ readonly update: DeployUpdate;
76
+ } & FailureChoices,
50
77
  ) {
51
- const { run, runtime, update } = command;
78
+ const { run, runtime } = command;
79
+ const { update } = options;
52
80
  const registry = useContext(RegistryContext);
53
81
  type Entry = UndoableNotice<TInput, A> & { readonly inverse: TInput };
54
82
  interface Removal {
@@ -71,22 +99,30 @@ export function useUndoableChange<TInput, A extends { readonly version: number }
71
99
  );
72
100
  const removeRun = useMemo(() => (request: Removal) => execute(request.input), [execute]);
73
101
  const undoRun = useMemo(() => (entry: Entry) => execute(entry.inverse), [execute]);
74
- const removal = useAction(owner.runtime, removeRun, {
75
- concurrent: true,
76
- onSuccess: (value, { input, inverse, sequence }) => {
77
- if (sequence === owner.sequence) {
78
- const undoInput = options.undoInput ? options.undoInput(value, input) : { ...input, ...inverse, expectedVersion: value.version };
79
- owner.registry.set(owner.notice, Option.some({ input, inverse: undoInput, message: options.describe(value, input), value }));
80
- }
102
+ const removal = useActionState(
103
+ { run: removeRun, runtime: owner.runtime },
104
+ {
105
+ ...failuresFor(options, (request: Removal) => request.input),
106
+ concurrent: true,
107
+ onSuccess: (value, { input, inverse, sequence }) => {
108
+ if (sequence === owner.sequence) {
109
+ const undoInput = options.undoInput ? options.undoInput(value, input) : { ...input, ...inverse, expectedVersion: value.version };
110
+ owner.registry.set(owner.notice, Option.some({ input, inverse: undoInput, message: options.describe(value, input), value }));
111
+ }
112
+ },
81
113
  },
82
- });
83
- const restoration = useAction(owner.runtime, undoRun, {
84
- onSuccess: (_value, entry) => {
85
- if (Option.getOrUndefined(owner.registry.get(owner.notice)) === entry) {
86
- owner.registry.set(owner.notice, Option.none());
87
- }
114
+ );
115
+ const restoration = useActionState(
116
+ { run: undoRun, runtime: owner.runtime },
117
+ {
118
+ ...failuresFor(options, (entry: Entry) => entry.inverse),
119
+ onSuccess: (_value, entry) => {
120
+ if (Option.getOrUndefined(owner.registry.get(owner.notice)) === entry) {
121
+ owner.registry.set(owner.notice, Option.none());
122
+ }
123
+ },
88
124
  },
89
- });
125
+ );
90
126
  const notice: Option.Option<UndoableNotice<TInput, A>> = useAtomValue(owner.notice);
91
127
  return {
92
128
  notice,
@@ -0,0 +1,13 @@
1
+ import type { Effect } from "effect";
2
+ import type * as Atom from "effect/reactivity/Atom";
3
+ import type { AtomServices } from "#AtomServices.ts";
4
+
5
+ // A bound contract command fits as it is. Any other Effect becomes one by naming the runtime that provides its services.
6
+ export interface BoundOperation<TInput, A, E, R, TRuntimeError> {
7
+ // A bound query also has `run` and `runtime`; this property turns passing one into an error that says why.
8
+ readonly query?: "a bound query only reads: read it with useQuery, and pass a command here";
9
+ readonly run: (input: TInput) => Effect.Effect<A, E, AtomServices<R>>;
10
+ readonly runtime: Atom.AtomRuntime<R, TRuntimeError>;
11
+ }
12
+
13
+ export type LooseOperation = BoundOperation<object, unknown, unknown, unknown, unknown> & { readonly payload?: unknown };
@@ -1,24 +1,22 @@
1
- import { type Effect, Equal, Option, type Schema } from "effect";
2
- import type * as Atom from "effect/reactivity/Atom";
1
+ import { Equal, Option, type Schema } from "effect";
3
2
  import { useCallback, useState } from "react";
4
3
  import { usePersistedDraft } from "@shivaedev/form/adapters/react.ts";
5
- import type { FieldRejectionMapping } from "@shivaedev/form/fieldRejection.ts";
6
4
  import type { PersistedDraftConfig } from "@shivaedev/form/persistence.ts";
7
5
  import type { Decoded, Encoded, FieldFailure, Fields, Form, Services } from "@shivaedev/form/shape.ts";
8
- import type { AtomServices } from "#AtomServices.ts";
6
+ import { formFields } from "#client/adapters/formFields.ts";
7
+ import { typedCreate } from "#client/adapters/operationHooks.ts";
9
8
  import { useSubmissionCallbacks } from "#client/adapters/useSubmissionCallbacks.ts";
9
+ import type { BoundOperation, LooseOperation } from "#client/boundOperation.ts";
10
+ import type { FailureChoices, FormFailuresOption } from "#client/failures.ts";
10
11
  import type { NoticeFeedback } from "#client/notices.ts";
12
+ import type { DecodingServicesOption, FieldsOption, FixedOption, FormFields, NoFixed, Unfixed } from "#client/operationForm.ts";
11
13
  import { type SaveState, useSaveState } from "#client/saveState.ts";
12
14
  import { type SubmissionConfig, submission } from "#submission.ts";
13
- export type CreateConfig<TFields extends Fields, TCreated, TSaveError, R, TRuntimeError> = {
15
+ export type CreateOptions<TFields extends Fields, TCreated, TSaveError, R, TRuntimeError> = {
14
16
  readonly persistedDraft?: PersistedDraftConfig | undefined;
15
- readonly fields: Schema.Struct<TFields>;
16
17
  readonly initialValues: Encoded<TFields>;
17
- readonly create: (values: Decoded<TFields>) => Effect.Effect<TCreated, TSaveError, AtomServices<R>>;
18
- readonly runtime: Atom.AtomRuntime<Services<TFields, R>, TRuntimeError>;
19
- readonly notices?: NoticeFeedback<Decoded<TFields>, TCreated, TSaveError, Services<TFields, R>>;
20
- } & FieldRejectionMapping<TFields, TSaveError> &
21
- Pick<SubmissionConfig<TFields, TCreated, TSaveError, R, TRuntimeError>, "requiredMessages" | "checks" | "debounce" | "arrayKeys">;
18
+ readonly notices?: NoticeFeedback<Decoded<TFields>, TCreated, Services<TFields, R>>;
19
+ } & Pick<SubmissionConfig<TFields, TCreated, TSaveError, R, TRuntimeError>, "requiredMessages" | "checks" | "debounce" | "arrayKeys">;
22
20
  export interface Create<TFields extends Fields, TCreated, TSaveError, TRuntimeError> extends SaveState<TSaveError | TRuntimeError> {
23
21
  readonly created: Option.Option<TCreated>;
24
22
  readonly form: Form<TFields, TCreated, TSaveError | FieldFailure, TRuntimeError>;
@@ -33,27 +31,58 @@ function resetValues(baseline: Readonly<Record<string, unknown>>, current: Reado
33
31
  }),
34
32
  );
35
33
  }
36
- export function useCreate<TFields extends Fields, TCreated, TSaveError, R, TRuntimeError>(
37
- config: CreateConfig<TFields, TCreated, TSaveError, R, TRuntimeError>,
38
- ): Create<TFields, TCreated, TSaveError, TRuntimeError> {
34
+ export type UseCreate = <
35
+ TInput,
36
+ TCreated,
37
+ TSaveError,
38
+ R,
39
+ TRuntimeError,
40
+ TPayload = never,
41
+ TFixed extends Partial<TInput> = NoFixed,
42
+ TFields extends Fields = never,
43
+ TSilent extends boolean = false,
44
+ >(
45
+ operation: BoundOperation<TInput, TCreated, TSaveError, R, TRuntimeError> & { readonly payload?: TPayload },
46
+ options: NoInfer<CreateOptions<FormFields<TPayload, TFixed, TFields>, TCreated, TSaveError, R, TRuntimeError>> &
47
+ FieldsOption<TPayload, TFields> &
48
+ FixedOption<TInput, TFixed, Unfixed<TInput, FormFields<TPayload, TFixed, TFields>, TFixed>> &
49
+ NoInfer<DecodingServicesOption<FormFields<TPayload, TFixed, TFields>, R>> &
50
+ FormFailuresOption<FormFields<TPayload, TFixed, TFields>, TSaveError, Services<FormFields<TPayload, TFixed, TFields>, R>, TSilent>,
51
+ ) => Create<FormFields<TPayload, TFixed, TFields>, TCreated, TSaveError, TRuntimeError>;
52
+ export type LooseCreate = (
53
+ operation: LooseOperation,
54
+ options: CreateOptions<Fields, unknown, unknown, unknown, unknown> &
55
+ FailureChoices & { readonly fields?: Schema.Struct<Fields>; readonly fixed?: object },
56
+ ) => Create<Fields, unknown, unknown, unknown>;
57
+ const useLooseCreate: LooseCreate = (operation, options) => {
58
+ const { fixed } = options;
59
+ const { runtime } = operation;
60
+ const fields = formFields(operation.payload, options.fields, fixed);
61
+ const config = { ...options, fields, runtime };
39
62
  const persistedDraft = usePersistedDraft(config.persistedDraft);
40
- const callbacks = useSubmissionCallbacks(config.fields, config.create, config.rejectField, config.runtime, config.notices);
63
+ const callbacks = useSubmissionCallbacks(
64
+ fields,
65
+ (values: Decoded<Fields>) => operation.run({ ...fixed, ...values }),
66
+ config,
67
+ runtime,
68
+ config.notices,
69
+ );
41
70
  function initialize() {
42
- const { fields, initialValues, runtime } = config;
71
+ const { initialValues } = config;
43
72
  function makeSubmission() {
44
73
  return submission({ ...config, ...callbacks, fields, initialValues, persistedDraft, runtime });
45
74
  }
46
- return { baseline: initialValues, created: Option.none<TCreated>(), current: makeSubmission(), fields, fresh: makeSubmission, runtime };
75
+ return { baseline: initialValues, created: Option.none<unknown>(), current: makeSubmission(), fields, fresh: makeSubmission, runtime };
47
76
  }
48
77
  const [held, hold] = useState(initialize);
49
78
  let entry = held;
50
- if (entry.fields !== config.fields || entry.runtime !== config.runtime) {
79
+ if (entry.fields !== fields || entry.runtime !== runtime) {
51
80
  entry = initialize();
52
81
  hold(entry);
53
82
  }
54
83
  const { baseline, created, current, fresh } = entry;
55
84
  const settled = useCallback(
56
- (value: TCreated) => {
85
+ (value: unknown) => {
57
86
  const next = fresh();
58
87
  next.form.values.set(resetValues(baseline, current.form.values.value, current.submitted()));
59
88
  hold({ ...entry, created: Option.some(value), current: next });
@@ -61,4 +90,5 @@ export function useCreate<TFields extends Fields, TCreated, TSaveError, R, TRunt
61
90
  [entry, current, fresh, baseline],
62
91
  );
63
92
  return { ...useSaveState(current.form, settled), created, form: current.form };
64
- }
93
+ };
94
+ export const useCreate = typedCreate(useLooseCreate);
@@ -1,75 +1,134 @@
1
- import { type Effect, Option, type Schema } from "effect";
1
+ import { Option, type Schema } from "effect";
2
2
  import type * as AsyncResult from "effect/reactivity/AsyncResult";
3
3
  import type * as Atom from "effect/reactivity/Atom";
4
4
  import { useEffect, useState } from "react";
5
5
  import { usePersistedDraft } from "@shivaedev/form/adapters/react.ts";
6
- import type { FieldRejectionMapping } from "@shivaedev/form/fieldRejection.ts";
7
6
  import type { PersistedDraftConfig } from "@shivaedev/form/persistence.ts";
8
7
  import type { Decoded, Encoded, FieldFailure, Fields, Form, Services } from "@shivaedev/form/shape.ts";
9
- import type { AtomServices } from "#AtomServices.ts";
8
+ import { formFields } from "#client/adapters/formFields.ts";
9
+ import { typedEditor } from "#client/adapters/operationHooks.ts";
10
+ import { rowValues } from "#client/adapters/rowValues.ts";
10
11
  import { useSubmissionCallbacks } from "#client/adapters/useSubmissionCallbacks.ts";
12
+ import type { BoundOperation, LooseOperation } from "#client/boundOperation.ts";
13
+ import type { FailureChoices, FormFailuresOption } from "#client/failures.ts";
11
14
  import type { NoticeFeedback } from "#client/notices.ts";
15
+ import type {
16
+ DecodingServicesOption,
17
+ FieldsOption,
18
+ FixedOption,
19
+ FormFields,
20
+ MissingFromRow,
21
+ NoFixed,
22
+ Unfixed,
23
+ ValuesOption,
24
+ } from "#client/operationForm.ts";
12
25
  import { type QueryOptions, type QueryState, useQuery } from "#client/resultState.ts";
13
26
  import { type SaveState, useSaveState } from "#client/saveState.ts";
14
27
  import type { LoadedQueryState } from "#client/useLoaderQuery.ts";
15
28
  import { loadedQuery } from "#loadedQuery.ts";
16
29
  import { type SubmissionConfig, submission } from "#submission.ts";
17
- export type EditorConfig<TFields extends Fields, TRow, TQueryError, TSaveError, R, TRuntimeError> = {
30
+ export type EditorOptions<TFields extends Fields, TRow, TQueryError, TSaved, TSaveError, R, TRuntimeError> = {
18
31
  readonly persistedDraft?: PersistedDraftConfig | undefined;
19
32
  readonly query: Atom.Atom<AsyncResult.AsyncResult<TRow, TQueryError>>;
20
- readonly fields: Schema.Struct<TFields>;
21
- readonly values: (row: TRow) => Encoded<TFields>;
22
- readonly save: (values: Decoded<TFields>) => Effect.Effect<TRow, TSaveError, AtomServices<R>>;
23
- readonly runtime: Atom.AtomRuntime<Services<TFields, R>, TRuntimeError>;
24
- readonly notices?: NoticeFeedback<Decoded<TFields>, TRow, TSaveError, Services<TFields, R>>;
33
+ readonly notices?: NoticeFeedback<Decoded<TFields>, TSaved, Services<TFields, R>>;
25
34
  readonly queryNotice?: QueryOptions<TQueryError>["notice"];
26
- } & FieldRejectionMapping<TFields, TSaveError> &
27
- Pick<SubmissionConfig<TFields, TRow, TSaveError, R, TRuntimeError>, "requiredMessages" | "checks" | "debounce" | "arrayKeys">;
28
- export interface Editor<TFields extends Fields, TRow, TQueryError, TSaveError, TRuntimeError> extends SaveState<TSaveError | TRuntimeError> {
29
- readonly form: Form<TFields, TRow, TSaveError | FieldFailure, TRuntimeError> | undefined;
35
+ } & Pick<SubmissionConfig<TFields, TSaved, TSaveError, R, TRuntimeError>, "requiredMessages" | "checks" | "debounce" | "arrayKeys">;
36
+ export interface Editor<TFields extends Fields, TRow, TQueryError, TSaveError, TRuntimeError, TSaved = TRow>
37
+ extends SaveState<TSaveError | TRuntimeError> {
38
+ readonly form: Form<TFields, TSaved, TSaveError | FieldFailure, TRuntimeError> | undefined;
30
39
  readonly query: QueryState<TRow, TQueryError>;
31
40
  }
32
- export interface LoadedEditor<TFields extends Fields, TRow, TQueryError, TSaveError, TRuntimeError>
33
- extends Omit<Editor<TFields, TRow, TQueryError, TSaveError, TRuntimeError>, "form" | "query"> {
34
- readonly form: Form<TFields, TRow, TSaveError | FieldFailure, TRuntimeError>;
41
+ export interface LoadedEditor<TFields extends Fields, TRow, TQueryError, TSaveError, TRuntimeError, TSaved = TRow>
42
+ extends Omit<Editor<TFields, TRow, TQueryError, TSaveError, TRuntimeError, TSaved>, "form" | "query"> {
43
+ readonly form: Form<TFields, TSaved, TSaveError | FieldFailure, TRuntimeError>;
35
44
  readonly query: LoadedQueryState<TRow, TQueryError>;
36
45
  }
37
- interface Held<TFields extends Fields, TRow, TSaveError, R, TRuntimeError> {
38
- readonly fields: Schema.Struct<TFields>;
39
- readonly form: Form<TFields, TRow, TSaveError | FieldFailure, TRuntimeError>;
46
+ type Derived<TFields> = [TFields] extends [never] ? true : false;
47
+ interface Held {
48
+ readonly fields: Schema.Struct<Fields>;
49
+ readonly form: Form<Fields, unknown, unknown, unknown>;
40
50
  readonly query: Atom.Atom<unknown>;
41
- readonly runtime: Atom.AtomRuntime<Services<TFields, R>, TRuntimeError>;
42
- readonly values: (row: TRow) => Encoded<TFields>;
51
+ readonly runtime: Atom.AtomRuntime<unknown, unknown>;
52
+ readonly values: (row: unknown) => Encoded<Fields>;
43
53
  }
44
- export function useEditor<TFields extends Fields, TRow, TQueryError, TSaveError, R, TRuntimeError>(
45
- config: EditorConfig<TFields, TRow, TQueryError, TSaveError, R, TRuntimeError> & { readonly loaded: TRow },
46
- ): LoadedEditor<TFields, TRow, TQueryError, TSaveError, TRuntimeError>;
47
- export function useEditor<TFields extends Fields, TRow, TQueryError, TSaveError, R, TRuntimeError>(
48
- config: EditorConfig<TFields, TRow, TQueryError, TSaveError, R, TRuntimeError>,
49
- ): Editor<TFields, TRow, TQueryError, TSaveError, TRuntimeError>;
50
- export function useEditor<TFields extends Fields, TRow, TQueryError, TSaveError, R, TRuntimeError>(
51
- config: EditorConfig<TFields, TRow, TQueryError, TSaveError, R, TRuntimeError> & { readonly loaded?: TRow },
52
- ): Editor<TFields, TRow, TQueryError, TSaveError, TRuntimeError> | LoadedEditor<TFields, TRow, TQueryError, TSaveError, TRuntimeError> {
54
+ // The command's success must be a row the form can read back, so `values` (or the derived values) reads both the query's row and the saved result.
55
+ export type UseEditor = <
56
+ TInput,
57
+ TSaved,
58
+ TSaveError,
59
+ R,
60
+ TRuntimeError,
61
+ TRow,
62
+ TQueryError,
63
+ TPayload = never,
64
+ TFixed extends Partial<TInput> = NoFixed,
65
+ TFields extends Fields = never,
66
+ TLoaded extends NoInfer<TRow> | undefined = undefined,
67
+ TSilent extends boolean = false,
68
+ >(
69
+ operation: BoundOperation<TInput, TSaved, TSaveError, R, TRuntimeError> & { readonly payload?: TPayload },
70
+ options: EditorOptions<
71
+ NoInfer<FormFields<TPayload, TFixed, TFields>>,
72
+ TRow,
73
+ TQueryError,
74
+ NoInfer<TSaved>,
75
+ NoInfer<TSaveError>,
76
+ NoInfer<R>,
77
+ NoInfer<TRuntimeError>
78
+ > & {
79
+ readonly loaded?: TLoaded;
80
+ } & FieldsOption<TPayload, TFields> &
81
+ FixedOption<
82
+ TInput,
83
+ TFixed,
84
+ | Unfixed<TInput, FormFields<TPayload, TFixed, TFields>, TFixed>
85
+ | (Derived<TFields> extends true ? MissingFromRow<TRow | TSaved, FormFields<TPayload, TFixed, TFields>> : never)
86
+ > &
87
+ NoInfer<ValuesOption<TRow | TSaved, FormFields<TPayload, TFixed, TFields>, Derived<TFields>>> &
88
+ NoInfer<DecodingServicesOption<FormFields<TPayload, TFixed, TFields>, R>> &
89
+ FormFailuresOption<FormFields<TPayload, TFixed, TFields>, TSaveError, Services<FormFields<TPayload, TFixed, TFields>, R>, TSilent>,
90
+ ) => [TLoaded] extends [undefined]
91
+ ? Editor<FormFields<TPayload, TFixed, TFields>, TRow, TQueryError, TSaveError, TRuntimeError, TSaved>
92
+ : LoadedEditor<FormFields<TPayload, TFixed, TFields>, TRow, TQueryError, TSaveError, TRuntimeError, TSaved>;
93
+ export type LooseEditor = (
94
+ operation: LooseOperation,
95
+ options: EditorOptions<Fields, unknown, unknown, unknown, unknown, unknown, unknown> &
96
+ FailureChoices & {
97
+ readonly fields?: Schema.Struct<Fields>;
98
+ readonly fixed?: object;
99
+ readonly loaded?: unknown;
100
+ readonly values?: (row: unknown) => Encoded<Fields>;
101
+ },
102
+ ) => Editor<Fields, unknown, unknown, unknown, unknown, unknown> | LoadedEditor<Fields, unknown, unknown, unknown, unknown, unknown>;
103
+ const useLooseEditor: LooseEditor = (operation, options) => {
104
+ const { fixed } = options;
105
+ const { runtime } = operation;
106
+ const fields = formFields(operation.payload, options.fields, fixed);
107
+ const config = { ...options, fields, runtime, values: options.values ?? rowValues(fields) };
53
108
  const persistedDraft = usePersistedDraft(config.persistedDraft);
54
- const callbacks = useSubmissionCallbacks(config.fields, config.save, config.rejectField, config.runtime, config.notices);
109
+ const callbacks = useSubmissionCallbacks(
110
+ fields,
111
+ (edited: Decoded<Fields>) => operation.run({ ...fixed, ...edited }),
112
+ config,
113
+ runtime,
114
+ config.notices,
115
+ );
55
116
  const query = useQuery(config.query, config.queryNotice === undefined ? {} : { notice: config.queryNotice });
56
117
  const row = Option.orElse(query.data, () => ("loaded" in config ? Option.some(config.loaded) : Option.none()));
57
- const [held, hold] = useState<Held<TFields, TRow, TSaveError, R, TRuntimeError> | undefined>(undefined);
58
- let current = held?.query === config.query && held.fields === config.fields && held.runtime === config.runtime ? held : undefined;
118
+ const [held, hold] = useState<Held | undefined>(undefined);
119
+ let current = held?.query === config.query && held.fields === fields && held.runtime === runtime ? held : undefined;
59
120
  if (current === undefined && Option.isSome(row)) {
60
121
  current = {
61
- fields: config.fields,
122
+ fields,
62
123
  form: submission({
63
124
  ...config,
64
125
  ...callbacks,
65
- fields: config.fields,
66
126
  initialValues: config.values(row.value),
67
127
  persistedDraft,
68
- runtime: config.runtime,
69
128
  savedValues: config.values,
70
129
  }).form,
71
130
  query: config.query,
72
- runtime: config.runtime,
131
+ runtime,
73
132
  values: config.values,
74
133
  };
75
134
  hold(current);
@@ -87,4 +146,5 @@ export function useEditor<TFields extends Fields, TRow, TQueryError, TSaveError,
87
146
  return { ...saveState, form, query: loadedQuery(query, config.loaded) };
88
147
  }
89
148
  return { ...saveState, form, query };
90
- }
149
+ };
150
+ export const useEditor = typedEditor(useLooseEditor);
@@ -0,0 +1,70 @@
1
+ import { Predicate } from "effect";
2
+ import { failureKind } from "@shivaedev/contract/failureKind.ts";
3
+ import type { FieldRejection } from "@shivaedev/form/fieldRejection.ts";
4
+ import type { FailureChoices } from "#client/failures.ts";
5
+ import type { NoticeDescriptor } from "#client/notices.ts";
6
+
7
+ export type Decision<R = never> =
8
+ | { readonly _tag: "field"; readonly rejection: FieldRejection<string> }
9
+ | { readonly _tag: "notice"; readonly descriptor: NoticeDescriptor<R> }
10
+ | { readonly _tag: "silent" }
11
+ | { readonly _tag: "unexpected" };
12
+
13
+ const silent = { _tag: "silent" } as const;
14
+ const unexpected = { _tag: "unexpected" } as const;
15
+
16
+ function isFieldRejection(value: object): value is FieldRejection<string> {
17
+ return (
18
+ Predicate.hasProperty(value, "field")
19
+ && (Predicate.isString(value.field) || Array.isArray(value.field))
20
+ && Predicate.hasProperty(value, "message")
21
+ && Predicate.isString(value.message)
22
+ );
23
+ }
24
+
25
+ function isDescriptor<R>(value: object): value is NoticeDescriptor<R> {
26
+ return Predicate.hasProperty(value, "message");
27
+ }
28
+
29
+ function outcome<R>(value: unknown): Decision<R> {
30
+ if (!Predicate.isObject(value)) {
31
+ return silent;
32
+ }
33
+ if (isFieldRejection(value)) {
34
+ return { _tag: "field", rejection: value };
35
+ }
36
+ return isDescriptor<R>(value) ? { _tag: "notice", descriptor: value } : silent;
37
+ }
38
+
39
+ function messageOf(error: unknown): string {
40
+ return Predicate.hasProperty(error, "message") && Predicate.isString(error.message) ? error.message : "";
41
+ }
42
+
43
+ // The app's handler for the tag wins, then a field the form owns, then the server's message for a request rejection; anything else
44
+ // belongs to the application's failure host.
45
+ export function decide<R>(
46
+ error: unknown,
47
+ input: unknown,
48
+ choices: FailureChoices,
49
+ field: (error: unknown) => FieldRejection<string> | undefined,
50
+ ): Decision<R> {
51
+ if (choices.silent === true) {
52
+ return silent;
53
+ }
54
+ const tag = Predicate.hasProperty(error, "_tag") && Predicate.isString(error._tag) ? error._tag : undefined;
55
+ const choice = tag === undefined ? undefined : choices.failures?.[tag];
56
+ if (choice === "silent") {
57
+ return silent;
58
+ }
59
+ if (choice === "message") {
60
+ return { _tag: "notice", descriptor: { message: messageOf(error) } };
61
+ }
62
+ if (Predicate.isFunction(choice)) {
63
+ return outcome<R>(choice(error, input));
64
+ }
65
+ const routed = field(error);
66
+ if (routed !== undefined) {
67
+ return { _tag: "field", rejection: routed };
68
+ }
69
+ return failureKind(error) === "request" ? { _tag: "notice", descriptor: { message: messageOf(error) } } : unexpected;
70
+ }