/** * @title Children that outlive the view with Component.child * * Bind tab editors to the component so each keeps its draft while another * tab is shown, and end an editor when its tab closes. */ import { Note } from "#domain/Note" import { Schema } from "effect" import { Component, UiSchema } from "effect/ui" import { Html } from "effect/ui/html" import { NoteActivity } from "../fixtures/notes/components/NoteActivity.ts" import { NoteEditor } from "../fixtures/notes/components/NoteEditor.ts" // Overview // A tab editor may need to keep its draft and finish saving while another // tab is shown. Separate the editor's lifetime from where its view appears. // An ordinary `NoteEditor(h, { ... })` unmounts when the view leaves it out, // discarding its Model and interrupting its Commands. Use that default when // the child has no work or state to retain while absent. // // Bind a child in `children` on the definition when its state must outlive // the view leaving it out: a tab, a wizard step, a panel a toggle hides. A // bound child starts with its parent, before any view places it, and lives // while the parent lives and its entry resolves to the same component and // key, unless a keyed ancestor Layer changes and restarts it. The view // decides where it shows, with `h.children.`. // Every bound child runs whether or not it's shown, so don't bind a long // list's rows to save a render. const scratchpad: Note = { id: "scratchpad", title: "Scratchpad", body: "" } export const NoteTabsMessage = UiSchema.TaggedEnum({ ClickedTab: { id: Schema.String }, ClickedClose: { id: Schema.String }, ClickedScratchpad: {}, ToggledActivity: {}, SavedNote: { id: Schema.String } }) export const NoteTabs = Html.component({ name: "NoteTabs", props: Schema.Struct({ notes: Schema.Array(Note) }), model: Schema.Struct({ open: Schema.Record(Schema.String, Note), active: Schema.NullOr(Schema.String), showActivity: Schema.Boolean, lastSaved: Schema.NullOr(Schema.String) }), message: NoteTabsMessage, // Evaluated with current Model, props and query results. Bound children's // requirements join the parent's, even when the children are unplaced. children: ($) => ({ // One child for the component's whole life. Its path is // `NoteTabs/NoteEditor[scratchpad]`; the editors below are NoteEditors // too, so their keys (note ids) must never be "scratchpad". scratchpad: Component.child(NoteEditor, { key: "scratchpad", props: { note: scratchpad } }), // One child per key. A key that leaves `keys` ends its child, so // closing a tab drops that editor's draft and interrupts its autosave. // `props` and `onEmit` get the key, and are re-read after every update: // a hidden editor still gets fresh props and reports to this parent. editors: Component.childMany(NoteEditor, { keys: Object.keys($.model.open), props: (id) => ({ note: $.model.open[id]! }), onEmit: { Saved: (_event, id) => NoteTabsMessage.SavedNote({ id }) } }), // `undefined`, `null` or `false` unbinds the entry and ends the child. // A changed key starts it over, so switching tabs gives the activity // panel a fresh instance for the new note. `NoteActivity` is a feature: // the child waits for its Layer, and `NoteActivity` joins this // component's requirements. A `Component.lazy` child starts loading // its module when it's bound, before any view places it. activity: $.model.showActivity && $.model.active !== null && Component.child(NoteActivity, { key: $.model.active, props: { noteId: $.model.active } }) }) }).make({ init: ($) => ({ open: Object.fromEntries($.props.notes.map((note) => [note.id, note])), active: $.props.notes[0]?.id ?? null, showActivity: false, lastSaved: null }), update: { ClickedTab: ($, { id }) => $.evolve({ active: id }), ClickedScratchpad: ($) => $.evolve({ active: null }), ToggledActivity: ($) => $.evolve({ showActivity: (shown) => !shown }), ClickedClose: ($, { id }) => $.evolve({ open: ({ [id]: _closed, ...rest }) => rest, active: (active) => active === id ? null : active }), SavedNote: ($, { id }) => $.evolve({ lastSaved: id }) }, view: (h, model) => h.div( h.nav( Object.values(model.open).map((note) => h.span.key(note.id).children( h.button.on("click", NoteTabsMessage.ClickedTab({ id: note.id })).children(note.title), h.button.on("click", NoteTabsMessage.ClickedClose({ id: note.id })).children("×") ) ), h.button.on("click", NoteTabsMessage.ClickedScratchpad()).children("Scratchpad"), h.button.on("click", NoteTabsMessage.ToggledActivity()).children("Activity") ), // Only the active editor is placed. The others are unplaced: each // keeps its Model, query results, Subscriptions and running Commands. // Its view stops running, its nodes are removed, and its view-scoped // children unmount. Scroll position, focus, the caret and uncontrolled // input text are lost. The draft survives because the Model holds it, // and an autosave in flight can still complete. // A `childMany` placer takes the key and returns `null` for a key // that isn't bound. model.active === null ? h.children.scratchpad() : h.children.editors(model.active, { fallback: () => h.p("This note couldn't be opened.") }), // Each placement owns its fallback for loading or failure. // An unbound entry returns `null`, without showing a fallback. h.aside(h.children.activity({ fallback: () => h.p("Loading activity…") })), model.lastSaved !== null && h.p.attr("role", "status").children(`Saved ${model.lastSaved}`) ) }) // Keep host nodes while hiding a tab // Keep each editor placed inside a hidden element to retain its DOM nodes // and uncontrolled input text. The editors still render when updated. // Hiding does not guarantee that focus returns when the tab is shown. // // Object.keys(model.open).map((id) => // h.section.key(id) // .attr("hidden", id === model.active ? undefined : "") // .children(h.children.editors(id)) // ) // // Ordinary `NoteEditor(h, { ... })` children also stay mounted inside a // hidden section while the view continues to declare them. // // Move a child between panels // Moving a placement in the same flush keeps its Model and reuses its nodes // where the host supports the move. Moving between HTML/SVG namespaces // rebuilds the affected nodes. On React Native, moving between native // parents recreates the native subtree: focus, scroll position and text // held only in the native control are lost. Text in the Model survives. // Reordering within one native parent preserves its native views. // // Other binding rules: // - Placing one child twice in a render fails the parent. // - A bound child resolves shared reads and Layers from its parent, not from // the element or slot it's placed in. // - `MessageLog` logs `Placed` when a view places a child and draws its // nodes, and `Unplaced` when the flush that left it out ends. // - Server rendering ships an unplaced child's state in the state map by its // path, with no nodes, and hydration adopts it. History restore saves and // restores bound children by path too. // - `children` is part of the definition, so a `Definition.logic` shared by // several hosts carries its bindings to each of them. // - `RouterStack.Screens` keeps every stacked screen this way: it draws // each entry and passes `covered`, and the screen hides itself when it's // covered.