Coverage for fastblocks / adapters / icons / phosphor.py: 24%

189 statements  

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

1"""Phosphor icons adapter for FastBlocks with multiple variants.""" 

2 

3from contextlib import suppress 

4from typing import Any 

5from uuid import UUID 

6 

7from oneiric.core.resolution import Resolver 

8 

9# Oneiric resolver for dependency injection 

10depends = Resolver() 

11 

12from ._base import IconsBase, IconsBaseSettings 

13 

14 

15class PhosphorIconsSettings(IconsBaseSettings): 

16 """Settings for Phosphor icons adapter.""" 

17 

18 # Required ACB 0.19.0+ metadata 

19 MODULE_ID: UUID = UUID("01937d86-9c7e-b18f-da0b-f9a0b1c2d3e4") # Static UUID7 

20 MODULE_STATUS: str = "stable" 

21 

22 # Phosphor configuration 

23 version: str = "2.0.8" 

24 cdn_url: str = "https://unpkg.com/@phosphor-icons/web" 

25 default_variant: str = "regular" # regular, thin, light, bold, fill, duotone 

26 default_size: str = "1em" 

27 

28 # Variant settings 

29 enabled_variants: list[str] = [ 

30 "regular", 

31 "thin", 

32 "light", 

33 "bold", 

34 "fill", 

35 "duotone", 

36 ] 

37 

38 # Icon mapping for common names 

39 icon_aliases: dict[str, str] = { 

40 "home": "house", 

41 "user": "user-circle", 

42 "settings": "gear", 

43 "search": "magnifying-glass", 

44 "menu": "list", 

45 "close": "x", 

46 "check": "check", 

47 "error": "warning-circle", 

48 "info": "info", 

49 "success": "check-circle", 

50 "warning": "warning", 

51 "edit": "pencil", 

52 "delete": "trash", 

53 "save": "floppy-disk", 

54 "download": "download", 

55 "upload": "upload", 

56 "email": "envelope", 

57 "phone": "phone", 

58 "location": "map-pin", 

59 "calendar": "calendar", 

60 "clock": "clock", 

61 "heart": "heart", 

62 "star": "star", 

63 "share": "share", 

64 "link": "link", 

65 "copy": "copy", 

66 "cut": "scissors", 

67 "paste": "clipboard", 

68 "undo": "arrow-counter-clockwise", 

69 "redo": "arrow-clockwise", 

70 "refresh": "arrow-clockwise", 

71 "logout": "sign-out", 

72 "login": "sign-in", 

73 } 

74 

75 

76class PhosphorIcons(IconsBase): 

77 """Phosphor icons adapter with multiple variants support.""" 

78 

79 # Required ACB 0.19.0+ metadata 

80 MODULE_ID: UUID = UUID("01937d86-9c7e-b18f-da0b-f9a0b1c2d3e4") # Static UUID7 

81 MODULE_STATUS: str = "stable" 

82 

83 def __init__(self) -> None: 

84 """Initialize Phosphor adapter.""" 

85 super().__init__() 

86 self.settings: PhosphorIconsSettings | None = None 

87 

88 # Register with Oneiric resolver (fail gracefully if not supported) 

89 with suppress(Exception): 

90 # Register with Oneiric resolver (fail gracefully if not supported) 

91 pass 

92 with suppress(Exception): 

93 depends.set(self) 

94 

95 def get_stylesheet_links(self) -> list[str]: 

96 """Get Phosphor icons stylesheet links.""" 

97 if not self.settings: 

98 self.settings = PhosphorIconsSettings() 

99 

100 links = [] 

101 

102 # Add CSS for each enabled variant 

103 for variant in self.settings.enabled_variants: 

104 css_url = ( 

105 f"{self.settings.cdn_url}@{self.settings.version}/{variant}/style.css" 

106 ) 

107 links.append(f'<link rel="stylesheet" href="{css_url}">') 

108 

109 # Add base Phosphor CSS if needed 

110 base_css = self._generate_phosphor_css() 

111 links.append(f"<style>{base_css}</style>") 

112 

113 return links 

114 

115 def _generate_phosphor_css(self) -> str: 

116 """Generate Phosphor-specific CSS.""" 

117 if not self.settings: 

118 self.settings = PhosphorIconsSettings() 

119 

120 return f""" 

121/* Phosphor Icons Base Styles */ 

122.ph {{ 

123 display: inline-block; 

124 font-style: normal; 

125 font-variant: normal; 

126 text-rendering: auto; 

127 line-height: 1; 

128 vertical-align: -0.125em; 

129 font-size: {self.settings.default_size}; 

130}} 

131 

132/* Size variants */ 

133.ph-xs {{ font-size: 0.75em; }} 

134.ph-sm {{ font-size: 0.875em; }} 

135.ph-lg {{ font-size: 1.125em; }} 

136.ph-xl {{ font-size: 1.25em; }} 

137.ph-2x {{ font-size: 2em; }} 

138.ph-3x {{ font-size: 3em; }} 

139.ph-4x {{ font-size: 4em; }} 

140.ph-5x {{ font-size: 5em; }} 

141 

142/* Rotation and transformation */ 

143.ph-rotate-90 {{ transform: rotate(90deg); }} 

144.ph-rotate-180 {{ transform: rotate(180deg); }} 

145.ph-rotate-270 {{ transform: rotate(270deg); }} 

146.ph-flip-horizontal {{ transform: scaleX(-1); }} 

147.ph-flip-vertical {{ transform: scaleY(-1); }} 

148 

149/* Animation support */ 

150.ph-spin {{ 

151 animation: ph-spin 2s linear infinite; 

152}} 

153 

154.ph-pulse {{ 

155 animation: ph-pulse 2s ease-in-out infinite alternate; 

156}} 

157 

158@keyframes ph-spin {{ 

159 0% {{ transform: rotate(0deg); }} 

160 100% {{ transform: rotate(360deg); }} 

161}} 

162 

163@keyframes ph-pulse {{ 

164 from {{ opacity: 1; }} 

165 to {{ opacity: 0.25; }} 

166}} 

167 

168/* Color utilities */ 

169.ph-primary {{ color: var(--primary-color, #007bff); }} 

170.ph-secondary {{ color: var(--secondary-color, #6c757d); }} 

171.ph-success {{ color: var(--success-color, #28a745); }} 

172.ph-warning {{ color: var(--warning-color, #ffc107); }} 

173.ph-danger {{ color: var(--danger-color, #dc3545); }} 

174.ph-info {{ color: var(--info-color, #17a2b8); }} 

175.ph-light {{ color: var(--light-color, #f8f9fa); }} 

176.ph-dark {{ color: var(--dark-color, #343a40); }} 

177.ph-muted {{ color: var(--muted-color, #6c757d); }} 

178 

179/* Interactive states */ 

180.ph-interactive {{ 

181 cursor: pointer; 

182 transition: all 0.2s ease; 

183}} 

184 

185.ph-interactive:hover {{ 

186 transform: scale(1.1); 

187 opacity: 0.8; 

188}} 

189 

190/* Alignment utilities */ 

191.ph-align-top {{ vertical-align: top; }} 

192.ph-align-middle {{ vertical-align: middle; }} 

193.ph-align-bottom {{ vertical-align: bottom; }} 

194.ph-align-baseline {{ vertical-align: baseline; }} 

195""" 

196 

197 def get_icon_class(self, icon_name: str, variant: str | None = None) -> str: 

198 """Get Phosphor icon class with variant support.""" 

199 if not self.settings: 

200 self.settings = PhosphorIconsSettings() 

201 

202 # Resolve icon aliases 

203 if icon_name in self.settings.icon_aliases: 

204 icon_name = self.settings.icon_aliases[icon_name] 

205 

206 # Use default variant if not specified 

207 if not variant: 

208 variant = self.settings.default_variant 

209 

210 # Validate variant 

211 if variant not in self.settings.enabled_variants: 

212 variant = self.settings.default_variant 

213 

214 # Build class name based on variant 

215 if variant == "regular": 

216 return f"ph ph-{icon_name}" 

217 

218 return f"ph-{variant} ph-{icon_name}" 

219 

220 def _apply_size_class( 

221 self, size: str | None, icon_class: str, attributes: dict[str, Any] 

222 ) -> str: 

223 """Apply size styling to icon class.""" 

224 if not size: 

225 return icon_class 

226 

227 if size in ("xs", "sm", "lg", "xl", "2x", "3x", "4x", "5x"): 

228 return f"{icon_class} ph-{size}" 

229 

230 # Custom size via style 

231 attributes["style"] = f"font-size: {size}; {attributes.get('style', '')}" 

232 return icon_class 

233 

234 def _apply_transformations( 

235 self, icon_class: str, attributes: dict[str, Any] 

236 ) -> str: 

237 """Apply rotation and flip transformations.""" 

238 if "rotate" in attributes: 

239 rotation = attributes.pop("rotate") 

240 icon_class += f" ph-rotate-{rotation}" 

241 

242 if "flip" in attributes: 

243 flip = attributes.pop("flip") 

244 if flip in ("horizontal", "vertical"): 

245 icon_class += f" ph-flip-{flip}" 

246 

247 return icon_class 

248 

249 def _apply_animations(self, icon_class: str, attributes: dict[str, Any]) -> str: 

250 """Apply animation classes.""" 

251 if "spin" in attributes and attributes.pop("spin"): 

252 icon_class += " ph-spin" 

253 

254 if "pulse" in attributes and attributes.pop("pulse"): 

255 icon_class += " ph-pulse" 

256 

257 return icon_class 

258 

259 def _apply_color_styling(self, icon_class: str, attributes: dict[str, Any]) -> str: 

260 """Apply color styling (semantic or custom).""" 

261 if "color" not in attributes: 

262 return icon_class 

263 

264 color = attributes.pop("color") 

265 semantic_colors = ( 

266 "primary", 

267 "secondary", 

268 "success", 

269 "warning", 

270 "danger", 

271 "info", 

272 "light", 

273 "dark", 

274 "muted", 

275 ) 

276 

277 if color in semantic_colors: 

278 return f"{icon_class} ph-{color}" 

279 

280 # Custom color via style 

281 attributes["style"] = f"color: {color}; {attributes.get('style', '')}" 

282 return icon_class 

283 

284 def _apply_interactive_and_alignment( 

285 self, icon_class: str, attributes: dict[str, Any] 

286 ) -> str: 

287 """Apply interactive and alignment classes.""" 

288 if "interactive" in attributes and attributes.pop("interactive"): 

289 icon_class += " ph-interactive" 

290 

291 if "align" in attributes: 

292 align = attributes.pop("align") 

293 if align in ("top", "middle", "bottom", "baseline"): 

294 icon_class += f" ph-align-{align}" 

295 

296 return icon_class 

297 

298 def get_icon_tag( 

299 self, 

300 icon_name: str, 

301 variant: str | None = None, 

302 size: str | None = None, 

303 **attributes: Any, 

304 ) -> str: 

305 """Generate Phosphor icon tag with full customization.""" 

306 icon_class = self.get_icon_class(icon_name, variant) 

307 

308 # Add custom classes first 

309 if "class" in attributes: 

310 icon_class += f" {attributes.pop('class')}" 

311 

312 # Apply all styling and features 

313 icon_class = self._apply_size_class(size, icon_class, attributes) 

314 icon_class = self._apply_transformations(icon_class, attributes) 

315 icon_class = self._apply_animations(icon_class, attributes) 

316 icon_class = self._apply_color_styling(icon_class, attributes) 

317 icon_class = self._apply_interactive_and_alignment(icon_class, attributes) 

318 

319 # Build final attributes 

320 attrs = {"class": icon_class} | attributes 

321 

322 # Add accessibility attributes 

323 if "aria-label" not in attrs and "title" not in attrs: 

324 attrs["aria-hidden"] = "true" 

325 

326 # Generate tag 

327 attr_string = " ".join(f'{k}="{v}"' for k, v in attrs.items()) 

328 return f"<i {attr_string}></i>" 

329 

330 def get_duotone_icon_tag( 

331 self, 

332 icon_name: str, 

333 primary_color: str | None = None, 

334 secondary_color: str | None = None, 

335 **attributes: Any, 

336 ) -> str: 

337 """Generate duotone Phosphor icon with custom colors.""" 

338 # Force duotone variant 

339 attributes["variant"] = "duotone" 

340 

341 # Handle duotone colors via CSS custom properties 

342 style = attributes.get("style", "") 

343 if primary_color: 

344 style += f" --ph-duotone-primary: {primary_color};" 

345 if secondary_color: 

346 style += f" --ph-duotone-secondary: {secondary_color};" 

347 

348 if style: 

349 attributes["style"] = style 

350 

351 return self.get_icon_tag(icon_name, **attributes) 

352 

353 def get_icon_sprite_tag( 

354 self, icon_name: str, variant: str | None = None, **attributes: Any 

355 ) -> str: 

356 """Generate SVG sprite-based icon tag (alternative approach).""" 

357 if not self.settings: 

358 self.settings = PhosphorIconsSettings() 

359 

360 if not variant: 

361 variant = self.settings.default_variant 

362 

363 # Resolve icon aliases 

364 if icon_name in self.settings.icon_aliases: 

365 icon_name = self.settings.icon_aliases[icon_name] 

366 

367 # Build SVG tag 

368 svg_class = f"ph ph-{icon_name}" 

369 if "class" in attributes: 

370 svg_class += f" {attributes.pop('class')}" 

371 

372 # Default attributes for SVG 

373 svg_attrs = { 

374 "class": svg_class, 

375 "width": attributes.pop("width", self.settings.default_size), 

376 "height": attributes.pop("height", self.settings.default_size), 

377 "fill": "currentColor", 

378 } | attributes 

379 

380 # Add accessibility 

381 if "aria-label" not in svg_attrs and "title" not in svg_attrs: 

382 svg_attrs["aria-hidden"] = "true" 

383 

384 attr_string = " ".join( 

385 f'{k}="{v}"' for k, v in svg_attrs.items() if v is not None 

386 ) 

387 

388 # Use symbol reference (assumes sprite is loaded) 

389 symbol_id = f"ph-{variant}-{icon_name}" 

390 return f'<svg {attr_string}><use href="#{symbol_id}"></use></svg>' 

391 

392 def get_available_icons(self) -> dict[str, list[str]]: 

393 """Get list of available icons by category.""" 

394 # This would typically come from the Phosphor icon registry 

395 # For now, return a sample of common categories 

396 return { 

397 "general": [ 

398 "house", 

399 "user-circle", 

400 "gear", 

401 "magnifying-glass", 

402 "list", 

403 "x", 

404 "check", 

405 "warning-circle", 

406 "info", 

407 "check-circle", 

408 ], 

409 "communication": [ 

410 "envelope", 

411 "phone", 

412 "chat-circle", 

413 "paper-plane-right", 

414 "bell", 

415 "speaker-high", 

416 "microphone", 

417 "video-camera", 

418 ], 

419 "media": [ 

420 "play", 

421 "pause", 

422 "stop", 

423 "skip-back", 

424 "skip-forward", 

425 "volume-high", 

426 "volume-low", 

427 "volume-x", 

428 "music-note", 

429 ], 

430 "navigation": [ 

431 "arrow-left", 

432 "arrow-right", 

433 "arrow-up", 

434 "arrow-down", 

435 "caret-left", 

436 "caret-right", 

437 "caret-up", 

438 "caret-down", 

439 ], 

440 "file": [ 

441 "file", 

442 "folder", 

443 "download", 

444 "upload", 

445 "floppy-disk", 

446 "file-text", 

447 "file-image", 

448 "file-video", 

449 "file-audio", 

450 ], 

451 "business": [ 

452 "briefcase", 

453 "calendar", 

454 "clock", 

455 "chart-line", 

456 "currency-dollar", 

457 "credit-card", 

458 "receipt", 

459 "invoice", 

460 ], 

461 "social": [ 

462 "heart", 

463 "star", 

464 "share", 

465 "thumbs-up", 

466 "thumbs-down", 

467 "bookmark", 

468 "flag", 

469 "gift", 

470 "trophy", 

471 ], 

472 } 

473 

474 

475# Template filter registration for FastBlocks 

476def _register_ph_basic_filters(env: Any) -> None: 

477 """Register basic Phosphor filters.""" 

478 

479 @env.filter("ph_icon") # type: ignore[misc] 

480 def ph_icon_filter( 

481 icon_name: str, 

482 variant: str = "regular", 

483 size: str | None = None, 

484 **attributes: Any, 

485 ) -> str: 

486 """Template filter for Phosphor icons.""" 

487 icons = depends.get_sync("icons") 

488 if isinstance(icons, PhosphorIcons): 

489 return icons.get_icon_tag(icon_name, variant, size, **attributes) 

490 return f"<!-- {icon_name} -->" 

491 

492 @env.filter("ph_class") # type: ignore[misc] 

493 def ph_class_filter(icon_name: str, variant: str = "regular") -> str: 

494 """Template filter for Phosphor icon classes.""" 

495 icons = depends.get_sync("icons") 

496 if isinstance(icons, PhosphorIcons): 

497 return icons.get_icon_class(icon_name, variant) 

498 return f"ph-{icon_name}" 

499 

500 @env.global_("phosphor_stylesheet_links") # type: ignore[misc] 

501 def phosphor_stylesheet_links() -> str: 

502 """Global function for Phosphor stylesheet links.""" 

503 icons = depends.get_sync("icons") 

504 if isinstance(icons, PhosphorIcons): 

505 return "\n".join(icons.get_stylesheet_links()) 

506 return "" 

507 

508 

509def _register_ph_duotone_functions(env: Any) -> None: 

510 """Register Phosphor duotone functions.""" 

511 

512 @env.global_("ph_duotone") # type: ignore[misc] 

513 def ph_duotone( 

514 icon_name: str, 

515 primary_color: str | None = None, 

516 secondary_color: str | None = None, 

517 **attributes: Any, 

518 ) -> str: 

519 """Generate duotone Phosphor icon.""" 

520 icons = depends.get_sync("icons") 

521 if isinstance(icons, PhosphorIcons): 

522 return icons.get_duotone_icon_tag( 

523 icon_name, primary_color, secondary_color, **attributes 

524 ) 

525 return f"<!-- {icon_name} duotone -->" 

526 

527 

528def _register_ph_interactive_functions(env: Any) -> None: 

529 """Register Phosphor interactive functions.""" 

530 

531 @env.global_("ph_interactive") # type: ignore[misc] 

532 def ph_interactive( 

533 icon_name: str, 

534 variant: str = "regular", 

535 action: str | None = None, 

536 **attributes: Any, 

537 ) -> str: 

538 """Generate interactive Phosphor icon with action.""" 

539 icons = depends.get_sync("icons") 

540 if not isinstance(icons, PhosphorIcons): 

541 return f"<!-- {icon_name} -->" 

542 

543 attributes["interactive"] = True 

544 if action: 

545 attributes["onclick"] = action 

546 attributes["style"] = f"cursor: pointer; {attributes.get('style', '')}" 

547 

548 return icons.get_icon_tag(icon_name, variant, **attributes) 

549 

550 @env.global_("ph_button_icon") # type: ignore[misc] 

551 def ph_button_icon( 

552 icon_name: str, 

553 text: str | None = None, 

554 variant: str = "regular", 

555 position: str = "left", 

556 **attributes: Any, 

557 ) -> str: 

558 """Generate button with Phosphor icon.""" 

559 icons = depends.get_sync("icons") 

560 if not isinstance(icons, PhosphorIcons): 

561 return f"<button>{text or icon_name}</button>" 

562 

563 icon_tag = icons.get_icon_tag(icon_name, variant, class_="ph-sm") 

564 

565 if text: 

566 content = ( 

567 f"{icon_tag} {text}" if position == "left" else f"{text} {icon_tag}" 

568 ) 

569 else: 

570 content = icon_tag 

571 

572 btn_class = attributes.pop("class", "btn") 

573 attr_string = " ".join( 

574 f'{k}="{v}"' for k, v in ({"class": btn_class} | attributes).items() 

575 ) 

576 return f"<button {attr_string}>{content}</button>" 

577 

578 

579def register_phosphor_filters(env: Any) -> None: 

580 """Register Phosphor filters for Jinja2 templates.""" 

581 _register_ph_basic_filters(env) 

582 _register_ph_duotone_functions(env) 

583 _register_ph_interactive_functions(env) 

584 

585 

586IconsSettings = PhosphorIconsSettings 

587Icons = PhosphorIcons 

588 

589# Register with Oneiric resolver (fail gracefully if not supported) 

590with suppress(Exception): 

591 depends.set(Icons, "phosphor") 

592 

593# ACB 0.19.0+ compatibility 

594__all__ = [ 

595 "PhosphorIcons", 

596 "PhosphorIconsSettings", 

597 "register_phosphor_filters", 

598 "Icons", 

599 "IconsSettings", 

600]