`@effect/ui` (Effect-TS/ui): pass an element's props to `Renderer.Host.createElement`, so a host can construct nodes that take constructor arguments

Abierto
#11,089 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
3/5
Tiempo estimado
1-2 días
Aptitud para principiantes
74/100
Tipo de issue
Nueva funcionalidad
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
typescript
Área
frontend

Línea de trabajo

Start with Renderer.Host.createElement in packages/ui/src/Renderer.ts and the kernel create path in packages/ui/src/internal/kernel.ts. Trace where element props are available before creation and how host implementations declare or forward createElement; the issue provides a focused reproduction in packages/ui/test/CreateElementProps.test.ts. Done when creation receives the element props while the existing attribute, child, and setProp order is preserved, and the reproduction constructs Box with the supplied dimensions.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

[!NOTE]
Please note that Claude Opus 5.5 at high effort assisted the author in preparing this content.

What is the problem this feature would solve?

TL;DR: Renderer.Host.createElement(tag) receives only the tag, and an element's props reach the host through setProp only after its children are placed, so a host whose nodes take constructor arguments can't construct them; passing the props to createElement as an optional second argument would fix it.

Hosts that render to object models built from classes need some values when an object is constructed. In three.js, BoxGeometry builds its buffers from width, height and depth in the constructor, and InstancedMesh sizes its instance buffer by the count it's constructed with, which can later be lowered but never raised. Such a host has to construct a placeholder and rebuild it when setProp brings the real values, or hold construction back until then, and either way it needs a wrapper node of its own, since the node the renderer, refs and mounts hold can't be swapped. The OpenTUI host in the repository works around the same gap: it constructs a slider with a fixed orientation and code and markdown views with a default syntaxStyle, then overwrites them with the element's own values through setProp. Custom renderers in React (createInstance(type, props, …)) and Vue (createElement(type, namespace, isCustomizedBuiltIn, vnodeProps)) receive the props when they create a node. Related work in the repository includes:

  • Effect-TS/ui#224: added the OpenTUI tags whose constructors need orientation and syntaxStyle, and with them the special cases in OpenTuiHost.createElement.

Save this as packages/ui/test/CreateElementProps.test.ts in Effect-TS/ui and run pnpm vitest run packages/ui/test/CreateElementProps.test.ts --silent=false:

import { Component, Renderer } from "@effect/ui"
import { TestHost } from "@effect/ui/testing"
import { it } from "@effect/vitest"
import { Effect, Schema } from "effect"

// Stands for a class such as three.js's BoxGeometry: its size is fixed when
// it is constructed.
class Box {
  constructor(readonly width = 1, readonly height = 1, readonly depth = 1) {}
}

const base = TestHost.makeHost()
const boxes = new WeakMap<object, Box>()
const host: Renderer.Host<any> = {
  ...base,
  createElement(tag: string, ...rest: Array<unknown>) {
    const props = rest[0] as { readonly args?: Array<number> } | undefined
    console.log(`createElement(${JSON.stringify(tag)}) props:`, props)
    const node = base.createElement(tag)
    if (tag === "box") boxes.set(node, new Box(...(props?.args ?? [])))
    return node
  },
  setProp(node, name, value) {
    console.log(`setProp(<${node.tag}>, ${JSON.stringify(name)})`)
    base.setProp(node, name, value)
  }
}

const App = Component.define({
  name: "App",
  model: Schema.Null,
  message: Schema.Never
}).make({
  init: () => null,
  update: ($) => $.model,
  view: (h) => h.el("box").prop("args", [2, 3, 4])
})

it.effect("constructor arguments", () =>
  Effect.gen(function*() {
    const root = yield* TestHost.mount(App, {})
    yield* TestHost.settle
    console.log("constructed:", boxes.get(root.container.children[0]!))
  }).pipe(
    Effect.provide(Renderer.layer(host)),
    Effect.provide(TestHost.layer())
  ))

It prints:

createElement("box") props: undefined
setProp(<box>, "args")
constructed: Box { width: 1, height: 1, depth: 1 }

The box should be constructed as Box { width: 2, height: 3, depth: 4 }, with createElement receiving { args: [ 2, 3, 4 ] }.

Root cause. Renderer.Host.createElement takes only the tag. The kernel's create calls it, sets the attributes, places the children and only then calls setProp for each prop, the order a patch also keeps so "a select's value wins over its options'". Nothing gives the host the props before then.

Package Version Commit
@effect/ui (Effect-TS/ui) 0.0.0 (unreleased) 1b89db4
@effect/ui-opentui (Effect-TS/ui) 0.0.0 (unreleased) 1b89db4
effect 4.1.6
What is the feature you are proposing to solve the problem?

Give Renderer.Host.createElement the element's props as an optional second argument:

createElement(tag: string, props?: Readonly<Record<string, unknown>>): Node

When the renderer creates an element, it passes the props record the element already holds, empty when it has none, so nothing is allocated. Everything else keeps its order: attributes right after creation, then the children, then setProp for every prop, so a select's value still wins over its options'. A host reads the constructor arguments it needs from props and can treat the setProp of the same value that follows as a no-op.

  • Existing hosts that declare createElement(tag) still satisfy the interface, and calls that create a container without props, such as host.createElement("#root"), stay valid. The DOM, server, native and test hosts ignore the argument, and a host that wraps another forwards it. Hydration adopts server nodes without calling createElement, so it doesn't change.
  • The OpenTUI host constructs a slider with the element's orientation and code and markdown views with its syntaxStyle, keeping its defaults when they're absent, so it no longer overwrites placeholders.
  • The change is additive. With it, the example above would print the expected output.

This is the first increment, and the scope of this issue. A later increment would cover a change of a construct-only prop: it still reaches the host through setProp, where it can't be applied. The renderer already has the path for it: an element whose tag or key changes is replaced, its subtree built again, its mounts restarted on the new node and its refs pointing at it. A host hook, such as replaces?(tag, previous, next): boolean, consulted wherever the renderer pairs an element with its previous render, would let a host declare that change, as react-three-fiber reconstructs an object when its args change. The hook decides equality, since an args array is new on every render. Its shape, and whether children should be rebuilt or moved to the new node, are for the maintainers to settle.

Nothing needs to be settled before the first increment; when and how it lands is for the maintainers to decide.

What alternatives have you considered?

Inside a host, construction can wait until setProp brings the values, or a placeholder can be rebuilt when they arrive, as the OpenTUI host does with its defaults. Both make each host work around the order of the renderer's calls with a wrapper node of its own, and neither removes the gap. Keying the element on its constructor arguments with .key(...) makes the renderer replace it when they change, but every author has to know which props each tag constructs with.

Lenguaje dominante
TypeScript
Estrellas
16.7k
Forks
808
Merge medio
21 h 22 min
PR fusionados (30 d)
486

Preparar el entorno

Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de Effect-TS/effect

Todos los issues de Effect-TS/effect

Issues similares

Más issues de TypeScript

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.