import { assert, describe, it } from "@effect/vitest" import { Cause, Deferred, Effect, Layer, Schema } from "effect" import { Command, Component, Feature, Head, type MessageLog, UiSchema } from "effect/ui" import { Locator, TestHost } from "effect/ui/testing" const provideHost = (effect: Effect.Effect) => effect.pipe(Effect.provide(TestHost.layer())) const click = (root: Pick, "get">, text: string) => Locator.fire(root.get(Locator.text(text, { exact: true })), "click") const lifecycle = (root: { readonly log: () => ReadonlyArray }, path: string) => root.log().flatMap((entry) => "path" in entry && entry.path === path && entry._tag !== "Update" && !entry._tag.startsWith("Command") ? [entry._tag] : [] ) const FormMsg = UiSchema.TaggedEnum({ Typed: {}, Save: {}, Saved: { text: Schema.String } }) const FormEvents = UiSchema.TaggedEnum({ Saved: { text: Schema.String } }) const makeForm = (saving: Deferred.Deferred) => { const Save = Command.make( "Save", { args: { text: Schema.String } }, ({ text }) => Deferred.await(saving).pipe(Effect.as(FormMsg.Saved({ text }))) ) return Component.define({ name: "Profile", props: Schema.Struct({ label: Schema.String }), model: Schema.Struct({ draft: Schema.String, saved: Schema.String }), message: FormMsg, events: FormEvents }).make({ head: () => [Head.title("Profile")], init: () => ({ draft: "", saved: "" }), update: ($, message) => FormMsg.match(message, { Typed: () => ({ ...$.model, draft: $.model.draft + "a" }), Save: () => $.run(Save.make({ text: $.model.draft })), Saved: ({ text }) => $.set({ ...$.model, saved: text }).emit(FormEvents.Saved({ text })) }), view: (h, model) => h.el( "form", h.el("button").on("click", FormMsg.Typed()).children(h.props.label + ":" + model.draft), h.el("button").on("click", FormMsg.Save()).children("save"), h.el("p", "saved:" + model.saved) ) }) } const Billing = Component.define({ name: "Billing", model: Schema.Null, message: Schema.Never }).make({ init: () => null, update: ($) => $.model, view: (h) => h.el("p", "billing") }) const SettingsMsg = UiSchema.TaggedEnum({ Show: { tab: Schema.String }, Saved: { text: Schema.String } }) const makeSettings = (Profile: ReturnType) => Component.define({ name: "Settings", model: Schema.Struct({ tab: Schema.String, saved: Schema.Array(Schema.String) }), message: SettingsMsg, children: ($) => ({ profile: Component.child(Profile, { key: "form", props: { label: "draft@" + $.model.tab }, onEmit: (event) => SettingsMsg.Saved({ text: event.text + "@" + $.model.tab }) }) }) }).make({ head: () => [Head.title("Settings")], init: () => ({ tab: "profile", saved: [] }), update: ($, message) => SettingsMsg.match(message, { Show: ({ tab }) => ({ ...$.model, tab }), Saved: ({ text }) => ({ ...$.model, saved: [...$.model.saved, text] }) }), view: (h, model) => h.el("main", model.tab === "profile" ? h.children.profile() : Billing(h, { key: "billing" })) }) describe("bound children", () => { it.effect("an unplaced child keeps its Model and Commands, takes fresh props, and emits through the latest onEmit", () => provideHost(Effect.gen(function*() { const saving = yield* Deferred.make() const root = yield* TestHost.mount(makeSettings(makeForm(saving)), {}) yield* TestHost.settle assert.strictEqual(root.text(), "draft@profile:savesaved:") click(root, "draft@profile:") yield* TestHost.settle click(root, "save") yield* TestHost.settle root.send(SettingsMsg.Show({ tab: "billing" })) yield* TestHost.settle assert.strictEqual(root.text(), "billing") assert.strictEqual(root.head().title, "Settings") assert.deepStrictEqual(root.pending().map((p) => p.path), ["/Settings/Profile[form]"]) yield* Deferred.succeed(saving, undefined) yield* TestHost.settle assert.deepStrictEqual(root.model()?.saved, ["a@billing"]) root.send(SettingsMsg.Show({ tab: "profile" })) yield* TestHost.settle assert.strictEqual(root.text(), "draft@profile:asavesaved:a") assert.strictEqual(root.head().title, "Profile") assert.deepStrictEqual(lifecycle(root, "/Settings/Profile[form]"), [ "Mounted", "Placed", "PropsChanged", "Unplaced", "PropsChanged", "Placed" ]) }))) it.effect("starts with its parent before any view places it, drops its view-scoped children when unplaced", () => provideHost(Effect.gen(function*() { const root = yield* TestHost.mount(Shelf, {}) yield* TestHost.settle assert.strictEqual(root.text(), "") assert.deepStrictEqual(root.model()?.started, ["c"]) assert.deepStrictEqual(lifecycle(root, "/Shelf/Counter[c]"), ["Mounted"]) root.send(ShelfMsg.Shown({ shown: true })) yield* TestHost.settle click(root, "count:0") yield* TestHost.settle assert.strictEqual(root.text(), "count:1note") root.send(ShelfMsg.Shown({ shown: false })) yield* TestHost.settle root.send(ShelfMsg.Shown({ shown: true })) yield* TestHost.settle assert.strictEqual(root.text(), "count:1note") assert.deepStrictEqual(lifecycle(root, "/Shelf/Counter[c]/Note[]"), ["Mounted", "Unmounted", "Mounted"]) }))) it.effect("ends a child its binding drops, and starts it again under a new key", () => provideHost(Effect.gen(function*() { const root = yield* TestHost.mount(Shelf, {}) yield* TestHost.settle root.send(ShelfMsg.Shown({ shown: true })) yield* TestHost.settle click(root, "count:0") yield* TestHost.settle root.send(ShelfMsg.Key({ key: "d" })) yield* TestHost.settle assert.strictEqual(root.text(), "count:0note") assert.deepStrictEqual(root.model()?.started, ["c", "d"]) assert.deepStrictEqual(lifecycle(root, "/Shelf/Counter[c]"), ["Mounted", "Placed", "Unmounted"]) root.send(ShelfMsg.Key({ key: undefined })) yield* TestHost.settle assert.strictEqual(root.text(), "") assert.deepStrictEqual(lifecycle(root, "/Shelf/Counter[d]"), ["Mounted", "Placed", "Unmounted"]) }))) it.effect("moves a child's nodes to its new place in one render", () => provideHost(Effect.gen(function*() { const root = yield* TestHost.mount(Shelf, {}) yield* TestHost.settle root.send(ShelfMsg.Shown({ shown: true })) yield* TestHost.settle const button = root.get(Locator.text("count:0", { exact: true })) root.send(ShelfMsg.Side({ left: false })) yield* TestHost.settle assert.strictEqual(root.get(Locator.text("count:0", { exact: true })), button) assert.strictEqual(root.get(Locator.tag("main")).children!.length, 0) assert.strictEqual(root.get(Locator.tag("aside")).children!.length, 1) assert.deepStrictEqual(lifecycle(root, "/Shelf/Counter[c]"), ["Mounted", "Placed"]) assert.deepStrictEqual(lifecycle(root, "/Shelf/Counter[c]/Note[]"), ["Mounted"]) }))) it.effect("fails the parent that places one child twice in a render", () => provideHost(Effect.gen(function*() { const root = yield* TestHost.mount(Twice, {}) yield* TestHost.settle assert.strictEqual(root.text(), "down") assert.include(Cause.pretty(failureOf(root)!.cause), "Counter[c]") }))) it.effect("binds one child per key, and hands its key to onEmit", () => provideHost(Effect.gen(function*() { const root = yield* TestHost.mount(Rows, {}) yield* TestHost.settle assert.strictEqual(root.text(), "count:0note") assert.deepStrictEqual(root.model()?.started, ["a", "b"]) root.send(RowsMsg.Keys({ keys: ["b", "c"] })) yield* TestHost.settle assert.deepStrictEqual(root.model()?.started, ["a", "b", "c"]) assert.deepStrictEqual(lifecycle(root, "/Rows/Counter[a]"), ["Mounted", "Placed", "Unmounted"]) assert.deepStrictEqual(lifecycle(root, "/Rows/Counter[b]"), ["Mounted"]) }))) it.effect("places nothing for a key its childMany doesn't bind, even one another binding has", () => provideHost(Effect.gen(function*() { const asked: Array = [] const Two = Component.define({ name: "Two", model: Schema.Null, message: Schema.Never, children: () => ({ shown: Component.childMany(Counter, { keys: ["a"] }), none: Component.childMany(Counter, { keys: [], props: (key) => { asked.push(key) return {} } }) }) }).make({ init: () => null, update: ($) => $.model, view: (h) => h.el("ul", h.children.none("a"), h.children.none("b")) }) const root = yield* TestHost.mount(Two, {}) yield* TestHost.settle assert.strictEqual(root.text(), "") assert.isUndefined(failureOf(root)) assert.deepStrictEqual(asked, []) }))) it.effect("starts loading a lazy child when bound, and shows a placement's fallback until it loads", () => provideHost(Effect.gen(function*() { let loads = 0 const Lazy = Component.lazy("LazyCounter", () => { loads++ return new Promise((resolve) => setTimeout(() => resolve(Counter), 10)) }) const Parent = Component.define({ name: "Parent", model: Schema.Boolean, message: Schema.Boolean, children: () => ({ counter: Component.child(Lazy, { key: "c" }) }) }).make({ init: () => false, update: (_, shown) => shown, view: (h, shown) => h.el("main", shown ? h.children.counter({ fallback: () => h.el("p", "loading") }) : null) }) const root = yield* TestHost.mount(Parent, {}) assert.strictEqual(loads, 1) assert.deepStrictEqual(root.pending(), [{ _tag: "Load", path: "/Parent/LazyCounter[c]", name: "LazyCounter" }]) root.send(true) yield* TestHost.settle assert.deepStrictEqual(root.frames(), ["", "loading", "count:0note"]) assert.strictEqual(loads, 1) }))) it.effect("shows a failed load, retries when bound again, and updates other placements showing the failure", () => provideHost(Effect.gen(function*() { let loads = 0 const Lazy = Component.lazy( "LazyCounter", () => loads++ === 0 ? Promise.reject(new Error("offline")) : Promise.resolve(Counter) ) const Parent = Component.define({ name: "Parent", model: Schema.Boolean, message: Schema.Boolean, children: ($) => ({ counter: $.model && Component.child(Lazy, { key: "c" }) }) }).make({ init: () => true, update: (_, bound) => bound, view: (h) => h.el( "main", h.children.counter({ fallback: (result) => h.el("p", result._tag === "Failure" ? "failed" : "loading") }) ) }) const first = yield* TestHost.mount(Parent, {}) const second = yield* TestHost.mount(Parent, {}) yield* TestHost.settle assert.strictEqual(first.text(), "failed") assert.strictEqual(second.text(), "failed") first.send(false) yield* TestHost.settle first.send(true) yield* TestHost.settle assert.strictEqual(loads, 2) assert.strictEqual(first.text(), "count:0note") assert.strictEqual(second.text(), "count:0note") }))) it.effect("resolves a feature child from its parent's Layers and starts it again under a keyed provide's new Layer", () => provideHost(Effect.gen(function*() { class Greeting extends Feature.Service()("Greeting", { props: Schema.Struct({}) }) {} const word = (text: string) => Component.define({ name: "Word", model: Schema.Null, message: Schema.Never }).make({ init: () => null, update: ($) => $.model, view: (h) => h.text(text) }) const Room = Component.define({ name: "Room", model: Schema.String, message: Schema.String, children: () => ({ greeting: Component.child(Greeting, { key: "g" }) }) }).make({ init: () => "a", update: (_, room) => room, view: (h) => h.el("main", h.children.greeting()) }) const Keyed = Component.provide(Room, { key: (_, room) => room, layer: (room) => Greeting.toLayer(word(room)) }) const root = yield* TestHost.mount(Keyed, {}) yield* TestHost.settle assert.strictEqual(root.text(), "a") root.send("b") yield* TestHost.settle assert.strictEqual(root.text(), "b") }))) it.effect("change the Layer of one no view places when its Model changes the key", () => provideHost(Effect.gen(function*() { const Moved = Command.make("Moved", {}, () => Effect.succeed("b")) const Room = Component.define({ name: "Room", model: Schema.String, message: Schema.String }).make({ init: ($) => $.set("a").run(Moved.make({})), update: (_, room) => room, view: (h, room) => h.text(room) }) const Keyed = Component.provide(Room, { key: (_, room) => room, layer: () => Layer.empty }) const Shell = Component.define({ name: "Shell", model: Schema.Boolean, message: Schema.Boolean, children: () => ({ room: Component.child(Keyed, { key: "r" }) }) }).make({ init: () => false, update: (_, shown) => shown, view: (h, shown) => h.el("main", shown ? h.children.room() : null) }) const root = yield* TestHost.mount(Shell, {}) yield* TestHost.settle assert.isUndefined(failureOf(root)) root.send(true) yield* TestHost.settle assert.strictEqual(root.text(), "b") }))) }) const failureOf = (root: { readonly log: () => ReadonlyArray }) => root.log().find((entry) => entry._tag === "Failed") as MessageLog.Failed | undefined const Note = Component.define({ name: "Note", model: Schema.Null, message: Schema.Never }).make({ init: () => null, update: ($) => $.model, view: (h) => h.el("i", "note") }) const CounterEvents = UiSchema.TaggedEnum({ Started: {} }) const CounterMsg = UiSchema.TaggedEnum({ Clicked: {}, Started: {} }) const Ready = Command.make("Ready", {}, () => Effect.succeed(CounterMsg.Started())) const Counter = Component.define({ name: "Counter", model: Schema.Number, message: CounterMsg, events: CounterEvents }).make({ init: ($) => $.set(0).run(Ready.make({})), update: ($, message) => CounterMsg.match(message, { Clicked: () => $.model + 1, Started: () => $.emit(CounterEvents.Started()) }), view: (h, count) => h.el("p", h.el("button").on("click", CounterMsg.Clicked()).children("count:" + count), Note(h, {})) }) const ShelfMsg = UiSchema.TaggedEnum({ Shown: { shown: Schema.Boolean }, Side: { left: Schema.Boolean }, Key: { key: Schema.UndefinedOr(Schema.String) }, Started: { key: Schema.String } }) const Shelf = Component.define({ name: "Shelf", model: Schema.Struct({ shown: Schema.Boolean, left: Schema.Boolean, key: Schema.UndefinedOr(Schema.String), started: Schema.Array(Schema.String) }), message: ShelfMsg, children: ($) => { const key = $.model.key return { counter: key === undefined ? undefined : Component.child(Counter, { key, onEmit: () => ShelfMsg.Started({ key }) }) } } }).make({ init: () => ({ shown: false, left: true, key: "c", started: [] }), update: ($, message) => ShelfMsg.match(message, { Shown: ({ shown }) => ({ ...$.model, shown }), Side: ({ left }) => ({ ...$.model, left }), Key: ({ key }) => ({ ...$.model, key }), Started: ({ key }) => ({ ...$.model, started: [...$.model.started, key] }) }), view: (h, model) => { const counter = model.shown ? h.children.counter() : null return h.el("div", h.el("main", model.left ? counter : null), h.el("aside", model.left ? null : counter)) } }) const TwiceInner = Component.define({ name: "Twice", model: Schema.Null, message: Schema.Never, children: () => ({ counter: Component.child(Counter, { key: "c" }) }) }).make({ init: () => null, update: ($) => $.model, view: (h) => h.el("div", h.el("main", h.children.counter()), h.el("aside", h.children.counter())) }) const Twice = Component.define({ name: "Host", model: Schema.Null, message: Schema.Never }).make({ init: () => null, update: ($) => $.model, view: (h) => h.el("main", TwiceInner(h, { key: "t", fallback: () => h.el("p", "down") })) }) const RowsMsg = UiSchema.TaggedEnum({ Keys: { keys: Schema.Array(Schema.String) }, Started: { key: Schema.String } }) const Rows = Component.define({ name: "Rows", model: Schema.Struct({ keys: Schema.Array(Schema.String), started: Schema.Array(Schema.String) }), message: RowsMsg, children: ($) => ({ rows: Component.childMany(Counter, { keys: $.model.keys, onEmit: (_, key) => RowsMsg.Started({ key }) }) }) }).make({ init: () => ({ keys: ["a", "b"], started: [] }), update: ($, message) => RowsMsg.match(message, { Keys: ({ keys }) => ({ ...$.model, keys }), Started: ({ key }) => ({ ...$.model, started: [...$.model.started, key] }) }), view: (h, model) => h.el("ul", model.keys.includes("a") ? h.children.rows("a") : null) })