Refactor Form
Lint / lint (push) Failing after 39s

This commit is contained in:
Julien Valverdé
2026-07-19 00:46:36 +02:00
parent 3fc3904c6c
commit cc64ae785d
4 changed files with 478 additions and 484 deletions
+316 -321
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -51,6 +51,7 @@
"react": "^19.2.0"
},
"dependencies": {
"@standard-schema/spec": "^1.1.0",
"effect-lens": "^2.0.0-beta.1"
}
}
+27 -30
View File
@@ -1,3 +1,4 @@
import type { StandardSchemaV1 } from "@standard-schema/spec"
import { Array, type Cause, Chunk, type Duration, Effect, Equal, Function, identity, Option, Pipeable, Predicate, type Scope, Stream, SubscriptionRef } from "effect"
import type * as React from "react"
import * as Component from "./Component.js"
@@ -8,11 +9,6 @@ import * as View from "./View.js"
export const FormTypeId: unique symbol = Symbol.for("@effect-fc/Form/Form")
export type FormTypeId = typeof FormTypeId
export interface FormIssue {
readonly path: readonly PropertyKey[]
readonly message: string
}
export interface Form<out P extends readonly PropertyKey[], in out A, in out I = A, in out ER = never, in out EW = never>
extends Pipeable.Pipeable {
readonly [FormTypeId]: FormTypeId
@@ -20,8 +16,8 @@ extends Pipeable.Pipeable {
readonly path: P
readonly value: View.View<Option.Option<A>, ER, never>
readonly encodedValue: Lens.Lens<I, ER, EW, never, never>
readonly issues: View.View<readonly FormIssue[], never, never>
readonly isValidating: View.View<boolean, never, never>
readonly issues: View.View<readonly StandardSchemaV1.Issue[], never, never>
readonly isValidating: View.View<boolean, ER, never>
readonly canCommit: View.View<boolean, never, never>
readonly isCommitting: View.View<boolean, never, never>
}
@@ -34,7 +30,7 @@ extends Pipeable.Class implements Form<P, A, I, ER, EW> {
readonly path: P,
readonly value: View.View<Option.Option<A>, ER, never>,
readonly encodedValue: Lens.Lens<I, ER, EW, never, never>,
readonly issues: View.View<readonly FormIssue[], never, never>,
readonly issues: View.View<readonly StandardSchemaV1.Issue[], never, never>,
readonly isValidating: View.View<boolean, never, never>,
readonly canCommit: View.View<boolean, never, never>,
readonly isCommitting: View.View<boolean, never, never>,
@@ -43,16 +39,17 @@ extends Pipeable.Class implements Form<P, A, I, ER, EW> {
}
}
export const isForm = (u: unknown): u is Form<readonly PropertyKey[], unknown, unknown> => Predicate.hasProperty(u, FormTypeId)
const filterIssuesByPath = (
issues: readonly FormIssue[],
issues: readonly StandardSchemaV1.Issue[],
path: readonly PropertyKey[],
): readonly FormIssue[] => Array.filter(issues, issue =>
issue.path.length >= path.length && Array.every(path, (p, i) => p === issue.path[i])
)
): readonly StandardSchemaV1.Issue[] => Array.filter(issues, issue => {
const issuePath = issue.path
if (!issuePath) return false
return issuePath.length >= path.length && Array.every(path, (p, i) => p === issuePath[i])
})
export const focusObjectOn: {
<P extends readonly PropertyKey[], A extends object, I extends object, ER, EW, K extends keyof A & keyof I>(
@@ -66,7 +63,7 @@ export const focusObjectOn: {
self: Form<P, A, I, ER, EW>,
key: K,
): Form<readonly [...P, K], A[K], I[K], ER, EW> => {
const form = self as unknown as FormImpl<P, A, I, ER, EW>
const form = self as FormImpl<P, A, I, ER, EW>
const path = [...form.path, key] as const
return new FormImpl(
@@ -92,12 +89,12 @@ export const focusArrayAt: {
self: Form<P, A, I, ER, EW>,
index: number,
): Form<readonly [...P, number], A[number], I[number], ER | Cause.NoSuchElementError, EW | Cause.NoSuchElementError> => {
const form = self as unknown as FormImpl<P, A, I, ER, EW>
const form = self as FormImpl<P, A, I, ER, EW>
const path = [...form.path, index] as const
return new FormImpl(
path,
View.mapOptionEffect(form.value, values => Effect.fromOption(Array.get(values, index))),
View.mapOptionEffect(form.value, value => Effect.fromOption(Array.get(value, index))),
Lens.focusArrayAt(form.encodedValue, index),
View.map(form.issues, issues => filterIssuesByPath(issues, path)),
form.isValidating,
@@ -118,12 +115,12 @@ export const focusTupleAt: {
self: Form<P, A, I, ER, EW>,
index: K,
): Form<readonly [...P, K], A[K], I[K], ER, EW> => {
const form = self as unknown as FormImpl<P, A, I, ER, EW>
const form = self as FormImpl<P, A, I, ER, EW>
const path = [...form.path, index] as const
return new FormImpl(
path,
View.mapOption(form.value, values => values[index]),
View.mapOption(form.value, Array.getUnsafe(index)),
Lens.focusTupleAt(form.encodedValue, index),
View.map(form.issues, issues => filterIssuesByPath(issues, path)),
form.isValidating,
@@ -144,12 +141,12 @@ export const focusChunkAt: {
self: Form<P, Chunk.Chunk<A>, Chunk.Chunk<I>, ER, EW>,
index: number,
): Form<readonly [...P, number], A, I, ER | Cause.NoSuchElementError, EW> => {
const form = self as unknown as FormImpl<P, Chunk.Chunk<A>, Chunk.Chunk<I>, ER, EW>
const form = self as FormImpl<P, Chunk.Chunk<A>, Chunk.Chunk<I>, ER, EW>
const path = [...form.path, index] as const
return new FormImpl(
path,
View.mapOptionEffect(form.value, values => Effect.fromOption(Chunk.get(values, index))),
View.mapOptionEffect(form.value, value => Effect.fromOption(Chunk.get(value, index))),
Lens.focusChunkAt(form.encodedValue, index),
View.map(form.issues, issues => filterIssuesByPath(issues, path)),
form.isValidating,
@@ -183,11 +180,9 @@ export const useInput = Effect.fnUntraced(function* <P extends readonly Property
yield* Effect.forkScoped(Effect.all([
Stream.runForEach(
Stream.drop(form.encodedValue.changes, 1),
upstreamEncodedValue => Effect.flatMap(
Lens.get(internalValueLens),
internalValue => !Equal.equals(upstreamEncodedValue, internalValue)
? Lens.set(internalValueLens, upstreamEncodedValue)
: Effect.succeed(undefined),
upstreamEncodedValue => Effect.when(
Lens.set(internalValueLens, upstreamEncodedValue),
Effect.map(Lens.get(internalValueLens), internalValue => !Equal.equals(upstreamEncodedValue, internalValue)),
),
),
@@ -242,11 +237,8 @@ export const useOptionalInput = Effect.fnUntraced(function* <P extends readonly
Stream.runForEach(
Stream.drop(field.encodedValue.changes, 1),
upstreamEncodedValue => Effect.flatMap(
Effect.all([Lens.get(enabledLens), Lens.get(internalValueLens)]),
([enabled, internalValue]) => Equal.equals(upstreamEncodedValue, enabled ? Option.some(internalValue) : Option.none())
? Effect.succeed(undefined)
: Option.match(upstreamEncodedValue, {
upstreamEncodedValue => Effect.when(
Option.match(upstreamEncodedValue, {
onSome: v => Effect.andThen(
Lens.set(enabledLens, true),
Lens.set(internalValueLens, v),
@@ -256,6 +248,11 @@ export const useOptionalInput = Effect.fnUntraced(function* <P extends readonly
Lens.set(internalValueLens, options.defaultValue),
),
}),
Effect.map(
Effect.all([Lens.get(enabledLens), Lens.get(internalValueLens)]),
([enabled, internalValue]) => !Equal.equals(upstreamEncodedValue, enabled ? Option.some(internalValue) : Option.none()),
),
),
),
+134 -133
View File
@@ -1,212 +1,213 @@
import {
Array,
Cause,
type Context,
Effect,
Fiber,
Option,
Pipeable,
Predicate,
Schema,
SchemaIssue,
SchemaParser,
type Scope,
Semaphore,
SubscriptionRef,
} from "effect"
import type { StandardSchemaV1 } from "@standard-schema/spec"
import { Array, Cause, type Context, Effect, Fiber, Option, Pipeable, Predicate, Schema, SchemaError, SchemaIssue, type Scope, Semaphore, SubscriptionRef } from "effect"
import { AsyncResult } from "effect/unstable/reactivity"
import * as Form from "./Form.js"
import * as Lens from "./Lens.js"
import * as Mutation from "./Mutation.js"
import * as Result from "./Result.js"
import * as View from "./View.js"
type FormSchema<A, I, R> = Schema.Top & {
readonly Type: A
readonly Encoded: I
readonly DecodingServices: R
}
export const SubmittableFormTypeId: unique symbol = Symbol.for("@effect-fc/Form/SubmittableForm")
export type SubmittableFormTypeId = typeof SubmittableFormTypeId
export interface SubmittableForm<in out A, in out I = A, in out R = never, in out MA = void, in out ME = never, in out MR = never, in out MP = never>
export interface SubmittableForm<in out A, in out I = A, in out R = never, in out MA = void, out ME = never, in out MR = never>
extends Form.Form<readonly [], A, I, never, never> {
readonly [SubmittableFormTypeId]: SubmittableFormTypeId
readonly schema: FormSchema<A, I, R>
readonly schema: Schema.ConstraintCodec<A, I, R, unknown>
readonly context: Context.Context<Scope.Scope | R>
readonly mutation: Mutation.Mutation<
readonly [value: A, form: SubmittableForm<A, I, R, unknown, unknown, unknown>],
MA, ME, MR, MP
MA, ME, MR
>
readonly validationFiber: View.View<Option.Option<Fiber.Fiber<A, SchemaIssue.Issue>>, never, never>
readonly validationFiber: View.View<Option.Option<Fiber.Fiber<A, Schema.SchemaError>>, never, never>
readonly run: Effect.Effect<void>
readonly submit: Effect.Effect<Option.Option<Result.Final<MA, ME, MP>>, Cause.NoSuchElementError>
readonly submit: Effect.Effect<Option.Option<AsyncResult.Success<MA, ME> | AsyncResult.Failure<MA, ME>>, Cause.NoSuchElementError>
}
export class SubmittableFormImpl<in out A, in out I = A, in out R = never, in out MA = void, in out ME = never, in out MR = never, in out MP = never>
extends Pipeable.Class implements SubmittableForm<A, I, R, MA, ME, MR, MP> {
export class SubmittableFormImpl<in out A, in out I = A, in out R = never, in out MA = void, in out ME = never, in out MR = never>
extends Pipeable.Class implements SubmittableForm<A, I, R, MA, ME, MR> {
readonly [Form.FormTypeId]: Form.FormTypeId = Form.FormTypeId
readonly [SubmittableFormTypeId]: SubmittableFormTypeId = SubmittableFormTypeId
readonly path = [] as const
readonly encodedValue: Lens.Lens<I, never, never, never, never>
readonly isValidating: View.View<boolean, never, never>
readonly canCommit: View.View<boolean, never, never>
readonly isCommitting: View.View<boolean, never, never>
constructor(
readonly schema: FormSchema<A, I, R>,
readonly schema: Schema.ConstraintCodec<A, I, R, unknown>,
readonly context: Context.Context<Scope.Scope | R>,
readonly mutation: Mutation.Mutation<
readonly [value: A, form: SubmittableForm<A, I, R, unknown, unknown, unknown>],
MA, ME, MR, MP
MA, ME, MR
>,
readonly value: Lens.Lens<Option.Option<A>, never, never, never, never>,
readonly internalEncodedValue: Lens.Lens<I, never, never, never, never>,
readonly issues: Lens.Lens<readonly Form.FormIssue[], never, never, never, never>,
readonly validationFiber: Lens.Lens<Option.Option<Fiber.Fiber<A, SchemaIssue.Issue>>, never, never, never, never>,
readonly issues: Lens.Lens<readonly StandardSchemaV1.Issue[], never, never, never, never>,
readonly validationFiber: Lens.Lens<Option.Option<Fiber.Fiber<A, Schema.SchemaError>>, never, never, never, never>,
readonly runSemaphore: Semaphore.Semaphore,
) {
super()
this.encodedValue = Lens.make({
get: Lens.get(internalEncodedValue),
changes: internalEncodedValue.changes,
commit: encoded => Effect.andThen(
Lens.set(internalEncodedValue, encoded),
this.synchronizeEncodedValue(encoded),
),
lock: Lens.asLensImpl(internalEncodedValue).lock,
})
this.isValidating = View.map(validationFiber, Option.isSome)
const commitState = View.zipLatestAll(
value as any,
issues as any,
validationFiber as any,
mutation.result as any,
) as unknown as View.View<readonly [
Option.Option<A>,
readonly Form.FormIssue[],
Option.Option<Fiber.Fiber<A, SchemaIssue.Issue>>,
Result.Result<MA, ME, MP>,
]>
this.canCommit = View.map(
commitState,
([current, currentIssues, fiber, result]: readonly [Option.Option<A>, readonly Form.FormIssue[], Option.Option<Fiber.Fiber<A, SchemaIssue.Issue>>, Result.Result<MA, ME, MP>]) => Option.isSome(current)
&& currentIssues.length === 0
&& Option.isNone(fiber)
&& !(Result.isRunning(result) || Result.hasRefreshingFlag(result)),
)
this.isCommitting = View.map(
mutation.result,
result => Result.isRunning(result) || Result.hasRefreshingFlag(result),
)
}
synchronizeEncodedValue(encodedValue: I): Effect.Effect<void> {
const self = this
return Effect.gen(function*() {
const current = yield* Lens.get(self.validationFiber)
if (Option.isSome(current)) yield* Fiber.interrupt(current.value)
const fiber = yield* Effect.forkScoped(
Effect.ensuring(
SchemaParser.decodeEffect(self.schema)(encodedValue),
Lens.set(self.validationFiber, Option.none()),
this.encodedValue = Effect.all([
Effect.succeed(this),
Effect.succeed(Lens.asLensImpl(this.internalEncodedValue)),
]).pipe(
Effect.map(([self, parent]) => Lens.make({
get: parent.get,
get changes() { return parent.changes },
commit: a => Effect.andThen(
Effect.flatMap(
parent.resolve,
resolved => resolved.commit(Effect.succeed(a)),
),
self.synchronizeEncodedValue(a),
),
)
yield* Lens.set(self.validationFiber, Option.some(fiber))
const decoded = yield* Fiber.join(fiber).pipe(
Effect.tap(value => Effect.andThen(
Lens.set(self.issues, Array.empty()),
Lens.set(self.value, Option.some(value)),
)),
Effect.catchIf(SchemaIssue.isIssue, issue => Lens.set(self.issues, formatIssue(issue))),
)
void decoded
}).pipe(Effect.provide(this.context)) as Effect.Effect<void>
lock: parent.lock,
})),
Lens.unwrap,
)
this.isValidating = Effect.succeed(this).pipe(
Effect.map(self => View.map(self.validationFiber, Option.isSome)),
View.unwrap,
)
this.canCommit = Effect.succeed(this).pipe(
Effect.map(self => View.map(
View.zipLatestAll(self.value, self.issues, self.validationFiber, self.mutation.state),
([value, issues, validationFiber, result]) => (
Option.isSome(value) &&
Array.isReadonlyArrayEmpty(issues) &&
Option.isNone(validationFiber) &&
!AsyncResult.isWaiting(result)
),
)),
View.unwrap,
)
this.isCommitting = Effect.succeed(this).pipe(
Effect.map(self => View.map(self.mutation.state, AsyncResult.isWaiting)),
View.unwrap,
)
}
get run(): Effect.Effect<void> {
return Effect.flatMap(
Lens.get(this.encodedValue),
SchemaParser.decodeEffect(this.schema),
).pipe(
synchronizeEncodedValue(encodedValue: I): Effect.Effect<void, never, never> {
return Lens.get(this.validationFiber).pipe(
Effect.andThen(Option.match({
onSome: Fiber.interrupt,
onNone: () => Effect.void,
})),
Effect.andThen(Effect.forkScoped(
Effect.ensuring(
Schema.decodeEffect(this.schema, { errors: "all" })(encodedValue),
Lens.set(this.validationFiber, Option.none()),
)
)),
Effect.tap(fiber => Lens.set(this.validationFiber, Option.some(fiber))),
Effect.flatMap(Fiber.join),
Effect.tap(() => Lens.set(this.issues, Array.empty())),
Effect.flatMap(value => Lens.set(this.value, Option.some(value))),
Effect.catchIf(
SchemaError.isSchemaError,
error => Lens.set(this.issues, SchemaIssue.makeFormatterStandardSchemaV1()(error.issue).issues),
),
Effect.provide(this.context),
)
}
get run(): Effect.Effect<void, never, never> {
return Lens.get(this.encodedValue).pipe(
Effect.flatMap(v => Schema.decodeEffect(this.schema)(v)),
Effect.option,
Effect.flatMap(value => Lens.set(this.value, value)),
Effect.flatMap(v => Lens.set(this.value, v)),
Effect.provide(this.context),
this.runSemaphore.withPermits(1),
)
}
get submit(): Effect.Effect<Option.Option<Result.Final<MA, ME, MP>>, Cause.NoSuchElementError> {
return Effect.flatMap(Lens.get(this.value), value => Effect.flatMap(Effect.fromOption(value), decoded => this.submitValue(decoded)))
get submit(): Effect.Effect<Option.Option<AsyncResult.Success<MA, ME> | AsyncResult.Failure<MA, ME>>, Cause.NoSuchElementError, never> {
return Lens.get(this.value).pipe(
Effect.flatMap(Effect.fromOption),
Effect.flatMap(value => this.submitValue(value)),
)
}
submitValue(value: A): Effect.Effect<Option.Option<Result.Final<MA, ME, MP>>> {
return Effect.flatMap(this.canCommit.get, canCommit => {
if (!canCommit) return Effect.succeed(Option.none())
return Effect.map(
Effect.tap(this.mutation.mutate([value, this as any]), result => {
if (!Result.isFailure(result)) return Effect.succeed(undefined)
const issue = Cause.findErrorOption(result.cause)
return Option.isSome(issue) && SchemaIssue.isIssue(issue.value)
? Lens.set(this.issues, formatIssue(issue.value))
: Effect.succeed(undefined)
}),
Option.some,
)
})
submitValue(value: A): Effect.Effect<Option.Option<AsyncResult.Success<MA, ME> | AsyncResult.Failure<MA, ME>>, never, never> {
return Effect.when(
Effect.tap(
this.mutation.mutate([value, this as any]),
result => AsyncResult.isFailure(result)
? Option.match(
Array.findFirst(
result.cause.reasons,
reason => Cause.isFailReason(reason) && SchemaError.isSchemaError(reason.error)
? Option.some(reason.error)
: Option.none(),
),
{
onSome: error => Lens.set(this.issues, SchemaIssue.makeFormatterStandardSchemaV1()(error.issue).issues),
onNone: () => Effect.void,
},
)
: Effect.void,
),
View.get(this.canCommit),
)
}
}
const formatIssue = (issue: SchemaIssue.Issue): readonly Form.FormIssue[] => {
const formatted = SchemaIssue.makeFormatterStandardSchemaV1()(issue)
return formatted.issues.map(item => ({
path: (item.path ?? []) as readonly PropertyKey[],
message: item.message,
}))
}
export const isSubmittableForm = (u: unknown): u is SubmittableForm<unknown, unknown, unknown, unknown, unknown, unknown> => Predicate.hasProperty(u, SubmittableFormTypeId)
export const isSubmittableForm = (u: unknown): u is SubmittableForm<unknown, unknown, unknown, unknown, unknown, unknown, unknown> => Predicate.hasProperty(u, SubmittableFormTypeId)
export declare namespace make {
export interface Options<in out A, in out I = A, in out R = never, in out MA = void, in out ME = never, in out MR = never, in out MP = never>
export interface Options<in out A, in out I = A, in out R = never, in out MA = void, in out ME = never, in out MR = never>
extends Mutation.make.Options<
readonly [value: NoInfer<A>, form: SubmittableForm<NoInfer<A>, NoInfer<I>, NoInfer<R>, unknown, unknown, unknown>],
MA, ME, MR, MP
MA, ME, MR
> {
readonly schema: FormSchema<A, I, R>
readonly schema: Schema.ConstraintCodec<A, I, R, unknown>
readonly initialEncodedValue: NoInfer<I>
}
}
export const make = Effect.fnUntraced(function* <A, I = A, R = never, MA = void, ME = never, MR = never, MP = never>(
options: make.Options<A, I, R, MA, ME, MR, MP>,
export const make = Effect.fnUntraced(function* <A, I = A, R = never, MA = void, ME = never, MR = never>(
options: make.Options<A, I, R, MA, ME, MR>
): Effect.fn.Return<
SubmittableForm<A, I, R, MA, ME, Result.forkEffect.OutputContext<MR, MP>, MP>,
SubmittableForm<A, I, R, MA, ME, MR>,
never,
Scope.Scope | R | Result.forkEffect.OutputContext<MR, MP>
Scope.Scope | R | MR
> {
return new SubmittableFormImpl(
options.schema,
yield* Effect.context<Scope.Scope | R>(),
yield* Effect.context<Scope.Scope | R | MR>(),
yield* Mutation.make(options),
Lens.fromSubscriptionRef(yield* SubscriptionRef.make(Option.none<A>())),
Lens.fromSubscriptionRef(yield* SubscriptionRef.make(options.initialEncodedValue)),
Lens.fromSubscriptionRef(yield* SubscriptionRef.make<readonly Form.FormIssue[]>(Array.empty())),
Lens.fromSubscriptionRef(yield* SubscriptionRef.make(Option.none<Fiber.Fiber<A, SchemaIssue.Issue>>())),
Lens.fromSubscriptionRef(yield* SubscriptionRef.make<readonly StandardSchemaV1.Issue[]>(Array.empty())),
Lens.fromSubscriptionRef(yield* SubscriptionRef.make(Option.none<Fiber.Fiber<A, Schema.SchemaError>>())),
yield* Semaphore.make(1),
)
})
export declare namespace service {
export interface Options<in out A, in out I = A, in out R = never, in out MA = void, in out ME = never, in out MR = never, in out MP = never>
extends make.Options<A, I, R, MA, ME, MR, MP> {}
export interface Options<in out A, in out I = A, in out R = never, in out MA = void, in out ME = never, in out MR = never>
extends make.Options<A, I, R, MA, ME, MR> {}
}
export const service = <A, I = A, R = never, MA = void, ME = never, MR = never, MP = never>(
options: service.Options<A, I, R, MA, ME, MR, MP>,
options: service.Options<A, I, R, MA, ME, MR>
): Effect.Effect<
SubmittableForm<A, I, R, MA, ME, Result.forkEffect.OutputContext<MR, MP>, MP>,
SubmittableForm<A, I, R, MA, ME, MR>,
never,
Scope.Scope | R | Result.forkEffect.OutputContext<MR, MP>
> => Effect.tap(make(options), form => Effect.asVoid(Effect.forkScoped(form.run)))
Scope.Scope | R | MR
> => Effect.tap(
make(options),
form => Effect.forkScoped(form.run),
)