class JSTree_json
A Panel ReactiveHTML component that wraps the jsTree JavaScript library to create an interactive, searchable tree view with custom icons and node selection capabilities.
/tf/active/vicechatdev/resources/py2html.py
549 - 619
moderate
Purpose
JSTree_json provides a web-based tree visualization component for hierarchical data structures. It integrates the jsTree library with Panel's reactive framework, allowing Python applications to display and interact with tree structures. The component supports searching, custom node types with Font Awesome icons, and tracks user interactions through node selection events. It's designed for applications that need to display hierarchical data like file systems, organizational structures, or nested configurations.
Source Code
class JSTree_json(ReactiveHTML):
data = param.List() #json
selected = param.String()
clicks = param.Integer(default=0)
_template = """
<input type="text" id="jstreesearch" class="input" placeholder="Search"></input>
<div id="jstree">
</div>
"""
_scripts = {
"render":
"""
console.log(data.data)
$(jstree)
.on("select_node.jstree", function (e, data) {
console.log(data.selected[0])
if(data.selected.length) {
self.myclick(selected=data.selected[0])
data.instance.deselect_node( [ data.selected[0] ] );
}
}).jstree({
'core': {
'data': data.data
},
'types' : {
'Configuration': {
'icon':'fa fa-home'
},
'a': {
'icon':'fas fa-layer-group'
},
'b': {
'icon':'fas fa-paw'
},
'c' : {
'icon':'fas fa-lungs'
},
'staining': {
'icon':'fas fa-splotch'
},
'slide': {
'icon':'fas fa-microscope'
},
},
"plugins": [ "search", "types" ]
});
$(jstreesearch).keyup(function () {
$("div[id^='jstree']").show();
$("div[id^='jstree']").jstree('search', $(this).val());
});
//$(jstree).on('ready.jstree', function() {
// $(jstree).jstree("open_all");
//});
""",
"myclick":"data.selected=selected; data.clicks+=1;",
}
_extension_name = 'JSTree'
__javascript_modules__ = [
'https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.15/jstree.min.js',
]
__css__ = [
"https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css",
"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"
]
def on_click(self, callback):
return self.param.watch(callback, 'clicks', onlychanged=False)
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
bases |
ReactiveHTML | - |
Parameter Details
data: A list containing JSON-formatted tree data compatible with jsTree's data format. Each item should be a dictionary with properties like 'id', 'text', 'parent', and optionally 'type' for custom icons. This defines the structure and content of the tree.
selected: A string representing the ID of the currently selected node. Updated automatically when a user clicks on a tree node. Can be monitored to track user selections.
clicks: An integer counter that increments each time a user clicks on a tree node. Defaults to 0. Used to trigger callbacks even when the same node is clicked multiple times.
Return Value
Instantiation returns a JSTree_json object that inherits from ReactiveHTML. This object can be added to Panel layouts and will render as an interactive tree widget in the browser. The on_click method returns a watcher object that can be used to manage callback subscriptions.
Class Interface
Methods
on_click(self, callback) -> watcher
Purpose: Registers a callback function to be executed whenever a tree node is clicked
Parameters:
callback: A callable function that will be invoked when the clicks parameter changes. The callback receives an event object with information about the parameter change.
Returns: A watcher object from param.watch that can be used to manage or remove the callback subscription
Attributes
| Name | Type | Description | Scope |
|---|---|---|---|
data |
param.List | Stores the JSON-formatted tree structure data. Each element should be a dictionary with jsTree-compatible fields (id, parent, text, type, etc.) | instance |
selected |
param.String | Holds the ID of the currently selected tree node. Updated automatically when users click on nodes. | instance |
clicks |
param.Integer | Counter that increments with each node click. Defaults to 0. Used to trigger callbacks even when the same node is clicked multiple times. | instance |
_template |
str | HTML template string defining the component's DOM structure with a search input and tree container div | class |
_scripts |
dict | Dictionary mapping script names to JavaScript code. Contains 'render' for initialization and 'myclick' for handling node selection events | class |
_extension_name |
str | Name identifier for the Panel extension, set to 'JSTree' | class |
__javascript_modules__ |
list | List of external JavaScript library URLs to load, specifically the jsTree library from CDN | class |
__css__ |
list | List of CSS stylesheet URLs to load for styling the tree and icons (jsTree theme and Font Awesome) | class |
Dependencies
parampaneljstree (JavaScript library, loaded via CDN)jQuery (implicit dependency of jstree)font-awesome (for icons, loaded via CDN)
Required Imports
import param
import panel as pn
from panel.reactive import ReactiveHTML
Usage Example
import panel as pn
from panel.reactive import ReactiveHTML
import param
# Define the JSTree_json class (as provided)
# Initialize Panel
pn.extension()
# Create tree data in jsTree format
tree_data = [
{'id': '1', 'parent': '#', 'text': 'Root', 'type': 'Configuration'},
{'id': '2', 'parent': '1', 'text': 'Child 1', 'type': 'a'},
{'id': '3', 'parent': '1', 'text': 'Child 2', 'type': 'b'},
{'id': '4', 'parent': '2', 'text': 'Grandchild', 'type': 'slide'}
]
# Instantiate the tree component
tree = JSTree_json(data=tree_data)
# Define a callback for node clicks
def handle_click(event):
print(f"Node selected: {tree.selected}")
print(f"Total clicks: {tree.clicks}")
# Register the callback
tree.on_click(handle_click)
# Display in a Panel app
app = pn.Column(tree)
app.servable()
Best Practices
- Ensure data is properly formatted according to jsTree specifications with 'id', 'parent', and 'text' fields
- Use the 'type' field in data items to assign custom icons from the predefined types (Configuration, a, b, c, staining, slide)
- Monitor the 'clicks' parameter rather than 'selected' if you need to detect repeated clicks on the same node
- The component automatically deselects nodes after selection to allow re-clicking the same node
- Use on_click() method to register callbacks rather than directly watching parameters for better encapsulation
- The search functionality is automatically enabled and filters the tree based on text input
- External CDN resources must be accessible; consider hosting locally for offline applications
- The component requires a browser environment and will not work in pure Python contexts
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class Extending_column 51.4% similar
-
function print_node_tree 51.0% similar
-
class Study_progress 50.9% similar
-
class Toolbar 50.1% similar
-
class Extending_row 49.4% similar