Implemented lazy loading

This commit is contained in:
2026-01-11 15:49:20 +01:00
parent a9eb23ad76
commit 5d6c02001e
8 changed files with 151 additions and 116 deletions

View File

@@ -9,74 +9,84 @@ from functools import lru_cache
from fasthtml.common import NotStr
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)
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()
"""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()
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)
"""Optimized Div element."""
def __init__(self, *args, **kwargs):
super().__init__("div", *args, **kwargs)