### Complete Workflow Example Setup Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/guide/magics.md Sets up the environment for a complete workflow example by loading the extension and preparing data and variables using pandas and Python. ```python # Load extension %load_ext dashboard_lego.ipython_magics # Load data and prepare variables import pandas as pd df = pd.read_csv('data.csv') # Prepare environment variables metric_options = [ {"label": "Sales", "value": "sales"}, {"label": "Profit", "value": "profit"}, {"label": "Revenue", "value": "revenue"} ] color_palette = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728"] ``` -------------------------------- ### Install Dashboard Lego and Setup Development Environment Source: https://github.com/blghtr/dashboard_lego/blob/main/README.md Clone the repository and install the dashboard-lego package using uv or pip. It's recommended to use uv. After installation, set up pre-commit hooks for automated checks. ```bash # Clone and setup [uv] pip install dashboard-lego # Run pre-commit hooks pre-commit install ``` -------------------------------- ### Set Up Development Environment Source: https://github.com/blghtr/dashboard_lego/blob/main/CONTRIBUTING.md Steps to set up the Python virtual environment and install project dependencies using uv. This includes activating the environment and installing development, documentation, ML, and SQL extras. ```powershell # Create virtual environment (recommended: use uv) uv venv # Activate environment (Windows) venv\Scripts\activate # Install dependencies uv pip install -e .[dev,docs,ml,sql] ``` -------------------------------- ### Install Dashboard Lego with Dev Dependencies Source: https://github.com/blghtr/dashboard_lego/blob/main/README.md Installs the library using uv and includes development dependencies. Ensure uv is installed first. ```bash pip install uv uv venv uv pip install -e .[dev] ``` -------------------------------- ### v0.15 DataSource Implementation Example Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/guide/core.md Demonstrates the v0.15 pattern for creating a DataSource using custom DataBuilder and DataTransformer classes, along with a parameter classifier. This setup is then used with `get_metric_row` to define dashboard metrics. ```python from dashboard_lego.core import DataSource, DataBuilder, DataTransformer from dashboard_lego.blocks import get_metric_row import pandas as pd # Step 1: Define a DataBuilder (combines loading and initial processing) class SalesDataBuilder(DataBuilder): def __init__(self, file_path: str, **kwargs): super().__init__(**kwargs) self.file_path = file_path def build(self, params: dict) -> pd.DataFrame: # Load AND process in one method df = pd.read_csv(self.file_path) df['Revenue'] = df['Price'] * df['Quantity'] df['Date'] = pd.to_datetime(df['Date']) return df # Step 2: Define a DataTransformer (for filtering, aggregation, etc.) class SalesTransformer(DataTransformer): def transform(self, data: pd.DataFrame, params: dict) -> pd.DataFrame: df = data.copy() if 'filters-category' in params: category = params['filters-category'] if category and category != 'All': df = df[df['Category'] == category] # ... other transformations return df # Step 3: Define a parameter classifier def param_classifier(key: str) -> str: return 'transform' if key.startswith('filters-') else 'build' # Step 4: Create the DataSource instance using composition datasource = DataSource( data_builder=SalesDataBuilder("sales.csv"), data_transformer=SalesTransformer(), param_classifier=param_classifier, cache_ttl=600 ) # Step 5: Use get_metric_row() factory to create metric blocks (v0.15+) # The get_kpis() method is removed from the datasource. metrics, row_opts = get_metric_row( metrics_spec={ 'total_revenue': { 'column': 'Revenue', 'agg': 'sum', 'title': 'Total Revenue', 'color': 'success' }, 'avg_price': { 'column': 'Price', 'agg': 'mean', 'title': 'Avg Price', 'color': 'info' } }, datasource=datasource, subscribes_to=['filters-category'] ) ``` -------------------------------- ### Set Up Development Environment Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/contributing.md Installs project dependencies and pre-commit hooks using uv. Ensure you have cloned your fork and navigated into the project directory. ```bash git clone https://github.com/YOUR_USERNAME/dashboard-lego.git cd dashboard-lego uv venv uv pip install -e .[dev,docs,ml,sql] pre-commit install ``` -------------------------------- ### Install uv Package Manager Source: https://github.com/blghtr/dashboard_lego/blob/main/README.md Installs the uv package manager, recommended for faster dependency installation. ```bash pip install uv ``` -------------------------------- ### Create virtual environment and install from source using uv Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/installation.md Create a virtual environment and install Dashboard Lego in editable mode with development dependencies using uv. This is the recommended approach for development. ```bash uv venv uv pip install -e .[dev] ``` -------------------------------- ### Install Dashboard Lego using uv Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/installation.md Install the Dashboard Lego package using uv, a fast Python package installer. This is the recommended method for faster installation. ```bash uv pip install dashboard-lego ``` -------------------------------- ### Run the Simple Dashboard Example Source: https://github.com/blghtr/dashboard_lego/blob/main/README.md Executes the Python script to launch the simple sales dashboard. Ensure the script is in the correct directory. ```bash python examples/01_simple_dashboard.py ``` -------------------------------- ### __init__ Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/api/presets.md Initializes a preset with flexible control configuration, allowing for custom titles, data sources, and control setups. ```APIDOC ## __init__ ### Description Initialize preset with flexible control configuration. ### Parameters: * **block_id** (str) - Unique identifier * **datasource** ([DataSource](core.md#dashboard_lego.core.datasource.DataSource)) - Data source instance * **subscribes_to** (Optional) - State ID(s) to subscribe to * **title** (str, optional) - Chart title. Defaults to 'Preset Chart'. * **controls** (bool | Dict[str, bool | [Control](blocks.md#dashboard_lego.blocks.typed_chart.Control)], optional) - Control configuration: - False (default): No controls, expects values in kwargs - True: Create default controls for all parameters - Dict[str, bool|Control]: Custom control configuration: > - bool: Enable/disable default control > - Control: Replace with custom control * **kwargs** - Additional styling parameters and control values ``` -------------------------------- ### Minimal Dashboard Setup Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/guide/reference.md Demonstrates how to create a minimal dashboard with a single metric row. Ensure necessary imports and data sources are configured. ```python import dash import dash_bootstrap_components as dbc import pandas as pd from dashboard_lego.core import DashboardPage, DataSource, DataBuilder from dashboard_lego.blocks import get_metric_row class MyDataBuilder(DataBuilder): def build(self, params): return pd.read_csv("data.csv") datasource = DataSource(data_builder=MyDataBuilder()) metrics, row_opts = get_metric_row( metrics_spec={ "total": { "column": "id", "agg": "count", "title": "Total", "color": "primary" } }, datasource=datasource, subscribes_to="dummy_state" ) page = DashboardPage(title="Dashboard", blocks=[(metrics, row_opts)]) app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP]) app.layout = page.build_layout() page.register_callbacks(app) app.run_server(debug=True) ``` -------------------------------- ### Create virtual environment and install from source using pip Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/installation.md Create a virtual environment and install Dashboard Lego in editable mode with development dependencies using pip. This is an alternative to uv for development. ```bash python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate pip install -e .[dev] ``` -------------------------------- ### Get Initial Publisher Values Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/api/core.md Call `get_initial_publisher_values` to retrieve the starting values for all registered state publishers. This is crucial for ensuring components have the necessary data before they are rendered. ```python initial_values = state_manager.get_initial_publisher_values() ``` -------------------------------- ### SQL Connection String Examples Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/guide/datasources.md Examples of SQLAlchemy connection strings for various database systems. ```sql # PostgreSQL "postgresql://user:password@localhost:5432/dbname" ``` ```sql # MySQL "mysql+pymysql://user:password@localhost:3306/dbname" ``` ```sql # SQLite "sqlite:///path/to/database.db" ``` -------------------------------- ### Install dashboard-lego Source: https://github.com/blghtr/dashboard_lego/blob/main/README.md Install the dashboard-lego library using pip. This command ensures that all necessary packages are downloaded and installed for the library to function. ```bash pip install dashboard-lego ``` -------------------------------- ### Install dashboard-lego with Jupyter Support Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/guide/patterns.md Install the dashboard-lego library with Jupyter support using pip. Alternatively, install jupyter-dash separately if needed. ```bash # Install with Jupyter support pip install dashboard-lego[jupyter] # Or install jupyter-dash separately pip install jupyter-dash ``` -------------------------------- ### TypedChartBlock Example Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/guide/blocks.md Example demonstrating how to create a `TypedChartBlock` with static and dynamic titles, and subscribing to a control. ```APIDOC ## TypedChartBlock Example ### Description This example shows the instantiation of a `TypedChartBlock` for sales analysis, utilizing a placeholder for a metric selector in both plot parameters and the plot title. ### Code ```python chart = TypedChartBlock( block_id="sales_chart", datasource=datasource, plot_type="scatter", plot_params={"x": "date", "y": "sales", "color": "{{metric_selector}}"}, title="Sales Analysis", # Static card title plot_title="Sales by {{metric_selector}}", # Dynamic plot title with placeholder subscribes_to=["metric_selector"] ) ``` ``` -------------------------------- ### Setup Async-Compatible Logging Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/api/utils.md Call setup_logging to configure the async-compatible logging system using Loguru. This function sets up dual output to the console and a rotating file, with an optional log directory. ```python setup_logging(level="DEBUG", log_dir="./logs") ``` -------------------------------- ### Layout Height Contract Example Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/guide/contracts.md Demonstrates how blocks within the same row achieve content-driven sizing, ensuring cards are compact and responsive without fixed heights or empty space. This example shows a metric and a chart in the same row. ```python # Metric (compact ~150px) + Chart (large ~500px) in same row metric = SingleMetricBlock(...) # Compact card, natural height chart = TypedChartBlock(...) # Larger card with graph page = DashboardPage(..., blocks=[[metric, chart]]) # Result: # - Row height = 500px (tallest child) # - Metric card = 150px (compact, no empty space) # - Chart card = 500px (natural graph size) # - Both preserve responsive widths (col-md-4, col-md-8, etc.) ``` -------------------------------- ### Layout Presets Example Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/guide/presets.md Shows how to use layout presets like `kpi_row_top` and `two_column_8_4` to structure dashboard content, combining KPI blocks with multi-column content rows. ```python from dashboard_lego.presets.layouts import kpi_row_top, two_column_8_4 layout = kpi_row_top( kpi_blocks=[kpi1, kpi2, kpi3], content_rows=[ two_column_8_4(main=chart, side=filter_panel), [table_block] ] ) ``` -------------------------------- ### Verify Dashboard Lego installation Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/installation.md Run a Python script to verify that Dashboard Lego is installed correctly and basic components can be imported. ```python import dashboard_lego print(f"Dashboard Lego version: {dashboard_lego.__version__}") # Test basic functionality from dashboard_lego.core import DashboardPage from dashboard_lego.blocks import get_metric_row print("Installation successful!") ``` -------------------------------- ### Example Control Panel Configuration Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/guide/patterns.md Configure a ControlPanelBlock with controls that map to specific pipeline stages using parameter naming conventions. 'transform__category' routes to the transform stage, while 'build__window_size' routes to the build stage. ```python control_panel = ControlPanelBlock( block_id="filters", datasource=datasource, title="Filters", controls={ "transform__category": Control(...), # → transform stage "transform__min_price": Control(...), # → transform stage "build__window_size": Control(...), # → build stage } ) ``` -------------------------------- ### State Flow Example Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/concepts.md Demonstrates how a block can publish filter state and another block can subscribe to it for interactive filtering. Requires importing necessary components from dashboard_lego.blocks and dash_core_components. ```python from dashboard_lego.blocks import TypedChartBlock, get_metric_row, Control import dash_core_components as dcc # Block A publishes filter state interactive_chart = TypedChartBlock( block_id="filter_chart", datasource=datasource, plot_type="bar", plot_params={"x": "{{category}}", "y": "Sales"}, controls={"category": Control(component=dcc.Dropdown, props={"options": [...]})} ) # Block B subscribes to filter state metrics, row_opts = get_metric_row( metrics_spec={ "total_sales": { "column": "Sales", "agg": "sum", "title": "Total Sales", "color": "success" } }, datasource=datasource, subscribes_to="filter_chart-category" # Subscribes to category filter ) ``` -------------------------------- ### Create a Simple Dashboard with Dashboard Lego Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/index.md Example of creating a basic dashboard using Dashboard Lego. It demonstrates defining a custom data builder, creating a data source, defining a metric block, and building the dashboard layout. ```python import dash import dash_bootstrap_components as dbc import pandas as pd from dashboard_lego.core import DashboardPage, DataSource, DataBuilder from dashboard_lego.blocks import get_metric_row # Define DataBuilder (v0.15+ pattern) class MyDataBuilder(DataBuilder): def __init__(self, file_path): super().__init__() self.file_path = file_path def build(self, params): return pd.read_csv(self.file_path) # Create datasource using composition datasource = DataSource( data_builder=MyDataBuilder("your_data.csv") ) # Create blocks using v0.15+ API with factory pattern metrics, row_opts = get_metric_row( metrics_spec={ "total": { "column": "id", # Count rows "agg": "count", "title": "Total Records", "color": "primary" } }, datasource=datasource, subscribes_to="dummy_state" ) # Create dashboard page = DashboardPage( title="My Dashboard", blocks=[ (metrics, row_opts) ] ) # Run the app app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP]) app.layout = page.build_layout() page.register_callbacks(app) app.run_server(debug=True) ``` -------------------------------- ### Example Usage of get_metric_row Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/guide/blocks.md Demonstrates how to use the get_metric_row function to create metric blocks and integrate them into a DashboardPage layout. ```python from dashboard_lego.blocks import get_metric_row metrics, row_opts = get_metric_row( metrics_spec={ 'total_revenue': { 'column': 'Revenue', 'agg': 'sum', 'title': 'Total Revenue', 'color': 'success' # Bootstrap theme color }, 'avg_price': { 'column': 'Price', 'agg': 'mean', 'title': 'Average Price', 'color': 'info' }, 'units_sold': { 'column': 'Quantity', 'agg': 'sum', 'title': 'Units Sold', 'color': 'primary' } }, datasource=datasource, subscribes_to=['filters-category'] ) # Use in page layout page = DashboardPage( title="Dashboard", blocks=[ (metrics, row_opts), # Metrics row [chart1, chart2] # Charts row ] ) ``` -------------------------------- ### Implementing a Custom Preset with BasePreset Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/api/presets.md Example of how to implement a custom preset by subclassing BasePreset. Subclasses must define default_controls, plot_type, and methods for building plot parameters and keyword arguments. ```python class MyPreset(BasePreset): @abstractproperty def default_controls(self) -> Dict[str, Control]: > return { > : “param1”: Control(component=dcc.Dropdown, props={…}), > “param2”: Control(component=dbc.Switch, props={…}), <> > } > @abstractproperty > def plot_type(self) -> str: > > return “my_plot_type” > def _build_plot_params(self, final_controls: Dict[str, Control], kwargs: Dict[str, Any]) -> Dict[str, Any]: > : plot_params = {} > if “param1” in final_controls: > <> > > plot_params[“param1”] = “{{param1}}” > <> > else: > : plot_params[“param1”] = kwargs.get(“param1”, “default_value”) > <> > return plot_params <> > def _build_plot_kwargs(self, final_controls: Dict[str, Control], kwargs: Dict[str, Any]) -> Dict[str, Any]: > : plot_kwargs = {} > if “param2” in final_controls: > <> > > plot_kwargs[“param2”] = “{{param2}}” > <> > else: > : plot_kwargs[“param2”] = kwargs.get(“param2”, False) > <> > return plot_kwargs <> > def _get_plot_title(self, final_controls: Dict[str, Control]) -> Optional[str]: > : if “param1” in final_controls: > : return “My Plot: {{param1}}” > <> > return None <> ``` -------------------------------- ### Two-Column Layout Example Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/concepts.md Illustrates a basic two-column layout using Dashboard Lego's grid system, where the first column occupies 8 Bootstrap columns and the second occupies 4. ```python # Two-column layout: 8 columns + 4 columns metrics, row_opts = get_metric_row(...) layout = [ [(chart_block, {'md': 8}), (metrics[0], {'md': 4})] ] ``` -------------------------------- ### Implementing a Custom Preset with BasePreset Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/api/presets.md Example of subclassing BasePreset to create a custom chart preset. Subclasses must implement default_controls, plot_type, _build_plot_params, _build_plot_kwargs, and _get_plot_title. The controls parameter allows for flexible configuration of user-facing controls. ```python class MyPreset(BasePreset): @abstractproperty def default_controls(self) -> Dict[str, Control]: return { “param1”: Control(component=dcc.Dropdown, props={…}), “param2”: Control(component=dbc.Switch, props={…}), } @abstractproperty def plot_type(self) -> str: return “my_plot_type” def _build_plot_params(self, final_controls: Dict[str, Control], kwargs: Dict[str, Any]) -> Dict[str, Any]: plot_params = {} if “param1” in final_controls: plot_params[“param1”] = “{{param1}}” else: plot_params[“param1”] = kwargs.get(“param1”, “default_value”) return plot_params def _build_plot_kwargs(self, final_controls: Dict[str, Control], kwargs: Dict[str, Any]) -> Dict[str, Any]: plot_kwargs = {} if “param2” in final_controls: plot_kwargs[“param2”] = “{{param2}}” else: plot_kwargs[“param2”] = kwargs.get(“param2”, False) return plot_kwargs def _get_plot_title(self, final_controls: Dict[str, Control]) -> Optional[str]: if “param1” in final_controls: return “My Plot: {{param1}}” return None ``` -------------------------------- ### Create Dashboard for Hyperparameter Exploration Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/guide/magics.md Use `%%dashboard_cell` to create a dashboard for exploring hyperparameters. This example shows a scatter plot with controls for selecting metrics and adjusting parameters like window step. Ensure `session_params` and `metric_options` are defined in the environment. ```python # Hyperparameter playground example session_params = { 'session_length': [10, 15, 20, 25, 30], 'max_idle': [600, 900, 1800, 3600, 7200], 'window_step': [3, 5, 7, 10] } %%dashboard_cell dataframe: session_hp_datasource title: "Session Hyperparameters Playground" environment: - session_params - metric_options cards: - type: chart plot_type: scatter plot_params: {x: session_length, y: max_idle} title: "Session Length vs Max Idle" controls: - name: metric_selector type: dropdown options: $metric_options value: "n_sessions" - name: window_step_slider type: slider min: 3 max: 10 step: 1 value: 5 ``` -------------------------------- ### Build and Serve Documentation Locally Source: https://github.com/blghtr/dashboard_lego/blob/main/README.md Navigate to the docs directory and use make commands to build and serve the documentation locally. This command also opens the documentation at http://localhost:8000. ```bash cd docs # Build and serve locally (opens http://localhost:8000) make serve ``` -------------------------------- ### Build Documentation with Makefile Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/README.md Use these commands to build and serve the documentation locally or perform other build-related tasks. ```bash cd docs # Build and serve locally at http://localhost:8000 make serve # Just build HTML make html # Clean build artifacts make clean # Check docs build without errors make check # Clean and rebuild make all ``` -------------------------------- ### Unit Test Example for KPIBlock Source: https://github.com/blghtr/dashboard_lego/blob/main/CONTRIBUTING.md Example of a unit test for the KPIBlock class using pytest. It demonstrates how to use fixtures, mock objects, and assert block properties during initialization. ```python import pytest from dashboard_lego.blocks.kpi import KPIBlock from dashboard_lego.core.datasource import BaseDataSource class TestKPIBlock: """Test suite for KPIBlock functionality.""" def test_kpi_block_initialization(self, mock_datasource): """ Test that KPIBlock initializes correctly. :hierarchy: [Unit Tests | Blocks | KPIBlock | Initialization] :covers: - object: "class: 'KPIBlock'" - requirement: "KPIBlock must initialize with valid parameters" :scenario: "Verifies that KPIBlock creates a valid instance with given parameters" :strategy: "Uses pytest fixtures to create mock datasource and asserts block properties" :contract: - pre: "Valid datasource and KPI definitions provided" - post: "KPIBlock instance created with correct block_id and definitions" """ kpi_definitions = [ {"key": "total", "title": "Total", "icon": "📊", "color": "primary"} ] block = KPIBlock( block_id="test-kpi", datasource=mock_datasource, kpi_definitions=kpi_definitions, subscribes_to="test_state" ) assert block.block_id == "test-kpi" assert len(block.kpi_definitions) == 1 ``` -------------------------------- ### Build a Simple Sales Dashboard with Dashboard Lego Source: https://github.com/blghtr/dashboard_lego/blob/main/README.md Demonstrates creating a basic dashboard with metrics and a bar chart. Requires sample_data.csv. Uses the v0.15+ DataBuilder and DataSource composition pattern. ```python # examples/01_simple_dashboard.py import dash import dash_bootstrap_components as dbc import plotly.express as px import pandas as pd from dashboard_lego.core import DataSource, DataBuilder, DashboardPage from dashboard_lego.blocks import get_metric_row, TypedChartBlock # 1. Define a DataBuilder (v0.15+ pattern) class SalesDataBuilder(DataBuilder): def __init__(self, file_path): super().__init__() self.file_path = file_path def build(self, params): """Load CSV and add calculated fields.""" df = pd.read_csv(self.file_path) # Add any calculated fields here return df # 2. Create datasource using composition (no inheritance!) datasource = DataSource( data_builder=SalesDataBuilder("examples/sample_data.csv") ) # 3. Create blocks using v0.15+ API # get_metric_row() factory creates metric blocks metrics, row_opts = get_metric_row( metrics_spec={ "total_sales": { "column": "Sales", "agg": "sum", "title": "Total Sales", "color": "success" }, "total_units": { "column": "UnitsSold", "agg": "sum", "title": "Total Units Sold", "color": "info" } }, datasource=datasource, subscribes_to="dummy_state" ) # TypedChartBlock with block-level transform chart_block = TypedChartBlock( block_id="sales_chart", datasource=datasource, plot_type="bar", plot_params={"x": "Fruit", "y": "Sales"}, plot_kwargs={"title": "Sales by Fruit"}, title="Fruit Sales", subscribes_to="dummy_state", # Optional: aggregate data at block level transform_fn=lambda df: df.groupby("Fruit")["Sales"].sum().reset_index() ) # 4. Assemble the dashboard page dashboard_page = DashboardPage( title="Simple Sales Dashboard", blocks=[ (metrics, row_opts), # Metrics row with proper layout [chart_block] # Chart block ], theme=dbc.themes.LUX ) # 5. Run the application app = dash.Dash(__name__, external_stylesheets=[dashboard_page.theme]) app.layout = dashboard_page.build_layout() dashboard_page.register_callbacks(app) if __name__ == "__main__": app.run_server(debug=True) ``` -------------------------------- ### __init__ Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/api/blocks.md Initializes the TextBlock with customizable styling and content generation capabilities. ```APIDOC ## __init__(block_id: str, datasource: Any, content_generator: Callable[[DataFrame], Component | str] | str, subscribes_to: str | List[str] | None = None, title: str | None = None, card_style: Dict[str, Any] | None = None, card_className: str | None = None, title_style: Dict[str, Any] | None = None, title_className: str | None = None, content_style: Dict[str, Any] | None = None, content_className: str | None = None, loading_type: str = 'default', color: str | Dict[str, Any] | None = None) ### Description Initializes the TextBlock with customizable styling. ### Parameters * **block_id** (str) - A unique identifier for this block instance. * **datasource** (Any) - An instance of a class that implements the DataSource interface. * **content_generator** (Callable[[DataFrame], Component | str] | str) - A function that takes a DataFrame and returns a Dash Component or a Markdown string, or a static string for fixed content. * **subscribes_to** (str | List[str] | None) - Optional state ID(s) to which this block subscribes to receive updates. Defaults to None. * **title** (str | None) - An optional title for the block’s card. * **card_style** (Dict[str, Any] | None) - Optional style dictionary for the card component. * **card_className** (str | None) - Optional CSS class name for the card component. * **title_style** (Dict[str, Any] | None) - Optional style dictionary for the title component. * **title_className** (str | None) - Optional CSS class name for the title component. * **content_style** (Dict[str, Any] | None) - Optional style dictionary for the content container. * **content_className** (str | None) - Optional CSS class name for the content container. * **loading_type** (str) - Type of loading indicator to display. Defaults to 'default'. * **color** (str | Dict[str, Any] | None) - Optional color specification. Can be a Bootstrap theme color name or a dictionary for keyword-based coloring. ``` -------------------------------- ### Python Test Structure Example Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/contributing.md Demonstrates the structure for Pytest unit tests, including docstring conventions for hierarchy, coverage, scenario, strategy, and contract. This example shows how to test a function's behavior. ```python def test_my_function_behavior(self, sample_data): """ Test that my_function behaves correctly. :hierarchy: [Unit Tests | MyModule | MyFunction | Behavior] :covers: - object: "function: 'my_function'" - requirement: "Function must process data correctly" :scenario: "Verifies that my_function processes sample data as expected" :strategy: "Uses pytest fixtures and assertions to validate behavior" :contract: - pre: "sample_data is a valid DataFrame" - post: "Function returns expected result" """ result = my_function(sample_data) assert result is not None assert len(result) > 0 ``` -------------------------------- ### Build Documentation HTML Source: https://github.com/blghtr/dashboard_lego/blob/main/README.md Use the make html command within the docs directory to generate the static HTML files for the documentation. ```bash # Just build HTML make html ``` -------------------------------- ### Cache Prewarming with DataSource Source: https://context7.com/blghtr/dashboard_lego/llms.txt Example of prewarming the cache for a DataSource by providing parameters for specific transformations. ```python import pandas as pd from dashboard_lego.core import DataSource, DataBuilder, DataTransformer # --- Cache prewarming --- # Assuming SalesBuilder is defined as in Option 2 # class SalesBuilder(DataBuilder): # ... ds_warm = DataSource( data_builder=SalesBuilder(), cache_prewarm_params=[ {"transform__category": "Electronics"}, {"transform__category": "Clothing"}, ], ) ``` -------------------------------- ### Run the Dash Application Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/quickstart.md Initialize a Dash app, build the layout using the `DashboardPage` object, register callbacks, and run the server. Ensure `debug=True` for development. ```python import dash # Create Dash app app = dash.Dash(__name__, external_stylesheets=[dashboard_page.theme]) app.layout = dashboard_page.build_layout() # Register callbacks (handled automatically) dashboard_page.register_callbacks(app) # Run the app if __name__ == "__main__": app.run_server(debug=True) ``` -------------------------------- ### TypedChartBlock with Data Transformation Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/guide/blocks.md Example illustrating the use of the `transform_fn` parameter in `TypedChartBlock` to perform data aggregation and filtering before plotting. ```APIDOC ## TypedChartBlock with Data Transformation ### Description This example demonstrates how to use the `transform_fn` parameter to create a chart showing the top 10 products by revenue. The transformation function groups data, sums revenue, resets the index, sorts values, and selects the top 10. ### Code ```python top_products_chart = TypedChartBlock( block_id="top_products", datasource=datasource, plot_type='bar', plot_params={'x': 'Product', 'y': 'total_revenue'}, title="Top 10 Products by Revenue", subscribes_to=['filters-category'], transform_fn=lambda df: ( df.groupby('Product')['Revenue'] .sum() .reset_index(name='total_revenue') .sort_values('total_revenue', ascending=False) .head(10) ) ) ``` ``` -------------------------------- ### Get Metric Row Function Signature Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/guide/blocks.md Signature for the factory function that creates individual metric blocks for flexible layout. ```python def get_metric_row( metrics_spec: Dict[str, Dict[str, Any]], datasource: DataSource, subscribes_to: Optional[Union[str, List[str]]] = None, row_options: Optional[Dict[str, Any]] = None, block_id_prefix: str = "metric", ) -> Tuple[List[SingleMetricBlock], Dict[str, Any]] ``` -------------------------------- ### Check Documentation Build Source: https://github.com/blghtr/dashboard_lego/blob/main/README.md Verify that the documentation can be built without errors by running the make check command. ```bash # Check docs build without errors make check ``` -------------------------------- ### Create Feature Branch Git Command Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/contributing.md Start a new feature by creating a dedicated branch. Use a descriptive name for clarity. ```bash git checkout -b feature/your-feature-name ``` -------------------------------- ### Run Tests for Dashboard Lego Source: https://github.com/blghtr/dashboard_lego/blob/main/README.md Execute the test suite for the dashboard-lego library using pytest. Ensure development dependencies are installed first. ```bash # Make sure you have dev dependencies installed # uv pip install -e .[dev,docs,ml,sql] # Run tests uv run pytest ``` -------------------------------- ### Build a Standard Dashboard Page Source: https://context7.com/blghtr/dashboard_lego/llms.txt Demonstrates creating a standard dashboard layout with explicit column widths for metrics and charts. Requires importing necessary components and defining a data source. ```python import dash import dash_bootstrap_components as dbc from dashboard_lego.core import ( DashboardPage, DataSource, DataBuilder, NavigationConfig, NavigationSection, ThemeConfig, ) from dashboard_lego.core.sidebar import SidebarConfig from dashboard_lego.blocks import get_metric_row from dashboard_lego.blocks.typed_chart import TypedChartBlock, Control from dashboard_lego.blocks.control_panel import ControlPanelBlock datasource = DataSource(build_fn=lambda p: __import__("pandas").read_csv("examples/sample_data.csv")) # --- Standard layout with explicit column widths --- chart = TypedChartBlock( block_id="rev", datasource=datasource, plot_type="bar", plot_params={"x": "Category", "y": "Price"}, plot_kwargs={"title": "Price by Category"}, ) metrics, row_opts = get_metric_row( metrics_spec={ "total": {"column": "Price", "agg": "sum", "title": "Total Price", "color": "success"} }, datasource=datasource, ) page = DashboardPage( title="Sales Dashboard", blocks=[ (metrics, row_opts), # metrics row (equal widths) [(chart, {"md": 8}), # chart takes 8/12 columns (chart, {"md": 4})], # sidebar chart takes 4/12 ], theme=dbc.themes.LUX, ) app = dash.Dash(__name__, external_stylesheets=[page.theme]) app.layout = page.build_layout() page.register_callbacks(app) app.run(debug=True) ``` -------------------------------- ### Create Simple One-Column Layout Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/guide/core.md Example of creating a simple one-column dashboard layout using the DashboardPage class and the one_column helper function. ```python # Simple one-column layout page = DashboardPage( title="My Dashboard", blocks=one_column([kpi_block, chart_block]), theme=dbc.themes.LUX ) ``` -------------------------------- ### Manually Build Documentation Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/README.md Commands for manually generating API documentation and building HTML output using Sphinx. ```bash # Generate API documentation uv run sphinx-apidoc -o docs/source/api --separate --module-first blocks/ core/ presets/ utils/ # Build HTML uv run sphinx-build -b html docs/source docs/build ``` -------------------------------- ### Clone Dashboard Lego Repository Source: https://github.com/blghtr/dashboard_lego/blob/main/README.md Clones the Dashboard Lego repository from GitHub and navigates into the project directory. This is the first step for local setup. ```bash git clone https://github.com/your-username/dashboard-lego.git cd dashboard-lego ``` -------------------------------- ### Create a Dashboard with Quick Dashboard Source: https://github.com/blghtr/dashboard_lego/blob/main/README.md Load data into a pandas DataFrame and then create a dashboard using the quick_dashboard function. This function takes the DataFrame and a list of card configurations to define the dashboard's appearance and functionality. The dashboard can be run directly, opening in a browser tab. ```python df = pd.DataFrame({ 'Product': ['Widget', 'Gadget', 'Tool', 'Device'], 'Sales': [100, 200, 150, 180], 'Revenue': [1000, 2000, 1500, 1800] }) app = quick_dashboard( df=df, cards=[ {"type": "metric", "column": "Revenue", "agg": "sum", "title": "Total Revenue", "color": "success"}, {"type": "chart", "plot_type": "bar", "x": "Product", "y": "Sales", "title": "Sales by Product"} ], title="Sales Dashboard", theme="lux" ) app.run(debug=True) ``` -------------------------------- ### Compare Traditional API vs. Magic Command Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/guide/patterns.md Illustrates the conciseness of using the %dashboard magic command compared to the traditional API for creating dashboards, highlighting its efficiency for quick exploration. ```python # Traditional API (3 lines): app = quick_dashboard(df=df, cards=[...]) app.run(port=8050) # Magic command (1 line): %dashboard df -m Sales sum "Total" -c bar Product Sales ``` -------------------------------- ### Get Initial Publisher Values Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/api/core.md Retrieves the initial values for all registered state publishers. This is crucial for synchronizing the initial state of components before rendering. ```python state_manager.get_initial_publisher_values() ``` -------------------------------- ### Base Preset Configuration Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/guide/presets.md Demonstrates how to configure the `controls` parameter for presets, allowing for no controls, default controls, or custom control configurations. ```APIDOC ## Base Preset Configuration Abstract base class for all TypedChartBlock presets with standardized control configuration. **Key Features:** - Flexible control configuration via `controls` parameter - Automatic plot parameter building based on available controls - Dynamic plot title generation - Datasource validation - Consistent preset development pattern **Usage:** ```python from dashboard_lego.presets import KneePlotPreset # No controls - use values from kwargs preset = KneePlotPreset( block_id="knee-plot", datasource=datasource, x_col="k", y_col="inertia" ) # All default controls preset = KneePlotPreset( block_id="knee-plot", datasource=datasource, controls=True ) # Custom control configuration preset = KneePlotPreset( block_id="knee-plot", datasource=datasource, controls={ "x_col": True, # Enable default control "y_col": False, # Disable control "auto_knee": CustomControl(…) } ) ``` ``` -------------------------------- ### Chart with Embedded Local Controls (YAML) Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/guide/magics.md Example of a chart with its own internal controls. These controls are private to the chart and do not publish state or affect other blocks in the dashboard. ```yaml - type: chart plot_type: histogram plot_params: {x: Price} title: "Price Distribution" # These are chart-local controls (don't publish state) controls: - name: x_col type: dropdown options: - {label: "Price", value: "Price"} - {label: "Quantity", value: "Quantity"} value: "Price" ``` -------------------------------- ### Using Lambda Functions with DataSource Source: https://context7.com/blghtr/dashboard_lego/llms.txt Demonstrates the simplest way to use DataSource with lambda functions for build and transform stages. Ensure the 'data.csv' file exists or provide a valid path. ```python import pandas as pd from dashboard_lego.core import DataSource, DataBuilder, DataTransformer # --- Option 1: lambda functions (simplest) --- ds_lambda = DataSource( build_fn=lambda params: pd.read_csv(params.get("file", "data.csv")), transform_fn=lambda df: df[df["active"] == True], cache_ttl=300, ) result = ds_lambda.get_processed_data({"file": "sales.csv"}) ``` -------------------------------- ### Get Initial Publisher Values Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/api/core.md Retrieves the initial values of all registered state publishers. This is useful for synchronizing the initial state of components when the dashboard loads. ```APIDOC ## get_initial_publisher_values() → Dict[str, Any] Get initial values of all registered publishers. * **Hierarchy:** [Feature | Initial State Sync | StateManager] * **Relates-to:** - motivated_by: “Blocks need initial state values before rendering” - implements: “method: ‘get_initial_publisher_values’” * **Contract:** - pre: “Publishers are registered” - post: “Returns {state_id: None or value} for all states” * **Returns:** Dict mapping state_id to initial value (None if not available) ``` -------------------------------- ### Run Tests with uv Source: https://github.com/blghtr/dashboard_lego/blob/main/README.md Execute the project's tests using pytest within the development environment managed by uv. Ensure you have Python 3.10+ installed. ```bash # Run tests uv run pytest ``` -------------------------------- ### Get Logger with Hierarchy Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/api/utils.md Use get_logger to create a logger instance with automatic hierarchy extraction from docstrings. This factory function configures a HierarchyLoggerAdapter for async-compatible logging. ```python logger = get_logger(__name__, MyClass) logger.debug("This will include hierarchy") logger.info("This is for users") ``` -------------------------------- ### __init__() Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/api/core.md Initializes the StateManager. The internal dependency_graph will store the relationships between components and their states. ```APIDOC ## __init__() ### Description Initializes the StateManager. The internal `dependency_graph` will store the relationships. ### Example ```default { 'selected_date_range': { 'publisher': { 'component_id': 'global-date-picker', 'component_prop': 'value' }, 'subscribers': [ { 'component_id': 'sales-trend-graph', 'component_prop': 'figure', 'callback_fn': '' }, { 'component_id': 'kpi-block-container', 'component_prop': 'children', 'callback_fn': '' } ] } } ``` ``` -------------------------------- ### Register Subscriber Example Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/api/core.md Use `register_subscriber` to link a component's property to a state. When the state changes, the specified `callback_fn` will be invoked to update the component's property. ```python state_manager.register_subscriber(state_id='selected_date_range', component_id='sales-trend-graph', component_prop='figure', callback_fn=update_graph_figure) ``` -------------------------------- ### Use BasePreset for Flexible Control Configuration Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/contributing.md Extend BasePreset to create ML presets with interactive controls. Define default controls and customize plot parameter generation. ```python class MyMLPresetWithControls(BasePreset): """ ML preset with controls. :hierarchy: [Presets | ML | MyMLPresetWithControls] :relates-to: - motivated_by: "ML workflow requires interactive controls" - implements: "preset: 'MyMLPresetWithControls'" - uses: ["block: 'BasePreset'"] """ @property def default_controls(self): return { "metric": Control(component=dcc.Dropdown, props={"options": [...]}) } def _build_plot_params(self, final_controls, kwargs): return {"x": "{{metric}}", "y": "target"} def __init__(self, block_id, datasource, **kwargs): super().__init__( block_id=block_id, datasource=datasource, metrics_spec={ 'accuracy': {'column': 'predictions', 'agg': 'mean', 'title': 'Accuracy'}, 'f1_score': {'column': 'f1', 'agg': 'mean', 'title': 'F1 Score'} }, **kwargs ) ``` -------------------------------- ### Register Publisher Example Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/api/core.md Use `register_publisher` to declare a component's property as a source of truth for a specific piece of state. This is essential for making state data available to other components. ```python state_manager.register_publisher(state_id='selected_date_range', component_id='global-date-picker', component_prop='value') ``` -------------------------------- ### Define a Data Builder Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/quickstart.md Create a custom DataBuilder class to load and process data. This example uses pandas to read a CSV file. Ensure the file path is correct. ```python import pandas as pd from dashboard_lego.core import DataBuilder, DataSource class SalesDataBuilder(DataBuilder): def __init__(self, file_path): super().__init__() self.file_path = file_path def build(self, params): """Load CSV and optionally add calculated fields.""" df = pd.read_csv(self.file_path) # Add any calculated columns here if needed return df # Create datasource using composition (no inheritance!) datasource = DataSource( data_builder=SalesDataBuilder("sample_data.csv") ) ``` -------------------------------- ### Clean and Rebuild Documentation Source: https://github.com/blghtr/dashboard_lego/blob/main/README.md To ensure a fresh build, clean the existing documentation artifacts and then rebuild the HTML using make clean and make html. ```bash # Clean and rebuild make clean && make html ``` -------------------------------- ### Auto-sizing Controls Configuration Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/guide/presets.md Illustrates how to configure auto-sizing for controls. By default, controls auto-size to content width. This example shows disabling auto-sizing and setting a custom character limit. ```python # Default auto-sizing (enabled by default) Control( > component=dcc.Dropdown, > props={“options”: [“Short”, “Very Long Option Name”]}, > # auto_size=True (default) > # max_ch=40 (default) > # col_props={“xs”: 12, “md”: “auto”} (default) ) ``` ```python # Disable auto-sizing for specific control Control( > component=dcc.Dropdown, > props={“options”: […]}, > auto_size=False, # Disable auto-sizing > col_props={“xs”: 12, “md”: 6} # Use fixed width ) ``` ```python # Custom character limit Control( > component=dcc.Dropdown, > props={“options”: […]}, > max_ch=60 # Allow wider controls ### ) ``` -------------------------------- ### Initialize SqlDataSource Source: https://github.com/blghtr/dashboard_lego/blob/main/docs/source/guide/datasources.md Connect to a database using SQLAlchemy and execute a query. Configure cache time-to-live for query results. ```python from dashboard_lego.core.datasources.sql_source import SqlDataSource datasource = SqlDataSource( connection_string="postgresql://user:pass@localhost/sales_db", query="SELECT * FROM sales WHERE year = 2024", cache_ttl=1800 # 30 minutes ) datasource.init_data() ```