255 lines
10 KiB
TypeScript
255 lines
10 KiB
TypeScript
import * as AsyncData from "@typed/async-data"
|
|
import { Array, Duration, Effect, Equal, Equivalence, identity, Option, ParseResult, pipe, Pipeable, Ref, Schema, Scope, Stream, Subscribable, SubscriptionRef } from "effect"
|
|
import type { NoSuchElementException } from "effect/Cause"
|
|
import * as React from "react"
|
|
import { Hooks } from "./hooks/index.js"
|
|
import { PropertyPath, Subscribable as SubscribableInternal, SubscriptionSubRef } from "./types/index.js"
|
|
|
|
|
|
export const FormTypeId: unique symbol = Symbol.for("effect-fc/Form")
|
|
export type FormTypeId = typeof FormTypeId
|
|
|
|
export interface Form<in out A, in out I = A, out R = never, in out SA = void, in out SE = A, out SR = never>
|
|
extends Pipeable.Pipeable {
|
|
readonly [FormTypeId]: FormTypeId
|
|
|
|
readonly schema: Schema.Schema<A, I, R>,
|
|
readonly submit: (value: NoInfer<A>) => Effect.Effect<SA, SE, SR>,
|
|
|
|
readonly valueRef: SubscriptionRef.SubscriptionRef<Option.Option<A>>,
|
|
readonly encodedValueRef: SubscriptionRef.SubscriptionRef<I>,
|
|
readonly errorRef: SubscriptionRef.SubscriptionRef<Option.Option<ParseResult.ParseError>>,
|
|
/** Whether or not a validation is currently being executed */
|
|
readonly isValidatingRef: SubscriptionRef.SubscriptionRef<boolean>
|
|
readonly submitStateRef: SubscriptionRef.SubscriptionRef<AsyncData.AsyncData<SA, SE>>,
|
|
|
|
readonly canSubmitSubscribable: Subscribable.Subscribable<boolean>
|
|
}
|
|
|
|
class FormImpl<in out A, in out I = A, out R = never, in out SA = void, in out SE = A, out SR = never>
|
|
extends Pipeable.Class() implements Form<A, I, R, SA, SE, SR> {
|
|
readonly [FormTypeId]: FormTypeId = FormTypeId
|
|
readonly canSubmitSubscribable: Subscribable.Subscribable<boolean>
|
|
|
|
constructor(
|
|
readonly schema: Schema.Schema<A, I, R>,
|
|
readonly submit: (value: NoInfer<A>) => Effect.Effect<SA, SE, SR>,
|
|
readonly valueRef: SubscriptionRef.SubscriptionRef<Option.Option<A>>,
|
|
readonly encodedValueRef: SubscriptionRef.SubscriptionRef<I>,
|
|
readonly errorRef: SubscriptionRef.SubscriptionRef<Option.Option<ParseResult.ParseError>>,
|
|
readonly isValidatingRef: SubscriptionRef.SubscriptionRef<boolean>,
|
|
readonly submitStateRef: SubscriptionRef.SubscriptionRef<AsyncData.AsyncData<SA, SE>>,
|
|
) {
|
|
super()
|
|
|
|
this.canSubmitSubscribable = pipe(
|
|
<A>([value, error, isValidating]: readonly [
|
|
Option.Option<A>,
|
|
Option.Option<ParseResult.ParseError>,
|
|
boolean,
|
|
]) => Option.isSome(value) && Option.isNone(error) && !isValidating,
|
|
|
|
filter => SubscribableInternal.make({
|
|
get: Effect.map(Effect.all([valueRef, errorRef, isValidatingRef]), filter),
|
|
get changes() { return Stream.map(Stream.zipLatestAll(valueRef.changes, errorRef.changes, isValidatingRef.changes), filter)},
|
|
}),
|
|
)
|
|
}
|
|
}
|
|
|
|
|
|
export const FormFieldTypeId: unique symbol = Symbol.for("effect-fc/FormField")
|
|
export type FormFieldTypeId = typeof FormFieldTypeId
|
|
|
|
export interface FormField<in out A, in out I = A>
|
|
extends Pipeable.Pipeable {
|
|
readonly [FormFieldTypeId]: FormFieldTypeId
|
|
|
|
readonly valueSubscribable: Subscribable.Subscribable<Option.Option<A>, NoSuchElementException>
|
|
readonly encodedValueRef: SubscriptionRef.SubscriptionRef<I>
|
|
readonly issuesSubscribable: Subscribable.Subscribable<readonly ParseResult.ArrayFormatterIssue[]>
|
|
readonly isValidatingSubscribable: Subscribable.Subscribable<boolean>
|
|
readonly isSubmittingSubscribable: Subscribable.Subscribable<boolean>
|
|
}
|
|
|
|
class FormFieldImpl<in out A, in out I = A>
|
|
extends Pipeable.Class() implements FormField<A, I> {
|
|
readonly [FormFieldTypeId]: FormFieldTypeId = FormFieldTypeId
|
|
|
|
constructor(
|
|
readonly valueSubscribable: Subscribable.Subscribable<Option.Option<A>, NoSuchElementException>,
|
|
readonly encodedValueRef: SubscriptionRef.SubscriptionRef<I>,
|
|
readonly issuesSubscribable: Subscribable.Subscribable<readonly ParseResult.ArrayFormatterIssue[]>,
|
|
readonly isValidatingSubscribable: Subscribable.Subscribable<boolean>,
|
|
readonly isSubmittingSubscribable: Subscribable.Subscribable<boolean>,
|
|
) {
|
|
super()
|
|
}
|
|
}
|
|
|
|
|
|
export namespace make {
|
|
export interface Options<in out A, in out I, out R, in out SA = void, in out SE = A, out SR = never> {
|
|
readonly schema: Schema.Schema<A, I, R>
|
|
readonly initialEncodedValue: NoInfer<I>
|
|
readonly submit: (value: NoInfer<A>) => Effect.Effect<SA, SE, SR>
|
|
}
|
|
}
|
|
|
|
export const make: {
|
|
<A, I = A, R = never, SA = void, SE = A, SR = never>(
|
|
options: make.Options<A, I, R, SA, SE, SR>
|
|
): Effect.Effect<Form<A, I, R, SA, SE, SR>>
|
|
} = Effect.fnUntraced(function* <A, I = A, R = never, SA = void, SE = A, SR = never>(
|
|
options: make.Options<A, I, R, SA, SE, SR>
|
|
) {
|
|
return new FormImpl(
|
|
options.schema,
|
|
options.submit,
|
|
yield* SubscriptionRef.make(Option.none<A>()),
|
|
yield* SubscriptionRef.make(options.initialEncodedValue),
|
|
yield* SubscriptionRef.make(Option.none<ParseResult.ParseError>()),
|
|
yield* SubscriptionRef.make(false),
|
|
yield* SubscriptionRef.make(AsyncData.noData<SA, SE>()),
|
|
)
|
|
})
|
|
|
|
export namespace service {
|
|
export interface Options<in out A, in out I, out R, in out SA = void, in out SE = A, out SR = never>
|
|
extends make.Options<A, I, R, SA, SE, SR> {}
|
|
}
|
|
|
|
export const service = <A, I = A, R = never, SA = void, SE = A, SR = never>(
|
|
options: service.Options<A, I, R, SA, SE, SR>
|
|
): Effect.Effect<Form<A, I, R, SA, SE, SR>, never, R | Scope.Scope> => Effect.tap(
|
|
make(options),
|
|
form => Effect.forkScoped(run(form)),
|
|
)
|
|
|
|
export namespace useForm {
|
|
export interface Options<in out A, in out I, out R, in out SA = void, in out SE = A, out SR = never>
|
|
extends make.Options<A, I, R, SA, SE, SR> {}
|
|
}
|
|
|
|
export const useForm: {
|
|
<A, I = A, R = never, SA = void, SE = A, SR = never>(
|
|
options: service.Options<A, I, R, SA, SE, SR>
|
|
): Effect.Effect<Form<A, I, R, SA, SE, SR>, never, R>
|
|
} = Effect.fnUntraced(function* <A, I = A, R = never, SA = void, SE = A, SR = never>(
|
|
options: service.Options<A, I, R, SA, SE, SR>
|
|
) {
|
|
const form = yield* Hooks.useOnce(() => make(options))
|
|
yield* Hooks.useFork(() => run(form), [form])
|
|
return form
|
|
})
|
|
|
|
const run = <A, I, R, SA, SE, SR>(self: Form<A, I, R, SA, SE, SR>) => Stream.runForEach(
|
|
self.encodedValueRef.changes,
|
|
encodedValue => SubscriptionRef.set(self.isValidatingRef, true).pipe(
|
|
Effect.andThen(Schema.decode(self.schema, { errors: "all" })(encodedValue)),
|
|
Effect.andThen(v => SubscriptionRef.set(self.valueRef, Option.some(v))),
|
|
Effect.andThen(SubscriptionRef.set(self.errorRef, Option.none())),
|
|
Effect.catchTag("ParseError", e => SubscriptionRef.set(self.errorRef, Option.some(e))),
|
|
Effect.andThen(SubscriptionRef.set(self.isValidatingRef, false)),
|
|
),
|
|
)
|
|
|
|
|
|
export const field = <A, I, R, SA, SE, SR, const P extends PropertyPath.Paths<NoInfer<I>>>(
|
|
self: Form<A, I, R, SA, SE, SR>,
|
|
path: P,
|
|
): FormField<PropertyPath.ValueFromPath<A, P>, PropertyPath.ValueFromPath<I, P>> => new FormFieldImpl(
|
|
pipe(
|
|
Option.match({
|
|
onSome: (v: A) => Option.map(PropertyPath.get(v, path), Option.some),
|
|
onNone: () => Option.some(Option.none()),
|
|
}),
|
|
filter => SubscribableInternal.make({
|
|
get: Effect.flatMap(self.valueRef, filter),
|
|
get changes() { return Stream.flatMap(self.valueRef.changes, filter) },
|
|
}),
|
|
),
|
|
|
|
SubscriptionSubRef.makeFromPath(self.encodedValueRef, path),
|
|
|
|
pipe(
|
|
Option.match({
|
|
onSome: (v: ParseResult.ParseError) => Effect.andThen(
|
|
ParseResult.ArrayFormatter.formatError(v),
|
|
Array.filter(issue => PropertyPath.equivalence(issue.path, path)),
|
|
),
|
|
onNone: () => Effect.succeed([]),
|
|
}),
|
|
filter => SubscribableInternal.make({
|
|
get: Effect.flatMap(self.errorRef.get, filter),
|
|
get changes() { return Stream.flatMap(self.errorRef.changes, filter) },
|
|
}),
|
|
),
|
|
|
|
self.isValidatingRef,
|
|
|
|
pipe(
|
|
AsyncData.isLoading,
|
|
filter => SubscribableInternal.make({
|
|
get: Effect.map(self.submitStateRef, filter),
|
|
get changes() { return Stream.map(self.submitStateRef.changes, filter) },
|
|
}),
|
|
),
|
|
)
|
|
|
|
export const useField = <A, I, R, SA, SE, SR, const P extends PropertyPath.Paths<NoInfer<I>>>(
|
|
self: Form<A, I, R, SA, SE, SR>,
|
|
path: P,
|
|
): FormField<PropertyPath.ValueFromPath<A, P>, PropertyPath.ValueFromPath<I, P>> => React.useMemo(
|
|
() => field(self, path),
|
|
[self, ...path],
|
|
)
|
|
|
|
|
|
export namespace useInput {
|
|
export interface Options {
|
|
readonly debounce?: Duration.DurationInput
|
|
}
|
|
|
|
export interface Result<T> {
|
|
readonly value: T
|
|
readonly setValue: React.Dispatch<React.SetStateAction<T>>
|
|
readonly issues: readonly ParseResult.ArrayFormatterIssue[]
|
|
}
|
|
}
|
|
|
|
export const useInput: {
|
|
<A, I>(
|
|
field: FormField<A, I>,
|
|
options?: useInput.Options,
|
|
): Effect.Effect<useInput.Result<I>, NoSuchElementException>
|
|
} = Effect.fnUntraced(function* <A, I>(
|
|
field: FormField<A, I>,
|
|
options?: useInput.Options,
|
|
) {
|
|
const internalValueRef = yield* Hooks.useMemo(() => Effect.andThen(field.encodedValueRef, SubscriptionRef.make), [field])
|
|
const [value, setValue] = yield* Hooks.useRefState(internalValueRef)
|
|
const [issues] = yield* Hooks.useSubscribables(field.issuesSubscribable)
|
|
|
|
yield* Hooks.useFork(() => Effect.all([
|
|
Stream.runForEach(
|
|
Stream.drop(field.encodedValueRef, 1),
|
|
upstreamEncodedValue => Effect.whenEffect(
|
|
Ref.set(internalValueRef, upstreamEncodedValue),
|
|
Effect.andThen(internalValueRef, internalValue => !Equal.equals(upstreamEncodedValue, internalValue)),
|
|
),
|
|
),
|
|
|
|
Stream.runForEach(
|
|
internalValueRef.changes.pipe(
|
|
Stream.drop(1),
|
|
Stream.changesWith(Equivalence.strict()),
|
|
options?.debounce ? Stream.debounce(options.debounce) : identity,
|
|
),
|
|
internalValue => Ref.set(field.encodedValueRef, internalValue),
|
|
),
|
|
], { concurrency: "unbounded" }), [field, internalValueRef])
|
|
|
|
return { value, setValue, issues }
|
|
})
|