Skip to content

Auto-generate reactpy.html elements (instead of manual defining each element) #1214

Closed
@Archmonger

Description

@Archmonger

Current Situation

Currently, we need to manually write every single HTML element that could exist. This is not efficient and is fairly annoying to maintain.

Proposed Actions

Create a generic that can automate this.

Here's an a draft implementation I made in a few minutes.

from reactpy.core.types import VdomDictConstructor
from reactpy.core.vdom import custom_vdom_constructor, make_vdom_constructor
from reactpy.html import _fragment, _script

NO_CHILDREN_ALLOWED = {
    "area",
    "base",
    "br",
    "col",
    "command",
    "embed",
    "hr",
    "img",
    "input",
    "iframe",
    "keygen",
    "link",
    "meta",
    "param",
    "portal",
    "source",
    "track",
    "wbr",
}


class HtmlConstructor:
    cache: dict[str, VdomDictConstructor] = {
        "script": custom_vdom_constructor(_script),
        "fragment": custom_vdom_constructor(_fragment),
    }

    def __getattribute__(self, value: str) -> VdomDictConstructor:
        if value.startswith("__") or value in {"cache"}:
            return super().__getattribute__(value)

        if value in self.cache:
            return self.cache[value]

        self.cache[value] = make_vdom_constructor(
            value,
            allow_children=value not in NO_CHILDREN_ALLOWED,
        )

        return self.cache[value]


html = HtmlConstructor()

# Here's an example usage...
tree = html.html(
    {"lang": "en"},
    html.head(
        html.title("Hello, world!"),
    ),
    html.body(
        html.h1("Hello, world!"),
        html.p("This is a paragraph."),
    ),
)

print(tree)

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority-2-moderateShould be resolved on a reasonable timeline.type-revisionAbout a change in functionality or behavior

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions