Coverage for fastblocks / adapters / templates / _enhanced_filters.py: 15%

237 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-01-02 20:00 -0800

1"""Enhanced Template Filters for Secondary Adapters Integration. 

2 

3This module provides comprehensive template filters for all FastBlocks secondary adapters: 

4- Cloudflare Images integration with transformations 

5- TwicPics integration with smart cropping 

6- WebAwesome icon integration 

7- Kelp component integration 

8- Phosphor, Heroicons, Remix, Material Icons support 

9- Font loading and optimization 

10- Advanced HTMX integrations 

11 

12Requirements: 

13- All secondary adapter packages as available 

14 

15Author: lesleslie <les@wedgwoodwebworks.com> 

16Created: 2025-01-12 

17""" 

18 

19import typing as t 

20from contextlib import suppress 

21from uuid import UUID 

22 

23# Oneiric imports 

24from oneiric.core.resolution import Resolver 

25 

26 

27# Custom implementations for ACB compatibility 

28class AdapterStatus: 

29 """Custom AdapterStatus for Oneiric compatibility.""" 

30 

31 STABLE = "STABLE" 

32 BETA = "BETA" 

33 ALPHA = "ALPHA" 

34 EXPERIMENTAL = "EXPERIMENTAL" 

35 

36 

37# Oneiric resolver for dependency injection 

38depends = Resolver() 

39 

40 

41# Cloudflare Images Filters 

42def cf_image_url(image_id: str, **transformations: t.Any) -> str: 

43 """Generate Cloudflare Images URL with transformations. 

44 

45 Usage in templates: 

46 [[ cf_image_url('hero.jpg', width=800, quality=85, format='webp') ]] 

47 """ 

48 with suppress(Exception): # Fallback 

49 cloudflare = depends.get_sync("cloudflare_images") 

50 if cloudflare: 

51 result = cloudflare.get_image_url(image_id, **transformations) 

52 return str(result) if result is not None else image_id 

53 

54 return image_id 

55 

56 

57def _build_cf_srcset( 

58 cloudflare: t.Any, image_id: str, sizes: dict[str, dict[str, t.Any]] 

59) -> tuple[list[str], str]: 

60 """Build Cloudflare Images srcset and determine default src URL. 

61 

62 Args: 

63 cloudflare: Cloudflare adapter instance 

64 image_id: Image identifier 

65 sizes: Size configurations 

66 

67 Returns: 

68 Tuple of (srcset_parts, default_src_url) 

69 """ 

70 srcset_parts = [] 

71 src_url = image_id 

72 

73 for size_params in sizes.values(): 

74 width = size_params.get("width", 400) 

75 size_url = cloudflare.get_image_url(image_id, **size_params) 

76 srcset_parts.append(f"{size_url} {width}w") 

77 

78 # Use largest as default src 

79 if width > 800: 

80 src_url = size_url 

81 

82 return srcset_parts, src_url 

83 

84 

85def _build_cf_img_attributes( 

86 src_url: str, 

87 alt: str, 

88 srcset_parts: list[str], 

89 attributes: dict[str, t.Any], 

90) -> list[str]: 

91 """Build HTML image attributes for Cloudflare Images. 

92 

93 Args: 

94 src_url: Source URL 

95 alt: Alt text 

96 srcset_parts: Srcset components 

97 attributes: Additional HTML attributes 

98 

99 Returns: 

100 List of formatted attribute strings 

101 """ 

102 attr_parts = [ 

103 f'src="{src_url}"', 

104 f'alt="{alt}"', 

105 f'srcset="{", ".join(srcset_parts)}"', 

106 ] 

107 

108 # Add default sizes if not provided 

109 if "sizes" not in attributes: 

110 attr_parts.append( 

111 'sizes="(max-width: 480px) 400px, (max-width: 768px) 800px, 1200px"' 

112 ) 

113 

114 for key, value in attributes.items(): 

115 if key in ("width", "height", "class", "id", "style", "loading", "sizes"): 

116 attr_parts.append(f'{key}="{value}"') 

117 

118 return attr_parts 

119 

120 

121def cf_responsive_image( 

122 image_id: str, alt: str, sizes: dict[str, dict[str, t.Any]], **attributes: t.Any 

123) -> str: 

124 """Generate responsive Cloudflare Images with srcset. 

125 

126 Usage in templates: 

127 [[ cf_responsive_image('hero.jpg', 'Hero Image', { 

128 'mobile': {'width': 400, 'quality': 75}, 

129 'tablet': {'width': 800, 'quality': 80}, 

130 'desktop': {'width': 1200, 'quality': 85} 

131 }) ]] 

132 """ 

133 try: 

134 cloudflare = depends.get_sync("cloudflare_images") 

135 if not cloudflare: 

136 return f'<img src="{image_id}" alt="{alt}">' 

137 

138 srcset_parts, src_url = _build_cf_srcset(cloudflare, image_id, sizes) 

139 attr_parts = _build_cf_img_attributes(src_url, alt, srcset_parts, attributes) 

140 

141 return f"<img {' '.join(attr_parts)}>" 

142 

143 except Exception: 

144 return f'<img src="{image_id}" alt="{alt}">' 

145 

146 

147# TwicPics Filters 

148def twicpics_image(image_id: str, **transformations: t.Any) -> str: 

149 """Generate TwicPics image URL with smart transformations. 

150 

151 Usage in templates: 

152 [[ twicpics_image('product.jpg', resize='400x300', focus='auto') ]] 

153 """ 

154 with suppress(Exception): 

155 twicpics = depends.get_sync("twicpics") 

156 if twicpics: 

157 result = twicpics.get_image_url(image_id, **transformations) 

158 return str(result) if result is not None else image_id 

159 

160 return image_id 

161 

162 

163def _separate_image_attributes( 

164 transform_params: dict[str, t.Any], 

165) -> tuple[dict[str, t.Any], dict[str, t.Any]]: 

166 """Separate image attributes from transformation parameters.""" 

167 img_attrs = {} 

168 transform_only = {} 

169 

170 for key, value in transform_params.items(): 

171 if key in ("class", "id", "style", "loading", "alt"): 

172 img_attrs[key] = value 

173 else: 

174 transform_only[key] = value 

175 

176 return img_attrs, transform_only 

177 

178 

179def twicpics_smart_crop( 

180 image_id: str, width: int, height: int, focus: str = "auto", **attributes: t.Any 

181) -> str: 

182 """Generate TwicPics image with smart cropping. 

183 

184 Usage in templates: 

185 [[ twicpics_smart_crop('landscape.jpg', 400, 300, 'face', class='hero-img') ]] 

186 """ 

187 with suppress(Exception): 

188 twicpics = depends.get_sync("twicpics") 

189 if twicpics: 

190 transform_params = { 

191 "resize": f"{width}x{height}", 

192 "focus": focus, 

193 } | attributes 

194 

195 # Extract img attributes from transform params 

196 img_attrs, transform_only = _separate_image_attributes(transform_params) 

197 

198 image_url = twicpics.get_image_url(image_id, **transform_only) 

199 

200 attr_parts = [f'src="{image_url}"'] 

201 if "alt" not in img_attrs: 

202 attr_parts.append(f'alt="{image_id}"') 

203 

204 for key, value in img_attrs.items(): 

205 attr_parts.append(f'{key}="{value}"') 

206 

207 return f"<img {' '.join(attr_parts)}>" 

208 

209 return f'<img src="{image_id}" alt="{image_id}" width="{width}" height="{height}">' 

210 

211 

212# WebAwesome Icon Filters 

213def wa_icon(icon_name: str, **attributes: t.Any) -> str: 

214 """Generate WebAwesome icon. 

215 

216 Usage in templates: 

217 [[ wa_icon('home', size='24', class='nav-icon') ]] 

218 """ 

219 with suppress(Exception): # Fallback 

220 webawesome = depends.get_sync("webawesome") 

221 if webawesome: 

222 result = webawesome.get_icon_tag(icon_name, **attributes) 

223 return str(result) if result is not None else f"[{icon_name}]" 

224 

225 css_class = attributes.get("class", "") 

226 size = attributes.get("size", "16") 

227 return f'<i class="wa wa-{icon_name} {css_class}" style="font-size: {size}px;"></i>' 

228 

229 

230def wa_icon_with_text( 

231 icon_name: str, text: str, position: str = "left", **attributes: t.Any 

232) -> str: 

233 """Generate WebAwesome icon with text. 

234 

235 Usage in templates: 

236 [[ wa_icon_with_text('save', 'Save Changes', 'left', class='btn-icon') ]] 

237 """ 

238 with suppress(Exception): # Fallback 

239 webawesome = depends.get_sync("webawesome") 

240 if webawesome and hasattr(webawesome, "get_icon_with_text"): 

241 result = webawesome.get_icon_with_text( 

242 icon_name, text, position, **attributes 

243 ) 

244 return ( 

245 str(result) 

246 if result is not None 

247 else f"{wa_icon(icon_name, **attributes)} {text}" 

248 ) 

249 

250 icon = wa_icon(icon_name, **attributes) 

251 if position == "right": 

252 return f"{text} {icon}" 

253 

254 return f"{icon} {text}" 

255 

256 

257# Kelp Component Filters 

258def kelp_component(component_type: str, content: str = "", **attributes: t.Any) -> str: 

259 """Generate Kelp component. 

260 

261 Usage in templates: 

262 [[ kelp_component('button', 'Click Me', variant='primary', size='large') ]] 

263 """ 

264 with suppress(Exception): # Fallback 

265 kelp = depends.get_sync("kelp") 

266 if kelp: 

267 result = kelp.build_component(component_type, content, **attributes) 

268 return ( 

269 str(result) 

270 if result is not None 

271 else f'<div class="kelp-{component_type}">{content}</div>' 

272 ) 

273 

274 css_class = f"kelp-{component_type}" 

275 variant = attributes.get("variant", "") 

276 size = attributes.get("size", "") 

277 

278 if variant: 

279 css_class += f" kelp-{component_type}--{variant}" 

280 if size: 

281 css_class += f" kelp-{component_type}--{size}" 

282 

283 if "class" in attributes: 

284 css_class += f" {attributes['class']}" 

285 

286 if component_type == "button": 

287 return f'<button class="{css_class}">{content}</button>' 

288 

289 return f'<div class="{css_class}">{content}</div>' 

290 

291 

292def kelp_card(title: str = "", content: str = "", **attributes: t.Any) -> str: 

293 """Generate Kelp card component. 

294 

295 Usage in templates: 

296 [[ kelp_card('Card Title', '<p>Card content here</p>', variant='elevated') ]] 

297 """ 

298 with suppress(Exception): 

299 kelp = depends.get_sync("kelp") 

300 if kelp and hasattr(kelp, "build_card"): 

301 result = kelp.build_card(title, content, **attributes) 

302 return ( 

303 str(result) 

304 if result is not None 

305 else _build_fallback_card(title, content, **attributes) 

306 ) 

307 

308 return _build_fallback_card(title, content, **attributes) 

309 

310 

311def _build_fallback_card(title: str, content: str, **attributes: t.Any) -> str: 

312 """Build fallback card HTML.""" 

313 css_class = "kelp-card" 

314 variant = attributes.get("variant", "") 

315 

316 if variant: 

317 css_class += f" kelp-card--{variant}" 

318 if "class" in attributes: 

319 css_class += f" {attributes['class']}" 

320 

321 card_html = [f'<div class="{css_class}">'] 

322 

323 if title: 

324 card_html.append( 

325 f'<div class="kelp-card__header"><h3 class="kelp-card__title">{title}</h3></div>' 

326 ) 

327 

328 if content: 

329 card_html.extend((f'<div class="kelp-card__content">{content}</div>', "</div>")) 

330 

331 return "".join(card_html) 

332 

333 

334# Phosphor Icons Filters 

335def phosphor_icon(icon_name: str, weight: str = "regular", **attributes: t.Any) -> str: 

336 """Generate Phosphor icon. 

337 

338 Usage in templates: 

339 [[ phosphor_icon('house', 'bold', size='24', class='nav-icon') ]] 

340 """ 

341 with suppress(Exception): # Fallback 

342 phosphor = depends.get_sync("phosphor") 

343 if phosphor: 

344 result = phosphor.get_icon_tag(icon_name, weight=weight, **attributes) 

345 return str(result) if result is not None else f"[{icon_name}]" 

346 

347 css_class = f"ph ph-{icon_name}" 

348 if weight != "regular": 

349 css_class += f" ph-{weight}" 

350 

351 if "class" in attributes: 

352 css_class += f" {attributes['class']}" 

353 

354 size = attributes.get("size", "16") 

355 return f'<i class="{css_class}" style="font-size: {size}px;"></i>' 

356 

357 

358# Heroicons Filters 

359def heroicon(icon_name: str, style: str = "outline", **attributes: t.Any) -> str: 

360 """Generate Heroicon. 

361 

362 Usage in templates: 

363 [[ heroicon('home', 'solid', size='24', class='nav-icon') ]] 

364 """ 

365 with suppress(Exception): # Fallback SVG approach 

366 heroicons = depends.get_sync("heroicons") 

367 if heroicons: 

368 result = heroicons.get_icon_tag(icon_name, style=style, **attributes) 

369 return str(result) if result is not None else f"[{icon_name}]" 

370 

371 css_class = attributes.get("class", "") 

372 size = attributes.get("size", "24") 

373 

374 return f'''<svg class="heroicon heroicon-{icon_name} {css_class}" 

375 width="{size}" height="{size}" 

376 fill="{style == "solid" and "currentColor" or "none"}" 

377 stroke="currentColor" stroke-width="1.5"> 

378 <use href="#heroicon-{icon_name}-{style}"></use> 

379 </svg>''' 

380 

381 

382# Remix Icons Filters 

383def remix_icon(icon_name: str, **attributes: t.Any) -> str: 

384 """Generate Remix icon. 

385 

386 Usage in templates: 

387 [[ remix_icon('home-line', size='24', class='nav-icon') ]] 

388 """ 

389 with suppress(Exception): # Fallback 

390 remix = depends.get_sync("remix_icons") 

391 if remix: 

392 result = remix.get_icon_tag(icon_name, **attributes) 

393 return str(result) if result is not None else f"[{icon_name}]" 

394 

395 css_class = f"ri-{icon_name}" 

396 if "class" in attributes: 

397 css_class += f" {attributes['class']}" 

398 

399 size = attributes.get("size", "16") 

400 return f'<i class="{css_class}" style="font-size: {size}px;"></i>' 

401 

402 

403# Material Icons Filters 

404def material_icon(icon_name: str, variant: str = "filled", **attributes: t.Any) -> str: 

405 """Generate Material Design icon. 

406 

407 Usage in templates: 

408 [[ material_icon('home', 'outlined', size='24', class='nav-icon') ]] 

409 """ 

410 with suppress(Exception): # Fallback 

411 material = depends.get_sync("material_icons") 

412 if material: 

413 result = material.get_icon_tag(icon_name, variant=variant, **attributes) 

414 return str(result) if result is not None else f"[{icon_name}]" 

415 

416 css_class = "material-icons" 

417 if variant != "filled": 

418 css_class += f"-{variant}" 

419 

420 if "class" in attributes: 

421 css_class += f" {attributes['class']}" 

422 

423 size = attributes.get("size", "24") 

424 return f'<span class="{css_class}" style="font-size: {size}px;">{icon_name}</span>' 

425 

426 

427# Advanced Font Filters 

428async def async_optimized_font_loading(fonts: list[str], critical: bool = True) -> str: 

429 """Generate optimized font loading with preload hints. 

430 

431 Usage in templates: 

432 [[ await async_optimized_font_loading(['Inter', 'Roboto Mono'], critical=True) ]] 

433 """ 

434 with suppress(Exception): # Fallback 

435 font_adapter = await depends.resolve("fastblocks", "fonts") 

436 if font_adapter and hasattr(font_adapter, "get_optimized_loading"): 

437 result = await font_adapter.get_optimized_loading(fonts, critical=critical) 

438 return str(result) if result is not None else "" 

439 

440 html_parts = [] 

441 for font in fonts: 

442 font_family = font.replace(" ", "+") 

443 if critical: 

444 html_parts.extend( 

445 ( 

446 f'<link rel="preload" href="https://fonts.googleapis.com/css2?family={font_family}&display=swap" as="style">', 

447 f'<link href="https://fonts.googleapis.com/css2?family={font_family}&display=swap" rel="stylesheet">', 

448 ) 

449 ) 

450 

451 return "\n".join(html_parts) 

452 

453 

454def font_face_declaration( 

455 font_name: str, font_files: dict[str, str], **attributes: t.Any 

456) -> str: 

457 """Generate @font-face CSS declaration. 

458 

459 Usage in templates: 

460 [[ font_face_declaration('CustomFont', { 

461 'woff2': '/fonts/custom.woff2', 

462 'woff': '/fonts/custom.woff' 

463 }, weight='400', style='normal') ]] 

464 """ 

465 with suppress(Exception): # Fallback 

466 font_adapter = depends.get_sync("fonts") 

467 if font_adapter and hasattr(font_adapter, "generate_font_face"): 

468 result = font_adapter.generate_font_face( 

469 font_name, font_files, **attributes 

470 ) 

471 return str(result) if result is not None else "" 

472 

473 src_parts = [] 

474 format_map = { 

475 "woff2": "woff2", 

476 "woff": "woff", 

477 "ttf": "truetype", 

478 "otf": "opentype", 

479 } 

480 

481 for ext, url in font_files.items(): 

482 format_name = format_map.get(ext, ext) 

483 src_parts.append(f'url("{url}") format("{format_name}")') 

484 

485 css_parts = [ 

486 "@font-face {", 

487 f' font-family: "{font_name}";', 

488 f" src: {', '.join(src_parts)};", 

489 ] 

490 

491 for key, value in attributes.items(): 

492 if key in ("weight", "style", "display", "stretch"): 

493 css_key = f"font-{key}" if key in ("weight", "style", "stretch") else key 

494 css_parts.extend((f" {css_key}: {value};", "}")) 

495 

496 return "\n".join(css_parts) 

497 

498 

499# Advanced HTMX Integration Filters 

500def htmx_progressive_enhancement( 

501 content: str, htmx_attrs: dict[str, str], fallback_action: str = "" 

502) -> str: 

503 """Create progressively enhanced element with HTMX. 

504 

505 Usage in templates: 

506 [[ htmx_progressive_enhancement('<button>Save</button>', { 

507 'hx-post': '/api/save', 

508 'hx-target': '#result' 

509 }, fallback_action='/save') ]] 

510 """ 

511 # Add fallback action if provided 

512 if fallback_action: 

513 if "<form" in content: 

514 content = content.replace( 

515 "<form", f'<form action="{fallback_action}" method="post"' 

516 ) 

517 elif "<button" in content and "onclick" not in content: 

518 content = content.replace( 

519 "<button", 

520 f"<button onclick=\"window.location.href='{fallback_action}'\"", 

521 ) 

522 

523 # Add HTMX attributes 

524 for attr_name, attr_value in htmx_attrs.items(): 

525 # Find the main element and add attributes 

526 if "<" in content: 

527 first_tag_end = content.find(">") 

528 if first_tag_end != -1: 

529 before_close = content[:first_tag_end] 

530 after_close = content[first_tag_end:] 

531 content = f'{before_close} {attr_name}="{attr_value}"{after_close}' 

532 

533 return content 

534 

535 

536def htmx_turbo_frame( 

537 frame_id: str, src: str = "", loading: str = "lazy", **attributes: t.Any 

538) -> str: 

539 """Create Turbo Frame-like behavior with HTMX. 

540 

541 Usage in templates: 

542 [[ htmx_turbo_frame('user-profile', '/users/123/profile', loading='eager') ]] 

543 """ 

544 attrs_list = [f'id="{frame_id}"'] 

545 

546 if src: 

547 attrs_list.extend( 

548 [ 

549 f'hx-get="{src}"', 

550 f'hx-trigger="{"load" if loading == "eager" else "revealed"}"', 

551 'hx-swap="innerHTML"', 

552 ] 

553 ) 

554 

555 for key, value in attributes.items(): 

556 if key.startswith("hx-") or key in ("class", "style"): 

557 attrs_list.append(f'{key}="{value}"') 

558 

559 attrs_str = " ".join(attrs_list) 

560 

561 placeholder = "Loading..." if loading == "eager" else "Click to load" 

562 return f"<div {attrs_str}>{placeholder}</div>" 

563 

564 

565def htmx_infinite_scroll_sentinel( 

566 next_url: str, container: str = "#content", threshold: str = "0px" 

567) -> str: 

568 """Create intersection observer sentinel for infinite scroll. 

569 

570 Usage in templates: 

571 [[ htmx_infinite_scroll_sentinel('/api/posts?page=2', '#posts', '100px') ]] 

572 """ 

573 return f'''<div hx-get="{next_url}" 

574 hx-trigger="revealed" 

575 hx-target="{container}" 

576 hx-swap="beforeend" 

577 style="height: 1px; margin-bottom: {threshold};"> 

578 </div>''' 

579 

580 

581# Filter registration mapping 

582ENHANCED_FILTERS = { 

583 # Cloudflare Images 

584 "cf_image_url": cf_image_url, 

585 "cf_responsive_image": cf_responsive_image, 

586 # TwicPics 

587 "twicpics_image": twicpics_image, 

588 "twicpics_smart_crop": twicpics_smart_crop, 

589 # WebAwesome 

590 "wa_icon": wa_icon, 

591 "wa_icon_with_text": wa_icon_with_text, 

592 # Kelp 

593 "kelp_component": kelp_component, 

594 "kelp_card": kelp_card, 

595 # Icon Libraries 

596 "phosphor_icon": phosphor_icon, 

597 "heroicon": heroicon, 

598 "remix_icon": remix_icon, 

599 "material_icon": material_icon, 

600 # Font Management 

601 "font_face_declaration": font_face_declaration, 

602 # HTMX Advanced 

603 "htmx_progressive_enhancement": htmx_progressive_enhancement, 

604 "htmx_turbo_frame": htmx_turbo_frame, 

605 "htmx_infinite_scroll_sentinel": htmx_infinite_scroll_sentinel, 

606} 

607 

608# Async filters 

609ENHANCED_ASYNC_FILTERS = { 

610 "async_optimized_font_loading": async_optimized_font_loading, 

611} 

612 

613 

614MODULE_ID = UUID("01937d8a-1234-7890-abcd-1234567890ab") 

615MODULE_STATUS = AdapterStatus.STABLE 

616 

617# Migration indicator 

618_using_oneiric = True