cacao


Namecacao JSON
Version 1.0.46 PyPI version JSON
download
home_pagehttps://github.com/cacao-research/Cacao
SummaryCacao is a high-performance, reactive web framework for Python, designed to simplify building interactive dashboards and data apps.
upload_time2025-07-18 04:56:42
maintainerNone
docs_urlNone
authorJuan Denis
requires_python>=3.7
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            ![image](https://github.com/user-attachments/assets/830a00ca-7948-42ff-9196-adb58357c536)

# ๐Ÿซ Cacao

[![PyPI Version](https://img.shields.io/pypi/v/Cacao)](https://pypi.org/project/Cacao/)
[![Downloads](https://static.pepy.tech/badge/Cacao)](https://pepy.tech/project/Cacao)
[![Python Versions](https://img.shields.io/pypi/pyversions/Cacao)](https://pypi.org/project/Cacao/)
[![License](https://img.shields.io/pypi/l/Cacao)](https://github.com/cacao-research/cacao/blob/main/LICENSE)
[![Build](https://img.shields.io/github/actions/workflow/status/cacao-research/cacao/publish.yml?branch=main)](https://github.com/cacao-research/cacao/actions)
[![GitHub Stars](https://img.shields.io/github/stars/cacao-research/cacao?style=social)](https://github.com/cacao-research/cacao)

---
## Description

Cacao is a modern, high-performance web framework for building reactive Python apps with real-time capabilities. Designed for developers who want full control without sacrificing simplicity, Cacao blends a clean decorator-based API with a powerful component and state management system โ€” all backed by JSON-defined UIs and WebSocket-driven live updates.

Whether you're creating dashboards, internal tools, or interactive data apps, Cacao offers a fully Pythonic development experience with robust features like hot reload, real-time communication, and seamless frontend-backend integration.

> **โš ๏ธ Warning:** Cacao is currently in early development. Features and APIs are subject to change, and breaking changes may occur in future updates. Use with caution in production environments.

## ๐Ÿ—๏ธ Architecture

### Core System
- **Decorator-based Routing**: Simple `@mix` decorators for defining UI routes
- **Hot Reload**: Real-time UI updates with WebSocket-based hot reload
- **JSON UI Definitions**: Define UIs using pure Python dictionaries
- **State Management**: Reactive state handling with automatic UI updates
- **Component System**: Create reusable, composable UI components with type-based state isolation
- **Progressive Web App (PWA)**: Built-in PWA capabilities with offline support
- **Session Management**: Persistent session state across page refreshes
- **Desktop Application Mode**: Run Cacao apps as native desktop applications
- **Hybrid Mode Support**: Run the same codebase in both web and desktop environments

### Extensions
- **Authentication**: Built-in auth system with multiple provider support
- **Plugins**: Extensible plugin system for custom functionality
- **Metrics**: Performance monitoring and analytics
- **Background Tasks**: Async task queue for long-running operations

## โœจ Features

- **Reactive UI**: Build interactive dashboards and data apps with ease
- **Hot Reload**: See your changes instantly with the built-in hot reload system
- **Component-Based**: Create reusable UI components with isolated state
- **Python-Powered**: Use Python for both frontend and backend logic
- **Real-time Updates**: WebSocket-based live updates
- **Theme Support**: Customizable themes with hot-reload support
- **Type Safety**: Full TypeScript-like type hints in Python
- **Developer Tools**: Built-in debugging and development tools
- **PWA Support**: Make your app installable with offline capabilities
- **Session Persistence**: Maintain state across page refreshes
- **Desktop Mode**: Run as a standalone desktop application
- **React Integration**: Use React components from npm packages directly in your Cacao apps
- **Hybrid Mode**: Switch between web and desktop modes with the same codebase
- **Global Theme System**: Consistent styling with theme inheritance
- **Component-Level Theming**: Override global themes at component level

## ๐Ÿงฉ Component State Management

Cacao provides advanced component state isolation:

- Each component can have its own unique state
- Components are identified by a `component_type`
- Server-side routing ensures state updates are component-specific
- Prevents unintended state sharing between components

```python
from cacao import mix, State, Component
from datetime import datetime

# Separate states for different components
counter_state = State(0)
timestamp_state = State(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

class Counter(Component):
    def __init__(self):
        super().__init__()
        self.component_type = "counter"  # Add component type
    
    def render(self, ui_state=None):
        counter_value = self._get_counter_value(ui_state)
        return {
            "type": "section",
            "component_type": self.component_type,
            "props": {
                "children": [
                    {
                        "type": "text",
                        "props": {"content": f"Counter: {counter_value}"}
                    },
                    {
                        "type": "button",
                        "props": {
                            "label": "Increment",
                            "action": "increment_counter"
                        }
                    }
                ]
            }
        }
```

## ๐Ÿ“ Project Structure

```
cacao/
โ”œโ”€โ”€ core/                   # Core framework functionality
โ”‚   โ”œโ”€โ”€ decorators.py      # Route decorators and registry
โ”‚   โ”œโ”€โ”€ server.py          # HTTP and WebSocket servers
โ”‚   โ”œโ”€โ”€ state.py           # State management system
โ”‚   โ”œโ”€โ”€ diffing.py         # UI diffing algorithm
โ”‚   โ”œโ”€โ”€ pwa.py            # PWA support functionality
โ”‚   โ”œโ”€โ”€ session.py        # Session persistence management
โ”‚   โ””โ”€โ”€ static/            # Static assets
โ”‚       โ”œโ”€โ”€ js/            # Client-side JavaScript
โ”‚       โ”œโ”€โ”€ css/           # Stylesheets
โ”‚       โ””โ”€โ”€ icons/         # PWA icons
โ”œโ”€โ”€ desktop.py            # Desktop application support
โ”œโ”€โ”€ ui/                    # UI component system
โ”‚   โ”œโ”€โ”€ components/        # Built-in components
โ”‚   โ”‚   โ”œโ”€โ”€ base.py       # Base component classes
โ”‚   โ”‚   โ”œโ”€โ”€ inputs.py     # Form inputs
โ”‚   โ”‚   โ”œโ”€โ”€ data.py       # Data display components
โ”‚   โ”‚   โ””โ”€โ”€ layout.py     # Layout components
โ”‚   โ””โ”€โ”€ themes/           # Theming system
โ”œโ”€โ”€ extensions/           # Framework extensions
โ”‚   โ”œโ”€โ”€ auth/            # Authentication system
โ”‚   โ”œโ”€โ”€ plugins/         # Plugin system
โ”‚   โ””โ”€โ”€ metrics/         # Performance metrics
โ”œโ”€โ”€ utilities/           # Helper utilities
โ”‚   โ”œโ”€โ”€ cache.py        # Caching system
โ”‚   โ””โ”€โ”€ task_queue.py   # Background task queue
โ””โ”€โ”€ cli/                # Command-line tools
```

## ๐Ÿš€ Quick Start

### Simple Example

Here's a minimal example showing how to create a basic Cacao application:

```python
import cacao

app = cacao.App()

@app.mix("/")
def home():
    return {
        "type": "div",
        "props": {
            "style": {
                "padding": "20px",
                "fontFamily": "Arial, sans-serif"
            }
        },
        "children": [
            {
                "type": "h1",
                "props": {
                    "content": "Welcome to Cacao",
                    "style": {
                        "color": "#f0be9b",
                        "marginBottom": "20px"
                    }
                }
            },
            {
                "type": "p",
                "props": {
                    "content": "A deliciously simple web framework!",
                    "style": {
                        "color": "#D4A76A"
                    }
                }
            }
        ]
    }

if __name__ == "__main__":
    app.brew()  # Run the app like brewing hot chocolate!
```

### Advanced Layout Example

For more complex applications, Cacao provides layout components like `SidebarLayout`:

```python
from cacao import App
from cacao.ui.components.sidebar_layout import SidebarLayout

app = App()

class DashboardPage:
    def render(self):
        return {
            "type": "div",
            "props": {
                "style": {"padding": "20px"},
                "children": [
                    {
                        "type": "div",
                        "props": {
                            "style": {
                                "display": "grid",
                                "gridTemplateColumns": "repeat(2, 1fr)",
                                "gap": "20px"
                            },
                            "children": [
                                {
                                    "type": "div",
                                    "props": {
                                        "style": {
                                            "backgroundColor": "#F5F5F5",
                                            "borderRadius": "8px",
                                            "padding": "20px"
                                        },
                                        "children": [
                                            {
                                                "type": "h2",
                                                "props": {
                                                    "content": "Users",
                                                    "style": {"color": "#6B4226"}
                                                }
                                            },
                                            {
                                                "type": "text",
                                                "props": {
                                                    "content": "1,234",
                                                    "style": {
                                                        "fontSize": "24px",
                                                        "fontWeight": "bold"
                                                    }
                                                }
                                            }
                                        ]
                                    }
                                }
                            ]
                        }
                    }
                ]
            }
        }

# Define navigation structure
nav_items = [
    {"id": "home", "label": "Home", "icon": "H"},
    {"id": "dashboard", "label": "Dashboard", "icon": "D"},
    {"id": "settings", "label": "Settings", "icon": "S"}
]

# Create layout with components
sidebar_layout = SidebarLayout(
    nav_items=nav_items,
    content_components={
        "dashboard": DashboardPage()
    },
    app_title="My Cacao App"
)

@app.mix("/")
def home():
    return sidebar_layout.render()

if __name__ == "__main__":
    app.brew(
        type="desktop",  # Can be "web" or "desktop"
        title="Cacao Example",
        width=800,
        height=600,
        resizable=True
    )
```

## ๐Ÿ› ๏ธ Creating UI Components

Cacao allows you to define UI components with isolated state management and automatic hot reload. For a complete example of component creation and state management, check out `examples/counter_example.py` which demonstrates:

- Component-specific state isolation using `component_type`
- Event handling with `@app.event` decorators
- State management with `State` class
- Type-safe component implementations

For example, see how a counter component is created:

```python
from cacao import App, State, Component

# Define state and create component - See examples/counter_example.py for full implementation
counter_state = State(0)

class Counter(Component):
    def __init__(self) -> None:
        super().__init__()
        self.component_type = "counter"  # Enable state isolation
```

## ๐Ÿ”„ Hot Reload

Cacao includes a powerful hot reload system that automatically refreshes your UI when you make changes to your code:

1. Start the development server
2. Open your browser to http://localhost:1634
3. Edit your UI code in `main.py`
4. Watch as your changes appear instantly with a smooth brown overlay animation

### Manual Refresh

If you need to force a refresh, you can:

- Click the refresh button in the bottom-right corner of the page
- Press Ctrl+R (or Cmd+R) to force a refresh
- Press F5 to reload the page completely

## ๐Ÿ“Š State Management

Cacao provides a flexible, component-aware state management system:

```python
from cacao import State
from datetime import datetime

# Create separate states for different components
counter_state = State(0)
timestamp_state = State(datetime.now())

# Update state values
counter_state.update(5)
timestamp_state.update(datetime.now())

# Component-specific state updates via event handlers
@mix.event("increment_counter")
async def handle_increment(event):
    counter_state.update(counter_state.value + 1)
    print(f"Counter changed to: {counter_state.value}")

@mix.event("refresh_timestamp")
async def handle_refresh(event):
    timestamp_state.update(datetime.now())
    print(f"Timestamp updated to: {timestamp_state.value}")
```

## ๐Ÿงฑ Component System

Create reusable components with the Component base class:

```python
from cacao import Component
from typing import Dict, Any, Optional

class MyComponent(Component):
    def __init__(self, title: str):
        """Initialize the component with a title."""
        super().__init__()
        self.title = title
        self.component_type = "my-component"  # Unique component type for state isolation
    
    def render(self, ui_state: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        """
        Render the component.
        
        Args:
            ui_state: Optional state from the UI definition
            
        Returns:
            JSON UI definition for the component
        """
        return {
            "type": "section",
            "component_type": self.component_type,  # Include component type in output
            "props": {
                "children": [
                    {
                        "type": "text",
                        "props": {"content": self.title}
                    },
                    {
                        "type": "button",
                        "props": {
                            "label": "Click Me",
                            "action": "component_action",
                            "params": {"component_id": id(self)}  # Pass component ID in action
                        }
                    }
                ]
            }
        }
```

## ๐ŸŒ Progressive Web App (PWA) Support

Cacao includes built-in PWA capabilities, allowing your applications to be installed on devices and work offline:

```python
from cacao import run
from cacao.core.server import CacaoServer

# Run with PWA support enabled
server = CacaoServer(
    verbose=True,
    enable_pwa=True,  # Enable PWA support
    persist_sessions=True  # Enable session persistence
)
server.run()
```

### PWA Configuration

The PWA support can be customized in your cacao.json configuration:

```json
{
    "pwa": {
        "name": "Cacao App",
        "short_name": "Cacao",
        "description": "A Cacao Progressive Web App",
        "theme_color": "#6B4226",
        "background_color": "#F5F5F5",
        "display": "standalone",
        "start_url": "/"
    }
}
```

### PWA Features

- **Offline Support**: Applications continue to work without an internet connection
- **Installation**: Users can install your app on mobile and desktop devices
- **Service Worker**: Automatic service worker generation for resource caching
- **PWA Manifest**: Auto-generated manifest.json with customizable options

## ๐Ÿ’พ Session Management

Cacao's session management system provides persistent state across page refreshes:

```python
from cacao import run

# Run with session persistence
run(persist_sessions=True, session_storage="memory")  # or "file"
```

### Session Storage Options

- **Memory Storage**: Sessions are stored in memory (default, cleared on server restart)
- **File Storage**: Sessions are stored in files (persists through server restarts)

### Session Features

- **Automatic State Persistence**: App state automatically persists across page refreshes
- **Session Expiration**: Configurable session timeout (defaults to 24 hours)
- **Cross-Tab State**: State can be shared across browser tabs (same session)
- **Security**: Sessions are secured with HTTP-only cookies

## ๐Ÿ–ฅ๏ธ Desktop Application Mode

Cacao's unified `brew()` method now supports both web and desktop applications through a single interface:

```python
# Run as web application
app.brew()

# Run as desktop application
app.brew(
    type="desktop",
    title="My Desktop App",
    width=800,
    height=600,
    resizable=True,
    fullscreen=False
)
```


### Desktop Features

- **Native Window**: Runs in a native OS window without browser UI
- **Window Controls**: Customize window size, title, and behavior
- **Automatic Server**: Built-in Cacao server runs in the background
- **Cross-Platform**: Works on Windows, macOS, and Linux
- **Hybrid Support**: Same codebase can run in both web and desktop modes


## โš›๏ธ React Integration

Cacao provides seamless integration with React components from npm packages:

```python
from cacao import App
from cacao.ui import ReactComponent
from cacao.extensions.react_extension import ReactExtension

# Create app with React extension
app = App(extensions=[ReactExtension()])

@app.mix("/")
def home():
    return {
        "type": "div",
        "props": {
            "children": [
                {
                    "type": "h1",
                    "props": {
                        "content": "CodeMirror Example"
                    }
                },
                # Use CodeMirror React component
                ReactComponent(
                    package="codemirror",
                    component="CodeMirror",
                    props={
                        "value": "const hello = 'world';",
                        "options": {
                            "mode": "javascript",
                            "theme": "material",
                            "lineNumbers": True
                        }
                    },
                    css=["lib/codemirror.css", "theme/material.css"]
                ).render()
            ]
        }
    }
```

### React Integration Features

- **NPM Package Integration**: Use React components from npm packages directly
- **Dynamic Loading**: Components are loaded on-demand from CDNs
- **Props Passing**: Pass props to React components from Python
- **Event Handling**: Handle events from React components in Python
- **CSS Loading**: Automatically load CSS files for React components
- **Multiple Components**: Use multiple React components in the same app

For more details, see [React Integration Guide](docs/REACT_INTEGRATION.md) and check out the examples in `examples/react_component_example.py` and `examples/advanced_react_example.py`.


### ๐ŸŽจ Theme System

Cacao now includes a powerful global theme system that allows consistent styling across your entire application:

### Setting a Global Theme

```python
import cacao

app = cacao.App()

# Define your custom theme
my_theme = {
    "colors": {
        "primary": "#2196F3",
        "secondary": "#03A9F4",
        "background": "#F0F8FF",
        "text": "#2C3E50",
        "accent": "#FF5722",
        "sidebar_bg": "#1A365D",
        "sidebar_header_bg": "#2C5282",
        "content_bg": "#F0F8FF",
        "card_bg": "#FFFFFF",
        "border_color": "#BEE3F8"
    }
}

# Apply theme when starting the app
app.brew(
    type="web",
    theme=my_theme
)
```

### Example Implementation

Check out the `examples/sidebar_layout_example.py` for a practical implementation of hybrid mode:

```bash
# Run in web browser mode
python examples/sidebar_layout_example.py

# Run in desktop mode
python examples/sidebar_layout_example.py --mode desktop
```

This example demonstrates how to create a multi-page application using the SidebarLayout component that can run in either web or desktop mode with identical functionality.

## ๐Ÿงช Testing Framework

Cacao includes a comprehensive testing framework built on pytest, making it easy to validate your application's behavior:

```python
# Run all tests with the test manager
python test.py

# Run specific test files
python test.py test/test_state.py test/test_server.py

# Run tests matching a pattern
python test.py -k "component"
```

### Test Organization

Tests are organized by subsystem for clear separation of concerns:

- **`test_components.py`**: Component creation and rendering
- **`test_integration.py`**: Component and state integration
- **`test_plugins.py`**: Plugin system functionality
- **`test_pwa.py`**: Progressive Web App features
- **`test_server.py`**: HTTP and WebSocket server
- **`test_session.py`**: Session management and persistence
- **`test_state.py`**: Reactive state management
- **`test_ui_components.py`**: UI component system

### Writing Tests

Cacao follows the Arrange-Act-Assert pattern for clear, readable tests:

```python
def test_state_reactivity():
    # Arrange
    counter = State(0)
    
    # Act
    counter.set(5)
    
    # Assert
    assert counter.value == 5

def test_component_rendering():
    # Arrange
    button = Button(label="Click me")
    
    # Act
    rendered = button.render()
    
    # Assert
    assert rendered["type"] == "button"
    assert rendered["props"]["label"] == "Click me"
```

### Test Fixtures

The testing framework provides useful fixtures to simplify testing:

```python
@pytest.fixture
def test_state():
    """Fixture for creating a test state instance"""
    return State(initial_value=0)

@pytest.fixture
def test_component():
    """Fixture for creating a basic test component"""
    class TestComponent(Component):
        def render(self):
            return {
                "type": "div",
                "props": {"content": "Test Component"}
            }
    return TestComponent()
```

Use the test runner to automatically discover and execute tests while suppressing warnings and providing clear output.

## ๐Ÿ“ธ Screenshots

<img width="1184" alt="image" src="https://github.com/user-attachments/assets/bfe66a0b-1712-49cd-a617-43c16590a5b9" />

<img width="1241" alt="image" src="https://github.com/user-attachments/assets/9dfd5cc8-b547-4a43-bcf0-acc322bf1e22" />

## โ“ Troubleshooting

If hot reload isn't working:

1. Check the browser console for errors
2. Make sure the WebSocket connection is established
3. Try using the manual refresh button
4. Restart the server with verbose logging: `python -m cacao serve -v`

## ๐Ÿ‘ฅ Contributing

Contributions are welcome! Please read our contributing guidelines for details.

## ๐Ÿ“„ License

MIT

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/cacao-research/Cacao",
    "name": "cacao",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": null,
    "keywords": null,
    "author": "Juan Denis",
    "author_email": "Juan@vene.co",
    "download_url": "https://files.pythonhosted.org/packages/32/b9/cb68e6bcadf833c03618753fb581d5f4179a9e86a31a4c7dc373960d3229/cacao-1.0.46.tar.gz",
    "platform": null,
    "description": "![image](https://github.com/user-attachments/assets/830a00ca-7948-42ff-9196-adb58357c536)\n\n# \ud83c\udf6b Cacao\n\n[![PyPI Version](https://img.shields.io/pypi/v/Cacao)](https://pypi.org/project/Cacao/)\n[![Downloads](https://static.pepy.tech/badge/Cacao)](https://pepy.tech/project/Cacao)\n[![Python Versions](https://img.shields.io/pypi/pyversions/Cacao)](https://pypi.org/project/Cacao/)\n[![License](https://img.shields.io/pypi/l/Cacao)](https://github.com/cacao-research/cacao/blob/main/LICENSE)\n[![Build](https://img.shields.io/github/actions/workflow/status/cacao-research/cacao/publish.yml?branch=main)](https://github.com/cacao-research/cacao/actions)\n[![GitHub Stars](https://img.shields.io/github/stars/cacao-research/cacao?style=social)](https://github.com/cacao-research/cacao)\n\n---\n## Description\n\nCacao is a modern, high-performance web framework for building reactive Python apps with real-time capabilities. Designed for developers who want full control without sacrificing simplicity, Cacao blends a clean decorator-based API with a powerful component and state management system \u2014 all backed by JSON-defined UIs and WebSocket-driven live updates.\n\nWhether you're creating dashboards, internal tools, or interactive data apps, Cacao offers a fully Pythonic development experience with robust features like hot reload, real-time communication, and seamless frontend-backend integration.\n\n> **\u26a0\ufe0f Warning:** Cacao is currently in early development. Features and APIs are subject to change, and breaking changes may occur in future updates. Use with caution in production environments.\n\n## \ud83c\udfd7\ufe0f Architecture\n\n### Core System\n- **Decorator-based Routing**: Simple `@mix` decorators for defining UI routes\n- **Hot Reload**: Real-time UI updates with WebSocket-based hot reload\n- **JSON UI Definitions**: Define UIs using pure Python dictionaries\n- **State Management**: Reactive state handling with automatic UI updates\n- **Component System**: Create reusable, composable UI components with type-based state isolation\n- **Progressive Web App (PWA)**: Built-in PWA capabilities with offline support\n- **Session Management**: Persistent session state across page refreshes\n- **Desktop Application Mode**: Run Cacao apps as native desktop applications\n- **Hybrid Mode Support**: Run the same codebase in both web and desktop environments\n\n### Extensions\n- **Authentication**: Built-in auth system with multiple provider support\n- **Plugins**: Extensible plugin system for custom functionality\n- **Metrics**: Performance monitoring and analytics\n- **Background Tasks**: Async task queue for long-running operations\n\n## \u2728 Features\n\n- **Reactive UI**: Build interactive dashboards and data apps with ease\n- **Hot Reload**: See your changes instantly with the built-in hot reload system\n- **Component-Based**: Create reusable UI components with isolated state\n- **Python-Powered**: Use Python for both frontend and backend logic\n- **Real-time Updates**: WebSocket-based live updates\n- **Theme Support**: Customizable themes with hot-reload support\n- **Type Safety**: Full TypeScript-like type hints in Python\n- **Developer Tools**: Built-in debugging and development tools\n- **PWA Support**: Make your app installable with offline capabilities\n- **Session Persistence**: Maintain state across page refreshes\n- **Desktop Mode**: Run as a standalone desktop application\n- **React Integration**: Use React components from npm packages directly in your Cacao apps\n- **Hybrid Mode**: Switch between web and desktop modes with the same codebase\n- **Global Theme System**: Consistent styling with theme inheritance\n- **Component-Level Theming**: Override global themes at component level\n\n## \ud83e\udde9 Component State Management\n\nCacao provides advanced component state isolation:\n\n- Each component can have its own unique state\n- Components are identified by a `component_type`\n- Server-side routing ensures state updates are component-specific\n- Prevents unintended state sharing between components\n\n```python\nfrom cacao import mix, State, Component\nfrom datetime import datetime\n\n# Separate states for different components\ncounter_state = State(0)\ntimestamp_state = State(datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"))\n\nclass Counter(Component):\n    def __init__(self):\n        super().__init__()\n        self.component_type = \"counter\"  # Add component type\n    \n    def render(self, ui_state=None):\n        counter_value = self._get_counter_value(ui_state)\n        return {\n            \"type\": \"section\",\n            \"component_type\": self.component_type,\n            \"props\": {\n                \"children\": [\n                    {\n                        \"type\": \"text\",\n                        \"props\": {\"content\": f\"Counter: {counter_value}\"}\n                    },\n                    {\n                        \"type\": \"button\",\n                        \"props\": {\n                            \"label\": \"Increment\",\n                            \"action\": \"increment_counter\"\n                        }\n                    }\n                ]\n            }\n        }\n```\n\n## \ud83d\udcc1 Project Structure\n\n```\ncacao/\n\u251c\u2500\u2500 core/                   # Core framework functionality\n\u2502   \u251c\u2500\u2500 decorators.py      # Route decorators and registry\n\u2502   \u251c\u2500\u2500 server.py          # HTTP and WebSocket servers\n\u2502   \u251c\u2500\u2500 state.py           # State management system\n\u2502   \u251c\u2500\u2500 diffing.py         # UI diffing algorithm\n\u2502   \u251c\u2500\u2500 pwa.py            # PWA support functionality\n\u2502   \u251c\u2500\u2500 session.py        # Session persistence management\n\u2502   \u2514\u2500\u2500 static/            # Static assets\n\u2502       \u251c\u2500\u2500 js/            # Client-side JavaScript\n\u2502       \u251c\u2500\u2500 css/           # Stylesheets\n\u2502       \u2514\u2500\u2500 icons/         # PWA icons\n\u251c\u2500\u2500 desktop.py            # Desktop application support\n\u251c\u2500\u2500 ui/                    # UI component system\n\u2502   \u251c\u2500\u2500 components/        # Built-in components\n\u2502   \u2502   \u251c\u2500\u2500 base.py       # Base component classes\n\u2502   \u2502   \u251c\u2500\u2500 inputs.py     # Form inputs\n\u2502   \u2502   \u251c\u2500\u2500 data.py       # Data display components\n\u2502   \u2502   \u2514\u2500\u2500 layout.py     # Layout components\n\u2502   \u2514\u2500\u2500 themes/           # Theming system\n\u251c\u2500\u2500 extensions/           # Framework extensions\n\u2502   \u251c\u2500\u2500 auth/            # Authentication system\n\u2502   \u251c\u2500\u2500 plugins/         # Plugin system\n\u2502   \u2514\u2500\u2500 metrics/         # Performance metrics\n\u251c\u2500\u2500 utilities/           # Helper utilities\n\u2502   \u251c\u2500\u2500 cache.py        # Caching system\n\u2502   \u2514\u2500\u2500 task_queue.py   # Background task queue\n\u2514\u2500\u2500 cli/                # Command-line tools\n```\n\n## \ud83d\ude80 Quick Start\n\n### Simple Example\n\nHere's a minimal example showing how to create a basic Cacao application:\n\n```python\nimport cacao\n\napp = cacao.App()\n\n@app.mix(\"/\")\ndef home():\n    return {\n        \"type\": \"div\",\n        \"props\": {\n            \"style\": {\n                \"padding\": \"20px\",\n                \"fontFamily\": \"Arial, sans-serif\"\n            }\n        },\n        \"children\": [\n            {\n                \"type\": \"h1\",\n                \"props\": {\n                    \"content\": \"Welcome to Cacao\",\n                    \"style\": {\n                        \"color\": \"#f0be9b\",\n                        \"marginBottom\": \"20px\"\n                    }\n                }\n            },\n            {\n                \"type\": \"p\",\n                \"props\": {\n                    \"content\": \"A deliciously simple web framework!\",\n                    \"style\": {\n                        \"color\": \"#D4A76A\"\n                    }\n                }\n            }\n        ]\n    }\n\nif __name__ == \"__main__\":\n    app.brew()  # Run the app like brewing hot chocolate!\n```\n\n### Advanced Layout Example\n\nFor more complex applications, Cacao provides layout components like `SidebarLayout`:\n\n```python\nfrom cacao import App\nfrom cacao.ui.components.sidebar_layout import SidebarLayout\n\napp = App()\n\nclass DashboardPage:\n    def render(self):\n        return {\n            \"type\": \"div\",\n            \"props\": {\n                \"style\": {\"padding\": \"20px\"},\n                \"children\": [\n                    {\n                        \"type\": \"div\",\n                        \"props\": {\n                            \"style\": {\n                                \"display\": \"grid\",\n                                \"gridTemplateColumns\": \"repeat(2, 1fr)\",\n                                \"gap\": \"20px\"\n                            },\n                            \"children\": [\n                                {\n                                    \"type\": \"div\",\n                                    \"props\": {\n                                        \"style\": {\n                                            \"backgroundColor\": \"#F5F5F5\",\n                                            \"borderRadius\": \"8px\",\n                                            \"padding\": \"20px\"\n                                        },\n                                        \"children\": [\n                                            {\n                                                \"type\": \"h2\",\n                                                \"props\": {\n                                                    \"content\": \"Users\",\n                                                    \"style\": {\"color\": \"#6B4226\"}\n                                                }\n                                            },\n                                            {\n                                                \"type\": \"text\",\n                                                \"props\": {\n                                                    \"content\": \"1,234\",\n                                                    \"style\": {\n                                                        \"fontSize\": \"24px\",\n                                                        \"fontWeight\": \"bold\"\n                                                    }\n                                                }\n                                            }\n                                        ]\n                                    }\n                                }\n                            ]\n                        }\n                    }\n                ]\n            }\n        }\n\n# Define navigation structure\nnav_items = [\n    {\"id\": \"home\", \"label\": \"Home\", \"icon\": \"H\"},\n    {\"id\": \"dashboard\", \"label\": \"Dashboard\", \"icon\": \"D\"},\n    {\"id\": \"settings\", \"label\": \"Settings\", \"icon\": \"S\"}\n]\n\n# Create layout with components\nsidebar_layout = SidebarLayout(\n    nav_items=nav_items,\n    content_components={\n        \"dashboard\": DashboardPage()\n    },\n    app_title=\"My Cacao App\"\n)\n\n@app.mix(\"/\")\ndef home():\n    return sidebar_layout.render()\n\nif __name__ == \"__main__\":\n    app.brew(\n        type=\"desktop\",  # Can be \"web\" or \"desktop\"\n        title=\"Cacao Example\",\n        width=800,\n        height=600,\n        resizable=True\n    )\n```\n\n## \ud83d\udee0\ufe0f Creating UI Components\n\nCacao allows you to define UI components with isolated state management and automatic hot reload. For a complete example of component creation and state management, check out `examples/counter_example.py` which demonstrates:\n\n- Component-specific state isolation using `component_type`\n- Event handling with `@app.event` decorators\n- State management with `State` class\n- Type-safe component implementations\n\nFor example, see how a counter component is created:\n\n```python\nfrom cacao import App, State, Component\n\n# Define state and create component - See examples/counter_example.py for full implementation\ncounter_state = State(0)\n\nclass Counter(Component):\n    def __init__(self) -> None:\n        super().__init__()\n        self.component_type = \"counter\"  # Enable state isolation\n```\n\n## \ud83d\udd04 Hot Reload\n\nCacao includes a powerful hot reload system that automatically refreshes your UI when you make changes to your code:\n\n1. Start the development server\n2. Open your browser to http://localhost:1634\n3. Edit your UI code in `main.py`\n4. Watch as your changes appear instantly with a smooth brown overlay animation\n\n### Manual Refresh\n\nIf you need to force a refresh, you can:\n\n- Click the refresh button in the bottom-right corner of the page\n- Press Ctrl+R (or Cmd+R) to force a refresh\n- Press F5 to reload the page completely\n\n## \ud83d\udcca State Management\n\nCacao provides a flexible, component-aware state management system:\n\n```python\nfrom cacao import State\nfrom datetime import datetime\n\n# Create separate states for different components\ncounter_state = State(0)\ntimestamp_state = State(datetime.now())\n\n# Update state values\ncounter_state.update(5)\ntimestamp_state.update(datetime.now())\n\n# Component-specific state updates via event handlers\n@mix.event(\"increment_counter\")\nasync def handle_increment(event):\n    counter_state.update(counter_state.value + 1)\n    print(f\"Counter changed to: {counter_state.value}\")\n\n@mix.event(\"refresh_timestamp\")\nasync def handle_refresh(event):\n    timestamp_state.update(datetime.now())\n    print(f\"Timestamp updated to: {timestamp_state.value}\")\n```\n\n## \ud83e\uddf1 Component System\n\nCreate reusable components with the Component base class:\n\n```python\nfrom cacao import Component\nfrom typing import Dict, Any, Optional\n\nclass MyComponent(Component):\n    def __init__(self, title: str):\n        \"\"\"Initialize the component with a title.\"\"\"\n        super().__init__()\n        self.title = title\n        self.component_type = \"my-component\"  # Unique component type for state isolation\n    \n    def render(self, ui_state: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:\n        \"\"\"\n        Render the component.\n        \n        Args:\n            ui_state: Optional state from the UI definition\n            \n        Returns:\n            JSON UI definition for the component\n        \"\"\"\n        return {\n            \"type\": \"section\",\n            \"component_type\": self.component_type,  # Include component type in output\n            \"props\": {\n                \"children\": [\n                    {\n                        \"type\": \"text\",\n                        \"props\": {\"content\": self.title}\n                    },\n                    {\n                        \"type\": \"button\",\n                        \"props\": {\n                            \"label\": \"Click Me\",\n                            \"action\": \"component_action\",\n                            \"params\": {\"component_id\": id(self)}  # Pass component ID in action\n                        }\n                    }\n                ]\n            }\n        }\n```\n\n## \ud83c\udf10 Progressive Web App (PWA) Support\n\nCacao includes built-in PWA capabilities, allowing your applications to be installed on devices and work offline:\n\n```python\nfrom cacao import run\nfrom cacao.core.server import CacaoServer\n\n# Run with PWA support enabled\nserver = CacaoServer(\n    verbose=True,\n    enable_pwa=True,  # Enable PWA support\n    persist_sessions=True  # Enable session persistence\n)\nserver.run()\n```\n\n### PWA Configuration\n\nThe PWA support can be customized in your cacao.json configuration:\n\n```json\n{\n    \"pwa\": {\n        \"name\": \"Cacao App\",\n        \"short_name\": \"Cacao\",\n        \"description\": \"A Cacao Progressive Web App\",\n        \"theme_color\": \"#6B4226\",\n        \"background_color\": \"#F5F5F5\",\n        \"display\": \"standalone\",\n        \"start_url\": \"/\"\n    }\n}\n```\n\n### PWA Features\n\n- **Offline Support**: Applications continue to work without an internet connection\n- **Installation**: Users can install your app on mobile and desktop devices\n- **Service Worker**: Automatic service worker generation for resource caching\n- **PWA Manifest**: Auto-generated manifest.json with customizable options\n\n## \ud83d\udcbe Session Management\n\nCacao's session management system provides persistent state across page refreshes:\n\n```python\nfrom cacao import run\n\n# Run with session persistence\nrun(persist_sessions=True, session_storage=\"memory\")  # or \"file\"\n```\n\n### Session Storage Options\n\n- **Memory Storage**: Sessions are stored in memory (default, cleared on server restart)\n- **File Storage**: Sessions are stored in files (persists through server restarts)\n\n### Session Features\n\n- **Automatic State Persistence**: App state automatically persists across page refreshes\n- **Session Expiration**: Configurable session timeout (defaults to 24 hours)\n- **Cross-Tab State**: State can be shared across browser tabs (same session)\n- **Security**: Sessions are secured with HTTP-only cookies\n\n## \ud83d\udda5\ufe0f Desktop Application Mode\n\nCacao's unified `brew()` method now supports both web and desktop applications through a single interface:\n\n```python\n# Run as web application\napp.brew()\n\n# Run as desktop application\napp.brew(\n    type=\"desktop\",\n    title=\"My Desktop App\",\n    width=800,\n    height=600,\n    resizable=True,\n    fullscreen=False\n)\n```\n\n\n### Desktop Features\n\n- **Native Window**: Runs in a native OS window without browser UI\n- **Window Controls**: Customize window size, title, and behavior\n- **Automatic Server**: Built-in Cacao server runs in the background\n- **Cross-Platform**: Works on Windows, macOS, and Linux\n- **Hybrid Support**: Same codebase can run in both web and desktop modes\n\n\n## \u269b\ufe0f React Integration\n\nCacao provides seamless integration with React components from npm packages:\n\n```python\nfrom cacao import App\nfrom cacao.ui import ReactComponent\nfrom cacao.extensions.react_extension import ReactExtension\n\n# Create app with React extension\napp = App(extensions=[ReactExtension()])\n\n@app.mix(\"/\")\ndef home():\n    return {\n        \"type\": \"div\",\n        \"props\": {\n            \"children\": [\n                {\n                    \"type\": \"h1\",\n                    \"props\": {\n                        \"content\": \"CodeMirror Example\"\n                    }\n                },\n                # Use CodeMirror React component\n                ReactComponent(\n                    package=\"codemirror\",\n                    component=\"CodeMirror\",\n                    props={\n                        \"value\": \"const hello = 'world';\",\n                        \"options\": {\n                            \"mode\": \"javascript\",\n                            \"theme\": \"material\",\n                            \"lineNumbers\": True\n                        }\n                    },\n                    css=[\"lib/codemirror.css\", \"theme/material.css\"]\n                ).render()\n            ]\n        }\n    }\n```\n\n### React Integration Features\n\n- **NPM Package Integration**: Use React components from npm packages directly\n- **Dynamic Loading**: Components are loaded on-demand from CDNs\n- **Props Passing**: Pass props to React components from Python\n- **Event Handling**: Handle events from React components in Python\n- **CSS Loading**: Automatically load CSS files for React components\n- **Multiple Components**: Use multiple React components in the same app\n\nFor more details, see [React Integration Guide](docs/REACT_INTEGRATION.md) and check out the examples in `examples/react_component_example.py` and `examples/advanced_react_example.py`.\n\n\n### \ud83c\udfa8 Theme System\n\nCacao now includes a powerful global theme system that allows consistent styling across your entire application:\n\n### Setting a Global Theme\n\n```python\nimport cacao\n\napp = cacao.App()\n\n# Define your custom theme\nmy_theme = {\n    \"colors\": {\n        \"primary\": \"#2196F3\",\n        \"secondary\": \"#03A9F4\",\n        \"background\": \"#F0F8FF\",\n        \"text\": \"#2C3E50\",\n        \"accent\": \"#FF5722\",\n        \"sidebar_bg\": \"#1A365D\",\n        \"sidebar_header_bg\": \"#2C5282\",\n        \"content_bg\": \"#F0F8FF\",\n        \"card_bg\": \"#FFFFFF\",\n        \"border_color\": \"#BEE3F8\"\n    }\n}\n\n# Apply theme when starting the app\napp.brew(\n    type=\"web\",\n    theme=my_theme\n)\n```\n\n### Example Implementation\n\nCheck out the `examples/sidebar_layout_example.py` for a practical implementation of hybrid mode:\n\n```bash\n# Run in web browser mode\npython examples/sidebar_layout_example.py\n\n# Run in desktop mode\npython examples/sidebar_layout_example.py --mode desktop\n```\n\nThis example demonstrates how to create a multi-page application using the SidebarLayout component that can run in either web or desktop mode with identical functionality.\n\n## \ud83e\uddea Testing Framework\n\nCacao includes a comprehensive testing framework built on pytest, making it easy to validate your application's behavior:\n\n```python\n# Run all tests with the test manager\npython test.py\n\n# Run specific test files\npython test.py test/test_state.py test/test_server.py\n\n# Run tests matching a pattern\npython test.py -k \"component\"\n```\n\n### Test Organization\n\nTests are organized by subsystem for clear separation of concerns:\n\n- **`test_components.py`**: Component creation and rendering\n- **`test_integration.py`**: Component and state integration\n- **`test_plugins.py`**: Plugin system functionality\n- **`test_pwa.py`**: Progressive Web App features\n- **`test_server.py`**: HTTP and WebSocket server\n- **`test_session.py`**: Session management and persistence\n- **`test_state.py`**: Reactive state management\n- **`test_ui_components.py`**: UI component system\n\n### Writing Tests\n\nCacao follows the Arrange-Act-Assert pattern for clear, readable tests:\n\n```python\ndef test_state_reactivity():\n    # Arrange\n    counter = State(0)\n    \n    # Act\n    counter.set(5)\n    \n    # Assert\n    assert counter.value == 5\n\ndef test_component_rendering():\n    # Arrange\n    button = Button(label=\"Click me\")\n    \n    # Act\n    rendered = button.render()\n    \n    # Assert\n    assert rendered[\"type\"] == \"button\"\n    assert rendered[\"props\"][\"label\"] == \"Click me\"\n```\n\n### Test Fixtures\n\nThe testing framework provides useful fixtures to simplify testing:\n\n```python\n@pytest.fixture\ndef test_state():\n    \"\"\"Fixture for creating a test state instance\"\"\"\n    return State(initial_value=0)\n\n@pytest.fixture\ndef test_component():\n    \"\"\"Fixture for creating a basic test component\"\"\"\n    class TestComponent(Component):\n        def render(self):\n            return {\n                \"type\": \"div\",\n                \"props\": {\"content\": \"Test Component\"}\n            }\n    return TestComponent()\n```\n\nUse the test runner to automatically discover and execute tests while suppressing warnings and providing clear output.\n\n## \ud83d\udcf8 Screenshots\n\n<img width=\"1184\" alt=\"image\" src=\"https://github.com/user-attachments/assets/bfe66a0b-1712-49cd-a617-43c16590a5b9\" />\n\n<img width=\"1241\" alt=\"image\" src=\"https://github.com/user-attachments/assets/9dfd5cc8-b547-4a43-bcf0-acc322bf1e22\" />\n\n## \u2753 Troubleshooting\n\nIf hot reload isn't working:\n\n1. Check the browser console for errors\n2. Make sure the WebSocket connection is established\n3. Try using the manual refresh button\n4. Restart the server with verbose logging: `python -m cacao serve -v`\n\n## \ud83d\udc65 Contributing\n\nContributions are welcome! Please read our contributing guidelines for details.\n\n## \ud83d\udcc4 License\n\nMIT\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Cacao is a high-performance, reactive web framework for Python, designed to simplify building interactive dashboards and data apps.",
    "version": "1.0.46",
    "project_urls": {
        "Homepage": "https://github.com/cacao-research/Cacao"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "0fd3035cd3ba9f773a8b8d3c7f39a7fb7caaa2f30256d452f2e26514370e6bc6",
                "md5": "c349f962f47651fa502d6c7efe664dfe",
                "sha256": "491619009f516d17d0332c5f18bf8badcd56c617b1e07156a7f0e0f1980bbd55"
            },
            "downloads": -1,
            "filename": "cacao-1.0.46-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "c349f962f47651fa502d6c7efe664dfe",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 1806987,
            "upload_time": "2025-07-18T04:56:41",
            "upload_time_iso_8601": "2025-07-18T04:56:41.415163Z",
            "url": "https://files.pythonhosted.org/packages/0f/d3/035cd3ba9f773a8b8d3c7f39a7fb7caaa2f30256d452f2e26514370e6bc6/cacao-1.0.46-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "32b9cb68e6bcadf833c03618753fb581d5f4179a9e86a31a4c7dc373960d3229",
                "md5": "d5e96a38af7dae1a8dd5923a51f11519",
                "sha256": "e41b929ab3e9571a88858997980fdf57ea3887862c25cd8e5322b13895ea98aa"
            },
            "downloads": -1,
            "filename": "cacao-1.0.46.tar.gz",
            "has_sig": false,
            "md5_digest": "d5e96a38af7dae1a8dd5923a51f11519",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 1784311,
            "upload_time": "2025-07-18T04:56:42",
            "upload_time_iso_8601": "2025-07-18T04:56:42.944898Z",
            "url": "https://files.pythonhosted.org/packages/32/b9/cb68e6bcadf833c03618753fb581d5f4179a9e86a31a4c7dc373960d3229/cacao-1.0.46.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-07-18 04:56:42",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "cacao-research",
    "github_project": "Cacao",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [],
    "lcname": "cacao"
}
        
Elapsed time: 0.41182s