[`ui`] `collects`: let the owner read its readers' reports as an input, so it needs no Model copy

Đang mở
#11,061 0 bình luận 0 reaction 1 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 1 ngày

@effect-bot đang làm issue này rồi.

Từ ngày 29/11/2026.

Đánh giá

Issue này chưa được đánh giá.

Mô tả

What is the problem this feature would solve?

collects.onChange turns the readers' reports into a message, and the owner's update stores what it says in the owner's Model (23_shared-state.ts#L169-L179). That field is a second copy of facts that live in the readers' Models, and it can disagree with them.

Three cases, each a passing test in the repro below (77391ee, effect 4.1.7, TypeScript 7.0.2, TestHost):

  1. Another handler writes the field, and nothing corrects it. A Reset handler sets anyDirty to false while a reader still reports true. The owner then reads clean beside a dirty field, and stays that way: collect compares the new message with the last message it dispatched, not with the owner's Model (sharedRun.ts#L373-L384), so an unchanged report dispatches nothing.
  2. A message the owner handles in the same step reads the old value. A reader changes its Model and sends its owner a message in one step. The owner's handler runs before the collection, so $.model.anyDirty is still false there. Only update sees this: I found one committed frame per interaction under every flush setting I tried.
  3. A kept-alive reader's report is dropped while it's hidden. This one is documented (View.ts#L315-L323), and it's right for a tooltip. For a fact about the reader's Model, such as unsaved changes in a hidden tab, the owner reads clean while the kept reader still holds dirty: true.

Case 1 is the hazard: it compiles, nothing warns, and the kit's own owners have the same shape. CheckboxGroup stores its collected items in its Model, where any handler could write them (CheckboxGroup.ts#L269-L298).

The guide already states the rule this works against. A mirrored prop is "two sources for one value" (27_state-ownership.ts#L304-L310), and a reader is told to read $.reads instead of copying the shared value into its Model (23_shared-state.ts#L216-L224). collects is the one place where the API requires the copy: the owner has no other way to see its reports.

Repro. One file. Every assertion passes, and each states the current behaviour.

collects-stale.repro.test.ts
/**
 * Repro for "collects: the owner's Model copy of its readers' reports can go stale".
 * Effect-TS/ui at 77391ee, effect 4.1.7, TypeScript 7.0.2. Every assertion passes:
 * each one states the current behaviour.
 */
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { HtmlPlay } from "@effect/ui/html/testing"
import { TestHost } from "@effect/ui/testing"
import { assert, it } from "@effect/vitest"
import { Effect, Schema } from "effect"

const GroupMessage = UiSchema.TaggedEnum({
  ChangedDirty: { dirty: Schema.Boolean },
  // Any other handler can write the cached field.
  PressedReset: {},
  // A message a reader sends in the same step as its own change.
  Pinged: {}
})

const Group = Html.component({
  name: "Group",
  model: Schema.Struct({
    anyDirty: Schema.Boolean,
    // What the cache held when `Pinged` was handled: null until then.
    seenAtPing: Schema.NullOr(Schema.Boolean)
  }),
  message: GroupMessage,
  shares: {
    value: ({ model }) => ({ anyDirty: model.anyDirty }),
    schema: Schema.Struct({ anyDirty: Schema.Boolean }),
    receives: ["Pinged"],
    collects: {
      schema: Schema.Boolean,
      onChange: (reports) =>
        GroupMessage.ChangedDirty({ dirty: reports.includes(true) })
    }
  }
}).make({
  init: () => ({ anyDirty: false, seenAtPing: null }),
  update: {
    ChangedDirty: ($, { dirty }) => $.evolve({ anyDirty: dirty }),
    PressedReset: ($) => $.evolve({ anyDirty: false }),
    Pinged: ($) => $.evolve({ seenAtPing: $.model.anyDirty })
  },
  parts: (p, model) => ({
    anyDirty: model.anyDirty,
    seenAtPing: model.seenAtPing,
    reset: p.part("button", (b) => b.on("click", GroupMessage.PressedReset()))
  })
})

const FieldMessage = UiSchema.TaggedEnum({
  PressedEdit: {},
  PressedEditAndPing: {}
})

const Field = Html.component({
  name: "Field",
  model: Schema.Struct({ dirty: Schema.Boolean }),
  message: FieldMessage,
  reads: { group: { owner: Group, report: (model) => model.dirty } }
}).make({
  init: () => ({ dirty: false }),
  update: {
    PressedEdit: ($) => $.evolve({ dirty: true }),
    PressedEditAndPing: ($) =>
      $.evolve({ dirty: true }).send(Group, GroupMessage.Pinged())
  },
  view: (h, model) =>
    h.span(
      h.button.on("click", FieldMessage.PressedEdit()).children("Change"),
      h.button.on("click", FieldMessage.PressedEditAndPing()).children("Notify"),
      h.i.children(model.dirty ? " field:dirty" : " field:pristine")
    )
})

const header = (group: { anyDirty: boolean; seenAtPing: boolean | null }) =>
  `cache:${group.anyDirty ? "dirty" : "clean"} seenAtPing:${group.seenAtPing} `

const Form = Html.component({
  name: "Form",
  model: Schema.Null,
  message: Schema.Never
}).make({
  init: () => null,
  update: ($) => $.model,
  view: (h) =>
    Group(h, {
      view: (group) =>
        h.div(
          h.p.children(header(group)),
          group.reset(h.button("Reset")),
          Field(h, {})
        )
    })
})

const TabsMessage = UiSchema.TaggedEnum({ PressedToggle: {} })

const Tabs = Html.component({
  name: "Tabs",
  model: Schema.Struct({ shown: Schema.Boolean }),
  message: TabsMessage
}).make({
  init: () => ({ shown: true }),
  update: { PressedToggle: ($) => $.evolve({ shown: (shown) => !shown }) },
  view: (h, model) =>
    Group(h, {
      view: (group) =>
        h.div(
          h.p.children(header(group)),
          h.button.on("click", TabsMessage.PressedToggle()).children("Toggle"),
          h.keepAlive((s) => model.shown && Field(s, { key: "a" }))
        )
    })
})

it.layer(TestHost.layer(), { buildPerTest: true })(
  "collects: the owner's Model copy goes stale",
  (it) => {
    it.effect("1. another handler overwrites it, and nothing corrects it", () =>
      Effect.gen(function*() {
        const play = yield* HtmlPlay.make(Form, {})
        yield* play.click("Change")
        assert.include(play.root.text(), "cache:dirty")
        yield* play.click("Reset")
        assert.include(play.root.text(), "cache:clean")
        assert.include(play.root.text(), "field:dirty")
        // The report is still `true`, so `onChange` returns the message it
        // returned last time, and nothing is dispatched.
        yield* play.click("Change")
        assert.include(play.root.text(), "cache:clean")
        assert.include(play.root.text(), "field:dirty")
      }))

    it.effect("2. a message handled in the same step reads the old value", () =>
      Effect.gen(function*() {
        const play = yield* HtmlPlay.make(Form, {})
        yield* play.click("Notify")
        // The field was already dirty when the owner handled `Pinged`.
        assert.include(play.root.text(), "seenAtPing:false")
        assert.include(play.root.text(), "cache:dirty")
      }))

    it.effect("3. a kept-alive reader's report is dropped while it is hidden", () =>
      Effect.gen(function*() {
        const play = yield* HtmlPlay.make(Tabs, {})
        yield* play.click("Change")
        assert.include(play.root.text(), "cache:dirty")
        yield* play.click("Toggle")
        // The field keeps its Model, `dirty: true`, and the owner reads clean.
        assert.include(play.root.text(), "cache:clean")
        yield* play.click("Toggle")
        assert.include(play.root.text(), "cache:dirty")
        assert.include(play.root.text(), "field:dirty")
      }))
  }
)
What is the feature you are proposing to solve the problem?

Give the owner its reports as a read-only input, beside props, reads and queries: collected in the argument of shares.value, p.collected in parts and $.collected in update.

// Proposed. The owner keeps no copy, and has no message for the reports.
export const FieldGroup = Html.component({
  name: "FieldGroup",
  model: Schema.Null,
  message: Schema.Never,
  shares: {
    collects: { schema: Schema.Boolean },
    value: ({ collected }) => ({ anyDirty: collected.includes(true) })
  }
}).make({
  init: () => null,
  update: ($) => $.model,
  parts: (p) => ({ anyDirty: p.collected.includes(true) })
})

Readers don't change: reads: { group: { owner: FieldGroup, report: (model) => model.dirty } } as today.

What this would take, as far as I can tell from the source:

  • onChange becomes optional. It stays for an update that must act on a change, which is what a reader's onChange is for today. Reading the current reports no longer needs it.
  • Reports are current when a message reaches the owner. $.props already has this guarantee: an ancestor waiting to render renders before a message reaches the instance (Component.ts#L951-L954). The same rule for an owner's reports removes case 2.
  • The owner's closure re-runs when collected changes. Today it re-runs because the collected message changed the Model, so the number of passes in a flush should be the same.
  • Kept readers become a choice, for example collects: { schema, kept: true }, with today's behaviour as the default.
  • The log records what $.collected held in each Update, as it does for $.reads, so a replay reads the same reports. Scene's collected([...]) step would set the input directly.

Open questions I haven't worked through:

  • A shared value derived from collected, read by a reader whose report depends on that value, is a cycle. Today's 100-round guard covers the message form of it. The input form needs the same fixed point.
  • Reports arrive in no promised order today. That stays true, so an owner that needs an order still sorts, as CheckboxGroup does.
What alternatives have you considered?
  • Keep the data above the readers. A parent that holds the fields in its Model and derives anyDirty in its view has no copy to go stale, and it works today. It doesn't fit a compound component, where the consumer's view decides which members exist.
  • Dispatch when the owner's Model disagrees. Comparing against the Model instead of the last message would repair case 1, but the runtime can't know which Model fields hold collected data.
  • A convention in the guide: only the handler for the collected message writes those fields. This is what the kit does now. Nothing checks it, and it leaves cases 2 and 3.
Ngôn ngữ chính
TypeScript
Star
16.7k
Fork
808
Merge trung bình
21 giờ 22 phút
Pull request đã merge (30 ngày)
486

Chuẩn bị môi trường

Dự án này không cung cấp dev container, Dockerfile hay hướng dẫn đóng góp, nên bạn cần tự thiết lập môi trường: hãy bắt đầu từ README và xem hướng dẫn đóng góp lần đầu của chúng tôi để biết các bước chung.

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của Effect-TS/effect

Tất cả issue của Effect-TS/effect

Issue tương tự

Thêm issue về TypeScript

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.