Chart Components

Main Chart Functions

Component Implementation

Component initialization for Streamlit Lightweight Charts Pro.

This module handles the initialization of the Streamlit custom component that enables TradingView Lightweight Charts in Streamlit applications. It manages the component lifecycle, handles both development and production modes, and provides utilities for debugging component initialization issues.

The module uses Streamlit’s components API to create a bidirectional bridge between Python (backend) and React/JavaScript (frontend). This bridge allows:

  • Sending chart configuration from Python to JavaScript

  • Receiving user interactions from JavaScript back to Python

  • Managing component state and lifecycle

  • Hot reloading during development

Key Features:
  • Automatic mode detection (development vs production)

  • Lazy component initialization to avoid import cycles

  • Comprehensive error handling and logging

  • Debug utilities for troubleshooting

  • Support for component reinitialization

Architecture:

The component follows a singleton pattern where _component_func is initialized once at module import time. This ensures consistent behavior across the application and avoids redundant initialization overhead.

Component Modes:
  • Production (_RELEASE=True): Uses pre-built static files from frontend/build directory. Optimized for deployment.

  • Development (_RELEASE=False): Connects to local dev server at localhost:3001 for hot reloading and rapid iteration.

Example

Basic chart rendering:

from streamlit_lightweight_charts_pro.component import get_component_func

# Get the initialized component function
component_func = get_component_func()

if component_func:
    # Render a chart with configuration
    result = component_func(config={"chart_options": {...}}, key="my_chart")
else:
    st.error("Chart component failed to initialize")

Debugging initialization issues:

from streamlit_lightweight_charts_pro.component import (
    debug_component_status,
    reinitialize_component,
)

# Check component status
status = debug_component_status()
print(f"Component initialized: {status['component_initialized']}")

# Attempt reinitialization if needed
if not status["component_initialized"]:
    success = reinitialize_component()
    print(f"Reinitialization {'succeeded' if success else 'failed'}")

Note

The module initializes the component automatically at import time. Component initialization failures are logged but don’t raise exceptions, allowing the application to start even if charts can’t be rendered.

raises ImportError:

If Streamlit components module cannot be imported

raises FileNotFoundError:

If frontend build directory is missing in production

streamlit_lightweight_charts_pro.component.get_component_func()[source]

Get the Streamlit component function for rendering charts.

This function returns the initialized component function that enables chart rendering in Streamlit applications. The component function acts as a bridge between Python configuration and the React frontend.

The returned function can be called with chart configuration to render interactive TradingView Lightweight Charts. It handles serialization, communication with the JavaScript frontend, and state management.

Returns:

The component function if successfully

initialized, None if initialization failed. When not None, the function has the signature:

component_func(

config: Dict[str, Any], key: Optional[str] = None, height: int = 400

) -> Any

Where:
  • config: Chart configuration dictionary

  • key: Unique identifier for the component instance

  • height: Component height in pixels

Return type:

Optional[Callable[…, Any]]

Example

Render a simple chart:

>>> component_func = get_component_func()
>>> if component_func:
...     component_func(
...         config={"chart_options": {"layout": {...}}},
...         key="my_chart",
...         height=500
...     )

Handle missing component gracefully:

>>> component_func = get_component_func()
>>> if component_func is None:
...     st.warning("Chart component unavailable")

Note

If the function returns None, check logs and use debug_component_status() to diagnose initialization issues. Common causes include:

  • Missing frontend build files

  • Incorrect file paths

  • Import errors

  • Permission issues

streamlit_lightweight_charts_pro.component.debug_component_status()[source]

Debug function to check component initialization status.

This utility function provides comprehensive information about the component’s initialization state, file paths, and available resources. It’s invaluable for troubleshooting component loading issues.

The function checks:
  • Whether component function was initialized

  • Current mode (production vs development)

  • Frontend directory existence and path

  • Static asset directory structure

  • JavaScript bundle files availability

Returns:

Status information dictionary containing:
  • component_initialized (bool): True if component loaded

  • release_mode (bool): True if in production mode

  • frontend_dir_exists (bool): True if build dir exists

  • component_type (str): Type name of component function

  • frontend_dir_path (str): Absolute path to frontend

  • static_dir_exists (bool): True if static dir exists

  • js_dir_exists (bool): True if js dir exists

  • js_files_count (int): Number of JavaScript files found

  • js_files (List[str]): Names of JavaScript bundle files

Return type:

Dict[str, Any]

Example

Basic status check:

>>> status = debug_component_status()
>>> print(f"Initialized: {status['component_initialized']}")
>>> print(f"Mode: {'Production' if status['release_mode'] else 'Dev'}")

Diagnose missing files:

>>> status = debug_component_status()
>>> if not status['component_initialized']:
...     if not status['frontend_dir_exists']:
...         print("Frontend build missing - run npm build")
...     elif not status['js_dir_exists']:
...         print("JavaScript bundles missing")
...     else:
...         print(f"Found {status['js_files_count']} JS files")

Note

This function only checks production mode files. Development mode status depends on the dev server running at localhost:3001.

streamlit_lightweight_charts_pro.component.reinitialize_component()[source]

Attempt to reinitialize the component if it failed to load initially.

This function provides a recovery mechanism for component initialization failures. It’s useful when the frontend build was missing at import time but has since been built, or when temporary errors prevented loading.

The function attempts to reinitialize the component using the same logic as the initial _initialize_component() call. It respects the current mode (production vs development) and updates the global _component_func.

Returns:

True if reinitialization succeeded, False if it failed.

Success means the component function was successfully declared and is ready for use. Failure indicates persistent issues that require investigation.

Return type:

bool

Example

Retry after building frontend:

>>> # Initial load failed, build frontend
>>> subprocess.run(["npm", "run", "build"], cwd="frontend")
>>> # Attempt to reinitialize
>>> if reinitialize_component():
...     print("Component now ready")
... else:
...     print("Reinitialization failed")

Check status before reinitializing:

>>> status = debug_component_status()
>>> if not status['component_initialized']:
...     if status['frontend_dir_exists']:
...         # Build exists, try reinitializing
...         success = reinitialize_component()
...     else:
...         print("Build frontend first")

Note

This function modifies the global _component_func variable. Reinitialization does not affect existing component instances, only new components created after this call.

Common reasons to reinitialize:
  • Frontend was built after module import

  • Temporary file system issues resolved

  • Network issues resolved (dev mode)

  • Manual troubleshooting steps completed

streamlit_lightweight_charts_pro.component._initialize_component()[source]

Initialize the component function based on environment.

This is an internal function called automatically at module import time to set up the Streamlit component. It detects the current mode (production vs development) and initializes the component accordingly.

The function is idempotent - calling it multiple times is safe, though typically it’s only called once during module initialization.

The initialization process:
  1. Checks the _RELEASE flag to determine mode

  2. In production: Verifies frontend build exists and declares component

  3. In development: Declares component pointing to dev server

  4. Logs all steps for debugging

  5. Sets _component_func on success, None on failure

Component Initialization Details:
Production Mode (_RELEASE=True):
  • Looks for frontend/build directory

  • Verifies directory exists before declaring component

  • Uses components.declare_component() with path parameter

  • Logs errors if build directory is missing

Development Mode (_RELEASE=False):
  • Declares component with url parameter

  • Points to http://localhost:3001 for dev server

  • Assumes developer has started dev server manually

  • Useful for hot reloading during development

Side Effects:
  • Modifies global _component_func variable

  • Writes log messages at INFO, WARNING, and ERROR levels

  • May attempt filesystem operations in production mode

Note

This function is called automatically when the module is imported. Manual calls to this function are unnecessary and may cause duplicate logging. Use reinitialize_component() instead for manual reinitialization.

Error Handling:

All exceptions are caught and logged. The function never raises exceptions to prevent import failures. If initialization fails, _component_func is set to None and the error is logged.

Return type:

None