🔍 Code Extractor

class Enter_watcher

Maturity: 55

A Panel ReactiveHTML wrapper class that monitors Enter key presses on wrapped panel objects (like text fields or buttons) and tracks the count of Enter key events.

File:
/tf/active/vicechatdev/resources/py2html.py
Lines:
165 - 217
Complexity:
moderate

Purpose

This class wraps Panel UI components to add Enter key detection functionality. It's useful for creating interactive forms or input fields where you want to trigger actions when users press Enter. The class maintains a counter of Enter key presses and provides a callback mechanism to respond to these events. It extends Panel's ReactiveHTML to integrate JavaScript DOM events with Python callbacks.

Source Code

class Enter_watcher(ReactiveHTML):
    """
    A wrapper class for panel objects that essentially places an enter watcher on the object
    
    parameters
    ----------
    parameter : param.Parameter
        Should be a panel object, i.e. a button or text field
    justify : param.String
        How to align the content. Options are 'start', 'center' or 'end'
        
    attributes
    ----------
    value : integer
        The number of times an enter key-press was registered
    """
    
    value = param.Integer(default=0)
    parameter = param.Parameter()
    justify = param.Selector(default='start', objects=['start','center','end'])
    
    _template = """
    <div id="wrapper" style="display:flex; justify-content:${justify};">${parameter}</div>
    """
    
    _dom_events = {'wrapper':['keyup']}

    
    def _wrapper_keyup(self,e):
        """
        Python callback that responds to a keyup. Incrementally increases the value attribute.
        
        parameters
        ----------
        e : event-like
            The javascript event object
        """
        try: #Mouse click events seemingly also get passed, but don't follow the same data structure, thus throwing an exception when trying to grab the 'key' key
            if e.data['key'] == 'Enter':
                self.value+=1
        except:
            pass
        
    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

parameter: A Panel widget object (e.g., pn.widgets.TextInput, pn.widgets.Button) that will be wrapped and monitored for Enter key presses. This is the UI component that will be displayed and watched.

justify: Controls the horizontal alignment of the wrapped component within its container. Accepts 'start' (left-aligned), 'center' (centered), or 'end' (right-aligned). Defaults to 'start'.

value: An integer counter that tracks the number of times the Enter key has been pressed while the wrapped component has focus. Defaults to 0 and increments with each Enter key press.

Return Value

Instantiation returns an Enter_watcher object that wraps the provided Panel component. The on_click method returns a watcher object from param.watch that can be used to unwatch the callback later. The _wrapper_keyup method does not return a value (implicitly returns None).

Class Interface

Methods

__init__(parameter=None, justify='start', value=0, **params)

Purpose: Initialize the Enter_watcher instance with a Panel widget to wrap and optional alignment settings

Parameters:

  • parameter: Panel widget object to wrap and monitor for Enter key presses
  • justify: Horizontal alignment of the wrapped component ('start', 'center', or 'end')
  • value: Initial count of Enter key presses (defaults to 0)
  • **params: Additional parameters passed to ReactiveHTML parent class

Returns: An Enter_watcher instance

_wrapper_keyup(self, e) -> None

Purpose: Internal callback that responds to keyboard keyup events, incrementing the value counter when Enter is pressed

Parameters:

  • e: JavaScript event object containing event data including the 'key' property

Returns: None (implicitly)

on_click(self, callback) -> param.Watcher

Purpose: Register a callback function to be executed whenever the Enter key is pressed on the wrapped component

Parameters:

  • callback: Function to execute when Enter is pressed. Receives an event object with 'new' and 'old' values of the counter

Returns: A param.Watcher object that can be used to unwatch the callback later

Attributes

Name Type Description Scope
value param.Integer Counter tracking the number of times Enter key has been pressed. Starts at 0 and increments with each Enter press. class
parameter param.Parameter The Panel widget object being wrapped and monitored for Enter key events. class
justify param.Selector Controls horizontal alignment of the wrapped component. Options are 'start', 'center', or 'end'. Defaults to 'start'. class
_template str HTML template string defining the component's DOM structure with flexbox layout and parameter injection. class
_dom_events dict Dictionary mapping DOM element IDs to event types to listen for. Configured to listen for 'keyup' events on the 'wrapper' element. 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

class Enter_watcher(ReactiveHTML):
    value = param.Integer(default=0)
    parameter = param.Parameter()
    justify = param.Selector(default='start', objects=['start','center','end'])
    _template = '<div id="wrapper" style="display:flex; justify-content:${justify};">${parameter}</div>'
    _dom_events = {'wrapper':['keyup']}
    def _wrapper_keyup(self,e):
        try:
            if e.data['key'] == 'Enter':
                self.value+=1
        except:
            pass
    def on_click(self, callback):
        return self.param.watch(callback, 'value', onlychanged=False)

# Create a text input widget
text_input = pn.widgets.TextInput(placeholder='Type and press Enter')

# Wrap it with Enter_watcher
enter_watcher = Enter_watcher(parameter=text_input, justify='center')

# Define callback function
def handle_enter(event):
    print(f'Enter pressed {event.new} times')

# Register callback
enter_watcher.on_click(handle_enter)

# Display in a Panel app
enter_watcher.servable()

Best Practices

  • Always pass a valid Panel widget object to the 'parameter' argument during instantiation
  • Use the on_click method to register callbacks rather than directly watching the 'value' attribute
  • The value attribute increments indefinitely - reset it manually if you need to track Enter presses in discrete sessions
  • The _wrapper_keyup method is internal and should not be called directly by users
  • The class uses a try-except block to handle mouse click events that may trigger keyup handlers - this is intentional design
  • Callbacks registered with on_click will fire every time Enter is pressed, even if the value doesn't change (onlychanged=False)
  • Ensure the wrapped component is focusable for keyboard events to be captured properly
  • This component requires a browser environment to function as it relies on JavaScript DOM events

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class Click_watcher 76.8% 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 Confirm_button 51.6% 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
  • function _eval_panel 49.1% similar

    Evaluates and initializes a panel component (function, template, or panel object) within a Bokeh document context, handling different panel types and modifying the document accordingly.

    From: /tf/active/vicechatdev/patches/server.py
  • class Inbox 48.6% similar

    A reactive HTML component that displays a mailbox/notification icon with a badge indicator and tracks user clicks.

    From: /tf/active/vicechatdev/resources/py2html.py
  • class Focus_button 48.1% 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
← Back to Browse