@shivaedev/react 0.49.1 → 0.50.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 (128) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +84 -116
  3. package/dist/client/FailureHostContext.d.ts +3 -0
  4. package/dist/client/FailureHostContext.d.ts.map +1 -0
  5. package/dist/client/FailureHostContext.js +3 -0
  6. package/dist/client/FailureHostContext.js.map +1 -0
  7. package/dist/client/NoticeContext.d.ts +1 -1
  8. package/dist/client/QueryView.d.ts +20 -5
  9. package/dist/client/QueryView.d.ts.map +1 -1
  10. package/dist/client/QueryView.js +23 -3
  11. package/dist/client/QueryView.js.map +1 -1
  12. package/dist/client/actionCompletion.d.ts +6 -5
  13. package/dist/client/actionCompletion.d.ts.map +1 -1
  14. package/dist/client/actionCompletion.js +19 -18
  15. package/dist/client/actionCompletion.js.map +1 -1
  16. package/dist/client/adapters/formFields.d.ts +4 -0
  17. package/dist/client/adapters/formFields.d.ts.map +1 -0
  18. package/dist/client/adapters/formFields.js +30 -0
  19. package/dist/client/adapters/formFields.js.map +1 -0
  20. package/dist/client/adapters/operationHooks.d.ts +5 -0
  21. package/dist/client/adapters/operationHooks.d.ts.map +1 -0
  22. package/dist/client/adapters/operationHooks.js +7 -0
  23. package/dist/client/adapters/operationHooks.js.map +1 -0
  24. package/dist/client/adapters/rowValues.d.ts +7 -0
  25. package/dist/client/adapters/rowValues.d.ts.map +1 -0
  26. package/dist/client/adapters/rowValues.js +17 -0
  27. package/dist/client/adapters/rowValues.js.map +1 -0
  28. package/dist/client/adapters/useFeedback.d.ts +11 -0
  29. package/dist/client/adapters/useFeedback.d.ts.map +1 -0
  30. package/dist/client/adapters/useFeedback.js +38 -0
  31. package/dist/client/adapters/useFeedback.js.map +1 -0
  32. package/dist/client/adapters/useQueryNotice.js +1 -1
  33. package/dist/client/adapters/useQueryNotice.js.map +1 -1
  34. package/dist/client/adapters/useStableRun.js +1 -1
  35. package/dist/client/adapters/useStableRun.js.map +1 -1
  36. package/dist/client/adapters/useSubmissionCallbacks.d.ts +4 -5
  37. package/dist/client/adapters/useSubmissionCallbacks.d.ts.map +1 -1
  38. package/dist/client/adapters/useSubmissionCallbacks.js +37 -17
  39. package/dist/client/adapters/useSubmissionCallbacks.js.map +1 -1
  40. package/dist/client/adapters/useUndoableChange.d.ts +13 -12
  41. package/dist/client/adapters/useUndoableChange.d.ts.map +1 -1
  42. package/dist/client/adapters/useUndoableChange.js +16 -4
  43. package/dist/client/adapters/useUndoableChange.js.map +1 -1
  44. package/dist/client/boundOperation.d.ts +12 -0
  45. package/dist/client/boundOperation.d.ts.map +1 -0
  46. package/dist/client/boundOperation.js +2 -0
  47. package/dist/client/boundOperation.js.map +1 -0
  48. package/dist/client/create.d.ts +15 -11
  49. package/dist/client/create.d.ts.map +1 -1
  50. package/dist/client/create.js +12 -5
  51. package/dist/client/create.js.map +1 -1
  52. package/dist/client/editor.d.ts +25 -18
  53. package/dist/client/editor.d.ts.map +1 -1
  54. package/dist/client/editor.js +14 -8
  55. package/dist/client/editor.js.map +1 -1
  56. package/dist/client/failureDecision.d.ts +16 -0
  57. package/dist/client/failureDecision.d.ts.map +1 -0
  58. package/dist/client/failureDecision.js +49 -0
  59. package/dist/client/failureDecision.js.map +1 -0
  60. package/dist/client/failures.d.ts +45 -0
  61. package/dist/client/failures.d.ts.map +1 -0
  62. package/dist/client/failures.js +2 -0
  63. package/dist/client/failures.js.map +1 -0
  64. package/dist/client/notices.d.ts +9 -4
  65. package/dist/client/notices.d.ts.map +1 -1
  66. package/dist/client/notices.js +22 -3
  67. package/dist/client/notices.js.map +1 -1
  68. package/dist/client/operationForm.d.ts +40 -0
  69. package/dist/client/operationForm.d.ts.map +1 -0
  70. package/dist/client/operationForm.js +2 -0
  71. package/dist/client/operationForm.js.map +1 -0
  72. package/dist/client/pendingCommand.d.ts +6 -9
  73. package/dist/client/pendingCommand.d.ts.map +1 -1
  74. package/dist/client/pendingCommand.js +3 -3
  75. package/dist/client/pendingCommand.js.map +1 -1
  76. package/dist/client/resultState.d.ts +7 -4
  77. package/dist/client/resultState.d.ts.map +1 -1
  78. package/dist/client/resultState.js +6 -3
  79. package/dist/client/resultState.js.map +1 -1
  80. package/dist/client/unexpectedFailure.d.ts +8 -0
  81. package/dist/client/unexpectedFailure.d.ts.map +1 -0
  82. package/dist/client/unexpectedFailure.js +17 -0
  83. package/dist/client/unexpectedFailure.js.map +1 -0
  84. package/dist/noticeEntry.d.ts +3 -1
  85. package/dist/noticeEntry.d.ts.map +1 -1
  86. package/dist/noticeEntry.js +2 -1
  87. package/dist/noticeEntry.js.map +1 -1
  88. package/dist/noticeStore.d.ts +3 -3
  89. package/dist/noticeStore.d.ts.map +1 -1
  90. package/dist/noticeStore.js +4 -4
  91. package/dist/noticeStore.js.map +1 -1
  92. package/dist/noticeTypes.d.ts +1 -2
  93. package/dist/noticeTypes.d.ts.map +1 -1
  94. package/dist/submission.d.ts +2 -4
  95. package/dist/submission.d.ts.map +1 -1
  96. package/dist/submission.js +1 -3
  97. package/dist/submission.js.map +1 -1
  98. package/package.json +22 -22
  99. package/src/client/FailureHostContext.ts +4 -0
  100. package/src/client/QueryView.ts +50 -7
  101. package/src/client/actionCompletion.ts +33 -23
  102. package/src/client/adapters/formFields.ts +33 -0
  103. package/src/client/adapters/operationHooks.ts +14 -0
  104. package/src/client/adapters/rowValues.ts +25 -0
  105. package/src/client/adapters/useFeedback.ts +50 -0
  106. package/src/client/adapters/useQueryNotice.ts +1 -1
  107. package/src/client/adapters/useStableRun.ts +1 -1
  108. package/src/client/adapters/useSubmissionCallbacks.ts +44 -21
  109. package/src/client/adapters/useUndoableChange.ts +66 -30
  110. package/src/client/boundOperation.ts +13 -0
  111. package/src/client/create.ts +50 -20
  112. package/src/client/editor.ts +98 -38
  113. package/src/client/failureDecision.ts +70 -0
  114. package/src/client/failures.ts +56 -0
  115. package/src/client/notices.ts +44 -6
  116. package/src/client/operationForm.ts +52 -0
  117. package/src/client/pendingCommand.ts +12 -14
  118. package/src/client/resultState.ts +20 -11
  119. package/src/client/unexpectedFailure.ts +24 -0
  120. package/src/noticeEntry.ts +5 -0
  121. package/src/noticeStore.ts +9 -4
  122. package/src/noticeTypes.ts +1 -2
  123. package/src/submission.ts +4 -6
  124. package/dist/client/adapters/useNoticePublisher.d.ts +0 -4
  125. package/dist/client/adapters/useNoticePublisher.d.ts.map +0 -1
  126. package/dist/client/adapters/useNoticePublisher.js +0 -8
  127. package/dist/client/adapters/useNoticePublisher.js.map +0 -1
  128. package/src/client/adapters/useNoticePublisher.ts +0 -10
@@ -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
+ }
@@ -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>() });