refactor: use component IDs as keys for slot fill llokup

This commit is contained in:
Juro Oravec 2024-04-16 14:31:51 +02:00
parent c1369ab2c7
commit ce5b5c40d8
5 changed files with 210 additions and 115 deletions

View file

@ -1,9 +1,7 @@
import glob
import random
from pathlib import Path
from typing import Callable, List, NamedTuple, Optional
from typing import List, NamedTuple, Optional
from django.template.base import Node, NodeList
from django.template.engine import Engine
from django_components.template_loader import Loader
@ -39,34 +37,15 @@ def search(search_glob: Optional[str] = None, engine: Optional[Engine] = None) -
return SearchResult(searched_dirs=dirs, matched_files=component_filenames)
def walk_nodelist(nodes: NodeList, callback: Callable[[Node], None]) -> None:
"""Recursively walk a NodeList, calling `callback` for each Node."""
node_queue = [*nodes]
while len(node_queue):
node: Node = node_queue.pop()
callback(node)
node_queue.extend(get_node_children(node))
def get_node_children(node: Node) -> NodeList:
"""
Get child Nodes from Node's nodelist atribute.
This function is taken from `get_nodes_by_type` method of `django.template.base.Node`.
"""
nodes = NodeList()
for attr in node.child_nodelists:
nodelist = getattr(node, attr, [])
if nodelist:
nodes.extend(nodelist)
return nodes
# Global counter to ensure that all IDs generated by `gen_id` WILL be unique
_id = 0
def gen_id(length: int = 5) -> str:
# Generate random value
# See https://stackoverflow.com/questions/2782229
value = random.randrange(16**length)
"""Generate a unique ID that can be associated with a Node"""
# Global counter to avoid conflicts
global _id
_id += 1
# Signed hexadecimal (lowercase).
# See https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting
return f"{value:x}"
# Pad the ID with `0`s up to 4 digits, e.g. `0007`
return f"{_id:04}"