Coverage for fastblocks / adapters / templates / _htmy_components.py: 89%
322 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"""HTMY Component Management System for FastBlocks.
3Provides advanced component discovery, validation, scaffolding, and lifecycle management
4for HTMY components with deep HTMX integration and async rendering capabilities.
6Key Features:
7- Automatic component discovery with intelligent caching
8- Dataclass-based component scaffolding with validation
9- Component composition and nesting patterns
10- HTMX-aware state management
11- Async component rendering with lifecycle hooks
12- Advanced error handling and debugging
13- Hot-reloading support for development
15Author: lesleslie <les@wedgwoodwebworks.com>
16Created: 2025-01-13
17"""
19import asyncio
20import inspect
21import tempfile
22import typing as t
23from abc import ABC, abstractmethod
24from dataclasses import dataclass, field, fields, is_dataclass
25from datetime import datetime
26from enum import Enum
27from pathlib import Path
28from typing import Any, Optional
29from uuid import uuid4
31from anyio import Path as AsyncPath
32from starlette.requests import Request
35# Custom debug function for Oneiric compatibility
36def debug(msg: str) -> None:
37 """Custom debug function for Oneiric compatibility."""
38 print(f"[DEBUG] {msg}")
41try:
42 from pydantic import BaseModel
43except ImportError:
44 BaseModel = None # type: ignore[no-redef]
47class ComponentStatus(str, Enum):
48 """Component lifecycle status."""
50 DISCOVERED = "discovered"
51 VALIDATED = "validated"
52 COMPILED = "compiled"
53 READY = "ready"
54 ERROR = "error"
55 DEPRECATED = "deprecated"
58class ComponentType(str, Enum):
59 """Component classification types."""
61 BASIC = "basic"
62 DATACLASS = "dataclass"
63 PYDANTIC = "pydantic"
64 ASYNC = "async"
65 HTMX = "htmx"
66 COMPOSITE = "composite"
69@dataclass
70class ComponentMetadata:
71 """Component metadata for discovery and management."""
73 name: str
74 path: AsyncPath
75 type: ComponentType
76 status: ComponentStatus = ComponentStatus.DISCOVERED
77 dependencies: list[str] = field(default_factory=list)
78 htmx_attributes: dict[str, Any] = field(default_factory=dict)
79 cache_key: str | None = None
80 last_modified: datetime | None = None
81 error_message: str | None = None
82 docstring: str | None = None
84 def __post_init__(self) -> None:
85 if self.cache_key is None:
86 self.cache_key = f"component_{self.name}_{self.path.stem}"
89class ComponentValidationError(Exception):
90 """Raised when component validation fails."""
92 pass
95class ComponentCompilationError(Exception):
96 """Raised when component compilation fails."""
98 pass
101class ComponentRenderError(Exception):
102 """Raised when component rendering fails."""
104 pass
107class HTMXComponentMixin:
108 """Mixin for HTMX-aware components."""
110 @property
111 def htmx_attrs(self) -> dict[str, str]:
112 """Default HTMX attributes for the component."""
113 return {}
115 def get_htmx_trigger(self, request: Request) -> str | None:
116 """Extract HTMX trigger from request."""
117 return request.headers.get("HX-Trigger")
119 def get_htmx_target(self, request: Request) -> str | None:
120 """Extract HTMX target from request."""
121 return request.headers.get("HX-Target")
123 def is_htmx_request(self, request: Request) -> bool:
124 """Check if request is from HTMX."""
125 return request.headers.get("HX-Request") == "true"
128class ComponentBase(ABC):
129 """Base class for all HTMY components."""
131 def __init__(self, **kwargs: Any) -> None:
132 self._context: dict[str, Any] = kwargs
133 self._request: Request | None = kwargs.get("request")
134 self._children: list[ComponentBase] = []
135 self._parent: ComponentBase | None = None
137 @abstractmethod
138 def htmy(self, context: dict[str, Any]) -> str:
139 """Render the component to HTML."""
140 pass
142 async def async_htmy(self, context: dict[str, Any]) -> str:
143 """Async version of htmy method."""
144 if asyncio.iscoroutinefunction(self.htmy):
145 return t.cast(str, await self.htmy(context))
146 return t.cast(str, self.htmy(context))
148 def add_child(self, child: "ComponentBase") -> None:
149 """Add a child component."""
150 child._parent = self
151 self._children.append(child)
153 def remove_child(self, child: "ComponentBase") -> None:
154 """Remove a child component."""
155 if child in self._children:
156 child._parent = None
157 self._children.remove(child)
159 @property
160 def children(self) -> list["ComponentBase"]:
161 """Get child components."""
162 return self._children.copy()
164 @property
165 def parent(self) -> Optional["ComponentBase"]:
166 """Get parent component."""
167 return self._parent
170class DataclassComponentBase(ComponentBase):
171 """Base class for dataclass-based components."""
173 def __init_subclass__(cls, **kwargs: Any) -> None:
174 super().__init_subclass__(**kwargs)
175 if not is_dataclass(cls):
176 raise ComponentValidationError(
177 f"Component {cls.__name__} must be a dataclass"
178 )
180 def validate_fields(self) -> None:
181 """Validate component fields."""
182 if not is_dataclass(self):
183 return
185 for field_info in fields(self):
186 value = getattr(self, field_info.name)
187 if field_info.type and value is not None:
188 # Basic type validation
189 origin = getattr(field_info.type, "__origin__", None)
190 # Only validate if field_info.type is a proper class
191 if origin is None and isinstance(field_info.type, type):
192 if not isinstance(value, field_info.type):
193 raise ComponentValidationError(
194 f"Field {field_info.name} must be of type {field_info.type}"
195 )
198class ComponentScaffolder:
199 """Scaffolding system for creating new components."""
201 @staticmethod
202 def create_basic_component(
203 name: str, props: dict[str, type] | None = None, htmx_enabled: bool = False
204 ) -> str:
205 """Create a basic component template."""
206 props = props or {}
208 # Generate prop fields
209 prop_lines = []
210 init_params = []
211 for prop_name, prop_type in props.items():
212 prop_lines.append(f" {prop_name}: {prop_type.__name__}")
213 init_params.append(f"{prop_name}: {prop_type.__name__}")
215 # Generate component class
216 mixins = ["HTMXComponentMixin"] if htmx_enabled else []
217 base_classes = ["DataclassComponentBase"] + mixins
219 template = f'''"""Component: {name}
221Auto-generated component using FastBlocks HTMY scaffolding.
222"""
224from dataclasses import dataclass
225from typing import Any
226from fastblocks.adapters.templates._htmy_components import (
227 DataclassComponentBase,
228 HTMXComponentMixin,
229)
232@dataclass
233class {name}({", ".join(base_classes)}):
234 """Auto-generated {name} component."""
235{chr(10).join(prop_lines) if prop_lines else " pass"}
237 def htmy(self, context: dict[str, Any]) -> str:
238 """Render the {name} component."""
239 return f"""
240 <div class="{name.lower()}-component">
241 <h3>{name} Component</h3>
242 {f'<p>{{self.{list(props.keys())[0]} if props else "content"}}</p>' if props else ""}
243 <!-- Add your HTML here -->
244 </div>
245 """
246'''
248 return template
250 @staticmethod
251 def create_htmx_component(
252 name: str, endpoint: str, trigger: str = "click", target: str = "#content"
253 ) -> str:
254 """Create an HTMX-enabled component template."""
255 template = f'''"""Component: {name}
257HTMX-enabled component for interactive behavior.
258"""
260from dataclasses import dataclass
261from typing import Any
262from fastblocks.adapters.templates._htmy_components import (
263 DataclassComponentBase,
264 HTMXComponentMixin,
265)
268@dataclass
269class {name}(DataclassComponentBase, HTMXComponentMixin):
270 """HTMX-enabled {name} component."""
271 label: str = "{name}"
272 css_class: str = "{name.lower()}-component"
274 @property
275 def htmx_attrs(self) -> dict[str, str]:
276 """HTMX attributes for the component."""
277 return {{
278 "hx-get": "{endpoint}",
279 "hx-trigger": "{trigger}",
280 "hx-target": "{target}",
281 "hx-swap": "innerHTML"
282 }}
284 def htmy(self, context: dict[str, Any]) -> str:
285 """Render the {name} component."""
286 attrs = " ".join([f'{{k}}="{{v}}"' for k, v in self.htmx_attrs.items()])
288 return f"""
289 <div class="{{self.css_class}}" {{attrs}}>
290 <button type="button">{{self.label}}</button>
291 </div>
292 """
293'''
295 return template
297 @staticmethod
298 def create_composite_component(name: str, children: list[str]) -> str:
299 """Create a composite component template."""
300 template = f'''"""Component: {name}
302Composite component containing multiple child components.
303"""
305from dataclasses import dataclass
306from typing import Any
307from fastblocks.adapters.templates._htmy_components import DataclassComponentBase
310@dataclass
311class {name}(DataclassComponentBase):
312 """Composite {name} component."""
313 title: str = "{name}"
315 def htmy(self, context: dict[str, Any]) -> str:
316 """Render the {name} composite component."""
317 # Access render_component from context if available
318 render_component = context.get("render_component")
320 children_html = ""
321 if render_component:
322{chr(10).join([f' children_html += render_component("{child}", context)' for child in children])}
324 return f"""
325 <div class="{name.lower()}-composite">
326 <h2>{{self.title}}</h2>
327 <div class="children">
328 {{children_html}}
329 </div>
330 </div>
331 """
332'''
334 return template
337class ComponentValidator:
338 """Component validation system."""
340 @staticmethod
341 async def validate_component_file(component_path: AsyncPath) -> ComponentMetadata:
342 """Validate a component file and extract metadata."""
343 try:
344 source = await component_path.read_text()
346 # Basic syntax validation
347 try:
348 compile(source, str(component_path), "exec")
349 except SyntaxError as e:
350 raise ComponentValidationError(f"Syntax error in {component_path}: {e}")
352 component_class = await ComponentValidator._load_component_class_from_file(
353 source, component_path
354 )
356 if component_class is None:
357 raise ComponentValidationError(
358 f"No valid component class found in {component_path}"
359 )
361 return await ComponentValidator._create_component_metadata(
362 component_class, component_path
363 )
365 except Exception as e:
366 return ComponentMetadata(
367 name=component_path.stem,
368 path=component_path,
369 type=ComponentType.BASIC,
370 status=ComponentStatus.ERROR,
371 error_message=str(e),
372 )
374 @staticmethod
375 async def _load_component_class_from_file(source: str, component_path: AsyncPath):
376 """Load component class from source file."""
377 # Import and analyze component safely
378 import importlib.util
380 # Create a temporary module to safely load the component
381 with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f:
382 f.write(source)
383 temp_module_path = f.name
385 try:
386 spec = importlib.util.spec_from_file_location(
387 component_path.stem, temp_module_path
388 )
389 if spec is None or spec.loader is None:
390 raise ComponentValidationError(
391 f"Could not load module from {component_path}"
392 )
394 module = importlib.util.module_from_spec(spec)
395 spec.loader.exec_module(module)
397 component_class = None
398 for obj in vars(module).values():
399 if (
400 inspect.isclass(obj)
401 and hasattr(obj, "htmy")
402 and callable(getattr(obj, "htmy"))
403 ):
404 component_class = obj
405 break
406 finally:
407 # Clean up the temporary file
408 Path(temp_module_path).unlink()
410 return component_class
412 @staticmethod
413 async def _create_component_metadata(
414 component_class: type, component_path: AsyncPath
415 ) -> ComponentMetadata:
416 """Create ComponentMetadata from component class and path."""
417 # Determine component type
418 component_type = ComponentValidator._determine_component_type(component_class)
420 # Extract metadata
421 metadata = ComponentMetadata(
422 name=component_path.stem,
423 path=component_path,
424 type=component_type,
425 status=ComponentStatus.VALIDATED,
426 docstring=inspect.getdoc(component_class),
427 last_modified=datetime.fromtimestamp(
428 (await component_path.stat()).st_mtime
429 ),
430 )
432 # Extract dependencies and HTMX attributes
433 if hasattr(component_class, "htmx_attrs"):
434 metadata.htmx_attributes = getattr(component_class, "htmx_attrs", {})
436 return metadata
438 @staticmethod
439 def _determine_component_type(component_class: type) -> ComponentType:
440 """Determine the type of component."""
441 if is_dataclass(component_class):
442 if issubclass(component_class, HTMXComponentMixin):
443 return ComponentType.HTMX
444 return ComponentType.DATACLASS
446 if BaseModel and issubclass(component_class, BaseModel):
447 return ComponentType.PYDANTIC
449 if hasattr(component_class, "async_htmy"):
450 return ComponentType.ASYNC
452 return ComponentType.BASIC
455class ComponentLifecycleManager:
456 """Manages component lifecycle and state."""
458 def __init__(self) -> None:
459 self._component_states: dict[str, dict[str, Any]] = {}
460 self._lifecycle_hooks: dict[str, list[t.Callable[..., Any]]] = {
461 "before_render": [],
462 "after_render": [],
463 "on_error": [],
464 "on_state_change": [],
465 }
467 def register_hook(self, event: str, callback: t.Callable[..., Any]) -> None:
468 """Register a lifecycle hook."""
469 if event in self._lifecycle_hooks:
470 self._lifecycle_hooks[event].append(callback)
472 async def execute_hooks(self, event: str, **kwargs: Any) -> None:
473 """Execute lifecycle hooks for an event."""
474 for hook in self._lifecycle_hooks.get(event, []):
475 try:
476 if asyncio.iscoroutinefunction(hook):
477 await hook(**kwargs)
478 else:
479 hook(**kwargs)
480 except Exception as e:
481 debug(f"Lifecycle hook error for {event}: {e}")
483 def set_component_state(self, component_id: str, state: dict[str, Any]) -> None:
484 """Set component state."""
485 old_state = self._component_states.get(component_id, {})
486 self._component_states[component_id] = state
488 # Trigger state change hooks
489 asyncio.create_task(
490 self.execute_hooks(
491 "on_state_change",
492 component_id=component_id,
493 old_state=old_state,
494 new_state=state,
495 )
496 )
498 def get_component_state(self, component_id: str) -> dict[str, Any]:
499 """Get component state."""
500 return self._component_states.get(component_id, {})
502 def clear_component_state(self, component_id: str) -> None:
503 """Clear component state."""
504 self._component_states.pop(component_id, None)
507class AdvancedHTMYComponentRegistry:
508 """Enhanced component registry with advanced features."""
510 def __init__(
511 self,
512 searchpaths: list[AsyncPath] | None = None,
513 cache: t.Any = None,
514 storage: t.Any = None,
515 ) -> None:
516 self.searchpaths = searchpaths or []
517 self.cache = cache
518 self.storage = storage
519 self._component_cache: dict[str, t.Any] = {}
520 self._metadata_cache: dict[str, ComponentMetadata] = {}
521 self._scaffolder = ComponentScaffolder()
522 self._validator = ComponentValidator()
523 self._lifecycle_manager = ComponentLifecycleManager()
524 self._hot_reload_enabled = False
526 async def discover_components(self) -> dict[str, ComponentMetadata]:
527 """Discover all components with metadata."""
528 components = {}
530 for search_path in self.searchpaths:
531 if not await search_path.exists():
532 continue
534 for component_file in search_path.rglob("*.py"):
535 if component_file.name == "__init__.py":
536 continue
538 component_name = component_file.stem
540 # Check cache first
541 cached_metadata = self._metadata_cache.get(component_name)
542 if cached_metadata and await self._is_cache_valid(cached_metadata):
543 components[component_name] = cached_metadata
544 continue
546 # Validate and cache metadata
547 metadata = await self._validator.validate_component_file(component_file)
548 self._metadata_cache[component_name] = metadata
549 components[component_name] = metadata
551 return components
553 async def _is_cache_valid(self, metadata: ComponentMetadata) -> bool:
554 """Check if cached metadata is still valid."""
555 try:
556 current_stat = await metadata.path.stat()
557 current_mtime = datetime.fromtimestamp(current_stat.st_mtime)
558 return metadata.last_modified == current_mtime
559 except Exception:
560 return False
562 async def get_component_class(self, component_name: str) -> t.Any:
563 """Get compiled component class with enhanced error handling."""
564 if component_name in self._component_cache:
565 return self._component_cache[component_name]
567 metadata = await self._validate_component_exists(component_name)
569 source = await metadata.path.read_text()
570 component_class = await self._load_component_from_source(source, metadata)
572 if component_class is None:
573 raise ComponentCompilationError(
574 f"No valid component class found in '{component_name}'"
575 )
577 self._component_cache[component_name] = component_class
578 metadata.status = ComponentStatus.READY
580 return component_class
582 async def _validate_component_exists(
583 self, component_name: str
584 ) -> ComponentMetadata:
585 """Validate that a component exists and return its metadata."""
586 components = await self.discover_components()
587 if component_name not in components:
588 raise ComponentValidationError(f"Component '{component_name}' not found")
590 metadata = components[component_name]
592 if metadata.status == ComponentStatus.ERROR:
593 raise ComponentCompilationError(
594 f"Component '{component_name}' has errors: {metadata.error_message}"
595 )
596 return metadata
598 async def _load_component_from_source(
599 self, source: str, metadata: ComponentMetadata
600 ) -> t.Any:
601 """Load a component class from source code."""
602 try:
603 # Import and analyze component safely
604 import importlib.util
606 # Create a temporary module to safely load the component
607 with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f:
608 f.write(source)
609 temp_module_path = f.name
611 try:
612 spec = importlib.util.spec_from_file_location(
613 metadata.path.stem, temp_module_path
614 )
615 if spec is None or spec.loader is None:
616 raise ComponentCompilationError(
617 f"Could not load module from {metadata.path}"
618 )
620 module = importlib.util.module_from_spec(spec)
621 spec.loader.exec_module(module)
623 component_class = None
624 for obj in vars(module).values():
625 if (
626 inspect.isclass(obj)
627 and hasattr(obj, "htmy")
628 and callable(getattr(obj, "htmy"))
629 ):
630 component_class = obj
631 break
632 finally:
633 # Clean up the temporary file
634 Path(temp_module_path).unlink()
636 return component_class
637 except Exception as e:
638 metadata.status = ComponentStatus.ERROR
639 metadata.error_message = str(e)
640 raise ComponentCompilationError(
641 f"Failed to compile component '{metadata.path.stem}': {e}"
642 ) from e
644 async def render_component_with_lifecycle(
645 self, component_name: str, context: dict[str, Any], request: Request
646 ) -> str:
647 """Render component with full lifecycle management."""
648 component_id = f"{component_name}_{uuid4().hex[:8]}"
650 try:
651 # Execute before_render hooks
652 await self._lifecycle_manager.execute_hooks(
653 "before_render",
654 component_name=component_name,
655 component_id=component_id,
656 context=context,
657 request=request,
658 )
660 component_class = await self.get_component_class(component_name)
661 component_instance = component_class(**context)
663 # Enhance context with lifecycle and state management
664 enhanced_context = context | {
665 "request": request,
666 "component_id": component_id,
667 "component_state": self._lifecycle_manager.get_component_state(
668 component_id
669 ),
670 "set_state": lambda state: self._lifecycle_manager.set_component_state(
671 component_id, state
672 ),
673 "render_component": self._create_nested_renderer(request),
674 }
676 # Render component
677 if hasattr(
678 component_instance, "async_htmy"
679 ) and asyncio.iscoroutinefunction(component_instance.async_htmy):
680 rendered_content = await component_instance.async_htmy(enhanced_context)
681 elif asyncio.iscoroutinefunction(component_instance.htmy):
682 rendered_content = await component_instance.htmy(enhanced_context)
683 else:
684 rendered_content = component_instance.htmy(enhanced_context)
686 # Execute after_render hooks
687 await self._lifecycle_manager.execute_hooks(
688 "after_render",
689 component_name=component_name,
690 component_id=component_id,
691 rendered_content=rendered_content,
692 request=request,
693 )
695 return t.cast(str, rendered_content)
697 except Exception as e:
698 # Execute error hooks
699 await self._lifecycle_manager.execute_hooks(
700 "on_error",
701 component_name=component_name,
702 component_id=component_id,
703 error=e,
704 request=request,
705 )
706 raise ComponentRenderError(
707 f"Failed to render component '{component_name}': {e}"
708 ) from e
710 def _create_nested_renderer(
711 self, request: Request
712 ) -> t.Callable[..., t.Awaitable[str]]:
713 """Create a nested component renderer for composition."""
715 async def render_nested(
716 component_name: str, context: dict[str, Any] | None = None
717 ) -> str:
718 if context is None:
719 context = {}
720 return await self.render_component_with_lifecycle(
721 component_name, context, request
722 )
724 return render_nested
726 async def scaffold_component(
727 self,
728 name: str,
729 component_type: ComponentType = ComponentType.DATACLASS,
730 target_path: AsyncPath | None = None,
731 **kwargs: Any,
732 ) -> AsyncPath:
733 """Scaffold a new component with the specified type."""
734 if target_path is None and self.searchpaths:
735 target_path = self.searchpaths[0] / f"{name.lower()}.py"
736 elif target_path is None:
737 raise ValueError("No target path specified and no searchpaths configured")
739 # Generate component code based on type
740 if component_type == ComponentType.HTMX:
741 content = self._scaffolder.create_htmx_component(name, **kwargs)
742 elif component_type == ComponentType.COMPOSITE:
743 content = self._scaffolder.create_composite_component(name, **kwargs)
744 else:
745 content = self._scaffolder.create_basic_component(name, **kwargs)
747 # Ensure directory exists
748 await target_path.parent.mkdir(parents=True, exist_ok=True)
750 # Write component file
751 await target_path.write_text(content)
753 # Clear cache to force re-discovery
754 self.clear_cache()
756 debug(f"Scaffolded {component_type.value} component '{name}' at {target_path}")
757 return target_path
759 def clear_cache(self, component_name: str | None = None) -> None:
760 """Clear component cache."""
761 if component_name:
762 self._component_cache.pop(component_name, None)
763 self._metadata_cache.pop(component_name, None)
764 else:
765 self._component_cache.clear()
766 self._metadata_cache.clear()
768 def enable_hot_reload(self) -> None:
769 """Enable hot reloading for development."""
770 self._hot_reload_enabled = True
771 debug("HTMY component hot reload enabled")
773 def disable_hot_reload(self) -> None:
774 """Disable hot reloading."""
775 self._hot_reload_enabled = False
776 debug("HTMY component hot reload disabled")
778 @property
779 def lifecycle_manager(self) -> ComponentLifecycleManager:
780 """Access to lifecycle manager."""
781 return self._lifecycle_manager