/** * @title Writing a component * * A note title editor: Schemas, `init`/`update`/`view`, a `Command.Service` * save and a `BrowserHost` mount. */ import { Note } from "#domain/Note" import { Effect, Layer, Schema } from "effect" import { FetchHttpClient } from "effect/http" import { Command, Component, UiSchema } from "effect/ui" import { BrowserHost, Html } from "effect/ui/html" import { Notes } from "../fixtures/notes/services/Notes.ts" // Messages are facts, verb first in the past tense. Events go to the parent. const NoteTitleMessage = UiSchema.TaggedEnum({ UpdatedTitle: { title: Schema.String }, SubmittedTitleForm: {}, SucceededRenameNote: { note: Note }, FailedRenameNote: { reason: Schema.String } }) const NoteTitleEvents = UiSchema.TaggedEnum({ Renamed: { note: Note } }) // I/O goes in a `Command.Service`. `toLayer` captures `Notes`, so the // component requires only `RenameNote`. The body returns this component's // messages, typed failure included. class RenameNote extends Command.Service()("notes/RenameNote", { args: { note: Note }, success: NoteTitleMessage }) { static readonly layer = this.toLayer(Effect.gen(function*() { const notes = yield* Notes return ({ note }) => notes.save(note).pipe(Effect.match({ onSuccess: (note) => NoteTitleMessage.SucceededRenameNote({ note }), onFailure: ({ reason }) => NoteTitleMessage.FailedRenameNote({ reason }) })) })) } export const NoteTitle = Html.component({ name: "NoteTitle", props: Schema.Struct({ note: Note }), model: Schema.Struct({ title: Schema.String, error: Schema.NullOr(Schema.String) }), message: NoteTitleMessage, events: NoteTitleEvents }).make({ init: ($) => ({ title: $.props.note.title, error: null }), // One pure handler per tag. `.run` issues a Command as data, `.emit` // reports to the parent. update: { UpdatedTitle: ($, { title }) => $.evolve({ title }), SubmittedTitleForm: ($) => $.evolve({ error: null }) .run(RenameNote.make({ note: { ...$.props.note, title: $.model.title } })), SucceededRenameNote: ($, { note }) => $.emit(NoteTitleEvents.Renamed({ note })), FailedRenameNote: ($, { reason }) => $.evolve({ error: reason }) }, view: (h, model) => h.form.on("submit", NoteTitleMessage.SubmittedTitleForm()).children( h.input.value(model.title) .on("input", ({ value }) => NoteTitleMessage.UpdatedTitle({ title: value })), h.button.disabled(h.isRunning(RenameNote)).children("Rename"), model.error && h.p.attr("role", "alert").children(model.error) ) }).pipe( // A component provides its own domain Layers. Component.provide(RenameNote.layer.pipe(Layer.provide(Notes.layerHttp))) ) // The browser entry provides only platform Layers. BrowserHost.mount( NoteTitle, { note: { id: "welcome", title: "Welcome", body: "" } }, document.getElementById("app")! ).pipe(Layer.provide(FetchHttpClient.layer), Layer.launch, Effect.runFork)