### Install Dependencies - Bash
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/DEVELOPER_GUIDE.md
Installs project dependencies using Pixi. This command ensures all necessary packages are available for development.
```bash
pixi install
```
--------------------------------
### Clone and Run Branding Example
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/branding.md
Provides instructions to clone the project repository, navigate to the branding examples directory, and run the application using `panel serve`. This allows users to see a complete implementation of the branding concepts.
```bash
git clone https://github.com/panel-extensions/panel-material-ui.git
cd examples/apps/branding
panel serve app.py --show
```
--------------------------------
### Serve for Development - Bash
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/DEVELOPER_GUIDE.md
Launches a Panel server in a separate terminal to preview components during development. This command is typically run after starting the development compilation.
```bash
pixi run serve-dev
```
--------------------------------
### Clone Repository - Bash
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/DEVELOPER_GUIDE.md
Clones the panel-material-ui repository from GitHub and navigates into the project directory.
```bash
git clone https://github.com/panel-extensions/panel-material-ui.git
cd panel-material-ui
```
--------------------------------
### Install Panel Material UI via pip
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/index.md
Installs the Panel Material UI library using pip, the standard package installer for Python. This command ensures all necessary dependencies are downloaded and configured.
```bash
pip install panel-material-ui
```
--------------------------------
### List Pixi Tasks - Bash
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/DEVELOPER_GUIDE.md
Displays all available tasks that can be run using the Pixi task runner.
```bash
pixi task list
```
--------------------------------
### Run Pre-commit Hooks - Bash
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/DEVELOPER_GUIDE.md
Executes pre-commit hooks, which typically include linting and formatting checks, to ensure code quality before committing.
```bash
pixi run pre-commit-run
```
--------------------------------
### Install Panel Material UI via conda
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/index.md
Installs the Panel Material UI library using conda, a popular package and environment manager. This is an alternative installation method, often used in data science workflows.
```bash
conda install -c conda-forge panel-material-ui
```
--------------------------------
### Run Unit Tests (Python 3.12) - Bash
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/DEVELOPER_GUIDE.md
Runs the unit test suite for the project using Python version 3.12. This verifies the core functionality of the code.
```bash
pixi run -e test-312 test
```
--------------------------------
### Compile for Development - Bash
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/DEVELOPER_GUIDE.md
Compiles the JavaScript bundle for development. This command watches for changes in React files (.jsx) and recompiles automatically.
```bash
pixi run compile-dev
```
--------------------------------
### Set Contrast Threshold for Accessibility (Python)
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/palette.md
Example of setting the `contrastThreshold` to 4.5 for improved accessibility, aligning with WCAG 2.1 recommendations for text contrast.
```python
my_theme = {
"palette": {
"contrastThreshold": 4.5,
"primary": {"main": "#3f50b5"},
}
}
```
--------------------------------
### Run UI Tests - Bash
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/DEVELOPER_GUIDE.md
Executes the UI test suite, likely involving visual regression or interaction testing. This ensures the user interface behaves as expected.
```bash
pixi run -e test-ui test-ui
```
--------------------------------
### Basic Theming with ThemeToggle for hvPlot Scatter
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/bokeh_holoviews.md
Demonstrates basic theming by integrating a `ThemeToggle` component with an hvPlot scatter plot. This setup allows the plot to automatically adapt to the active Material UI theme. It requires Panel, Panel Material UI, Pandas, and hvplot.
```python
import panel as pn
import panel_material_ui as pmu
import pandas as pd
import hvplot.pandas
pn.extension()
df = pd.read_csv("https://datasets.holoviz.org/penguins/v1/penguins.csv")
toggle = pmu.ThemeToggle(styles={"margin-left": "auto"})
pmu.Container(
toggle,
df.hvplot.scatter(
x="bill_length_mm", y="bill_depth_mm", by="species",
height=400, responsive=True
),
width_option="md"
).preview()
```
--------------------------------
### Responsive Typography with SX
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/typography.md
Apply responsive font sizes to a single Typography component using the 'sx' prop. This example adjusts the font size based on viewport width using media queries.
```python
from panel_material_ui import Typography
Typography(
"Responsive Typography",
sx={
"fontSize": "1.2rem",
"@media (min-width: 600px)": {
"fontSize": "1.5rem"
},
"@media (min-width: 900px)": {
"fontSize": "2.4rem"
}
}
).servable()
```
--------------------------------
### Customize Primary and Secondary Colors in Panel Material UI
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/color.md
This snippet demonstrates how to define custom primary and secondary colors for Panel Material UI components by providing a `theme_config` dictionary. It includes detailed light, main, dark, and contrast text configurations for both primary and secondary palettes. The example shows how to render `Button` components with these custom themes.
```python
from panel_material_ui import Button, Row
my_theme = {
"palette": {
"primary": {
"light": "#757575",
"main": "#424242",
"dark": "#212121",
"contrastText": "#fff"
},
"secondary": {
"light": "#ff7961",
"main": "#f44336",
"dark": "#ba000d",
"contrastText": "#000"
}
}
}
Row(
Button(label="Primary Button", theme_config=my_theme, button_type="primary"),
Button(label="Secondary Button", theme_config=my_theme, button_type="secondary"),
).servable()
```
--------------------------------
### Set Global Font Family
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/typography.md
Customize the default font family for the entire application by setting the 'fontFamily' in the theme configuration. This example applies a system font stack.
```python
from panel_material_ui import Typography
my_theme = {
"typography": {
"fontFamily": (
"-apple-system, "
"BlinkMacSystemFont, "
"\"Segoe UI\", "
"Roboto, "
"\"Helvetica Neue\", "
"Arial, sans-serif, "
"\"Apple Color Emoji\", "
"\"Segoe UI Emoji\", "
"\"Segoe UI Symbol\""
)
}
}
Typography(
"Hello with a System Font!",
theme_config=my_theme
).servable()
```
--------------------------------
### Add and Disable Typography Variants
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/typography.md
Extend the typography system by adding new variants or disabling existing ones. This example adds a 'poster' variant and disables the 'h3' variant.
```python
from panel_material_ui import Typography
my_theme = {
"typography": {
# Custom 'poster' variant
"poster": {
"fontSize": "4rem",
"color": "red"
},
# Disable h3
"h3": None
}
}
Typography(
"I'm a subtitle", theme_config=my_theme, variant="poster"
).servable()
```
--------------------------------
### Set Primary and Secondary Colors with Main Shade in Panel Material UI
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/color.md
This example shows a simplified approach to customizing primary and secondary colors in Panel Material UI. It only specifies the 'main' shade for each color, relying on the library to automatically calculate the light, dark, and contrast text values. This is useful for quick theme adjustments and renders `Button` components reflecting the chosen main colors.
```python
from panel_material_ui import Button, Row
my_theme = {
"palette": {
"primary": {
"main": "#9c27b0" # Purple 500
},
"secondary": {
"main": "#f44336" # Red 500
}
}
}
Row(
Button(label="Purple", theme_config=my_theme, button_type="primary"),
Button(label="Red", theme_config=my_theme, button_type="secondary"),
).servable()
```
--------------------------------
### Set Base Font Size
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/typography.md
Adjust the base font size for the application using 'rem' units. This example sets the base size to 12px, impacting all 'rem' based scaling. Accessibility is a key consideration, as users may have their own browser defaults.
```python
from panel_material_ui import Typography
my_theme = {
"typography": {
"fontSize": 12 # Default 14 in MUI
}
}
Typography(
"Smaller base font (12px -> 0.75rem).",
theme_config=my_theme
).servable()
```
--------------------------------
### Customize Dark Mode Palette with theme_config
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/dark_mode.md
Explains how to override the default dark mode color palette using the `theme_config` parameter. This example customizes the primary color for a `Button` component in dark mode.
```python
from panel_material_ui import Button
dark_theme_config = {
"dark": {
"palette": {
"primary": {
"main": "#450c0c"
}
}
},
"light": {
"palette": {
"primary": {
"main": "#eb5252"
}
}
}
}
Button(
label="Custom Dark",
dark_theme=True,
button_type="primary",
theme_config=dark_theme_config
).servable()
```
--------------------------------
### Adjust Global Button Typography (Python)
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/components.md
This example demonstrates how to adjust global theme variables by modifying the typography settings. Specifically, it changes the font size for buttons to '1rem' by targeting the 'button' key within the 'typography' dictionary in the `theme_config`.
```python
from panel_material_ui import Button
custom_theme = {
"typography": {
"button": {
"fontSize": "1rem"
}
}
}
Button(
label="Big Button Text", theme_config=custom_theme
).servable()
```
--------------------------------
### Globally Style Button Font Size (Python)
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/components.md
This code example shows how to globally override the font size for all Button components by using `styleOverrides` in the `theme_config`. The `root` slot targets the outermost element of the component, and the `fontSize` CSS property is set to '1rem'.
```python
from panel_material_ui import Button
custom_theme = {
"components": {
"MuiButton": {
"styleOverrides": {
"root": {
"fontSize": "1rem"
}
}
}
}
}
Button(label="Styled Button", theme_config=custom_theme).servable()
```
--------------------------------
### Manage Application State with Theme Support
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/branding.md
Defines an application state class using Panel's param system to manage reactive states like theme preference and currency selection. It synchronizes with the Panel theme configuration.
```python
import param
from panel.viewable import Viewer
class AppState(Viewer):
"""Application state management with theme support."""
dark_theme = param.Boolean(default=False, label="Dark Theme")
currency = param.Selector(default="EUR", objects=["EUR", "GBP", "USD"])
def __init__(self, **params):
super().__init__(**params)
# Sync with Panel's theme configuration
self.dark_theme = pn.config.theme == "dark"
def __panel__(self):
"""Render state controls."""
return pmui.Column(
pmui.Switch.from_param(self.param.dark_theme),
pmui.Select.from_param(self.param.currency),
)
```
--------------------------------
### Create Branded Application Layout
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/branding.md
Constructs the main application layout using Panel Material-UI components, incorporating branding elements like logos, state controls, and navigation links, while ensuring responsive design.
```python
def create_app():
"""Create the main application with branded layout."""
state = AppState()
# Create branded page layout
page = pmui.Page(
sidebar=[
pn.pane.Image(LOGO_PATH, sizing_mode="scale_width"),
pmui.Column(
"# Settings",
state,
"### References",
pmui.Button(
name="Documentation",
href="https://panel-material-ui.holoviz.org/",
target="_blank",
variant="outlined"
),
),
],
sidebar_width=400,
main=[
pmui.Container(
"## Welcome to Your Branded App",
"Your main content goes here...",
)
],
)
# Sync theme state
state.dark_theme = page.param.dark_theme
return page
```
--------------------------------
### Configure Page with Brand Assets and Custom CSS
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/branding.md
Configures the Panel page with brand assets such as the logo and favicon, sets the page meta name, and appends custom CSS.
```python
def configure():
# Brand assets configuration
pmui.Page.param.logo.default = LOGO_PATH
pmui.Page.favicon = FAVICON_PATH
pmui.Page.meta.name = "Your Brand Name"
# Add custom CSS
if RAW_CSS:
pmui.Page.config.raw_css.append(RAW_CSS)
```
--------------------------------
### Configure Deployment Settings for Branding
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/branding.md
Sets up deployment-specific branding configurations for Panel applications. This includes customizing the disconnect notification message, setting a default theme, and configuring static directory caching for assets.
```python
def configure_deployment():
"""Configure deployment-specific brand settings."""
# Custom disconnect notification
pn.config.disconnect_notification = (
"Connection lost. Please refresh to reconnect to your branded app."
)
# Ensure theme persistence
pn.config.theme = "light" # or "dark" as default
# Configure caching for assets
pn.config.static_dirs = {"assets": "brand/assets"}
def main():
"""Main application entry point."""
# Apply brand configuration
from brand.mui import configure
configure()
# Configure deployment
configure_deployment()
# Create and serve app
app = create_app()
app.servable()
if pn.state.served:
main()
```
--------------------------------
### Provide Color Tokens Directly (Python)
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/palette.md
Illustrates specifying color tokens directly within the theme configuration for 'primary' and 'secondary', with optional 'light', 'dark', and 'contrastText' for secondary.
```python
my_theme = {
"palette": {
"primary": {
"main": "#ff69b4", # Changed to pink
# light, dark, and contrastText can be automatically computed
},
"secondary": {
"main": "#E0C2FF",
"light": "#F5EBFF", # optional
"dark": "#BA99D5", # optional
"contrastText": "#47008F", # optional
}
}
}
Button(label="Custom Themed Button", theme_config=my_theme, button_type='primary')
```
--------------------------------
### Configure Light Theme for Panel Material-UI
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/branding.md
Defines the configuration dictionary for the light theme, including palette, typography, shape, and component defaults. This configuration is applied to the application's theme settings.
```python
LIGHT_THEME_CONFIG = {
"palette": {
"primary": {"main": LIGHT_THEME.primary},
"secondary": {"main": LIGHT_THEME.secondary},
"success": {"main": LIGHT_THEME.success},
"error": {"main": LIGHT_THEME.error},
"warning": {"main": LIGHT_THEME.warning},
"info": {"main": LIGHT_THEME.info},
},
"typography": {
"fontFamily": ("Montserrat", "Helvetica Neue", "Arial", "sans-serif"),
"fontSize": 16,
"fontWeight": 700,
"letterSpacing": 0.2,
"lineHeight": 1.5,
},
"shape": {
"borderRadius": 8,
},
"components": {
"MuiButtonBase": {
"defaultProps": {"disableRipple": True},
},
},
}
```
--------------------------------
### Create Branded Chart and Table with Panel
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/branding.md
Applies brand colors to charts and custom styles to data tables using Panel and HoloViews. It requires sample data and categorical color palettes. The table styling uses custom formatters for progress bars.
```python
def create_branded_chart(dark_theme: bool = False):
"""Create a chart with brand colors."""
df = get_sample_data()
cmap = get_categorical_palette(dark_theme=dark_theme, n_colors=3)
return df.hvplot.scatter(
x="x", y="y",
color="category",
cmap=cmap,
height=350,
responsive=True,
title="Branded Chart",
)
def create_branded_table():
"""Create a table with brand styling."""
df = get_sample_data()
# Custom formatters using brand colors
formatters = {
"progress": {
"type": "progress",
"color": [LIGHT_THEME.success, LIGHT_THEME.warning, LIGHT_THEME.error],
}
}
return pn.widgets.Tabulator(
df,
formatters=formatters,
theme="materialize",
sizing_mode="stretch_width",
)
```
--------------------------------
### Apply Global Theming with `theme_config` in Panel Material UI Button
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/customize.md
Demonstrates how to apply global styles to a Panel Material UI Button using the `theme_config` parameter. This allows for consistent theming by defining palette colors (primary and secondary) that can be applied across multiple components.
```python
from panel_material_ui import Button
theme_config = {
"palette": {
"primary": {"main": "#d219c9"},
"secondary": {"main": "#dc004e"},
}
}
Button(
label="Themed Button", theme_config=theme_config, button_type="primary"
).servable()
```
--------------------------------
### Apply One-off Styles with `sx` Parameter in Panel Material UI Button
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/customize.md
Demonstrates how to apply specific styles to a single instance of a Panel Material UI Button using the `sx` parameter. This allows for quick, local customizations like changing text color, background color, and hover effects.
```python
from panel_material_ui import Button
Button(
label="Click Me!",
sx={
"color": "white",
"backgroundColor": "black",
"&:hover": {
"backgroundColor": "gray",
}
}
).servable()
```
--------------------------------
### CSS for Material UI Theming and Layout
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/src/panel_material_ui/_templates/base.html
Defines core CSS rules for the application's layout, including box-sizing, height, margin, and padding for HTML and body elements. It also sets Material UI theme colors and typography for headings and body text, ensuring a consistent visual appearance.
```css
html, body { display: flow-root; box-sizing: border-box; height: 100%; margin: 0; padding: 0; }
html, body { color: var(--mui-palette-text-primary); background-color: var(--mui-palette-background-default); font: var(--mui-font-body1); }
h1 { font: var(--mui-font-h1) }
h2 { font: var(--mui-font-h2) }
h3 { font: var(--mui-font-h3) }
h4 { font: var(--mui-font-h4) }
h5 { font: var(--mui-font-h5) }
h6 { font: var(--mui-font-h6) }
```
--------------------------------
### Define Default Primary Color Tokens (Python)
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/palette.md
Demonstrates the structure of color tokens for a default primary color, including 'main', 'light', 'dark', and 'contrastText'.
```python
primary = {
'main': '#1976d2',
'light': '#42a5f5',
'dark': '#1565c0',
'contrastText': '#fff',
}
```
--------------------------------
### Embed and Configure Demo Iframe
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/index.md
Embeds a demo HTML file in an iframe and dynamically sets its source based on the current document's theme (light or dark). This script is crucial for visualizing the Material UI components within the Panel environment.
```html
```
--------------------------------
### Resolve Asset Paths for Branding
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/branding.md
Utility to resolve absolute paths for brand assets like favicons and logos. It also handles reading custom CSS files.
```python
# brand/assets/__init__.py
from pathlib import Path
ROOT = Path(__file__).parent
def _absolute(path: str) -> str:
"""Convert relative path to absolute path string."""
return str(Path(ROOT / path).resolve())
# Brand assets with absolute paths
FAVICON_PATH = _absolute("favicon.ico")
LOGO_PATH = _absolute("logo.png")
VISION_PATH = _absolute("vision.png")
# Load custom CSS
css_file = ROOT / "style.css"
RAW_CSS = css_file.read_text(encoding="utf-8") if css_file.exists() else ""
```
--------------------------------
### Define Dark and Light Mode Themes with `theme_config`
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/customize.md
Shows how to define distinct theme configurations for both dark and light modes in Panel Material UI components. By providing a dictionary with `light` and `dark` keys to `theme_config`, you can specify different palette colors for each theme.
```python
from panel_material_ui import Button, Row, ThemeToggle
theme_config = {
"light": {
"palette": {
"primary": {"main": "#d219c9"},
"secondary": {"main": "#dc004e"},
}
},
"dark": {
"palette": {
"primary": {"main": "#dc004e"},
"secondary": {"main": "#d219c9"},
}
}
}
Row(
Button(
label="Global Button", theme_config=theme_config, button_type="primary"
),
ThemeToggle(),
).preview()
```
--------------------------------
### Adjust Contrast Threshold for Auto-ContrastText (Python)
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/palette.md
Demonstrates how to set a custom `contrastThreshold` to influence the automatic computation of `contrastText` for better color contrast.
```python
my_theme = {
"palette": {
"primary": {
"main": "#3f50b5",
},
"contrastThreshold": 4.5 # Increase for higher contrast
}
}
```
--------------------------------
### CSS for Loading Spinner
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/src/panel_material_ui/_templates/base.html
Provides CSS for a loading spinner component. It styles a fixed overlay with a centered spinner that animates rotation, indicating that content is being loaded or processed. The spinner uses a Material Design-like appearance with a primary color accent.
```css
#loader { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.5); display: none; justify-content: center; align-items: center; z-index: 9999; }
.spinner { width: 50px; height: 50px; border: 5px solid #f3f3f3; border-top: 5px solid #3498db; border-radius: 50%; animation: spin 1s linear infinite; }
@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
```
--------------------------------
### Apply Theme and Fonts with Panel Material-UI
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/branding.md
Applies the theme configuration (light and dark) and custom fonts to the Panel application. It also sets default component properties like disabling elevation for buttons.
```python
def configure():
"""Configure the complete theme for the application."""
# Set theme configuration
pmui.Page.param.theme_config.default = {
"light": LIGHT_THEME_CONFIG,
"dark": DARK_THEME_CONFIG,
}
# Add custom fonts
pmui.Page.config.css_files.append(
"https://fonts.googleapis.com/css2?family=Montserrat:wght@100..900&display=swap"
)
# Configure component defaults
pmui.Button.param.disable_elevation.default = True
```
--------------------------------
### Apply Component-Specific Styling
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/branding.md
Applies specific styling to Panel components, such as rounded borders for images and setting the theme for Tabulator widgets.
```python
# Configure component-specific styling
pn.pane.Image.stylesheets = ["img {border-radius: 8px}"]
pn.widgets.Tabulator.param.theme = "materialize"
```
--------------------------------
### Use Material UI Icons in ButtonIcon (Python)
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/icons.md
Demonstrates how to use the 'icon' parameter in Panel Material UI's ButtonIcon component. Supports both filled and outlined versions of icons by appending '_outline' to the icon name. Requires the panel-material-ui library.
```python
import panel_material_ui as pmui
pmui.Row(
pmui.ButtonIcon(icon="lightbulb"),
pmui.ButtonIcon(icon="lightbulb_outline")
)
```
--------------------------------
### Categorical Color Palette Generation for hvPlot Scatter
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/bokeh_holoviews.md
Shows how to generate a categorical color palette aligned with a Material theme for an hvPlot scatter plot. It uses `pmu.theme.generate_palette` with a specified primary color to ensure distinct visual representation of categorical data. Dependencies include Pandas, hvplot, and Panel Material UI.
```python
import pandas as pd
import hvplot.pandas
import panel_material_ui as pmu
df = pd.read_csv("https://datasets.holoviz.org/penguins/v1/penguins.csv")
primary_color = "#6200ea"
colors = pmu.theme.generate_palette(primary_color)
toggle = pmu.ThemeToggle(styles={"margin-left": "auto"})
pmu.Container(
toggle,
df.hvplot.scatter(
x="bill_length_mm", y="bill_depth_mm", color="species",
height=400, responsive=True, cmap=colors
),
theme_config={"palette": {"primary": {"main": primary_color}}},
width_option="md"
).preview()
```
--------------------------------
### Continuous Color Map Generation for hvPlot Scatter
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/bokeh_holoviews.md
Illustrates creating a continuous color map aligned with a Material theme using `pmu.theme.linear_gradient`. This function generates a gradient between two colors, suitable for visualizing continuous data in hvPlot scatter plots. Requires Panel, Panel Material UI, Pandas, and hvplot.
```python
import panel as pn
import panel_material_ui as pmu
import pandas as pd
import hvplot.pandas
df = pd.read_csv("https://datasets.holoviz.org/penguins/v1/penguins.csv")
primary_color = "#6200ea"
pn.extension()
cmap = pmu.theme.linear_gradient("#ffffff", primary_color, n=256)
toggle = pmu.ThemeToggle(styles={"margin-left": "auto"})
plot = df.hvplot.scatter(
x="bill_length_mm", y="flipper_length_mm", c="body_mass_g",
cmap=cmap, colorbar=True, height=400, responsive=True
).opts(
backend_opts={
'plot.toolbar.autohide': True
},
toolbar='above'
)
pmu.Container(
toggle,
plot,
theme_config={"palette": {"primary": {"main": primary_color}}},
width_option="md"
).preview()
```
--------------------------------
### Define RainbowButton in Python
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/custom.md
This Python code defines the `RainbowButton` class, inheriting from `MaterialUIComponent`. It sets up parameters for colors, label, size, mode, and interval, and specifies the associated React component file and import map.
```python
import param
from panel_material_ui import MaterialUIComponent
RAINBOW = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]
class RainbowButton(MaterialUIComponent):
"""
A Button that cycles through rainbow colors.
:Example:
>>> RainbowButton(label="Go!", size="medium", mode="hover")
"""
colors = param.List(default=RAINBOW, doc="""
The colors to cycle through.""")
label = param.String(default="Click me!", doc="""
The label shown on the button.""")
size = param.Selector(default="medium", objects=["small", "medium", "large"], doc="""
Material-UI button size.""")
mode = param.Selector(default="hover", objects=["hover", "click"], doc="""
When to cycle: on hover or on click.""")
interval = param.Integer(default=200, doc="""
Time in ms between color changes.""")
_esm_base = "RainbowButton.jsx"
_importmap = {
"imports": {
"confetti": "https://esm.sh/canvas-confetti@1.6.0"
}
}
```
--------------------------------
### Basic Plotly Theming with Panel Material UI
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/plotly.md
Applies the default Material UI theme to a Plotly scatter plot. The theme is applied automatically, ensuring consistency with the Panel application's appearance. No external dependencies beyond Panel and Plotly are required.
```python
import panel as pn
import panel_material_ui as pmui
import plotly.express as px
pn.extension("plotly")
df = px.data.iris()
plot = px.scatter(
df, x="sepal_length", y="sepal_width", color="species",
height=400
)
pmui.Container(
plot, width_option="md"
).preview(height=500)
```
--------------------------------
### Use Page Component for Managed Dark Mode
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/dark_mode.md
Illustrates using the `Page` component from `panel_material_ui` to manage dark mode automatically. The `Page` component includes a theme toggle and respects the `dark_theme` setting, simplifying global theme control.
```python
from panel_material_ui import Page, Button
Page(
dark_theme=True,
main=[
Button(
label="Dark Button"
)
],
title="Dark Mode Demo",
).preview()
```
--------------------------------
### Customize Button Theme with Custom Palette (Python)
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/palette.md
Shows how to override default palette colors for 'primary' and 'secondary' when creating a Button component using `theme_config`.
```python
from panel_material_ui import Button
my_theme = {
"palette": {
"primary": {
"main": "#ff69b4", # Changed to pink
"light": "#42a5f5",
"dark": "#1565c0",
"contrastText": "#fff",
},
"secondary": {
"main": "#f44336",
},
}
}
Button(label="Custom Themed Button", theme_config=my_theme, button_type='primary')
```
--------------------------------
### Enable Global Dark Mode with Panel Extension
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/dark_mode.md
Shows how to enable dark mode globally for all Panel components by configuring the Panel extension with `theme='dark'`. This affects all subsequent Panel elements in the session.
```python
import panel as pn
pn.extension(theme='dark')
```
--------------------------------
### Theme Inheritance in Panel Material UI Card and Button
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/customize.md
Illustrates theme inheritance in Panel Material UI, where a child component (Button) automatically adopts the theming properties (primary color) defined in its parent container (Card). This pattern is recommended for applying consistent styles from a top-level container.
```python
from panel_material_ui import Card, Button
Card(
Button(label="Child Button", button_type="primary"), # Inherits parent's theme
title="Parent Card",
theme_config={
"palette": {
"primary": {"main": "#d219c9"},
}
}
).servable()
```
--------------------------------
### Embed Material UI Icons in Markdown/HTML (Python)
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/icons.md
Shows how to embed Material UI icons directly into strings intended for Panel's Markdown or HTML components. Icons are rendered by applying 'material-icons' or 'material-icons-outlined' CSS classes to a span element, along with a style for size. Requires the panel-material-ui library.
```python
import panel_material_ui as pmui
pmui.Column(
'Here is a lightbulb: lightbulb',
'Here is an outlined lightbulb: lightbulb'
)
```
--------------------------------
### Override Tonal Offset for Light/Dark Variants (Python)
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/palette.md
Shows how to modify the `tonalOffset` value to control how 'light' and 'dark' color tokens are computed from the 'main' color.
```python
my_theme = {
"palette": {
"tonalOffset": 0.25,
"primary": {
"main": "#FF5733",
},
}
}
```
--------------------------------
### Embed ThemeToggle for Global Dark Mode Switching
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/dark_mode.md
Demonstrates embedding the `ThemeToggle` component to manage dark mode globally across the Panel application. This component allows users to switch between light and dark themes interactively.
```python
from panel_material_ui import Button, Row, ThemeToggle
Row(Button(name="Hello"), ThemeToggle()).preview()
```
--------------------------------
### Conditional Styling with `.mui-dark`/`.mui-light` in Panel Material UI Button
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/customize.md
Shows how to apply styles to a Panel Material UI Button conditionally based on the theme mode (dark or light) using the `.mui-dark` and `.mui-light` classes within the `sx` parameter. This enables theme-aware styling for hover states.
```python
from panel_material_ui import Button, Row, ThemeToggle
Row(
Button(
label="Click Me!",
sx={
"color": "white",
"backgroundColor": "black",
"&:hover": {
"backgroundColor": "pink",
},
"&.mui-dark:hover": {
"backgroundColor": "orange",
}
}
),
ThemeToggle(),
).preview()
```
--------------------------------
### Plotly Theming with Dark Mode Toggle
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/plotly.md
Demonstrates integrating a `ThemeToggle` with a Plotly chart to switch between light and dark themes. The `dark_theme` argument in `pmui.Container` controls the applied theme. This is useful for user-controlled appearance preferences.
```python
import panel as pn
import panel_material_ui as pmui
import plotly.express as px
pn.extension("plotly")
df = px.data.iris()
toggle = pmui.ThemeToggle(styles={"margin-left": "auto"}, value=True)
plot = px.scatter(
df, x="sepal_length", y="sepal_width", color="species",
height=400
)
pmui.Container(
toggle, plot, dark_theme=True, width_option="md"
).preview(height=500)
```
--------------------------------
### Style Card Variant 'outlined' (Python)
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/components.md
This snippet illustrates how to apply conditional styling to Card components based on their `variant` prop. It increases the border thickness to '3px' when the `variant` is set to 'outlined' using the `variants` array within `styleOverrides`.
```python
from panel_material_ui import Card
custom_theme = {
"components": {
"MuiCard": {
"styleOverrides": {
"root": {
"variants": [
{
"props": {"variant": "outlined"},
"style": {
"borderWidth": "3px"
}
}
]
}
}
}
}
}
Card(
title="Thick Outlined Card", variant="outlined", theme_config=custom_theme
).servable()
```
--------------------------------
### Enforce High Contrast Ratio in Panel Material UI Theme
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/color.md
This code snippet illustrates how to enforce a higher contrast ratio for text on components within Panel Material UI, aiming for AA-level compliance (4.5:1). By setting the `contrastThreshold` in the `theme_config`, developers can override the default contrast behavior, ensuring better readability for users, especially with specific color choices.
```python
my_theme = {
"palette": {
"primary": {"main": "#3f50b5"},
"contrastThreshold": 4.5, # Force higher contrast across the board
}
}
```
--------------------------------
### Render RainbowButton in React
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/custom.md
This React code defines the `render` function for the `RainbowButton` component. It synchronizes Python parameters, manages internal state for color cycling, handles hover and click events, and applies dynamic styling to the Material UI Button.
```jsx
import Button from "@mui/material/Button";
import confetti from "confetti"
export function render({model}) {
// Sync Python params into React state
const [label] = model.useState("name");
const [size] = model.useState("size");
const [mode] = model.useState("mode");
const [interval] = model.useState("interval");
// Internal state: current color index
const [index, setIndex] = React.useState(0);
// Function to advance the color
const nextColor = () => (
setIndex(i => (i + 1) % model.colors.length)
);
// On “click” mode, cycle once per click
const handleClick = () => {
confetti();
if (mode === "click") nextColor();
};
// On “hover” mode, cycle continuously while hovered
let hoverTimer = React.useRef(null);
const handleMouseEnter = () => {
if (mode === "hover") {
hoverTimer.current = setInterval(nextColor, interval);
}
};
const handleMouseLeave = () => {
if (mode === "hover") {
clearInterval(hoverTimer.current);
}
};
const currentColor = model.colors[index];
return (
);
}
```
--------------------------------
### JavaScript for Bokeh Plot Loading Indicator
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/src/panel_material_ui/_templates/base.html
Implements a JavaScript function to control the visibility of a loading indicator. It periodically checks the status of Bokeh plots and hides the loader once the plots are idle or have loaded. If the plots remain non-idle for a certain duration, the loader is displayed.
```javascript
let timeout = 0;
function checkIdle() {
if (Bokeh.index && Bokeh.index.roots[0] && Bokeh.index.roots[0].model.document.is_idle) {
document.getElementById('loader').style.display = 'none';
} else {
timeout += 100;
if (timeout > 500) {
document.getElementById('loader').style.display = 'flex';
}
setTimeout(checkIdle, 100);
}
}
setTimeout(checkIdle, 100)
```
--------------------------------
### Override Typography Variants
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/typography.md
Customize individual text variants like 'subtitle1', 'body1', and 'button' through the theme configuration. This allows fine-grained control over specific text styles.
```python
from panel_material_ui import Typography
my_theme = {
"typography": {
"subtitle1": {"fontSize": 12},
"body1": {"fontWeight": 500},
"button": {"fontStyle": "italic"},
}
}
Typography(
"I'm a subtitle", theme_config=my_theme, variant="subtitle1"
).servable()
```
--------------------------------
### Embedding Bokeh Plots in Panel
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/src/panel_material_ui/_templates/base.html
This Jinja2 template snippet demonstrates how to embed Bokeh plots within a Panel application. It iterates through documented roots and embeds them using the `embed` function, handling cases where elements have specific IDs.
```jinja
{% for doc in docs %}
{{ embed(doc) if doc.elementid }}
{%- for root in doc.roots %}
{% block root scoped %}
{{ embed(root) }}
{% endblock %}
{% endfor %}
{% endfor %}
{{ plot_script | indent(4) }}
```
--------------------------------
### Custom Categorical Colors for Plotly
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/plotly.md
Generates a custom categorical color palette using `pmui.theme.generate_palette` to match a primary color. This palette is then applied to a Plotly scatter plot using the `color_discrete_sequence` argument, ensuring visual consistency with the Material UI theme.
```python
import panel as pn
import plotly.express as px
import panel_material_ui as pmui
pn.extension("plotly")
df = px.data.iris()
primary_color = "#4099da"
# Generate colors using existing theme function
colors = pmui.theme.generate_palette(primary_color, n_colors=3)
plot = px.scatter(
df, x="sepal_length", y="sepal_width", color="species",
height=400,
color_discrete_sequence=colors
)
toggle = pmui.ThemeToggle(styles={"margin-left": "auto"}, value=False)
pmui.Container(
toggle,
plot,
theme_config={"palette": {"primary": {"main": primary_color}}},
width_option="md"
).preview(height=500)
```
--------------------------------
### Custom Continuous Color Scale for Plotly
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/plotly.md
Creates a custom continuous color scale for Plotly using `pmui.theme.linear_gradient`. This function generates a gradient between two specified colors, which is then applied to a Plotly scatter plot via the `color_continuous_scale` argument for continuous data visualization.
```python
import panel as pn
import plotly.express as px
import panel_material_ui as pmui
pn.extension("plotly")
df = px.data.iris()
primary_color = "#4099da"
colorscale = pmui.theme.linear_gradient("#ffffff", primary_color, n=256)
plot = px.scatter(
df, x="sepal_length", y="sepal_width", color="petal_length",
height=400,
color_continuous_scale=colorscale
)
toggle = pmui.ThemeToggle(styles={"margin-left": "auto"}, value=False)
pmui.Container(
toggle,
plot,
theme_config={"palette": {"primary": {"main": primary_color}}},
width_option="md"
).preview(height=500)
```
--------------------------------
### Override Button Ripple Effect Globally (Python)
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/components.md
This snippet demonstrates how to disable the ripple effect for all Button components by setting `disableRipple` to `True` in the `defaultProps` for `MuiButton` within the `theme_config`. This ensures a consistent UI behavior across the application.
```python
from panel_material_ui import Button
custom_theme = {
"components": {
"MuiButton": {
"defaultProps": {
"disableRipple": True
}
}
}
}
Button(label="No Ripple!", theme_config=custom_theme).servable()
```
--------------------------------
### Force Dark Mode with Button Component
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/dark_mode.md
Demonstrates how to force a Panel Material UI Button component to always render in dark mode by setting the `dark_theme` parameter to `True`. This is useful for specific components that should override global theme settings.
```python
from panel_material_ui import Button
Button(
label="Dark Button", dark_theme=True
).servable()
```
--------------------------------
### Override Nested Component Styles in Panel Material UI FloatSlider
Source: https://github.com/panel-extensions/panel-material-ui/blob/main/doc/how_to/customize.md
Illustrates how to target and override the styles of a nested element within a Panel Material UI component, specifically the thumb of a `FloatSlider`. This is achieved by using Material UI's internal class names (e.g., `.MuiSlider-thumb`) within the `sx` parameter to modify properties like border-radius.
```python
from panel_material_ui import FloatSlider
FloatSlider(
sx={
"& .MuiSlider-thumb": {
"borderRadius": 0 # square
}
}
).servable()
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.