@kouovo/dom-helper
v0.1.46
Published
Enhanced DOM utilities for interactive element management with TypeScript support, improved performance, and comprehensive error handling.
Readme
@kouovo/dom-helper
Enhanced DOM utilities for interactive element management with TypeScript support, improved performance, and comprehensive error handling.
Overview
The @kouovo/dom-helper package provides robust utilities for managing interactive DOM elements including accordion components, active element groups, and next/previous navigation. Features include performance optimizations, comprehensive error handling, and flexible configuration options.
Recent Improvements (v0.1.8+)
- Enhanced Type Safety: Comprehensive TypeScript interfaces and centralized type definitions
- Performance Optimizations: Element caching, batched DOM operations, and debounced functions
- Improved Error Handling: Centralized error management with custom exception types
- Memory Management: Automatic cleanup and event listener management
- API Consistency: Standardized naming conventions and patterns across all utilities
Installation
npm install @kouovo/dom-helper
# or
pnpm add @kouovo/dom-helper
# or
yarn add @kouovo/dom-helperCore Features
🎯 Enhanced Accordion Component
- Smooth Animations: CSS-based transitions with configurable duration
- Height Calculation: Automatic content height measurement and caching
- Performance: Debounced height recalculation and batched DOM operations
- Memory Safe: Automatic cleanup of event listeners and timers
🔄 Active Element Groups Manager
- Flexible Configuration: Event delegation or direct element control
- Auto-Switching: Optional timer-based switching with pause/resume
- Event Types: Support for click, auto, and manual event tracking
- Error Recovery: Comprehensive validation and graceful error handling
⏯️ Next/Previous Navigation
- Button Control: Dedicated next/previous button management
- Loop Support: Optional wrapping from end to beginning
- Type Safety: Full TypeScript support with interface validation
- Performance: Optimized event handling and state management
Installation
npm install @kouovo/dom-helper
# or
pnpm add @kouovo/dom-helper
# or
yarn add @kouovo/dom-helperFeatures
- Accordion Component: Full-featured accordion with smooth animations and customizable options
- Element Group Management: Manage active states across groups of elements with click handling
- Next/Previous Navigation: Control element groups with dedicated navigation buttons
- TypeScript Support: Fully typed with comprehensive interfaces
- Flexible Configuration: Multiple configuration options for different use cases
API Reference
useAccordion(options)
Creates a fully functional accordion component with smooth animations.
Parameters
interface AccordionOptions {
rootSelector: string; // CSS selector for the root element
itemsSelector?: string; // CSS selector for accordion items (default: ".accordion-item")
contentsSelector?: string; // CSS selector for content elements (default: ".accordion-content")
contentPadding?: number; // Content padding in pixels (default: 12)
onActiveChange?: ( // Callback when active item changes
activeIndex: number,
prevIndex: number,
active: HTMLElement[],
prev: HTMLElement[]
) => void;
onInit?: (elements: { // Callback after initialization
root: HTMLElement;
groups: HTMLElement[];
contents: HTMLElement[];
wrapper: HTMLElement;
}) => void;
}Returns
{
cleanup: () => void; // Cleanup function to remove event listeners
root: HTMLElement; // Root element reference
groups: HTMLElement[]; // Array of accordion item elements
contents: HTMLElement[]; // Array of content elements
wrapper: HTMLElement; // Wrapper element reference
}Example
import { useAccordion } from '@kouovo/dom-helper';
const accordion = useAccordion({
rootSelector: '.my-accordion',
itemsSelector: '.accordion-item',
contentsSelector: '.accordion-content',
contentPadding: 16,
onActiveChange: (activeIndex, prevIndex, active, prev) => {
console.log(`Accordion item ${activeIndex} activated`);
},
onInit: ({ root, groups, contents, wrapper }) => {
console.log('Accordion initialized with', groups.length, 'items');
}
});
// Later, when component is destroyed
accordion.cleanup();manageActiveElementGroups(options)
Manages the active state of groups of elements with flexible click handling options.
Parameters
interface ActiveElementGroupSwitchOptions {
groups: HTMLElement[][]; // Groups of elements to manage
initialIndex?: number; // Initial active index (default: 0)
loop?: boolean; // Whether to loop navigation (default: true)
interval?: number | null; // Auto-switching interval in ms (default: null)
// Option 1: Event Delegation
parentElement?: HTMLElement; // Parent element for event delegation
elementSelector?: string; // CSS selector for clickable elements
elements?: HTMLElement[]; // Array of elements matching selector
// Option 2: Direct Elements
controllerElements?: HTMLElement[]; // Direct array of clickable elements
onActiveChange?: ( // Callback when active group changes
activeIndex: number,
previousIndex: number,
activeGroup: HTMLElement[],
previousGroup: HTMLElement[]
) => void;
}Returns
{
cleanup: () => void; // Remove event listeners and reset state
getCurrentIndex: () => number; // Get current active index
next: () => void; // Move to next group
previous: () => void; // Move to previous group
setActive: (index: number) => void; // Set specific group as active
pause: () => void; // Pause auto-switching
resume: () => void; // Resume auto-switching
}Example
import { manageActiveElementGroups } from '@kouovo/dom-helper';
// Using event delegation
const manager = manageActiveElementGroups({
groups: [[element1], [element2], [element3]],
parentElement: document.querySelector('.tab-container'),
elementSelector: '.tab-button',
elements: Array.from(document.querySelectorAll('.tab-button')),
onActiveChange: (activeIndex, prevIndex, activeGroup, prevGroup) => {
prevGroup.forEach(el => el.classList.remove('active'));
activeGroup.forEach(el => el.classList.add('active'));
}
});
// Using direct controller elements
const directManager = manageActiveElementGroups({
groups: [[panel1], [panel2], [panel3]],
controllerElements: [button1, button2, button3],
interval: 3000, // Auto-switch every 3 seconds
onActiveChange: (activeIndex, prevIndex, activeGroup, prevGroup) => {
// Handle group activation
}
});manageElementsByNextPrev(options)
Manages element groups using dedicated Next/Previous buttons for navigation.
Parameters
interface ElementsByNextPrevOptions {
groups: HTMLElement[][]; // Groups of elements to manage
nextButton: HTMLElement; // Button element for next navigation
prevButton: HTMLElement; // Button element for previous navigation
initialIndex?: number; // Initial active index (default: 0)
loop?: boolean; // Whether to loop navigation (default: true)
onActiveChange?: ( // Callback when active group changes
activeIndex: number,
previousIndex: number,
activeGroup: HTMLElement[],
previousGroup: HTMLElement[]
) => void;
}Returns
{
cleanup: () => void; // Remove event listeners and reset state
getCurrentIndex: () => number; // Get current active index
next: () => void; // Move to next group
previous: () => void; // Move to previous group
setActive: (index: number) => void; // Set specific group as active
}Example
import { manageElementsByNextPrev } from '@kouovo/dom-helper';
const navigation = manageElementsByNextPrev({
groups: [[slide1], [slide2], [slide3]],
nextButton: document.querySelector('.next-btn'),
prevButton: document.querySelector('.prev-btn'),
loop: true,
onActiveChange: (activeIndex, prevIndex, activeGroup, prevGroup) => {
// Update slide visibility
prevGroup.forEach(el => el.style.display = 'none');
activeGroup.forEach(el => el.style.display = 'block');
}
});
// Manual navigation
navigation.next();
navigation.previous();
navigation.setActive(2);TypeScript Support
All functions are fully typed with comprehensive TypeScript interfaces. The package exports all necessary types for proper type checking in your projects.
Error Handling
All functions include comprehensive error handling with console warnings for:
- Missing required elements
- Invalid configuration options
- Mismatched array lengths
- Runtime callback errors
Browser Support
Compatible with all modern browsers that support:
- ES6+ features
- DOM APIs (querySelector, addEventListener, etc.)
- CSS custom properties (for accordion animations)
License
MIT
