Optimized Datagrid.render()

This commit is contained in:
2026-01-10 22:54:02 +01:00
parent 47848bb2fd
commit a9eb23ad76
3 changed files with 319 additions and 52 deletions

View File

@@ -0,0 +1,82 @@
"""
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 fasthtml.common import NotStr
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)
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()
class OptimizedDiv(OptimizedFt):
"""Optimized Div element."""
def __init__(self, *args, **kwargs):
super().__init__("div", *args, **kwargs)