Coverage for fastblocks / adapters / icons / heroicons.py: 28%
159 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"""Heroicons adapter for FastBlocks with outline/solid variants."""
3from contextlib import suppress
4from typing import Any
5from uuid import UUID
7from oneiric.core.resolution import Resolver
9# Oneiric resolver for dependency injection
10depends = Resolver()
12from ._base import IconsBase, IconsBaseSettings
13from ._utils import (
14 add_accessibility_attributes,
15 build_attr_string,
16 process_animations,
17 process_semantic_colors,
18 process_state_attributes,
19 process_transformations,
20)
23class HeroiconsIconsSettings(IconsBaseSettings):
24 """Settings for Heroicons adapter."""
26 # Required ACB 0.19.0+ metadata
27 MODULE_ID: UUID = UUID("01937d86-ad8f-c29a-eb1c-0a1b2c3d4e5f") # Static UUID7
28 MODULE_STATUS: str = "stable"
30 # Heroicons configuration
31 version: str = "2.0.18"
32 cdn_url: str = "https://cdn.jsdelivr.net/npm/heroicons"
33 default_variant: str = "outline" # outline, solid, mini
34 default_size: str = "24" # 20 (mini), 24 (outline/solid)
36 # Variant settings
37 enabled_variants: list[str] = ["outline", "solid", "mini"]
39 # Icon mapping for common names and aliases
40 icon_aliases: dict[str, str] = {
41 "home": "home",
42 "user": "user",
43 "settings": "cog-6-tooth",
44 "search": "magnifying-glass",
45 "menu": "bars-3",
46 "close": "x-mark",
47 "check": "check",
48 "error": "exclamation-triangle",
49 "info": "information-circle",
50 "success": "check-circle",
51 "warning": "exclamation-triangle",
52 "edit": "pencil",
53 "delete": "trash",
54 "save": "document-arrow-down",
55 "download": "arrow-down-tray",
56 "upload": "arrow-up-tray",
57 "email": "envelope",
58 "phone": "phone",
59 "location": "map-pin",
60 "calendar": "calendar-days",
61 "clock": "clock",
62 "heart": "heart",
63 "star": "star",
64 "share": "share",
65 "link": "link",
66 "copy": "document-duplicate",
67 "cut": "scissors",
68 "paste": "clipboard",
69 "undo": "arrow-uturn-left",
70 "redo": "arrow-uturn-right",
71 "refresh": "arrow-path",
72 "logout": "arrow-right-on-rectangle",
73 "login": "arrow-left-on-rectangle",
74 "plus": "plus",
75 "minus": "minus",
76 "eye": "eye",
77 "eye-off": "eye-slash",
78 "lock": "lock-closed",
79 "unlock": "lock-open",
80 }
82 # Size presets
83 size_presets: dict[str, str] = {
84 "xs": "16",
85 "sm": "20",
86 "md": "24",
87 "lg": "28",
88 "xl": "32",
89 "2xl": "40",
90 "3xl": "48",
91 }
94class HeroiconsIcons(IconsBase):
95 """Heroicons adapter with outline/solid/mini variants."""
97 # Required ACB 0.19.0+ metadata
98 MODULE_ID: UUID = UUID("01937d86-ad8f-c29a-eb1c-0a1b2c3d4e5f") # Static UUID7
99 MODULE_STATUS: str = "stable"
101 def __init__(self) -> None:
102 """Initialize Heroicons adapter."""
103 super().__init__()
104 self.settings: HeroiconsIconsSettings | None = None
106 # Register with Oneiric resolver (fail gracefully if not supported)
107 with suppress(Exception):
108 # Register with Oneiric resolver (fail gracefully if not supported)
109 pass
110 with suppress(Exception):
111 depends.set(self)
113 def get_stylesheet_links(self) -> list[str]:
114 """Get Heroicons stylesheet links."""
115 if not self.settings:
116 self.settings = HeroiconsIconsSettings()
118 links = []
120 # Heroicons base CSS
121 heroicons_css = self._generate_heroicons_css()
122 links.append(f"<style>{heroicons_css}</style>")
124 return links
126 def _generate_heroicons_css(self) -> str:
127 """Generate Heroicons-specific CSS."""
128 if not self.settings:
129 self.settings = HeroiconsIconsSettings()
131 return f"""
132/* Heroicons Base Styles */
133.heroicon {{
134 display: inline-block;
135 vertical-align: -0.125em;
136 width: {self.settings.default_size}px;
137 height: {self.settings.default_size}px;
138 flex-shrink: 0;
139}}
141/* Size variants */
142.heroicon-xs {{ width: 16px; height: 16px; }}
143.heroicon-sm {{ width: 20px; height: 20px; }}
144.heroicon-md {{ width: 24px; height: 24px; }}
145.heroicon-lg {{ width: 28px; height: 28px; }}
146.heroicon-xl {{ width: 32px; height: 32px; }}
147.heroicon-2xl {{ width: 40px; height: 40px; }}
148.heroicon-3xl {{ width: 48px; height: 48px; }}
150/* Variant-specific styles */
151.heroicon-outline {{
152 stroke: currentColor;
153 fill: none;
154 stroke-width: 1.5;
155}}
157.heroicon-solid {{
158 fill: currentColor;
159}}
161.heroicon-mini {{
162 fill: currentColor;
163 width: 20px;
164 height: 20px;
165}}
167/* Rotation and transformation */
168.heroicon-rotate-90 {{ transform: rotate(90deg); }}
169.heroicon-rotate-180 {{ transform: rotate(180deg); }}
170.heroicon-rotate-270 {{ transform: rotate(270deg); }}
171.heroicon-flip-horizontal {{ transform: scaleX(-1); }}
172.heroicon-flip-vertical {{ transform: scaleY(-1); }}
174/* Animation support */
175.heroicon-spin {{
176 animation: heroicon-spin 2s linear infinite;
177}}
179.heroicon-pulse {{
180 animation: heroicon-pulse 2s ease-in-out infinite alternate;
181}}
183.heroicon-bounce {{
184 animation: heroicon-bounce 1s ease-in-out infinite;
185}}
187@keyframes heroicon-spin {{
188 0% {{ transform: rotate(0deg); }}
189 100% {{ transform: rotate(360deg); }}
190}}
192@keyframes heroicon-pulse {{
193 from {{ opacity: 1; }}
194 to {{ opacity: 0.25; }}
195}}
197@keyframes heroicon-bounce {{
198 0%, 100% {{ transform: translateY(0); }}
199 50% {{ transform: translateY(-25%); }}
200}}
202/* Color utilities */
203.heroicon-primary {{ color: var(--primary-color, #3b82f6); }}
204.heroicon-secondary {{ color: var(--secondary-color, #6b7280); }}
205.heroicon-success {{ color: var(--success-color, #10b981); }}
206.heroicon-warning {{ color: var(--warning-color, #f59e0b); }}
207.heroicon-danger {{ color: var(--danger-color, #ef4444); }}
208.heroicon-info {{ color: var(--info-color, #3b82f6); }}
209.heroicon-gray {{ color: var(--gray-color, #6b7280); }}
210.heroicon-white {{ color: white; }}
211.heroicon-black {{ color: black; }}
213/* Interactive states */
214.heroicon-interactive {{
215 cursor: pointer;
216 transition: all 0.2s ease;
217}}
219.heroicon-interactive:hover {{
220 transform: scale(1.1);
221 opacity: 0.8;
222}}
224.heroicon-interactive:active {{
225 transform: scale(0.95);
226}}
228/* States */
229.heroicon-disabled {{
230 opacity: 0.5;
231 cursor: not-allowed;
232}}
234.heroicon-loading {{
235 opacity: 0.6;
236}}
238/* Button integration */
239.btn .heroicon {{
240 margin-right: 0.5rem;
241}}
243.btn .heroicon:last-child {{
244 margin-right: 0;
245 margin-left: 0.5rem;
246}}
248.btn .heroicon:only-child {{
249 margin: 0;
250}}
252/* Badge integration */
253.badge .heroicon {{
254 width: 1em;
255 height: 1em;
256 margin-right: 0.25rem;
257}}
259/* Navigation integration */
260.nav-link .heroicon {{
261 width: 1.25rem;
262 height: 1.25rem;
263 margin-right: 0.5rem;
264}}
265"""
267 def get_icon_class(self, icon_name: str, variant: str | None = None) -> str:
268 if not self.settings:
269 self.settings = HeroiconsIconsSettings()
271 # Resolve icon aliases
272 if icon_name in self.settings.icon_aliases:
273 icon_name = self.settings.icon_aliases[icon_name]
275 # Use default variant if not specified
276 if not variant:
277 variant = self.settings.default_variant
279 # Validate variant
280 if variant not in self.settings.enabled_variants:
281 variant = self.settings.default_variant
283 return f"heroicon heroicon-{variant}"
285 def _get_icon_size(self, size: str | None, variant: str) -> str:
286 """Determine icon size based on input and variant."""
287 if size and size in self.settings.size_presets:
288 return self.settings.size_presets[size]
289 elif size and size.isdigit():
290 return size
291 # Default size based on variant
292 return "20" if variant == "mini" else self.settings.default_size
294 def _build_icon_class(
295 self, icon_name: str, variant: str, size: str | None, attributes: dict[str, Any]
296 ) -> str:
297 """Build the complete icon class string."""
298 # Build base icon class
299 icon_class = self.get_icon_class(icon_name, variant)
301 # Add size class if using preset
302 if size and size in self.settings.size_presets:
303 icon_class += f" heroicon-{size}"
305 # Add custom classes
306 if "class" in attributes:
307 icon_class += f" {attributes.pop('class')}"
309 # Process attributes using shared utilities
310 transform_classes, attributes = process_transformations(attributes, "heroicon")
311 animation_classes, attributes = process_animations(
312 attributes, ["spin", "pulse", "bounce"], "heroicon"
313 )
314 semantic_colors = [
315 "primary",
316 "secondary",
317 "success",
318 "warning",
319 "danger",
320 "info",
321 "gray",
322 "white",
323 "black",
324 ]
325 color_class, attributes = process_semantic_colors(
326 attributes, semantic_colors, "heroicon"
327 )
328 state_classes, attributes = process_state_attributes(attributes, "heroicon")
330 # Combine all classes
331 return icon_class + (
332 transform_classes + animation_classes + color_class + state_classes
333 )
335 def _build_svg_attributes(
336 self, icon_class: str, icon_size: str, variant: str, attributes: dict[str, Any]
337 ) -> dict[str, Any]:
338 """Build SVG attributes with variant-specific settings."""
339 # Build SVG attributes
340 svg_attrs = {
341 "class": icon_class,
342 "width": icon_size,
343 "height": icon_size,
344 "viewBox": f"0 0 {icon_size} {icon_size}",
345 } | attributes
347 # Add accessibility and variant-specific attributes
348 svg_attrs = add_accessibility_attributes(svg_attrs)
349 if variant == "outline":
350 svg_attrs.setdefault("stroke-width", "1.5")
351 svg_attrs.setdefault("stroke", "currentColor")
352 svg_attrs.setdefault("fill", "none")
353 else:
354 svg_attrs.setdefault("fill", "currentColor")
356 return svg_attrs
358 def get_icon_tag(
359 self,
360 icon_name: str,
361 variant: str | None = None,
362 size: str | None = None,
363 **attributes: Any,
364 ) -> str:
365 if not self.settings:
366 self.settings = HeroiconsIconsSettings()
368 # Resolve icon aliases
369 if icon_name in self.settings.icon_aliases:
370 icon_name = self.settings.icon_aliases[icon_name]
372 # Use default variant if not specified
373 if not variant:
374 variant = self.settings.default_variant
376 # Validate variant
377 if variant not in self.settings.enabled_variants:
378 variant = self.settings.default_variant
380 # Determine size
381 icon_size = self._get_icon_size(size, variant)
383 # Build icon class
384 icon_class = self._build_icon_class(icon_name, variant, size, attributes)
386 # Build SVG attributes
387 svg_attrs = self._build_svg_attributes(
388 icon_class, icon_size, variant, attributes
389 )
391 # Generate SVG content and build tag
392 svg_content = self._get_icon_svg_content(icon_name, variant)
393 attr_string = build_attr_string(svg_attrs)
394 return f"<svg {attr_string}>{svg_content}</svg>"
396 def _get_icon_svg_content(self, icon_name: str, variant: str) -> str:
397 """Get SVG content for specific icon and variant."""
398 # This would typically come from the Heroicons icon registry
399 # For now, return placeholder content for common icons
401 # Common icon paths (simplified examples)
402 icon_paths = {
403 "home": {
404 "outline": '<path stroke-linecap="round" stroke-linejoin="round" d="m2.25 12 8.954-8.955c.44-.439 1.152-.439 1.591 0L21.75 12M4.5 9.75v10.125c0 .621.504 1.125 1.125 1.125H9.75v-4.875c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125V21h4.125c.621 0 1.125-.504 1.125-1.125V9.75M8.25 21h8.25" />',
405 "solid": '<path d="M11.47 3.84a.75.75 0 011.06 0l8.69 8.69a.75.75 0 101.06-1.06l-8.689-8.69a2.25 2.25 0 00-3.182 0l-8.69 8.69a.75.75 0 001.061 1.06l8.69-8.69z"/><path d="M12 5.432l8.159 8.159c.03.03.06.058.091.086v6.198c0 1.035-.84 1.875-1.875 1.875H15a.75.75 0 01-.75-.75v-4.5a.75.75 0 00-.75-.75h-3a.75.75 0 00-.75.75V21a.75.75 0 01-.75.75H5.625a1.875 1.875 0 01-1.875-1.875v-6.198a2.29 2.29 0 00.091-.086L12 5.432z"/>',
406 "mini": '<path d="M9.293 2.293a1 1 0 011.414 0l7 7A1 1 0 0117 11h-1v6a1 1 0 01-1 1h-2a1 1 0 01-1-1v-3a1 1 0 00-1-1H9a1 1 0 00-1 1v3a1 1 0 01-1 1H5a1 1 0 01-1-1v-6H3a1 1 0 01-.707-1.707l7-7z"/>',
407 },
408 "user": {
409 "outline": '<path stroke-linecap="round" stroke-linejoin="round" d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z" />',
410 "solid": '<path fill-rule="evenodd" d="M7.5 6a4.5 4.5 0 119 0 4.5 4.5 0 01-9 0zM3.751 20.105a8.25 8.25 0 0116.498 0 .75.75 0 01-.437.695A18.683 18.683 0 0112 22.5c-2.786 0-5.433-.608-7.812-1.7a.75.75 0 01-.437-.695z" clip-rule="evenodd" />',
411 "mini": '<path d="M10 8a3 3 0 100-6 3 3 0 000 6zM3.465 14.493a1.23 1.23 0 00.41 1.412A9.957 9.957 0 0010 18c2.31 0 4.438-.784 6.131-2.1.43-.333.604-.903.408-1.41a7.002 7.002 0 00-13.074.003z"/>',
412 },
413 "x-mark": {
414 "outline": '<path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />',
415 "solid": '<path fill-rule="evenodd" d="M5.47 5.47a.75.75 0 011.06 0L12 10.94l5.47-5.47a.75.75 0 111.06 1.06L13.06 12l5.47 5.47a.75.75 0 11-1.06 1.06L12 13.06l-5.47 5.47a.75.75 0 01-1.06-1.06L10.94 12 5.47 6.53a.75.75 0 010-1.06z" clip-rule="evenodd" />',
416 "mini": '<path d="M6.28 5.22a.75.75 0 00-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 101.06 1.06L10 11.06l3.72 3.72a.75.75 0 101.06-1.06L11.06 10l3.72-3.72a.75.75 0 00-1.06-1.06L10 8.94 6.28 5.22z"/>',
417 },
418 "check": {
419 "outline": '<path stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5" />',
420 "solid": '<path fill-rule="evenodd" d="M19.916 4.626a.75.75 0 01.208 1.04l-9 13.5a.75.75 0 01-1.154.114l-6-6a.75.75 0 011.06-1.06l5.353 5.353 8.493-12.739a.75.75 0 011.04-.208z" clip-rule="evenodd" />',
421 "mini": '<path fill-rule="evenodd" d="M16.704 4.153a.75.75 0 01.143 1.052l-8 10.5a.75.75 0 01-1.127.075l-4.5-4.5a.75.75 0 011.06-1.06l3.894 3.893 7.48-9.817a.75.75 0 011.05-.143z" clip-rule="evenodd" />',
422 },
423 }
425 # Return path for the requested icon and variant
426 if icon_name in icon_paths and variant in icon_paths[icon_name]:
427 return icon_paths[icon_name][variant]
429 # Fallback for unknown icons
430 return f"<!-- {icon_name} ({variant}) not found -->"
432 def get_icon_sprite_url(self, variant: str = "outline") -> str:
433 """Get URL for Heroicons sprite file."""
434 if not self.settings:
435 self.settings = HeroiconsIconsSettings()
437 return f"{self.settings.cdn_url}@{self.settings.version}/{variant}.svg"
439 @staticmethod
440 def get_available_icons() -> dict[str, list[str]]:
441 """Get list of available icons by category."""
442 return {
443 "general": [
444 "home",
445 "user",
446 "cog-6-tooth",
447 "magnifying-glass",
448 "bars-3",
449 "x-mark",
450 "check",
451 "plus",
452 "minus",
453 "ellipsis-horizontal",
454 ],
455 "navigation": [
456 "arrow-left",
457 "arrow-right",
458 "arrow-up",
459 "arrow-down",
460 "chevron-left",
461 "chevron-right",
462 "chevron-up",
463 "chevron-down",
464 "arrow-path",
465 "arrow-uturn-left",
466 "arrow-uturn-right",
467 ],
468 "communication": [
469 "envelope",
470 "phone",
471 "chat-bubble-left",
472 "paper-airplane",
473 "bell",
474 "speaker-wave",
475 "microphone",
476 "video-camera",
477 ],
478 "media": [
479 "play",
480 "pause",
481 "stop",
482 "backward",
483 "forward",
484 "speaker-wave",
485 "speaker-x-mark",
486 "musical-note",
487 ],
488 "file": [
489 "document",
490 "folder",
491 "arrow-down-tray",
492 "arrow-up-tray",
493 "document-arrow-down",
494 "document-text",
495 "photo",
496 "film",
497 ],
498 "editing": [
499 "pencil",
500 "trash",
501 "document-duplicate",
502 "scissors",
503 "clipboard",
504 "eye",
505 "eye-slash",
506 "lock-closed",
507 "lock-open",
508 ],
509 "status": [
510 "check-circle",
511 "x-circle",
512 "exclamation-triangle",
513 "information-circle",
514 "question-mark-circle",
515 "light-bulb",
516 ],
517 }
520# Template filter registration for FastBlocks
521def _create_hero_button(
522 text: str,
523 icon: str | None,
524 variant: str,
525 icon_position: str,
526 icons: HeroiconsIcons,
527 **attributes: Any,
528) -> str:
529 """Build button HTML with Heroicons icon."""
530 btn_class = attributes.pop("class", "btn btn-primary")
532 # Build button content
533 if icon:
534 icon_tag = icons.get_icon_tag(icon, variant, size="sm")
535 if icon_position == "left":
536 content = f"{icon_tag} {text}"
537 elif icon_position == "right":
538 content = f"{text} {icon_tag}"
539 else:
540 content = text
541 else:
542 content = text
544 # Build button attributes
545 btn_attrs = {"class": btn_class} | attributes
546 attr_string = " ".join(f'{k}="{v}"' for k, v in btn_attrs.items())
548 return f"<button {attr_string}>{content}</button>"
551def _create_hero_badge(
552 text: str,
553 icon: str | None,
554 variant: str,
555 icons: HeroiconsIcons,
556 **attributes: Any,
557) -> str:
558 """Build badge HTML with Heroicons icon."""
559 badge_class = attributes.pop("class", "badge badge-primary")
561 # Build badge content
562 if icon:
563 icon_tag = icons.get_icon_tag(icon, variant, size="xs")
564 content = f"{icon_tag} {text}"
565 else:
566 content = text
568 # Build badge attributes
569 badge_attrs = {"class": badge_class} | attributes
570 attr_string = " ".join(f'{k}="{v}"' for k, v in badge_attrs.items())
572 return f"<span {attr_string}>{content}</span>"
575def register_heroicons_filters(env: Any) -> None:
576 """Register Heroicons filters for Jinja2 templates."""
578 @env.filter("heroicon") # type: ignore[misc] # Jinja2 decorator preserves signature
579 def heroicon_filter(
580 icon_name: str,
581 variant: str = "outline",
582 size: str | None = None,
583 **attributes: Any,
584 ) -> str:
585 """Template filter for Heroicons."""
586 icons = depends.get_sync("icons")
587 if isinstance(icons, HeroiconsIcons):
588 return icons.get_icon_tag(icon_name, variant, size, **attributes)
589 return f"<!-- {icon_name} -->"
591 @env.filter("heroicon_class") # type: ignore[misc] # Jinja2 decorator preserves signature
592 def heroicon_class_filter(icon_name: str, variant: str = "outline") -> str:
593 """Template filter for Heroicons classes."""
594 icons = depends.get_sync("icons")
595 if isinstance(icons, HeroiconsIcons):
596 return icons.get_icon_class(icon_name, variant)
597 return f"heroicon-{icon_name}"
599 @env.global_("heroicons_stylesheet_links") # type: ignore[misc] # Jinja2 decorator preserves signature
600 def heroicons_stylesheet_links() -> str:
601 """Global function for Heroicons stylesheet links."""
602 icons = depends.get_sync("icons")
603 if isinstance(icons, HeroiconsIcons):
604 return "\n".join(icons.get_stylesheet_links())
605 return ""
607 @env.global_("hero_button") # type: ignore[misc] # Jinja2 decorator preserves signature
608 def hero_button(
609 text: str,
610 icon: str | None = None,
611 variant: str = "outline",
612 icon_position: str = "left",
613 **attributes: Any,
614 ) -> str:
615 """Generate button with Heroicons icon."""
616 icons = depends.get_sync("icons")
617 if isinstance(icons, HeroiconsIcons):
618 return _create_hero_button(
619 text, icon, variant, icon_position, icons, **attributes
620 )
621 return f"<button>{text}</button>"
623 @env.global_("hero_badge") # type: ignore[misc] # Jinja2 decorator preserves signature
624 def hero_badge(
625 text: str, icon: str | None = None, variant: str = "outline", **attributes: Any
626 ) -> str:
627 """Generate badge with Heroicons icon."""
628 icons = depends.get_sync("icons")
629 if isinstance(icons, HeroiconsIcons):
630 return _create_hero_badge(text, icon, variant, icons, **attributes)
631 return f"<span class='badge'>{text}</span>"
634IconsSettings = HeroiconsIconsSettings
635Icons = HeroiconsIcons
637# Register with Oneiric resolver (fail gracefully if not supported)
638with suppress(Exception):
639 depends.set(Icons, "heroicons")
642# ACB 0.19.0+ compatibility
643__all__ = [
644 "HeroiconsIcons",
645 "HeroiconsIconsSettings",
646 "register_heroicons_filters",
647 "Icons",
648 "IconsSettings",
649]