Skip to content

AST change: introducing a parent property #81

@RomFouq

Description

@RomFouq

First of all, thank you for PostHTML and its companion projects!

I am currently working on a plugin that needs frequent access to parent nodes.
I would like to propose a couple of changes to the AST generated by https://github.com/posthtml/posthtml-parser, to make it easier to use and faster for some use cases.

Introducing a parent property to the Node type, referencing the parent node, would for instance make posthtml/posthtml#226 more straightforward to solve.
Sometimes matching the parent node then handling the child is not possible, e.g. when the child may or may not have a parent node, forcing to handle the case where the child is an orphan separately.

Of course it is possible to insert this property in each node after the tree has been generated by the parser, but this requires traversing the whole tree, which can have a significant impact on performance for big trees.

To introduce this property, it would be needed to change the way HTML text nodes are encoded in the AST, as it is not possible to append an additional property to JS string objects.
HTML text nodes could for instance be encoded in the form { text: string | number, parent?: NodeTag | Node[] }, unfortunately breaking backward compatibility for the parser (but https://github.com/posthtml/posthtml-render could still be backward compatible) but I think this is inevitable.

I have working code for both https://github.com/posthtml/posthtml-parser and https://github.com/posthtml/posthtml-render with updated type definitions and passing unit tests and can make a couple of PRs if you would want to take a look.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions