97 lines
2.7 KiB
Python
97 lines
2.7 KiB
Python
"""
|
|
Optimized FastHTML-compatible elements that generate HTML directly.
|
|
|
|
These classes bypass FastHTML's overhead for performance-critical rendering
|
|
by generating HTML strings directly instead of creating full FastHTML objects.
|
|
"""
|
|
|
|
from functools import lru_cache
|
|
|
|
from fastcore.xml import FT
|
|
from fasthtml.common import NotStr
|
|
from fasthtml.components import Span
|
|
|
|
from myfasthtml.core.constants import NO_DEFAULT_VALUE
|
|
|
|
|
|
class OptimizedFt:
|
|
"""Lightweight FastHTML-compatible element that generates HTML directly."""
|
|
|
|
ATTR_MAP = {
|
|
"cls": "class",
|
|
"_id": "id",
|
|
}
|
|
|
|
def __init__(self, tag, *args, **kwargs):
|
|
self.tag = tag
|
|
self.children = args
|
|
self.attrs = {self.safe_attr(k): v for k, v in kwargs.items() if v is not None}
|
|
|
|
@staticmethod
|
|
@lru_cache(maxsize=128)
|
|
def safe_attr(attr_name):
|
|
"""Convert Python attribute names to HTML attribute names."""
|
|
attr_name = attr_name.replace("hx_", "hx-")
|
|
attr_name = attr_name.replace("data_", "data-")
|
|
return OptimizedFt.ATTR_MAP.get(attr_name, attr_name)
|
|
|
|
@staticmethod
|
|
def to_html_helper(item):
|
|
"""Convert any item to HTML string."""
|
|
if item is None:
|
|
return ""
|
|
elif isinstance(item, str):
|
|
return item
|
|
elif isinstance(item, (int, float, bool)):
|
|
return str(item)
|
|
elif isinstance(item, OptimizedFt):
|
|
return item.to_html()
|
|
elif isinstance(item, NotStr):
|
|
return str(item)
|
|
elif isinstance(item, FT):
|
|
return str(item)
|
|
else:
|
|
raise Exception(f"Unsupported type: {type(item)}, {item=}")
|
|
|
|
def to_html(self):
|
|
"""Generate HTML string."""
|
|
# Build attributes
|
|
attrs_list = []
|
|
for k, v in self.attrs.items():
|
|
if v is False:
|
|
continue # Skip False attributes
|
|
if v is True:
|
|
attrs_list.append(k) # Boolean attribute
|
|
else:
|
|
# No need to escape v since we control the values (width, IDs, etc.)
|
|
attrs_list.append(f'{k}="{v}"')
|
|
|
|
attrs_str = ' ' + ' '.join(attrs_list) if attrs_list else ''
|
|
|
|
# Build children HTML
|
|
children_html = ''.join(self.to_html_helper(child) for child in self.children)
|
|
|
|
return f'<{self.tag}{attrs_str}>{children_html}</{self.tag}>'
|
|
|
|
def __ft__(self):
|
|
"""FastHTML compatibility - returns NotStr to avoid double escaping."""
|
|
return NotStr(self.to_html())
|
|
|
|
def __str__(self):
|
|
return self.to_html()
|
|
|
|
def get(self, attr_name, default=NO_DEFAULT_VALUE):
|
|
try:
|
|
return self.attrs[self.safe_attr(attr_name)]
|
|
except KeyError:
|
|
if default is NO_DEFAULT_VALUE:
|
|
raise
|
|
return default
|
|
|
|
|
|
class OptimizedDiv(OptimizedFt):
|
|
"""Optimized Div element."""
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
super().__init__("div", *args, **kwargs)
|