Coverage for fastblocks / adapters / templates / _async_filters.py: 58%
130 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-02 20:00 -0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-02 20:00 -0800
1"""Async versions of Jinja2 custom filters for FastBlocks adapter integration."""
3from typing import Any
5# Oneiric imports
6from oneiric.core.resolution import Resolver
8# Oneiric resolver for dependency injection
9depends = Resolver()
12async def async_image_url(image_id: str, **transformations: Any) -> str:
13 """Generate image URL with transformations using configured image adapter (async).
15 Usage in templates:
16 [[ await async_image_url('product.jpg', width=300, height=200, crop='fill') ]]
17 """
18 try:
19 images = await depends.resolve("fastblocks", "images")
20 except Exception:
21 images = None
23 if images and hasattr(images, "get_image_url"):
24 result = await images.get_image_url(image_id, **transformations)
25 return str(result) if result is not None else image_id
27 # Fallback to basic URL
28 return image_id
31async def async_font_import() -> str:
32 """Generate font import statements using configured font adapter (async).
34 Usage in templates:
35 [% block head %]
36 [[ await async_font_import() ]]
37 [% endblock %]
38 """
39 try:
40 fonts = await depends.resolve("fastblocks", "fonts")
41 except Exception:
42 fonts = None
44 if fonts and hasattr(fonts, "get_font_import"):
45 result = await fonts.get_font_import()
46 return str(result) if result is not None else ""
48 # Fallback - no custom fonts
49 return ""
52def _build_img_attributes(
53 image_url: str, alt: str, attributes: dict[str, Any]
54) -> list[str]:
55 """Build image tag attributes."""
56 attr_parts = [f'src="{image_url}"', f'alt="{alt}"']
57 for key, value in attributes.items():
58 # Handle class_ as alias for class to avoid Python keyword conflict
59 attr_name = "class" if key == "class_" else key
60 if key in (
61 "width",
62 "height",
63 "class",
64 "class_",
65 "id",
66 "style",
67 "loading",
68 "decoding",
69 ):
70 attr_parts.append(f'{attr_name}="{value}"')
71 return attr_parts
74async def async_image_with_transformations(
75 image_id: str,
76 alt: str,
77 transformations: dict[str, Any] | None = None,
78 **attributes: Any,
79) -> str:
80 """Generate image tag with on-demand transformations (async).
82 Usage in templates:
83 [[ await async_image_with_transformations('hero.jpg', 'Hero Image',
84 {'width': 1200, 'quality': 80},
85 class='hero-img') ]]
86 """
87 try:
88 images = await depends.resolve("fastblocks", "images")
89 except Exception:
90 images = None
92 if images:
93 # Get transformed URL first
94 transform_params = transformations or {}
95 image_url = await images.get_image_url(image_id, **transform_params)
97 # Build img tag with transformed URL
98 attr_parts = _build_img_attributes(image_url, alt, attributes)
99 return f"<img {' '.join(attr_parts)}>"
101 # Fallback to basic img tag
102 attr_parts = _build_img_attributes(image_id, alt, attributes)
103 return f"<img {' '.join(attr_parts)}>"
106async def async_responsive_image(
107 image_id: str, alt: str, sizes: dict[str, dict[str, Any]], **attributes: Any
108) -> str:
109 """Generate responsive image with multiple sizes using image adapter (async).
111 Usage in templates:
112 [[ await async_responsive_image('article.jpg', 'Article Image', {
113 'mobile': {'width': 400, 'quality': 75},
114 'tablet': {'width': 800, 'quality': 80},
115 'desktop': {'width': 1200, 'quality': 85}
116 }) ]]
117 """
118 try:
119 images = await depends.resolve("fastblocks", "images")
120 except Exception:
121 images = None
123 if not images:
124 # Fallback to basic img tag
125 return f'<img src="{image_id}" alt="{alt}">'
127 # Generate srcset with different sizes
128 srcset_parts = []
129 src_url = image_id # Default fallback
131 for size_params in sizes.values():
132 width = size_params.get("width", 400)
133 size_url = await images.get_image_url(image_id, **size_params)
134 srcset_parts.append(f"{size_url} {width}w")
136 # Use the largest size as default src
137 if width > 400: # Default to largest size for src
138 src_url = size_url
140 # Build img tag with srcset
141 attr_parts = [
142 f'src="{src_url}"',
143 f'alt="{alt}"',
144 f'srcset="{", ".join(srcset_parts)}"',
145 ]
147 # Add sizes attribute if not provided
148 if "sizes" not in attributes:
149 # Default responsive sizes
150 attr_parts.append(
151 'sizes="(max-width: 480px) 400px, (max-width: 768px) 800px, 1200px"'
152 )
154 for key, value in attributes.items():
155 # Handle class_ as alias for class to avoid Python keyword conflict
156 attr_name = "class" if key == "class_" else key
157 if key in (
158 "width",
159 "height",
160 "class",
161 "class_",
162 "id",
163 "style",
164 "loading",
165 "decoding",
166 "sizes",
167 ):
168 attr_parts.append(f'{attr_name}="{value}"')
170 return f"<img {' '.join(attr_parts)}>"
173async def async_optimized_font_stack() -> str:
174 """Generate optimized font stack with preload and fallback support (async).
176 Usage in templates:
177 [% block head %]
178 [[ await async_optimized_font_stack() ]]
179 [% endblock %]
180 """
181 try:
182 fonts = await depends.resolve("fastblocks", "fonts")
183 except Exception:
184 fonts = None
186 if not fonts:
187 return ""
189 font_html_parts = []
191 # Get font imports
192 if hasattr(fonts, "get_font_import"):
193 font_imports = await fonts.get_font_import()
194 if font_imports:
195 font_html_parts.append(font_imports)
197 # Get preload links for critical fonts
198 if hasattr(fonts, "get_preload_links"):
199 preload_links = fonts.get_preload_links()
200 if preload_links:
201 font_html_parts.append(preload_links)
203 # Get CSS variables if available
204 if hasattr(fonts, "get_css_variables"):
205 css_vars = fonts.get_css_variables()
206 if css_vars:
207 font_html_parts.append(f"<style>\n{css_vars}\n</style>")
209 return "\n".join(font_html_parts)
212async def async_critical_css_fonts(critical_fonts: list[str] | None = None) -> str:
213 """Generate critical font CSS for above-the-fold content (async).
215 Usage in templates:
216 [% block head %]
217 [[ await async_critical_css_fonts(['Inter', 'Roboto']) ]]
218 [% endblock %]
219 """
220 try:
221 fonts = await depends.resolve("fastblocks", "fonts")
222 except Exception:
223 fonts = None
225 if not fonts:
226 return ""
228 # If the adapter supports optimized imports with critical font prioritization
229 if hasattr(fonts, "get_optimized_import"):
230 result = await fonts.get_optimized_import(critical_fonts)
231 return str(result) if result is not None else ""
233 # Fallback to regular import
234 if hasattr(fonts, "get_font_import"):
235 result = await fonts.get_font_import()
236 return str(result) if result is not None else ""
238 return ""
241async def async_image_placeholder(
242 width: int,
243 height: int,
244 text: str = "",
245 bg_color: str = "#f0f0f0",
246 text_color: str = "#666666",
247) -> str:
248 """Generate placeholder image URL for loading states (async).
250 Usage in templates:
251 [[ await async_image_placeholder(400, 300, 'Loading...') ]]
252 """
253 try:
254 images = await depends.resolve("fastblocks", "images")
255 except Exception:
256 images = None
258 # If the image adapter supports placeholder generation
259 if images and hasattr(images, "get_placeholder_url"):
260 result = await images.get_placeholder_url(
261 width=width,
262 height=height,
263 text=text,
264 bg_color=bg_color,
265 text_color=text_color,
266 )
267 return (
268 str(result)
269 if result is not None
270 else f"https://via.placeholder.com/{width}x{height}"
271 )
273 # Fallback to data URL or placeholder service
274 if text:
275 placeholder_text = text.replace(" ", "%20")
276 return f"https://via.placeholder.com/{width}x{height}/{bg_color.lstrip('#')}/{text_color.lstrip('#')}?text={placeholder_text}"
278 return f"https://via.placeholder.com/{width}x{height}/{bg_color.lstrip('#')}"
281async def async_lazy_image(
282 image_id: str, alt: str, placeholder_url: str | None = None, **attributes: Any
283) -> str:
284 """Generate lazy-loading image with proper placeholder (async).
286 Usage in templates:
287 [[ await async_lazy_image('hero.jpg', 'Hero Image', loading='lazy') ]]
288 """
289 try:
290 images = await depends.resolve("fastblocks", "images")
291 except Exception:
292 images = None
294 # Get the actual image URL
295 if images and hasattr(images, "get_image_url"):
296 result = await images.get_image_url(image_id, **attributes)
297 actual_url = str(result) if result is not None else image_id
298 else:
299 actual_url = image_id
301 # Generate placeholder if not provided
302 if not placeholder_url:
303 placeholder_url = await async_image_placeholder(
304 width=attributes.get("width", 400),
305 height=attributes.get("height", 300),
306 text="Loading...",
307 )
309 # Build lazy-loading img tag
310 attr_parts = [
311 f'src="{placeholder_url}"',
312 f'data-src="{actual_url}"',
313 f'alt="{alt}"',
314 'loading="lazy"',
315 ]
317 for key, value in attributes.items():
318 if key not in ("width", "height") and key in (
319 "class",
320 "id",
321 "style",
322 "decoding",
323 ):
324 attr_parts.append(f'{key}="{value}"')
325 elif key in ("width", "height"):
326 attr_parts.append(f'{key}="{value}"')
328 return f"<img {' '.join(attr_parts)}>"
331# Async filter registration mapping
332FASTBLOCKS_ASYNC_FILTERS = {
333 "async_image_url": async_image_url,
334 "async_font_import": async_font_import,
335 "async_image_with_transformations": async_image_with_transformations,
336 "async_responsive_image": async_responsive_image,
337 "async_optimized_font_stack": async_optimized_font_stack,
338 "async_critical_css_fonts": async_critical_css_fonts,
339 "async_image_placeholder": async_image_placeholder,
340 "async_lazy_image": async_lazy_image,
341}
343# Migration indicator
344_using_oneiric = True