/** * @title Swappable children with Feature.Service * * Render a swappable child with `Feature.Service`, implemented differently by * the app and a story. */ import { Schema } from "effect" import { AsyncResult } from "effect/reactivity" import { Component, UiSchema } from "effect/ui" import { Html } from "effect/ui/html" // `NoteActivity` is the contract, a `Feature.Service` with the props (and // events) Schemas. `ActivityLog` is the app's implementation. Both are in // `fixtures/notes/components`. import { ActivityLog } from "../fixtures/notes/components/ActivityLog.ts" import { NoteActivity } from "../fixtures/notes/components/NoteActivity.ts" // Use a feature when the parent shouldn't pick the implementation: a live // one in the app, a cheap one in stories and tests, or one per customer. To // split a component into its own chunk, use `Component.lazy` instead. export const NoteSidebarNoDeps = Html.component({ name: "NoteSidebar", props: Schema.Struct({ noteId: Schema.String }), model: Schema.Struct({}), message: Schema.Never }).make({ init: () => ({}), update: ($) => $.model, view: (h) => h.aside( h.h2("Activity"), // `render` declares the child like a component call. The parent requires // `NoteActivity` only, never what the implementation needs. `fallback` // is required: the service's Layer may still be building (`Initial`) or // may have failed (`Failure`). The path is `NoteActivity[activity]` // whichever implementation runs, so tests and saved state don't change. NoteActivity.render(h, { key: "activity", props: { noteId: h.props.noteId }, fallback: (result) => h.p(AsyncResult.isInitial(result) ? "Loading activity…" : "Activity is unavailable.") }) ) }) // The app's choice. `toLayer` doesn't compile unless the component's props // and events fit the contract, and the implementation's own requirements are // closed here. export const NoteSidebar = NoteSidebarNoDeps.pipe( Component.provide(NoteActivity.toLayer(ActivityLog)) ) // A story's choice: a stand-in with fixed content, built against the same // contract. A test provides it to `NoteSidebarNoDeps` the same way. const ActivityPreviewMessage = UiSchema.TaggedEnum({ ClickedMore: {} }) const ActivityPreview = Html.component({ name: "ActivityPreview", props: NoteActivity.props, model: Schema.Struct({ expanded: Schema.Boolean }), message: ActivityPreviewMessage }).make({ init: () => ({ expanded: false }), update: { ClickedMore: ($) => $.evolve({ expanded: true }) }, view: (h, model) => h.ul( h.li("Edited by Ada · 2 minutes ago"), model.expanded ? h.li("Created by Grace · yesterday") : h.button.on("click", ActivityPreviewMessage.ClickedMore()).children("More") ) }) export const NoteSidebarStory = NoteSidebarNoDeps.pipe( Component.provide(NoteActivity.toLayer(ActivityPreview)) )