Skip to content

Unify Component and VDOM Element Constructor Interface #755

Closed

Description

@rmorshea

Current Situation

Currently the vdom element constructor and component constructors have different interfaces. Component constructors are effectively just the same as the functions which define them. For the vdom constructor though we pass vdom(tag, attrs_dict, *children). The fact that these two constructors have different interfaces won't play well with this tagged strings PEP.

Proposed Actions

In anticipation of the work from the tagged strings PEP we should have a unified interface for constructing elements and components. I think the best way to do this would be to effectively copy the interface for React's functional components.

When constructing a component or element the interface would be:

constructor(*children, key=..., **attributes)

However the definition for the constructor would be:

def constructor(children: list[any], **attributes: any): ...

In the function definition, *children gets bundled together into a special children argument that gets passed to the function. Component functions without a children argument then do not support *children. Additionally (as is currently the case) the special key parameter is hidden and handled separately.

One wrinkle in this is that the attribute for most user defined components will be snake_case while the attributes for standard HTML elements are camelCase. I suspect this will be confusing for most users. As a result, I suggest that, for standard HTML elements, we include a snake_case to camelCase conversion. Thus something like div(background_color) would be treated the same as div(backgroundColor=...).

This will be a relatively large change, so we will provide a way for users to transition to the new interface.

Notes

We should probably do #545 at the same time. So we'd add a fallback kwarg to the constructor:

constructor(*children, key=..., fallback=..., **attributes)

Activity

  1. added
    priority-2-moderateShould be resolved on a reasonable timeline.
    and removed on May 23, 2022
  2. added this to the 1.0 milestone on May 23, 2022
  3. rmorshea commented on May 31, 2022

    @rmorshea
    CollaboratorAuthor

    @Archmonger thoughts on this?

  4. Archmonger commented on May 31, 2022

    @Archmonger
    Contributor

    I would recommend automatically changing all attributes from snake_case to camelCase on the backend.

    I vaguely recall seeing some regex for this in Django core.

  5. rmorshea commented on May 31, 2022

    @rmorshea
    CollaboratorAuthor

    I think I want to implement the conversion client-side since that's where they have to be interpreted, but the effect for the user would be the same - all attributes would automatically become camelCase.

  6. Archmonger commented on May 31, 2022

    @Archmonger
    Contributor
  7. rmorshea commented on Nov 24, 2022

    @rmorshea
    CollaboratorAuthor

    It looks like there's approx 200 instances I'll need to modify. I drafted a script to auto-convert the old-style to the new one, but ast.unparse removes a lot of information (e.g. visually useful new lines) so I don't think I'll use it on IDOM's source:

    import ast
    import re
    from pathlib import Path
    from idom import html
    
    _CAMEL_CASE_SUB_PATTERN = re.compile(r"(?<!^)(?=[A-Z])")
    
    def update_vdom_constructor_usages(file: Path) -> None:
        tree = ast.parse(file.read_text())
    
        changed = False
        for node in ast.walk(tree):
            if isinstance(node, ast.Call):
                match (func := node.func):
                    case ast.Attribute():
                        name = func.attr
                    case ast.Name(ctx=ast.Load()):
                        name = func.id
                    case _:
                        name = ""
                if hasattr(html, name):
                    match node.args:
                        case [ast.Dict(), *_]:
                            first_arg = node.args[0]
                            new_keywords = list(node.keywords)
                            for k, v in zip(first_arg.keys, first_arg.values):
                                if isinstance(k, ast.Constant) and isinstance(k.value, str):
                                    new_keywords.append(ast.keyword(arg=conv_attr_name(k.value), value=v))
                                else:
                                    break
                            else:
                                changed=True
                                node.args = node.args[1:]
                                node.keywords = new_keywords
                        case _:
                            first_arg = None
    
        if changed:
            tree = ast.fix_missing_locations(tree)
            file.write_text(ast.unparse(tree))
    
    def conv_attr_name(name: str) -> str:
        return _CAMEL_CASE_SUB_PATTERN.sub("_", name).replace("-", "_").lower()
  8. rmorshea commented on Nov 29, 2022

    @rmorshea
    CollaboratorAuthor

    I have an updated script that has much less impact on code style. I've run this script against IDOM's docs and tests to automatically convert html.*() usages to the new style.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions