🔍 Code Extractor

class Toggle_switch

Maturity: 55

A customizable toggle switch widget in C-Path style that extends ReactiveHTML, providing a checkbox-like interface with visual slider representation.

File:
/tf/active/vicechatdev/resources/py2html.py
Lines:
113 - 162
Complexity:
moderate

Purpose

This class creates an interactive toggle switch UI component that can be used in Panel dashboards. It provides a boolean on/off control with customizable appearance (square or round) and optional text label. The component is reactive, meaning changes to its state automatically update the UI and can trigger callbacks. It's designed for use in data applications where users need to toggle settings or features on and off.

Source Code

class Toggle_switch(ReactiveHTML):
    """
    A toggle slider in C-Path style.
    
    Attributes
    ----------
    value : param.Boolean
        The default status of the widget, either True or False
    text : param.String
        The text shown next to the widget.
    toggle_type : param.Selector
        The type of toggle widget, should be either 'square' (default) or 'round'
    
    Raises
    ------
    ValueError
        When kwargs do not match their specified datatype.
    """
    
    value = param.Boolean(default=False)
    disabled = param.Boolean(default=False)
    text = param.String()
    toggle_type = param.Selector(default='square', objects=['square','round'])

    _template = """
    <div>
        <label class="switch toggle-span">
            <input id="span-input" type="checkbox" checked="${value}" disabled="${disabled}" onclick="${_update_value}" style="display:none;"></input>
            <span id="slider" class="slider ${toggle_type}"></span>
        </label>
        <span id="title_holder" class="text-span">{{ text }}</span>
    </div>
    """
    
    def _update_value(self, e):
        """
        Update value attribute when the checkbox is pressed
        """
        self.value = not self.value
        
    def on_click(self, callback):
        """
        Set an on click function for this widget
        
        parameters
        ----------
        callback : function
            function to carry out when the widget is clicked
        """
        return self.param.watch(callback, 'value', onlychanged=False)

Parameters

Name Type Default Kind
bases ReactiveHTML -

Parameter Details

value: Boolean parameter (default: False) that represents the current state of the toggle switch. When True, the switch is in the 'on' position; when False, it's 'off'. This parameter is reactive and can be watched for changes.

disabled: Boolean parameter (default: False) that controls whether the toggle switch is interactive. When True, the switch cannot be clicked or changed by the user.

text: String parameter that sets the label text displayed next to the toggle switch. Can be empty or any string value to describe the switch's purpose.

toggle_type: Selector parameter (default: 'square') that determines the visual style of the toggle slider. Must be either 'square' or 'round'. This affects the CSS class applied to the slider element.

Return Value

Instantiating this class returns a Toggle_switch object that is a Panel ReactiveHTML component. The on_click method returns a watcher object that can be used to remove the callback later. The _update_value method does not return a value (implicitly returns None).

Class Interface

Methods

_update_value(self, e) -> None

Purpose: Internal method that toggles the value attribute when the checkbox is clicked in the UI

Parameters:

  • e: Event object passed from the JavaScript onclick handler

Returns: None - updates the value attribute as a side effect

on_click(self, callback) -> Watcher

Purpose: Registers a callback function to be executed when the toggle switch value changes

Parameters:

  • callback: A function that will be called when the toggle is clicked. The function receives an event object with 'new' and 'old' attributes representing the value state

Returns: A Watcher object from param.watch that can be used to remove the callback later

Attributes

Name Type Description Scope
value param.Boolean The current state of the toggle switch (True for on, False for off). Default is False. This is a reactive parameter that triggers UI updates when changed. class
disabled param.Boolean Controls whether the toggle switch is interactive. When True, the switch cannot be clicked. Default is False. class
text param.String The label text displayed next to the toggle switch. Can be any string value or empty. class
toggle_type param.Selector The visual style of the toggle slider. Must be either 'square' (default) or 'round'. This determines the CSS class applied to the slider element. class
_template str HTML template string that defines the structure and reactive bindings for the toggle switch component. Contains the checkbox input, slider span, and text label elements. class

Dependencies

  • param
  • panel

Required Imports

import param
import panel as pn
from panel.reactive import ReactiveHTML

Usage Example

import param
import panel as pn
from panel.reactive import ReactiveHTML

# Define the Toggle_switch class (code from above)

# Instantiate a toggle switch
toggle = Toggle_switch(
    value=False,
    text='Enable Feature',
    toggle_type='round',
    disabled=False
)

# Define a callback function
def handle_toggle_change(event):
    print(f'Toggle switched to: {event.new}')

# Attach the callback
toggle.on_click(handle_toggle_change)

# Display in a Panel app
pn.extension()
app = pn.Column(toggle)
app.servable()

# Access current value
print(toggle.value)  # False

# Programmatically change value
toggle.value = True  # This will trigger the callback

Best Practices

  • Always define CSS styles for the 'switch', 'slider', 'square', 'round', and 'text-span' classes before using this component to ensure proper visual rendering
  • Use the on_click method to attach callbacks rather than directly watching the value parameter for cleaner code organization
  • Set the disabled parameter to True when you want to prevent user interaction temporarily without removing the widget
  • The toggle_type parameter must be either 'square' or 'round' - passing other values will raise a ValueError
  • The component is reactive, so changing the value attribute programmatically will update the UI automatically
  • Callbacks attached via on_click receive an event object with 'new' and 'old' attributes representing the value state
  • This component requires a Panel server or notebook environment to function properly as it relies on ReactiveHTML
  • The _update_value method is internal and should not be called directly by users

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class Confirm_button 57.8% similar

    A custom Panel button widget that conditionally displays a confirmation dialog before registering clicks, built on ReactiveHTML with integrated JavaScript handlers.

    From: /tf/active/vicechatdev/resources/py2html.py
  • class Focus_button 49.4% similar

    A custom Panel ReactiveHTML button widget that displays an eye icon and tracks the number of times it has been clicked.

    From: /tf/active/vicechatdev/resources/py2html.py
  • class Click_watcher 46.6% similar

    A wrapper class that adds click detection functionality to Panel objects by wrapping them in a clickable div element and tracking the number of clicks.

    From: /tf/active/vicechatdev/resources/py2html.py
  • class Scrollmenu 46.3% similar

    A horizontal scroll menu component that displays a series of clickable icons representing different stages of a pathology workflow, built using Panel's ReactiveHTML for enhanced CSS customization.

    From: /tf/active/vicechatdev/resources/py2html.py
  • class Browser_button 46.3% similar

    A custom Panel ReactiveHTML button component that displays a file or folder icon with text and tracks click events.

    From: /tf/active/vicechatdev/resources/py2html.py
← Back to Browse