Metadata-Version: 2.4
Name: cjm-fasthtml-app-core
Version: 0.0.4
Summary: Core utilities and reusable patterns for FastHTML applications including page layouts, HTMX request handling, alerts, and navbar components.
Home-page: https://github.com/cj-mills/cjm-fasthtml-app-core
Author: Christian J. Mills
Author-email: 9126128+cj-mills@users.noreply.github.com
License: Apache Software License 2.0
Keywords: nbdev jupyter notebook python
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Natural Language :: English
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: License :: OSI Approved :: Apache Software License
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: cjm_fasthtml_daisyui
Provides-Extra: dev
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: keywords
Dynamic: license
Dynamic: license-file
Dynamic: provides-extra
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# cjm-fasthtml-app-core


<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

## Install

``` bash
pip install cjm_fasthtml_app_core
```

## Project Structure

    nbs/
    ├── components/ (2)
    │   ├── alerts.ipynb  # Alert components for displaying success, error, warning, and info messages
    │   └── navbar.ipynb  # Responsive navigation bar components with mobile support
    └── core/ (5)
        ├── errors.ipynb    # Utilities for converting structured errors to FastHTML responses, alerts, and error pages
        ├── html_ids.ipynb  # Base HTML ID constants for FastHTML applications
        ├── htmx.ipynb      # Utilities for handling HTMX requests and responses
        ├── layout.ipynb    # Page layout utilities for wrapping content with common page structure
        └── routing.ipynb   # Routing utilities for FastHTML applications

Total: 7 notebooks across 2 directories

## Module Dependencies

``` mermaid
graph LR
    components_alerts[components.alerts<br/>Alerts]
    components_navbar[components.navbar<br/>Navbar]
    core_errors[core.errors<br/>Error Utilities]
    core_html_ids[core.html_ids<br/>HTML IDs]
    core_htmx[core.htmx<br/>HTMX Utilities]
    core_layout[core.layout<br/>Layout]
    core_routing[core.routing<br/>routing]

    components_alerts --> core_html_ids
    components_navbar --> core_html_ids
    core_errors --> components_alerts
    core_errors --> core_html_ids
    core_layout --> core_html_ids
```

*5 cross-module dependencies detected*

## CLI Reference

No CLI commands found in this project.

## Module Overview

Detailed documentation for each module in the project:

### Alerts (`alerts.ipynb`)

> Alert components for displaying success, error, warning, and info
> messages

#### Import

``` python
from cjm_fasthtml_app_core.components.alerts import (
    create_success_alert,
    create_error_alert,
    create_warning_alert,
    create_info_alert
)
```

#### Functions

``` python
def _create_auto_dismiss_script(
    timeout_ms:int=3000 # Time in milliseconds before auto-dismiss
) -> FT: # Script element for auto-dismissing alerts
    "Create a script that auto-dismisses the alert after a timeout."
```

``` python
def create_success_alert(
    message:str, # The success message to display
    timeout_ms:int=3000 # Time in milliseconds before auto-dismiss
) -> FT: # Div element containing the success alert
    "Create a success alert that auto-dismisses."
```

``` python
def create_error_alert(
    message:str, # The error message to display
    details:Optional[str]=None # Optional additional details text
) -> FT: # Div element containing the error alert
    "Create an error alert with optional details."
```

``` python
def create_warning_alert(
    message: str,  # The warning message to display
    details: Optional[str] = None  # Optional additional details text
) -> Div:  # Div element containing the warning alert
    "Create a warning alert with optional details."
```

``` python
def create_info_alert(
    message:str, # The info message to display
    details:Optional[str]=None # Optional additional details text
) -> FT: # Div element containing the info alert
    "Create an info alert with optional details."
```

### Error Utilities (`errors.ipynb`)

> Utilities for converting structured errors to FastHTML responses,
> alerts, and error pages

#### Import

``` python
from cjm_fasthtml_app_core.core.errors import (
    error_to_alert,
    error_to_htmx_response,
    create_error_page,
    error_to_page
)
```

#### Functions

```` python
def error_to_alert(
    error: Any,  # Error object (BaseError from cjm-error-handling or standard Exception)
    include_debug_info: bool = False  # Whether to include debug information in the alert
) -> FT:  # Alert component (error or warning)
    """
    Convert an error to an alert component.
    
    - Uses user-friendly message for display
    - Optionally includes debug information
    - Maps severity to alert type (error/warning)
    - Falls back to standard exception str() for non-structured errors
    
    Example:
        ```python
        try:
            result = manager.load_plugin(plugin_meta)
        except PluginError as e:
            return error_to_alert(e)
        ```
    """
````

```` python
def error_to_htmx_response(
    error: Any,  # Error object (BaseError or Exception)
    target_id: str = AppHtmlIds.ALERT_CONTAINER,  # ID of element to update with error
    include_debug_info: bool = False  # Whether to include debug information
) -> FT:  # Alert component with correct ID for HTMX targeting
    """
    Create an HTMX-compatible error response.
    
    Returns an alert that HTMX can swap into the target element.
    
    Example:
        ```python
        @app.post("/save-config")
        async def save_config(request):
            try:
                config = await load_config()
                return create_success_alert("Saved!")
            except ConfigurationError as e:
                return error_to_htmx_response(e)
        ```
    """
````

```` python
def create_error_page(
    title: str = "Error",  # Page title
    message: str = "An error occurred",  # Main error message
    details: Optional[str] = None,  # Optional details or debug info
    show_home_link: bool = True,  # Whether to show a link back to home
    home_path: str = "/"  # Path for the home link (defaults to root)
) -> FT:  # Div element containing the full error page
    """
    Create a full-page error display.
    
    Useful for critical errors or standard HTTP error pages (404, 500, etc.).
    
    Example:
        ```python
        @app.get("/not-found")
        def not_found():
            return create_error_page(
                title="Page Not Found",
                message="The page you're looking for doesn't exist",
                details="Error 404",
                home_path="/dashboard"
            )
        ```
    """
````

```` python
def error_to_page(
    error: Any,  # Error object (BaseError or Exception)
    include_debug_info: bool = False,  # Whether to include debug information
    show_home_link: bool = True,  # Whether to show a link back to home
    home_path: str = "/"  # Path for the home link (defaults to root)
) -> FT:  # Full error page component
    """
    Convert an error to a full-page error display.
    
    Useful for critical errors that need a dedicated page.
    
    Example:
        ```python
        try:
            critical_operation()
        except CriticalError as e:
            return error_to_page(e, include_debug_info=True, home_path="/dashboard")
        ```
    """
````

### HTML IDs (`html_ids.ipynb`)

> Base HTML ID constants for FastHTML applications

#### Import

``` python
from cjm_fasthtml_app_core.core.html_ids import (
    AppHtmlIds
)
```

#### Classes

``` python
class AppHtmlIds:
    "Base HTML ID constants for FastHTML applications."
    
    def as_selector(
            id_str:str # The HTML ID to convert
        ) -> str: # CSS selector with # prefix
        "Convert an ID to a CSS selector format."
```

### HTMX Utilities (`htmx.ipynb`)

> Utilities for handling HTMX requests and responses

#### Import

``` python
from cjm_fasthtml_app_core.core.htmx import (
    is_htmx_request,
    handle_htmx_request
)
```

#### Functions

``` python
def is_htmx_request(
    request # FastHTML request object
) -> bool: # True if request is from HTMX
    "Check if a request is an HTMX request."
```

``` python
def handle_htmx_request(
    request, # FastHTML request object
    content_fn:Callable, # Function to generate content
    *args, # Positional arguments for content_fn
    wrap_fn:Optional[Callable]=None, # Optional wrapper function for full page requests
    **kwargs # Keyword arguments for content_fn
): # Content or wrapped content based on request type
    "Handle HTMX vs full page response pattern."
```

### Layout (`layout.ipynb`)

> Page layout utilities for wrapping content with common page structure

#### Import

``` python
from cjm_fasthtml_app_core.core.layout import (
    wrap_with_layout
)
```

#### Functions

``` python
def wrap_with_layout(
    content:FT, # The main content to display
    navbar:Optional[FT]=None, # Optional navbar component
    footer:Optional[FT]=None, # Optional footer component
    container_id:str=AppHtmlIds.MAIN_CONTENT, # ID for the main content container
    container_tag:str="div" # HTML tag for the container
) -> FT: # Main element with navbar and content
    "Wrap content with the full page layout including optional navbar and footer."
```

### Navbar (`navbar.ipynb`)

> Responsive navigation bar components with mobile support

#### Import

``` python
from cjm_fasthtml_app_core.components.navbar import (
    create_nav_link,
    create_navbar
)
```

#### Functions

``` python
def create_nav_link(
    label:str, # Link text to display
    route, # FastHTML route object with .to() method
    target_id:str=AppHtmlIds.MAIN_CONTENT # HTMX target container ID
) -> FT: # Anchor element with HTMX attributes
    "Create a navigation link with HTMX attributes for SPA-like behavior."
```

``` python
def create_navbar(
    title:str, # Application title
    nav_items:List[Tuple[str, Any]], # List of (label, route) tuples
    home_route:Optional[Any]=None, # Optional home route for title link
    theme_selector:bool=True, # Whether to include theme selector
    target_id:str=AppHtmlIds.MAIN_CONTENT, # HTMX target container ID
    **navbar_kwargs # Additional kwargs for navbar styling
) -> FT: # Navbar component
    "Create a responsive navigation bar with mobile dropdown menu."
```

### routing (`routing.ipynb`)

> Routing utilities for FastHTML applications

#### Import

``` python
from cjm_fasthtml_app_core.core.routing import (
    register_routes
)
```

#### Functions

```` python
def register_routes(
    app,  # FastHTML app instance
    *routers  # One or more APIRouter instances to register
) -> None
    """
    Register multiple APIRouter instances to a FastHTML app at once.
    
    This is a convenience function that replaces multiple `.to_app(app)` calls
    with a single function call.
    
    Example:
        ```python
        from fasthtml.common import *
        from cjm_fasthtml_app_core.core.routing import register_routes
        
        # Create routers
        main_ar = APIRouter(prefix="/")
        settings_ar = APIRouter(prefix="/settings")
        api_ar = APIRouter(prefix="/api")
        
        # Instead of:
        # main_ar.to_app(app)
        # settings_ar.to_app(app)
        # api_ar.to_app(app)
        
        # Do this:
        register_routes(app, main_ar, settings_ar, api_ar)
        ```
    """
````
