pyx/proxy.py
2025-08-15 13:09:46 -04:00

78 lines
2.1 KiB
Python

from typing import List, Protocol, Tuple, Union
render_depth:int = 0
def MakeAttrs(css:str|Tuple[str, ...]|None, id:str|None, attributes: dict[str, str | None]|None) -> str:
if not attributes:
attributes = {}
if css:
attributes['class'] = " ".join(css) if isinstance(css, (list, tuple)) else css
if id:
attributes['id'] = id
attrList: List[str] = []
for key, value in attributes.items():
if value:
attrList.append(f'{key}="{value}"')
return " ".join(attrList)
class ComplexProxyLeaf(dict):
name:str = ""
attrs:str = ""
def __init__(self, name:str):
self.name = name
def props(self, css:str|Tuple[str, ...]|None, id:str|None, attributes: dict[str, str | None]|None):
clone = clone = self.__class__(self.name)
clone.attrs = MakeAttrs(css, id, attributes)
return clone
def __call__(self, css:str|None = None, id:str|None = None):
return self.props(css, id, {})
def __repr__(self) -> str:
return f'<{self.name} {self.attrs}/>'
class ComplexProxyBranch(ComplexProxyLeaf):
name:str = ""
attrs:str = ""
def __init__(self, name:str):
self.name = name
def __call__(self, css:str|None = None, id:str|None = None):
return self.props(css, id, None)
def __repr__(self) -> str:
return f'<{self.name} {self.attrs}></{self.name}>'
def __getitem__(self, key:Union[str, 'ComplexProxyBranch', ComplexProxyLeaf, Tuple[Union[str, 'ComplexProxyBranch', ComplexProxyLeaf], ...]]) -> str:
global render_depth
render_depth = render_depth + 1
if isinstance(key, tuple):
children = f'\n'.join(str(k) for k in key)
else:
children = key
render_depth = render_depth - 1
return f'<{self.name} {self.attrs}>\n{children}\n</{self.name}>'
IMG = ComplexProxyLeaf("img")
BR = ComplexProxyLeaf("br")
A = ComplexProxyBranch("a")
print(
A
[
"click here",
BR,
IMG(id="header.png"),
A(css="test"),
A["other?"],
A(css="www.site.com")
[
IMG(id="image.png")
]
]
)