### Treeselect.js Initialization Example Source: https://github.com/dipson88/treeselectjs/blob/main/README.md A comprehensive example demonstrating how to initialize Treeselect.js with nested options, set initial values, attach event listeners, and integrate custom HTML elements as slots. This showcases the component's core functionality. ```javascript import Treeselect from 'treeselectjs' const options = [ { name: 'England', value: 1, children: [ { name: 'London', value: 2, children: [ { name: 'Chelsea', value: 3, children: [] }, { name: 'West End', value: 4, children: [] } ] }, { name: 'Brighton', value: 5, children: [] } ] }, { name: 'France', value: 6, children: [ { name: 'Paris', value: 7, children: [] }, { name: 'Lyon', value: 8, children: [] } ] } ] // Use slot if you need const slot = document.createElement('div') slot.innerHTML='Click!' const domElement = document.querySelector('.treeselect-demo') const treeselect = new Treeselect({ parentHtmlContainer: domElement, value: [4, 7, 8], options: options, listSlotHtmlComponent: slot }) treeselect.srcElement.addEventListener('input', (e) => { console.log('Selected value:', e.detail) }) slot.addEventListener('click', (e) => { e.preventDefault() alert('Slot click!') }) ``` -------------------------------- ### Basic TreeselectJS Setup (ES Module) Source: https://context7.com/dipson88/treeselectjs/llms.txt Demonstrates how to import and initialize TreeselectJS using ES Modules. It includes defining hierarchical options, rendering the component, and listening for input events. ```javascript import Treeselect from 'treeselectjs' import 'treeselectjs/dist/treeselectjs.css' const options = [ { name: 'England', value: 1, children: [ { name: 'London', value: 2, children: [ { name: 'Chelsea', value: 3, children: [] }, { name: 'West End', value: 4, children: [] } ] }, { name: 'Brighton', value: 5, children: [] } ] }, { name: 'France', value: 6, children: [ { name: 'Paris', value: 7, children: [] }, { name: 'Lyon', value: 8, children: [] } ] } ] const container = document.querySelector('#treeselect-container') const treeselect = new Treeselect({ parentHtmlContainer: container, value: [4, 7, 8], // Pre-selected values options: options }) // Listen to value changes treeselect.srcElement.addEventListener('input', (e) => { console.log('Selected values:', e.detail) // [4, 7, 8] console.log('Current value:', treeselect.value) // [4, 7, 8] console.log('Selected name:', treeselect.selectedName) // 'West End, Paris, Lyon' }) ``` -------------------------------- ### Install Treeselect.js with npm Source: https://github.com/dipson88/treeselectjs/blob/main/README.md This command installs the Treeselect.js library as a project dependency using npm. It's the standard way to add the library to your project for use in bundled applications. ```bash npm install --save treeselectjs ``` -------------------------------- ### Treeselect JS - Initialization and Usage Source: https://github.com/dipson88/treeselectjs/blob/main/README.md This section details how to initialize and use the Treeselect JS component, including installation, import statements, and basic configuration with options. ```APIDOC ## Treeselect JS Initialization and Usage ### Description Provides instructions for installing Treeselect JS via npm and importing it into your project. It also demonstrates how to instantiate the component with example options and event handling. ### Method JavaScript instantiation ### Endpoint N/A (Client-side JavaScript) ### Parameters #### Core props - **parentHtmlContainer** (HTMLElement) - Required - The HTML element where the Treeselect component will be mounted. - **value** (Array[String | Number]) - Optional (default: []) - An array of values to be pre-selected. - **options** (Array[Object]) - Optional (default: []) - The data structure for the selectable options. Each option can have `name`, `value`, `disabled`, `htmlAttr`, `isGroupSelectable`, and `children` properties. - **disabled** (Boolean) - Optional (default: false) - Disables the entire Treeselect component. - **id** (String) - Optional (default: '') - Sets the `id` attribute for accessibility. - **ariaLabel** (String) - Optional (default: '') - Sets the `ariaLabel` attribute for accessibility. - **isSingleSelect** (Boolean) - Optional (default: false) - Enables single selection mode, removing checkboxes. - **isGroupedValue** (Boolean) - Optional (default: false) - Returns group values when selected instead of individual leaf node values. - **isIndependentNodes** (Boolean) - Optional (default: false) - Makes nodes independent, ignoring parent/child selection logic. - **rtl** (Boolean) - Optional (default: false) - Enables Right-To-Left text direction. - **isBoostedRendering** (Boolean) - Optional (default: false) - Enables experimental rendering optimizations for large lists using IntersectionObserver. ### Request Example ```javascript import Treeselect from 'treeselectjs' const options = [ { name: 'England', value: 1, children: [ { name: 'London', value: 2, children: [ { name: 'Chelsea', value: 3, children: [] }, { name: 'West End', value: 4, children: [] } ] }, { name: 'Brighton', value: 5, children: [] } ] }, { name: 'France', value: 6, children: [ { name: 'Paris', value: 7, children: [] }, { name: 'Lyon', value: 8, children: [] } ] } ] const slot = document.createElement('div') slot.innerHTML='Click!' const domElement = document.querySelector('.treeselect-demo') const treeselect = new Treeselect({ parentHtmlContainer: domElement, value: [4, 7, 8], options: options, listSlotHtmlComponent: slot }) treeselect.srcElement.addEventListener('input', (e) => { console.log('Selected value:', e.detail) }) slot.addEventListener('click', (e) => { e.preventDefault() alert('Slot click!') }) ``` ### Response #### Success Response (N/A) N/A - This is a client-side component initialization. #### Response Example N/A ``` -------------------------------- ### Add Custom HTML Attributes and Icons in TreeSelectJS Source: https://context7.com/dipson88/treeselectjs/llms.txt This example shows how to add custom HTML attributes, including data attributes and inline styles, to TreeSelectJS options. It also demonstrates inserting custom icons dynamically into list items based on these attributes. This requires the 'treeselectjs' library and its CSS. ```javascript import Treeselect from 'treeselectjs' import 'treeselectjs/dist/treeselectjs.css' const icons = { check: 'ico-check', shield: 'ico-shield' } const options = [ { name: 'England', value: 1, htmlAttr: { ico: icons.check, 'data-country': 'UK', style: 'font-weight: bold' }, children: [ { name: 'London', value: 2, children: [ { name: 'Chelsea', value: 3, children: [] }, { name: 'West End', value: 4, htmlAttr: { ico: icons.check }, children: [] } ] } ] }, { name: 'France', value: 6, htmlAttr: { ico: icons.shield, 'data-country': 'FR' }, children: [ { name: 'Paris', value: 7, htmlAttr: { ico: icons.shield }, children: [] } ] } ] const svgCheck = `` const svgShield = `` const container = document.querySelector('#icons-container') let isIconsInserted = false const treeselect = new Treeselect({ parentHtmlContainer: container, value: [1, 4, 7], options: options, openLevel: 3, openCallback: () => { if (isIconsInserted) return isIconsInserted = true // Insert custom icons based on htmlAttr Array.from(container.querySelectorAll('[ico]')).forEach((item) => { const ico = item.getAttribute('ico') let iconHtml = null if (ico === icons.check) iconHtml = svgCheck if (ico === icons.shield) iconHtml = svgShield if (iconHtml) { const iconElement = document.createElement('div') iconElement.style.cssText = 'height: 20px; width: 25px; position: relative;' iconElement.innerHTML = iconHtml item.insertBefore(iconElement, item.lastChild) } }) } }) ``` -------------------------------- ### Grouped Value Mode Configuration in TreeselectJS Source: https://context7.com/dipson88/treeselectjs/llms.txt This JavaScript snippet demonstrates how to initialize TreeselectJS with the `isGroupedValue` option set to `true`. It shows the setup of options, the container, and event handling to log the grouped and ungrouped values. The `isGroupedValue` option changes the behavior of value retrieval when entire groups are selected. ```javascript import Treeselect from 'treeselectjs' import 'treeselectjs/dist/treeselectjs.css' const options = [ { name: 'USA', value: 'usa', children: [ { name: 'New York', value: 'ny', children: [] }, { name: 'California', value: 'ca', children: [] }, { name: 'Texas', value: 'tx', children: [] } ] }, { name: 'Canada', value: 'canada', children: [ { name: 'Ontario', value: 'on', children: [] }, { name: 'Quebec', value: 'qc', children: [] } ] } ] const container = document.querySelector('#grouped-container') const treeselect = new Treeselect({ parentHtmlContainer: container, options: options, value: ['ny', 'ca', 'tx'], // All children of USA isGroupedValue: true // Return 'usa' instead of ['ny', 'ca', 'tx'] }) treeselect.srcElement.addEventListener('input', (e) => { console.log('Grouped value:', e.detail) // ['usa'] console.log('Ungrouped value:', treeselect.ungroupedValue) // ['ny', 'ca', 'tx'] console.log('Grouped value:', treeselect.groupedValue) // ['usa'] }) // If you select all children of USA: // - Normal mode returns: ['ny', 'ca', 'tx'] // - Grouped mode returns: ['usa'] ``` -------------------------------- ### Configure Treeselect.js Advanced Options (JavaScript) Source: https://context7.com/dipson88/treeselectjs/llms.txt This snippet demonstrates advanced configuration for Treeselect.js, covering appearance, behavior, and performance. It initializes a Treeselect instance with various options like 'openLevel', 'appendToBody', 'showCount', 'searchable', 'isBoostedRendering', and a custom 'listSlotHtmlComponent'. It assumes a large hierarchical dataset is available and includes imports for the library and its CSS. ```javascript import Treeselect from 'treeselectjs' import 'treeselectjs/dist/treeselectjs.css' const largeDataset = [] // Assume large hierarchical dataset const container = document.querySelector('#advanced-container') const treeselect = new Treeselect({ parentHtmlContainer: container, options: largeDataset, value: [], // Core settings id: 'my-treeselect', ariaLabel: 'Select categories', disabled: false, rtl: false, // Right-to-left mode // List behavior openLevel: 1, // Auto-expand groups to level 1 appendToBody: true, // Append list to body (fixes overflow issues) alwaysOpen: false, // Keep list always visible staticList: false, // Position list statically (no overlap) direction: 'auto', // 'auto' | 'top' | 'bottom' expandSelected: true, // Auto-expand groups with selected items saveScrollPosition: true, // Remember scroll position listClassName: 'custom-list-class', // List content showCount: true, // Show count of children in groups emptyText: 'No results found...', disabledBranchNode: false, // Disable group node selection // Input appearance showTags: true, // Show selections as tags tagsCountText: 'items selected', // Text when showTags is false clearable: true, // Show clear button searchable: true, // Enable search placeholder: 'Search...', grouped: true, // Show groups in input // Tag sorting tagsSortFn: (a, b) => { // Sort tags alphabetically by name return a.name.localeCompare(b.name) }, // Selection behavior isSingleSelect: false, isGroupedValue: false, // Return group IDs instead of leaf IDs isIndependentNodes: false, // Independent node selection // Performance isBoostedRendering: true, // Use IntersectionObserver for large lists // Custom slot listSlotHtmlComponent: (() => { const slot = document.createElement('div') slot.innerHTML = '' slot.querySelector('.custom-button').addEventListener('click', (e) => { e.preventDefault() console.log('Custom slot clicked') }) return slot })() }) console.log('Is list opened:', treeselect.isListOpened) console.log('Selected name:', treeselect.selectedName) console.log('Root element:', treeselect.srcElement) ``` -------------------------------- ### TreeselectJS Usage with CDN Source: https://context7.com/dipson88/treeselectjs/llms.txt Shows how to use TreeselectJS by including its script and CSS files from a CDN. This method is suitable for projects that do not use a build system. ```html
``` -------------------------------- ### Search and Filtering with Treeselect.js Source: https://context7.com/dipson88/treeselectjs/llms.txt Explains how to enable and configure real-time search and filtering in Treeselect.js. It covers setting search-related options like `searchable`, `placeholder`, and `emptyText`, and demonstrates the use of `searchCallback` for debounced search queries and potential remote data fetching. ```javascript import Treeselect from 'treeselectjs' import 'treeselectjs/dist/treeselectjs.css' const options = [ { name: 'Electronics', value: 'elec', children: [ { name: 'Laptops', value: 'laptops', children: [] }, { name: 'Smartphones', value: 'phones', children: [] }, { name: 'Tablets', value: 'tablets', children: [] } ] }, { name: 'Books', value: 'books', children: [ { name: 'Fiction', value: 'fiction', children: [] }, { name: 'Non-Fiction', value: 'nonfiction', children: [] } ] } ] const container = document.querySelector('#search-container') const treeselect = new Treeselect({ parentHtmlContainer: container, options: options, searchable: true, // Enable search placeholder: 'Type to search...', emptyText: 'No matching items found', // Search event fires with 350ms debounce searchCallback: (searchText) => { console.log('Search query:', searchText) // Use for autocomplete or remote filtering if (searchText.length >= 3) { // Fetch remote data fetch(`/api/search?q=${encodeURIComponent(searchText)}`) .then(res => res.json()) .then(data => { console.log('Remote results:', data) // Update options if needed }) } } }) // Search is automatically filtered client-side // Groups with matches are auto-expanded treeselect.srcElement.addEventListener('search', (e) => { console.log('Search event detail:', e.detail) }) ``` -------------------------------- ### Manage Treeselect.js Lifecycle Methods (JavaScript) Source: https://context7.com/dipson88/treeselectjs/llms.txt This snippet illustrates how to manage the lifecycle of a Treeselect.js component. It covers updating component properties and re-mounting, destroying the component, re-mounting after destruction, focusing the input, and toggling the open/close state of the list. It assumes the Treeselect library and its CSS are imported and that corresponding HTML elements exist for interaction. ```javascript import Treeselect from 'treeselectjs' import 'treeselectjs/dist/treeselectjs.css' const options = [ { name: 'Category A', value: 'a', children: [ { name: 'Item 1', value: '1', children: [] }, { name: 'Item 2', value: '2', children: [] } ] } ] const container = document.querySelector('#lifecycle-container') const treeselect = new Treeselect({ parentHtmlContainer: container, options: options, value: ['1'] }) // Update props and re-mount document.querySelector('#btn-update-props').addEventListener('click', () => { treeselect.appendToBody = true treeselect.showTags = false treeselect.placeholder = 'Updated placeholder' treeselect.mount() // Apply changes }) // Destroy component (remove from DOM) document.querySelector('#btn-destroy').addEventListener('click', () => { treeselect.destroy() console.log('Component destroyed') }) // Re-mount after destroy document.querySelector('#btn-remount').addEventListener('click', () => { treeselect.mount() console.log('Component re-mounted with previous data') }) // Focus input without opening/closing document.querySelector('#btn-focus').addEventListener('click', () => { treeselect.focus() }) // Toggle open/close state document.querySelector('#btn-toggle').addEventListener('click', () => { treeselect.toggleOpenClose() console.log('List opened:', treeselect.isListOpened) }) // Check if list is currently opened if (treeselect.isListOpened) { console.log('List is currently open') } ``` -------------------------------- ### TypeScript Usage with Treeselect.js Source: https://context7.com/dipson88/treeselectjs/llms.txt Demonstrates strongly typed usage of Treeselect.js with TypeScript, including type definitions for options, parameters, and event handling. It shows how to instantiate the component and access its properties safely. ```typescript import Treeselect from 'treeselectjs' import type { ITreeselectParams, OptionType, ValueType, ValueOptionType, DirectionType, TagsSortItem } from 'treeselectjs' import 'treeselectjs/dist/treeselectjs.css' // Strongly typed options const options: OptionType[] = [ { name: 'Category', value: 1, disabled: false, isGroupSelectable: true, htmlAttr: { 'data-custom': 'value' }, children: [ { name: 'Item A', value: 2, children: [] }, { name: 'Item B', value: 3, children: [] } ] } ] // Strongly typed parameters const params: ITreeselectParams = { parentHtmlContainer: document.querySelector('#container') as HTMLElement, value: [2, 3] as ValueOptionType[], options: options, openLevel: 1, appendToBody: false, direction: 'auto' as DirectionType, inputCallback: (value: ValueType) => { console.log('Selected:', value) // value is ValueOptionType[] | ValueOptionType | null }, searchCallback: (searchText: string) => { console.log('Search:', searchText) }, tagsSortFn: (a: TagsSortItem, b: TagsSortItem): number => { return a.name.localeCompare(b.name) } } const treeselect = new Treeselect(params) // Type-safe property access const currentValue: ValueType = treeselect.value const selectedName: string = treeselect.selectedName const isOpened: boolean = treeselect.isListOpened const rootElement: HTMLElement | null = treeselect.srcElement // Type-safe event listeners treeselect.srcElement?.addEventListener('input', (e: Event) => { const customEvent = e as CustomEvent