Coverage for fastblocks / adapters / templates / _filters.py: 80%

173 statements  

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

1"""Jinja2 custom filters for FastBlocks adapter integration.""" 

2 

3from typing import Any 

4 

5# Oneiric imports 

6from oneiric.core.resolution import Resolver 

7 

8# Oneiric resolver for dependency injection 

9depends = Resolver() 

10 

11 

12def img_tag(image_id: str, alt: str, **attributes: Any) -> str: 

13 """Generate image tag using configured image adapter. 

14 

15 Usage in templates: 

16 [[ img_tag('product.jpg', 'Product Image', width=300, class='responsive') ]] 

17 """ 

18 images = depends.get_sync("images") 

19 if images: 

20 result = images.get_img_tag(image_id, alt, **attributes) 

21 return ( 

22 str(result) if result is not None else f'<img src="{image_id}" alt="{alt}">' 

23 ) 

24 

25 # Fallback to basic img tag 

26 attr_parts = [f'src="{image_id}"', f'alt="{alt}"'] 

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

28 # Convert Python-style attribute names to HTML-style (e.g., class_ to class) 

29 html_key = key.rstrip("_") if key.endswith("_") else key 

30 if html_key in ("width", "height", "class", "id", "style"): 

31 attr_parts.append(f'{html_key}="{value}"') 

32 

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

34 

35 

36def image_url(image_id: str, **transformations: Any) -> str: 

37 """Generate image URL with transformations using configured image adapter. 

38 

39 Note: For full functionality with transformations, use async_image_url in async templates. 

40 

41 Usage in templates: 

42 [[ image_url('product.jpg', width=300, height=200, crop='fill') ]] 

43 [[ await async_image_url('product.jpg', width=300, height=200, crop='fill') ]] # async version 

44 """ 

45 images = depends.get_sync("images") 

46 if images and hasattr(images, "get_sync_image_url"): 

47 # Some adapters may provide sync methods for simple URLs 

48 result = images.get_sync_image_url(image_id, **transformations) 

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

50 elif images: 

51 # Return base URL with query parameters as fallback 

52 if transformations: 

53 params = "&".join([f"{k}={v}" for k, v in transformations.items()]) 

54 return f"{image_id}?{params}" 

55 return image_id 

56 

57 # Fallback to basic URL 

58 return image_id 

59 

60 

61def _get_base_component_class(styles: Any, component: str) -> str: 

62 """Get the base class for a component from styles adapter.""" 

63 base_class = styles.get_component_class(component) 

64 return str(base_class) if base_class is not None else component.replace("_", "-") 

65 

66 

67def _apply_utility_modifiers( 

68 base_class: str, styles: Any, modifiers: dict[str, Any] 

69) -> str: 

70 """Apply utility class modifiers to base class if supported.""" 

71 if not hasattr(styles, "get_utility_classes"): 

72 return base_class 

73 

74 utilities = styles.get_utility_classes() 

75 if not utilities: 

76 return base_class 

77 

78 for modifier, value in modifiers.items(): 

79 utility_key = f"{modifier}_{value}" 

80 if utility_key in utilities: 

81 utility_class = utilities[utility_key] 

82 if utility_class: 

83 base_class = f"{base_class} {utility_class}" 

84 

85 return base_class 

86 

87 

88def style_class(component: str, **modifiers: Any) -> str: 

89 """Get style framework class for component. 

90 

91 Usage in templates: 

92 [[ style_class('button', variant='primary', size='large') ]] 

93 """ 

94 styles = depends.get_sync("styles") 

95 if not styles: 

96 # Fallback to semantic class name 

97 return component.replace("_", "-") 

98 

99 base_class = _get_base_component_class(styles, component) 

100 return _apply_utility_modifiers(base_class, styles, modifiers) 

101 

102 

103def icon_tag(icon_name: str, **attributes: Any) -> str: 

104 """Generate icon tag using configured icon adapter. 

105 

106 Usage in templates: 

107 [[ icon_tag('home', class='nav-icon', size='24') ]] 

108 """ 

109 icons = depends.get_sync("icons") 

110 if icons: 

111 result = icons.get_icon_tag(icon_name, **attributes) 

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

113 

114 # Fallback to text placeholder 

115 return f"[{icon_name}]" 

116 

117 

118def icon_with_text( 

119 icon_name: str, text: str, position: str = "left", **attributes: Any 

120) -> str: 

121 """Generate icon with text using configured icon adapter. 

122 

123 Usage in templates: 

124 [[ icon_with_text('save', 'Save Changes', position='left') ]] 

125 """ 

126 icons = depends.get_sync("icons") 

127 if icons and hasattr(icons, "get_icon_with_text"): 

128 result = icons.get_icon_with_text(icon_name, text, position, **attributes) 

129 return ( 

130 str(result) 

131 if result is not None 

132 else f"{icon_tag(icon_name, **attributes)} {text}" 

133 ) 

134 

135 # Fallback implementation 

136 icon = icon_tag(icon_name, **attributes) 

137 if position == "right": 

138 return f"{text} {icon}" 

139 

140 return f"{icon} {text}" 

141 

142 

143def font_import() -> str: 

144 """Generate font import statements using configured font adapter. 

145 

146 Note: For full functionality, use async_font_import in async templates. 

147 

148 Usage in templates: 

149 [% block head %] 

150 [[ font_import() ]] 

151 [[ await async_font_import() ]] # async version for full functionality 

152 [% endblock %] 

153 """ 

154 fonts = depends.get_sync("fonts") 

155 if fonts and hasattr(fonts, "get_sync_font_import"): 

156 # Some adapters may provide sync methods for basic imports 

157 result = fonts.get_sync_font_import() 

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

159 elif fonts: 

160 # Return basic stylesheet links if available 

161 if hasattr(fonts, "get_stylesheet_links"): 

162 links = fonts.get_stylesheet_links() 

163 return "\n".join(links) if links else "" 

164 

165 # Fallback - no custom fonts 

166 return "" 

167 

168 

169def font_family(font_type: str = "primary") -> str: 

170 """Get font family CSS value using configured font adapter. 

171 

172 Usage in templates: 

173 <style> 

174 body { font-family: [[ font_family('primary') ]]; } 

175 h1 { font-family: [[ font_family('heading') ]]; } 

176 </style> 

177 """ 

178 fonts = depends.get_sync("fonts") 

179 if fonts: 

180 result = fonts.get_font_family(font_type) 

181 return str(result) if result is not None else "inherit" 

182 

183 # Fallback fonts 

184 fallbacks = { 

185 "primary": "-apple-system, BlinkMacSystemFont, sans-serif", 

186 "secondary": "Georgia, serif", 

187 "heading": "-apple-system, BlinkMacSystemFont, sans-serif", 

188 "body": "-apple-system, BlinkMacSystemFont, sans-serif", 

189 "monospace": "'Courier New', monospace", 

190 } 

191 return fallbacks.get(font_type, "inherit") 

192 

193 

194def stylesheet_links() -> str: 

195 """Generate all stylesheet links for configured adapters. 

196 

197 Usage in templates: 

198 [% block head %] 

199 [[ stylesheet_links() ]] 

200 [% endblock %] 

201 """ 

202 links = [] 

203 

204 # Get style framework links 

205 styles = depends.get_sync("styles") 

206 if styles: 

207 links.extend(styles.get_stylesheet_links()) 

208 

209 # Get icon framework links 

210 icons = depends.get_sync("icons") 

211 if icons and hasattr(icons, "get_stylesheet_links"): 

212 links.extend(icons.get_stylesheet_links()) 

213 

214 return "\n".join(links) 

215 

216 

217def component_html(component: str, content: str = "", **attributes: Any) -> str: 

218 """Generate complete HTML component using style adapter. 

219 

220 Usage in templates: 

221 [[ component_html('button', 'Click Me', variant='primary', class='my-btn') ]] 

222 """ 

223 styles = depends.get_sync("styles") 

224 if styles and hasattr(styles, "build_component_html"): 

225 result = styles.build_component_html(component, content, **attributes) 

226 return ( 

227 str(result) 

228 if result is not None 

229 else f'<div class="{component}">{content}</div>' 

230 ) 

231 

232 # Fallback to basic HTML 

233 css_class = style_class(component) 

234 if "class" in attributes: 

235 css_class = f"{css_class} {attributes.pop('class')}" 

236 

237 attr_parts = [f'class="{css_class}"'] 

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

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

240 

241 attrs_str = " ".join(attr_parts) 

242 

243 if component.startswith("button"): 

244 return f"<button {attrs_str}>{content}</button>" 

245 

246 return f"<div {attrs_str}>{content}</div>" 

247 

248 

249def htmx_attrs(**htmx_attributes: Any) -> str: 

250 """Generate HTMX attributes for enhanced interactivity. 

251 

252 Usage in templates: 

253 <button [[ htmx_attrs(get='/api/data', target='#content', swap='innerHTML') ]]> 

254 Load Data 

255 </button> 

256 """ 

257 attr_parts = [] 

258 

259 # Map common HTMX attributes with enhanced support 

260 attr_mapping = { 

261 "get": "hx-get", 

262 "post": "hx-post", 

263 "put": "hx-put", 

264 "delete": "hx-delete", 

265 "patch": "hx-patch", 

266 "target": "hx-target", 

267 "swap": "hx-swap", 

268 "trigger": "hx-trigger", 

269 "indicator": "hx-indicator", 

270 "confirm": "hx-confirm", 

271 "vals": "hx-vals", 

272 "headers": "hx-headers", 

273 "include": "hx-include", 

274 "params": "hx-params", 

275 "boost": "hx-boost", 

276 "push_url": "hx-push-url", 

277 "replace_url": "hx-replace-url", 

278 "ext": "hx-ext", 

279 "select": "hx-select", 

280 "select_oob": "hx-select-oob", 

281 "sync": "hx-sync", 

282 "history": "hx-history", 

283 "disabled_elt": "hx-disabled-elt", 

284 "encoding": "hx-encoding", 

285 "preserve": "hx-preserve", 

286 } 

287 

288 for key, value in htmx_attributes.items(): 

289 htmx_attr = attr_mapping.get(key, f"hx-{key.replace('_', '-')}") 

290 attr_parts.append(f'{htmx_attr}="{value}"') 

291 

292 return " ".join(attr_parts) 

293 

294 

295def htmx_component(component_type: str, **attributes: Any) -> str: 

296 """Generate HTMX-enabled components with adapter integration. 

297 

298 Usage in templates: 

299 <div [[ htmx_component('card', get='/api/details/{id}', target='#details') ]]> 

300 [[ component_html('card-header', 'Title') ]] 

301 <div id="details"></div> 

302 </div> 

303 """ 

304 # Extract HTMX attributes 

305 htmx_attrs_dict = {} 

306 component_attrs = {} 

307 

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

309 if key in ( 

310 "get", 

311 "post", 

312 "put", 

313 "delete", 

314 "patch", 

315 "target", 

316 "swap", 

317 "trigger", 

318 "indicator", 

319 "confirm", 

320 "vals", 

321 "headers", 

322 "include", 

323 "params", 

324 "boost", 

325 "push_url", 

326 "replace_url", 

327 "ext", 

328 "select", 

329 "select_oob", 

330 "sync", 

331 "history", 

332 "disabled_elt", 

333 "encoding", 

334 "preserve", 

335 ): 

336 htmx_attrs_dict[key] = value 

337 else: 

338 component_attrs[key] = value 

339 

340 # Get component styling from style adapter 

341 css_class = style_class(component_type, **component_attrs) 

342 

343 # Add HTMX attributes if any 

344 htmx_str = htmx_attrs(**htmx_attrs_dict) if htmx_attrs_dict else "" 

345 

346 # Build complete attribute string 

347 attr_parts = [f'class="{css_class}"'] 

348 if htmx_str: 

349 attr_parts.append(htmx_str) 

350 

351 return " ".join(attr_parts) 

352 

353 

354def htmx_form(action: str, **attributes: Any) -> str: 

355 """Generate HTMX-enabled forms with validation and feedback. 

356 

357 Usage in templates: 

358 <form [[ htmx_form('/users/create', target='#form-container', 

359 validation_target='#form-errors') ]]> 

360 <!-- form fields --> 

361 </form> 

362 """ 

363 # Set default HTMX behavior for forms 

364 form_attrs = { 

365 "post": action, 

366 "swap": "outerHTML", 

367 "indicator": "#form-loading", 

368 } | attributes 

369 

370 # Handle validation target if specified 

371 if "validation_target" in form_attrs: 

372 validation_target = form_attrs.pop("validation_target") 

373 form_attrs["headers"] = f'{{"HX-Error-Target": "{validation_target}"}}' 

374 

375 return htmx_attrs(**form_attrs) 

376 

377 

378def htmx_lazy_load(url: str, placeholder: str = "Loading...", **attributes: Any) -> str: 

379 """Create lazy-loading containers with intersection observers. 

380 

381 Usage in templates: 

382 <div [[ htmx_lazy_load('/api/content', 'Loading content...', 

383 trigger='revealed once') ]]> 

384 </div> 

385 """ 

386 lazy_attrs = { 

387 "get": url, 

388 "trigger": "revealed once", 

389 "indicator": "this", 

390 } | attributes 

391 

392 attrs_str = htmx_attrs(**lazy_attrs) 

393 return f'{attrs_str} data-placeholder="{placeholder}"' 

394 

395 

396def htmx_infinite_scroll( 

397 next_url: str, container: str = "#infinite-container", **attributes: Any 

398) -> str: 

399 """Generate infinite scroll triggers. 

400 

401 Usage in templates: 

402 <div [[ htmx_infinite_scroll('/api/posts?page=2', '#posts-container') ]]> 

403 Loading more posts... 

404 </div> 

405 """ 

406 scroll_attrs = { 

407 "get": next_url, 

408 "trigger": "revealed", 

409 "target": container, 

410 "swap": "afterend", 

411 } | attributes 

412 

413 return htmx_attrs(**scroll_attrs) 

414 

415 

416def htmx_search(endpoint: str, debounce: int = 300, **attributes: Any) -> str: 

417 """Generate debounced search inputs. 

418 

419 Usage in templates: 

420 <input type="text" name="q" 

421 [[ htmx_search('/api/search', 500, target='#results') ]]> 

422 """ 

423 search_attrs = { 

424 "get": endpoint, 

425 "trigger": f"keyup changed delay:{debounce}ms", 

426 "target": "#search-results", 

427 "indicator": "#search-loading", 

428 } | attributes 

429 

430 return htmx_attrs(**search_attrs) 

431 

432 

433def htmx_modal(content_url: str, **attributes: Any) -> str: 

434 """Create modal dialog triggers. 

435 

436 Usage in templates: 

437 <button [[ htmx_modal('/modal/user/{id}', target='#modal-container') ]]> 

438 View Details 

439 </button> 

440 """ 

441 modal_attrs = { 

442 "get": content_url, 

443 "target": "#modal-container", 

444 "swap": "innerHTML", 

445 } | attributes 

446 

447 return htmx_attrs(**modal_attrs) 

448 

449 

450def htmx_img_swap( 

451 image_id: str, transformations: dict[str, Any] | None = None, **attributes: Any 

452) -> str: 

453 """Dynamic image swapping with transformations using image adapter. 

454 

455 Usage in templates: 

456 <img [[ htmx_img_swap('product.jpg', {'width': 300}, 

457 trigger='mouseenter once', target='this') ]]> 

458 """ 

459 images = depends.get_sync("images") 

460 if not images: 

461 return htmx_attrs(**attributes) 

462 

463 # Build transformation URL 

464 if transformations: 

465 # This would typically be handled by the image adapter 

466 transform_url = f"/api/images/{image_id}/transform" 

467 swap_attrs = { 

468 "get": transform_url, 

469 "vals": str(transformations), 

470 "target": "this", 

471 "swap": "outerHTML", 

472 } | attributes 

473 else: 

474 swap_attrs = { 

475 "get": f"/api/images/{image_id}", 

476 "target": "this", 

477 "swap": "outerHTML", 

478 } | attributes 

479 

480 return htmx_attrs(**swap_attrs) 

481 

482 

483def htmx_icon_toggle(icon_on: str, icon_off: str, **attributes: Any) -> str: 

484 """Icon state toggles for interactive elements. 

485 

486 Usage in templates: 

487 <button [[ htmx_icon_toggle('heart-filled', 'heart-outline', 

488 post='/favorites/toggle/{id}') ]]> 

489 [[ icon_tag('heart-outline') ]] 

490 </button> 

491 """ 

492 toggle_attrs = {"swap": "outerHTML", "target": "this"} | attributes 

493 

494 # Add data attributes for icon states 

495 attrs_str = htmx_attrs(**toggle_attrs) 

496 return f'{attrs_str} data-icon-on="{icon_on}" data-icon-off="{icon_off}"' 

497 

498 

499def htmx_ws_connect(endpoint: str, **attributes: Any) -> str: 

500 """Generate WebSocket connection attributes for real-time features. 

501 

502 Usage in templates: 

503 <div [[ htmx_ws_connect('/ws/notifications', 

504 listen='notification-received') ]]> 

505 </div> 

506 """ 

507 ws_attrs = {"ext": "ws"} | attributes 

508 

509 # Handle WebSocket-specific attributes 

510 if "listen" in ws_attrs: 

511 listen_event = ws_attrs.pop("listen") 

512 attrs_str = htmx_attrs(**ws_attrs) 

513 return f'{attrs_str} ws-connect="{endpoint}" sse-listen="{listen_event}"' 

514 else: 

515 attrs_str = htmx_attrs(**ws_attrs) 

516 return f'{attrs_str} ws-connect="{endpoint}"' 

517 

518 

519def htmx_validation_feedback(field_name: str, **attributes: Any) -> str: 

520 """Generate real-time validation feedback containers. 

521 

522 Usage in templates: 

523 <input name="email" 

524 [[ htmx_validation_feedback('email', 

525 validate_url='/validate/email') ]]> 

526 """ 

527 validate_url = attributes.pop("validate_url", f"/validate/{field_name}") 

528 

529 validation_attrs = { 

530 "get": validate_url, 

531 "trigger": "blur, keyup changed delay:500ms", 

532 "target": f"#{field_name}-feedback", 

533 "include": "this", 

534 } | attributes 

535 

536 return htmx_attrs(**validation_attrs) 

537 

538 

539def htmx_error_container(container_id: str = "htmx-errors") -> str: 

540 """Generate error display containers for HTMX responses. 

541 

542 Usage in templates: 

543 <div [[ htmx_error_container('form-errors') ]]></div> 

544 """ 

545 return f'id="{container_id}" class="htmx-error-container" role="alert"' 

546 

547 

548def htmx_retry_trigger(max_retries: int = 3, backoff: str = "exponential") -> str: 

549 """Generate retry mechanisms for failed HTMX requests. 

550 

551 Usage in templates: 

552 <div [[ htmx_retry_trigger(3, 'exponential') ]]> 

553 """ 

554 return f'data-max-retries="{max_retries}" data-backoff="{backoff}"' 

555 

556 

557# Filter registration mapping for template engines 

558FASTBLOCKS_FILTERS = { 

559 "img_tag": img_tag, 

560 "image_url": image_url, 

561 "style_class": style_class, 

562 "icon_tag": icon_tag, 

563 "icon_with_text": icon_with_text, 

564 "font_import": font_import, 

565 "font_family": font_family, 

566 "stylesheet_links": stylesheet_links, 

567 "component_html": component_html, 

568 "htmx_attrs": htmx_attrs, 

569 "htmx_component": htmx_component, 

570 "htmx_form": htmx_form, 

571 "htmx_lazy_load": htmx_lazy_load, 

572 "htmx_infinite_scroll": htmx_infinite_scroll, 

573 "htmx_search": htmx_search, 

574 "htmx_modal": htmx_modal, 

575 "htmx_img_swap": htmx_img_swap, 

576 "htmx_icon_toggle": htmx_icon_toggle, 

577 "htmx_ws_connect": htmx_ws_connect, 

578 "htmx_validation_feedback": htmx_validation_feedback, 

579 "htmx_error_container": htmx_error_container, 

580 "htmx_retry_trigger": htmx_retry_trigger, 

581} 

582 

583# Migration indicator 

584_using_oneiric = True