### Clone and Install KTUI
Source: https://github.com/keenthemes/ktui/blob/main/CONTRIBUTING.md
Clone the repository and install dependencies to get started with local development.
```sh
git clone https://github.com/keenthemes/ktui.git
cd ktui
npm install
```
--------------------------------
### Install KTUI via NPM
Source: https://github.com/keenthemes/ktui/blob/main/README.md
Use this command to install the KTUI library using NPM. Ensure Node.js and Tailwind CSS are pre-installed.
```bash
npm i @keenthemes/ktui
```
--------------------------------
### Install KtUI Package
Source: https://github.com/keenthemes/ktui/blob/main/skills/ktui-install/SKILL.md
Use npm to install the KtUI package. This is the first step in integrating KtUI into your project.
```bash
npm install @keenthemes/ktui
```
--------------------------------
### Basic Toast Example
Source: https://github.com/keenthemes/ktui/blob/main/examples/toast/example.html
A simple example to show a basic toast message. This is useful for simple notifications.
```javascript
const btnBasic = document.getElementById('toast-basic');
btnBasic.addEventListener('click', () => {
KTToast.show({
message: 'This is a basic toast!'
});
});
```
--------------------------------
### Get and Manage KTUI Component Instances
Source: https://github.com/keenthemes/ktui/blob/main/skills/ktui/SKILL.md
Demonstrates how to get an existing instance of a KTUI component, or create a new one with configuration. Also shows common instance methods for controlling the component's state and lifecycle.
```typescript
const instance = KTModal.getInstance(element);
const instance = KTModal.getOrCreateInstance(element, config);
instance.show();
instance.hide();
instance.toggle();
instance.isOpen();
instance.dispose();
```
--------------------------------
### Initialize KtUI Components
Source: https://github.com/keenthemes/ktui/blob/main/skills/ktui/SKILL.md
Initialize KtUI components globally in your application. This setup is typically done once during application startup.
```ts
import { KTComponents } from '@keenthemes/ktui';
import '@keenthemes/ktui/dist/styles.css';
KTComponents.init();
```
--------------------------------
### Toast Positioning Examples
Source: https://github.com/keenthemes/ktui/blob/main/examples/toast/example.html
Demonstrates how to display toasts at different positions on the screen. Ensure the corresponding HTML elements with the specified IDs exist.
```javascript
const posExamples = [
{ id: 'toast-pos-top-end', position: 'top-end', label: 'Top End (Right)' },
{ id: 'toast-pos-top-center', position: 'top-center', label: 'Top Center' },
{ id: 'toast-pos-top-start', position: 'top-start', label: 'Top Start (Left)' },
{ id: 'toast-pos-middle-end', position: 'middle-end', label: 'Middle End (Right)' },
{ id: 'toast-pos-middle-center', position: 'middle-center', label: 'Middle Center' },
{ id: 'toast-pos-middle-start', position: 'middle-start', label: 'Middle Start (Left)' },
{ id: 'toast-pos-bottom-end', position: 'bottom-end', label: 'Bottom End (Right)' },
{ id: 'toast-pos-bottom-center', position: 'bottom-center', label: 'Bottom Center' },
{ id: 'toast-pos-bottom-start', position: 'bottom-start', label: 'Bottom Start (Left)' }
];
posExamples.forEach(({ id, position, label }) => {
const btn = document.getElementById(id);
if (btn) {
btn.addEventListener('click', () => {
KTToast.show({ message: `Toast at ${label}`, position, variant: 'info' });
});
}
});
```
--------------------------------
### Basic KTTabs HTML Structure
Source: https://github.com/keenthemes/ktui/blob/main/skills/ktui/SKILL.md
Demonstrates the HTML setup for a tabbed interface, where clicking on tab toggle elements reveals corresponding content panels.
```html
Tab 1
Tab 2
Content 1
Content 2
```
--------------------------------
### Component Instance Management
Source: https://github.com/keenthemes/ktui/blob/main/skills/ktui/SKILL.md
Demonstrates how to get, create, and manage instances of KTUI components programmatically. This includes retrieving existing instances, creating new ones with configurations, and initializing all components on the page.
```APIDOC
## Component Instance Management
### Static Methods
- **`KTComponent.getInstance(el)`**
- **Description**: Retrieves the existing instance of a component associated with the given DOM element.
- **Returns**: The component instance if found, otherwise `null`.
- **`KTComponent.getOrCreateInstance(el, config?)`**
- **Description**: Retrieves the existing instance of a component associated with the given DOM element, or creates a new instance if none exists. An optional configuration object can be provided for new instances.
- **Returns**: The existing or newly created component instance.
- **`KTComponent.init()`**
- **Description**: Scans the DOM for elements with component root attributes, creates instances for them, and registers necessary global event handlers.
- **Returns**: void
```
--------------------------------
### Basic KTSelect Usage
Source: https://github.com/keenthemes/ktui/blob/main/skills/ktui-select/SKILL.md
Demonstrates the basic HTML structure for a KTSelect component with search enabled. This is the foundational setup for most KTSelect instances.
```html
```
--------------------------------
### Add KTUI Skills via CLI
Source: https://github.com/keenthemes/ktui/blob/main/README.md
Install KTUI skills directly from the GitHub repository using the skills CLI. This method is useful for integrating directly from source.
```bash
npx skills add keenthemes/ktui
```
--------------------------------
### Toast Sizes
Source: https://github.com/keenthemes/ktui/blob/main/examples/toast/example.html
Illustrates how to set different sizes for toasts (small, medium, large). This example is incomplete as the source code is truncated.
```javascript
const sizes = ['sm', 'md', 'l
```
--------------------------------
### Conventional Commit Message Example
Source: https://github.com/keenthemes/ktui/blob/main/CONTRIBUTING.md
Follow conventional prefixes for commit messages to categorize changes effectively. This example shows a feature addition to components.
```sh
feat(components): add new prop to avatar
```
--------------------------------
### Initialize and Control KTDropdown
Source: https://github.com/keenthemes/ktui/blob/main/skills/ktui/SKILL.md
Get an instance of a dropdown component and control its visibility and state programmatically. The element `el` should be the dropdown's root element.
```javascript
const dd = KTDropdown.getInstance(el);
dd.show();
dd.hide();
dd.toggle();
dd.isOpen();
dd.disable(); // prevent interaction
dd.enable();
```
--------------------------------
### Initialize KTSelect Programmatically
Source: https://github.com/keenthemes/ktui/blob/main/skills/ktui-select/SKILL.md
Shows how to get an instance of KTSelect from an existing HTML element using its static getInstance method. This is useful for interacting with the component via JavaScript.
```typescript
import { KTSelect } from '@keenthemes/ktui';
const select = KTSelect.getInstance(el);
```
--------------------------------
### Initialize KtUI DataTable Instance
Source: https://github.com/keenthemes/ktui/blob/main/skills/ktui-datatable/SKILL.md
After setting up the HTML structure, use this TypeScript code to get an instance of the KTDataTable. This is necessary to interact with the DataTable programmatically. Ensure the table element is correctly referenced.
```typescript
import { KTDataTable } from '@keenthemes/ktui';
const dt = KTDataTable.getInstance(tableEl);
```
--------------------------------
### Use Logical CSS Properties for RTL
Source: https://github.com/keenthemes/ktui/blob/main/README.md
KTUI uses logical CSS properties by default for RTL support. This example shows text alignment and padding using logical properties.
```html
Example text
```
--------------------------------
### KtUI Dropdown Declarative API Example
Source: https://github.com/keenthemes/ktui/blob/main/skills/ktui/SKILL.md
Implement a KtUI dropdown using data attributes. `data-kt-dropdown-toggle` triggers the dropdown menu, which is marked with `data-kt-dropdown-menu` and contains items marked with `data-kt-dropdown-item`.
```html
```
--------------------------------
### JavaScript for File Upload and State Checking
Source: https://github.com/keenthemes/ktui/blob/main/examples/image-input/file-upload-example.html
Provides JavaScript to get the KTUI Image Input instance, access the selected file for form submission, and check the component's state (empty or changed).
```javascript
// Get the KTUI Image Input instance
const imageInput = KTImageInput.getInstance(element);
// Access the selected file for form submission
const selectedFile = imageInput.getSelectedFile();
if (selectedFile) {
const formData = new FormData();
formData.append('image', selectedFile);
// Submit formData to server
}
// Check component state
if (imageInput.isEmpty()) {
console.log('No file selected');
}
if (imageInput.isChanged()) {
console.log('File has been selected');
}
```
--------------------------------
### KTDataTable Initialization
Source: https://github.com/keenthemes/ktui/blob/main/skills/ktui-datatable/SKILL.md
Demonstrates how to initialize the KTDataTable component using its instance method.
```APIDOC
## KTDataTable Initialization
### Description
Initializes the KTDataTable component from an existing HTML table element.
### Method
`KTDataTable.getInstance(tableElement: HTMLElement)`
### Parameters
#### Path Parameters
- **tableElement** (HTMLElement) - Required - The HTML table element to initialize the DataTable on.
### Request Example
```html
Name
Email
```
### Response
#### Success Response (Instance)
- **KTDataTable** - The initialized DataTable instance.
### Response Example
```ts
import { KTDataTable } from '@keenthemes/ktui';
const tableEl = document.querySelector('div[data-kt-datatable="true"]');
const dt = KTDataTable.getInstance(tableEl);
```
```
--------------------------------
### KTComponent Static Methods for Instance Management
Source: https://github.com/keenthemes/ktui/blob/main/skills/ktui/SKILL.md
Provides an overview of static methods available on `KTComponent` for managing component instances, including retrieving existing ones, creating new ones with optional configurations, and initializing all components found in the DOM.
```typescript
// Get existing instance
KTComponent.getInstance(el);
// Get or create instance
KTComponent.getOrCreateInstance(el, config?);
// Initialize all components in DOM
KTComponent.init();
```
--------------------------------
### Initialize KtUI Components
Source: https://github.com/keenthemes/ktui/blob/main/skills/ktui-install/SKILL.md
Import and initialize KtUI components using `KTComponents.init()`. This should be called once after the DOM is ready.
```typescript
import { KTComponents } from '@keenthemes/ktui';
// Call once after DOM is ready
KTComponents.init();
```
--------------------------------
### JavaScript Initialization and Helper Functions
Source: https://github.com/keenthemes/ktui/blob/main/examples/image-input/file-upload-example.html
Initializes the KTUI Image Input component on DOM ready and includes helper functions for adding test results, accessing files, testing public methods, and handling form submissions.
```javascript
let imageInputInstance = null; // Initialize when DOM is ready document.addEventListener('DOMContentLoaded', function() { const element = document.querySelector('\\[data-kt-image-input\\]'); if (element) { imageInputInstance = KTImageInput.getInstance(element); addResult('Component initialized successfully', 'success'); } }); function addResult(message, type = 'info') { const results = document.getElementById('test-results'); const div = document.createElement('div'); div.className = `test-result ${type}`; div.textContent = `${new Date().toLocaleTimeString()}: ${message}`; results.appendChild(div); } function testFileAccess() { if (!imageInputInstance) { addResult('Image input instance not found', 'error'); return; } const file = imageInputInstance.getSelectedFile(); if (file) { addResult(`File access successful: ${file.name} (${file.size} bytes)`, 'success'); } else { addResult('No file selected', 'info'); } } function testPublicMethods() { if (!imageInputInstance) { addResult('Image input instance not found', 'error'); return; } const isEmpty = imageInputInstance.isEmpty(); const isChanged = imageInputInstance.isChanged(); addResult(`isEmpty(): ${isEmpty}`, isEmpty ? 'info' : 'success'); addResult(`isChanged(): ${isChanged}`, isChanged ? 'success' : 'info'); } function testFormSubmission() { const form = document.getElementById('test-form'); const fileInput = form.querySelector('input[type="file"]'); const formData = new FormData(form); addResult('Form data created', 'info'); if (fileInput.files.length > 0) { addResult(`File in form: ${fileInput.files[0].name}`, 'success'); } else { addResult('No file in form data (expected - input is cleared for UI)', 'info'); } // Test with KTUI instance const formImageInput = KTImageInput.getInstance(form.querySelector('\\[data-kt-image-input\\]')); if (formImageInput) { const selectedFile = formImageInput.getSelectedFile(); if (selectedFile) { addResult(`KTUI file access: ${selectedFile.name}`, 'success'); } else { addResult('No file in KTUI instance', 'error'); } } } function handleFormSubmit(event) { event.preventDefault(); addResult('Form submission intercepted for testing', 'info'); testFormSubmission(); } function clearResults() { document.getElementById('test-results').innerHTML = ''; }
```
--------------------------------
### Initialize KTPinInput
Source: https://github.com/keenthemes/ktui/blob/main/skills/ktui/SKILL.md
HTML structure for initializing the KTPinInput component. Specify the desired length using the data-kt-pin-input-length attribute.
```html
```
--------------------------------
### Initialize and Debug KTSticky
Source: https://github.com/keenthemes/ktui/blob/main/examples/sticky/debug-sticky.html
This script initializes the KTSticky component and sets up event listeners to update debug information on scroll and resize. It logs initialization status and errors to the console.
```javascript
document.addEventListener('DOMContentLoaded', function() {
const debugInfo = document.getElementById('debugInfo');
function updateDebugInfo() {
const stickyElement = document.querySelector('\\[data-kt-sticky\\]');
const initializedElement = document.querySelector('\\[data-kt-sticky-initialized\\]');
const activeElement = document.querySelector('\\[data-kt-sticky-initialized\\]\.active');
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
const viewportHeight = window.innerHeight;
let info = ` Debug Info:
Scroll: ${scrollTop}px
Viewport Height: ${viewportHeight}px
KTSticky Available: ${!!window.KTSticky}
Sticky Elements: ${document.querySelectorAll('\\[data-kt-sticky\\]').length}
Initialized Elements: ${document.querySelectorAll('\\[data-kt-sticky-initialized\\]').length}
Active Elements: ${document.querySelectorAll('\\[data-kt-sticky-initialized\\]\.active').length}
`;
if (stickyElement) {
const computedStyle = window.getComputedStyle(stickyElement);
const height = stickyElement.offsetHeight;
const top = stickyElement.getAttribute('data-kt-sticky-top') || '0';
const offset = stickyElement.getAttribute('data-kt-sticky-offset') || '0';
info += ` Sticky Element:
Height: ${height}px
Top: ${top}px
Offset: ${offset}px
Height + Top: ${height + parseInt(top)}px
Position: ${computedStyle.position}
Z-Index: ${computedStyle.zIndex}
InsetBlockStart: ${computedStyle.insetBlockStart}
`;
}
if (initializedElement) {
info +=
` Initialized Element:
`;
info += `Classes: ${initializedElement.className}
`;
info += `Data Attributes: ${Array.from(initializedElement.attributes).filter(attr => attr.name.startsWith('data-kt-sticky')).map(attr =>
`${attr.name}=
```
--------------------------------
### Show and Configure KTToast
Source: https://github.com/keenthemes/ktui/blob/main/skills/ktui/SKILL.md
Demonstrates basic and advanced usage of the static KTToast API for displaying notifications. Includes options for variants, appearance, size, position, duration, and custom content. Global configuration is also shown.
```typescript
import { KTToast } from '@keenthemes/ktui';
// Basic usage
KTToast.show({ message: 'Saved!', variant: 'success' });
// Full options
KTToast.show({
message: 'Item deleted',
variant: 'error',
appearance: 'solid', // 'solid' | 'outline' | 'light'
size: 'md', // 'sm' | 'md' | 'lg'
position: 'top-end', // 'top-end' | 'top-center' | 'top-start' |
// 'bottom-end' | 'bottom-center' | 'bottom-start' |
// 'middle-end' | 'middle-center' | 'middle-start'
duration: 5000, // ms, auto-dismiss
important: false, // if true, no auto-dismiss
progress: true, // show progress bar
pauseOnHover: true, // pause timer on hover
dismiss: true, // show close button
icon: '', // leading icon HTML
action: {
label: 'Undo',
onClick: (id) => { /* ... */ },
className: 'btn btn-sm',
},
cancel: {
label: 'Cancel',
onClick: (id) => { /* ... */ },
},
beep: true, // play notification sound
onAutoClose: (id) => {},
onDismiss: (id) => {},
});
// Global config
KTToast.config({
position: 'bottom-end',
duration: 4000,
maxToasts: 5,
offset: 15,
gap: 10,
});
```
```typescript
KTToast.show({
content: document.getElementById('my-toast-template'),
// or: content: () => document.createElement('div'),
// or: content: '
HTML string
',
});
```
--------------------------------
### Initialize KTRating
Source: https://github.com/keenthemes/ktui/blob/main/skills/ktui/SKILL.md
HTML structure for initializing the KTRating component. Set the initial value and maximum rating using data attributes.
```html
```
--------------------------------
### Initialize KTClipboard
Source: https://github.com/keenthemes/ktui/blob/main/skills/ktui/SKILL.md
HTML structure for initializing the KTClipboard component. Specify the target element to copy from using the data-kt-clipboard-target attribute.
```html
text to copy
```
--------------------------------
### KtUI Modal Declarative API Example
Source: https://github.com/keenthemes/ktui/blob/main/skills/ktui/SKILL.md
Use data attributes to declaratively control KtUI modals. The `data-kt-modal-toggle` attribute on a button opens the modal, and `data-kt-modal-dismiss` on another button closes it. The modal itself is marked with `data-kt-modal`.
```html
Hello
```
--------------------------------
### Check and Initialize KTSticky
Source: https://github.com/keenthemes/ktui/blob/main/examples/sticky/test-sticky-positioning.html
Logs the status of KTSticky and initializes it if found. It also checks for sticky elements, logs their count, and logs details about each initialized element.
```javascript
document.addEventListener('DOMContentLoaded', function() {
console.log('DOM loaded, checking KTUI...');
console.log('window.KTSticky:', window.KTSticky);
if (window.KTSticky) {
console.log('KTSticky found, initializing...');
// Check sticky elements before initialization
const stickyElements = document.querySelectorAll('[data-kt-sticky]');
console.log('Found sticky elements:', stickyElements.length);
// Initialize all sticky elements
window.KTSticky.init();
console.log('KTSticky initialized');
// Check if elements were initialized
const initializedElements = document.querySelectorAll('[data-kt-sticky-initialized]');
console.log('Initialized sticky elements:', initializedElements.length);
// Log viewport height
console.log('Viewport height:', window.innerHeight);
// Check each sticky element
stickyElements.forEach((element, index) => {
const computedStyle = window.getComputedStyle(element);
const height = element.offsetHeight;
const top = element.getAttribute('data-kt-sticky-top') || '0';
console.log(`Sticky ${index + 1}: height=${height}, top=${top}, height+top=${height + parseInt(top)}`);
});
} else {
console.error('KTSticky not found!');
}
});
```
--------------------------------
### KTUI CSS Variables for Tailwind CSS
Source: https://github.com/keenthemes/ktui/blob/main/README.md
Include these CSS variables in your Tailwind entry file (e.g., style.css) to configure KTUI's theming. This example shows both light and dark mode color definitions.
```css
/** Colors **/
:root {
/** Base Colors **/
--background: oklch(1 0 0); /* --color-white **/
--foreground: oklch(14.1% 0.005 285.823); /* --color-zinc-950 **/
--card: oklch(1 0 0); /* --color-white **/
--card-foreground: oklch(14.1% 0.005 285.823); /* --color-zinc-950 **/
--popover: oklch(1 0 0); /* --color-white **/
--popover-foreground: oklch(14.1% 0.005 285.823); /* --color-zinc-950 **/
--primary: oklch(62.3% 0.214 259.815); /* --color-blue-500 **/
--primary-foreground: oklch(1 0 0); /* --color-white **/
--secondary: oklch(96.7% 0.003 264.542); /* --color-zinc-100 **/
--secondary-foreground: oklch(21% 0.006 285.885); /* --color-zinc-900 **/
--muted: oklch(96.7% 0.003 264.542); /* --color-zinc-100 **/
--muted-foreground: oklch(55.2% 0.016 285.938); /* --color-zinc-500 **/
--accent: oklch(96.7% 0.003 264.542); /* --color-zinc-100 **/
--accent-foreground: oklch(21% 0.006 285.885); /* --color-zinc-900 **/
--destructive: oklch(57.7% 0.245 27.325); /* --color-red-600 **/
--destructive-foreground: oklch(1 0 0); /* --color-white **/
--mono: oklch(14.1% 0.005 285.823); /* --color-zinc-950 **/
--mono-foreground: oklch(1 0 0); /* --color-white **/
/** Base Styles **/
--border: oklch(94% 0.004 286.32); /* between --color-zinc-100 and --color-zinc-200 **/
--input: oklch(92% 0.004 286.32); /* --color-zinc-200 **/
--ring: oklch(87.1% 0.006 286.286); /* --color-zinc-400 **/
--radius: 0.5rem;
}
.dark {
/** Base Colors **/
--background: oklch(14.1% 0.005 285.823); /* --color-zinc-950 **/
--foreground: oklch(98.5% 0 0); /* --color-zinc-50 **/
--card: oklch(14.1% 0.005 285.823); /* --color-zinc-950 **/
--card-foreground: oklch(98.5% 0 0); /* --color-zinc-50 **/
--popover: oklch(14.1% 0.005 285.823); /* --color-zinc-950 **/
--popover-foreground: oklch(98.5% 0 0); /* --color-zinc-50 **/
--primary: oklch(54.6% 0.245 262.881); /* --color-blue-600 **/
--primary-foreground: oklch(1 0 0); /* --color-white **/
--secondary: oklch(27.4% 0.006 286.033); /* --color-zinc-800 **/
--secondary-foreground: oklch(98.5% 0 0); /* --color-zinc-50 **/
--muted: oklch(21% 0.006 285.885); /* --color-zinc-900 **/
--muted-foreground: oklch(55.2% 0.016 285.938); /* --color-zinc-500 **/
--accent: oklch(21% 0.006 285.885); /* --color-zinc-900 **/
--accent-foreground: oklch(98.5% 0 0); /* --color-zinc-50 **/
--destructive: oklch(57.7% 0.245 27.325); /* --color-red-600 **/
--destructive-foreground: oklch(1 0 0); /* --color-white **/
--mono: oklch(87.1% 0.006 286.286); /* --color-zinc-300 **/
--mono-foreground: oklch(0 0 0); /* --color-black **/
/** Base Styles **/
--border: oklch(27.4% 0.006 286.033); /* --color-zinc-800 **/
--input: oklch(27.4% 0.006 286.033); /* --color-zinc-800 **/
--ring: oklch(27.4% 0.006 286.033); /* --color-zinc-600 **/
}
/** Theme Setup **/
@theme inline {
/** Base Colors **/
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-destructive: var(--destructive);
--color-destructive-foreground: var(--destructive-foreground);
--color-mono: var(--mono);
--color-mono-foreground: var(--mono-foreground);
/** Base Styles **/
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--radius-xl: calc(var(--radius) + 4px);
--radius-lg: var(--radius);
--radius-md: calc(var(--radius) - 2px);
--radius-sm: calc(var(--radius) - 4px);
}
```
--------------------------------
### Instance Management
Source: https://github.com/keenthemes/ktui/blob/main/skills/ktui-select/SKILL.md
Manage KTSelect instances, including retrieving existing instances, creating new ones, initializing all instances on the page, and configuring global defaults.
```APIDOC
## Instance Management
| Static method | Returns |
|-----------------------------------|------------------------------------------|
| `KTSelect.getInstance(el)` | Existing instance or `null` |
| `KTSelect.getOrCreateInstance(el, config?)` | Existing or new instance |
| `KTSelect.init()` | Scans DOM, creates instances |
| `KTSelect.config(opts)` | Set global defaults |
### `KTSelect.getInstance(el)`
Retrieves an existing KTSelect instance associated with the provided HTML element.
- **el** (HTMLElement) - The root element of the select component.
- **Returns**: (KTSelect | null) - The instance if found, otherwise null.
### `KTSelect.getOrCreateInstance(el, config?)`
Retrieves an existing KTSelect instance or creates a new one if it doesn't exist.
- **el** (HTMLElement) - The root element of the select component.
- **config** (object) - Optional - Configuration options for a new instance.
- **Returns**: (KTSelect) - The existing or newly created instance.
### `KTSelect.init()`
Scans the DOM for elements that can be initialized as KTSelect components and creates instances for them.
### `KTSelect.config(opts)`
Sets global default configuration options for all KTSelect instances. See Global Config section for available options.
```
--------------------------------
### Get Select Element Value and Text
Source: https://github.com/keenthemes/ktui/blob/main/examples/select/native-selected.html
This snippet retrieves the value and text of the selected option from a native HTML select element. It includes a delay to ensure remote data is loaded before checking the value. Use this to dynamically display user selections or form data.
```javascript
document.addEventListener('DOMContentLoaded', function() {
const selectEl = document.getElementById('select-remote');
const checkBtn = document.getElementById('check-value');
const valueDisplay = document.getElementById('value-display');
// Wait for remote data to load
setTimeout(() => {
checkBtn.addEventListener('click', function() {
const value = selectEl.value;
const selectedText = selectEl.options[selectEl.selectedIndex]?.text || 'No selection';
valueDisplay.innerHTML = `
Select Value: "${value}" Selected Text: "${selectedText}" Options Count: ${selectEl.options.length} Options:
${Array.from(selectEl.options).map(opt => `- ${opt.value}: ${opt.text}`).join(' ')}
`;
});
}, 3000); // Wait 3 seconds for remote data to load
});
```
--------------------------------
### KTUI Development Commands
Source: https://github.com/keenthemes/ktui/blob/main/CONTRIBUTING.md
Run these commands for local development, building, formatting, linting, and type checking.
```sh
npm run dev
npm run build
npm run format
npm run lint
npm run type-check:strict
```
--------------------------------
### Open Visual Sticky Test in Browser
Source: https://github.com/keenthemes/ktui/blob/main/examples/sticky/README.md
Command to open the visual testing HTML file in your web browser.
```bash
open examples/sticky/test-sticky-positioning.html
```
--------------------------------
### KTToast Static API
Source: https://github.com/keenthemes/ktui/blob/main/skills/ktui/SKILL.md
Demonstrates the usage of the static KTToast API for displaying toast messages with basic and advanced configurations.
```APIDOC
## KTToast Static API
### Description
Provides a static API for displaying temporary toast messages with customizable appearance, behavior, and content.
### Methods
- **show(options):** Displays a toast message.
- **config(options):** Sets global configuration for all toasts.
### Parameters for `show()`
#### options (object)
- **message** (string) - Required - The main text content of the toast.
- **variant** (string) - Optional - The visual style of the toast (e.g., 'success', 'error', 'info').
- **appearance** (string) - Optional - The appearance style ('solid', 'outline', 'light').
- **size** (string) - Optional - The size of the toast ('sm', 'md', 'lg').
- **position** (string) - Optional - The screen position ('top-end', 'bottom-center', etc.).
- **duration** (number) - Optional - Auto-dismiss duration in milliseconds.
- **important** (boolean) - Optional - If true, toast will not auto-dismiss.
- **progress** (boolean) - Optional - Whether to show a progress bar.
- **pauseOnHover** (boolean) - Optional - Pause timer when the mouse hovers over the toast.
- **dismiss** (boolean) - Optional - Show a close button.
- **icon** (string) - Optional - HTML string for a leading icon.
- **action** (object) - Optional - Configuration for an action button.
- **label** (string) - Button text.
- **onClick** (function) - Callback function when the button is clicked.
- **className** (string) - CSS classes for the button.
- **cancel** (object) - Optional - Configuration for a cancel button.
- **label** (string) - Button text.
- **onClick** (function) - Callback function when the button is clicked.
- **beep** (boolean) - Optional - Play a notification sound.
- **onAutoClose** (function) - Optional - Callback when the toast auto-dismisses.
- **onDismiss** (function) - Optional - Callback when the toast is manually dismissed.
- **content** (HTMLElement | string | function) - Optional - Custom content for the toast.
### Parameters for `config()`
#### options (object)
- **position** (string) - Optional - Default position for toasts.
- **duration** (number) - Optional - Default auto-dismiss duration.
- **maxToasts** (number) - Optional - Maximum number of toasts to display simultaneously.
- **offset** (number) - Optional - Offset from the screen edge.
- **gap** (number) - Optional - Space between multiple toasts.
### Variants
'info', 'success', 'error', 'warning', 'primary', 'secondary', 'destructive', 'mono'
### Request Example (Basic)
```ts
KTToast.show({ message: 'Saved!', variant: 'success' });
```
### Request Example (Full Options)
```ts
KTToast.show({
message: 'Item deleted',
variant: 'error',
appearance: 'solid',
size: 'md',
position: 'top-end',
duration: 5000,
important: false,
progress: true,
pauseOnHover: true,
dismiss: true,
icon: '',
action: {
label: 'Undo',
onClick: (id) => { /* ... */ },
className: 'btn btn-sm',
},
cancel: {
label: 'Cancel',
onClick: (id) => { /* ... */ },
},
beep: true,
onAutoClose: (id) => {},
onDismiss: (id) => {},
});
```
### Request Example (Custom Content)
```ts
KTToast.show({
content: document.getElementById('my-toast-template'),
});
```
### Global Configuration Example
```ts
KTToast.config({
position: 'bottom-end',
duration: 4000,
maxToasts: 5,
offset: 15,
gap: 10,
});
```
```
--------------------------------
### KTDataTable Configuration Options
Source: https://github.com/keenthemes/ktui/blob/main/skills/ktui-datatable/SKILL.md
Lists and describes the available configuration options for customizing the KTDataTable.
```APIDOC
## KTDataTable Configuration Options
### Description
These options can be passed to the DataTable constructor or set via `data-kt-datatable-*` attributes to customize its behavior and appearance.
### Parameters
#### Config Options
- **`apiEndpoint`** (string) - Remote data URL.
- **`requestMethod`** (string) - HTTP method (default `'POST'`).
- **`requestHeaders`** (object) - Custom headers.
- **`mapResponse`** (function) - Transform API response.
- **`mapRequest`** (function) - Transform request params.
- **`pageSize`** (number) - Rows per page.
- **`pageSizes`** (number[]) - Page size options.
- **`stateSave`** (boolean) - Persist state in localStorage.
- **`columns`** (object) - Column config (render, checkbox, sortType, sortValue, createdCell).
- **`sort`** (object) - Sort config with classes and callback.
- **`search`** (object) - Search config with delay and callback.
- **`pagination`** (object) - Pagination markup config.
- **`loading`** (object) - Spinner template.
- **`checkbox`** (object) - Row checkbox config (checkedClass, preserveSelection).
- **`lockedLayout`** (object) - Sticky headers/columns.
- **`tableLayout`** (string) - `'fixed'` for fixed column widths (use with `
`).
- **`filter`** (object) - Column filter config (type, value).
- **`infoEmpty`** (string) - Empty state HTML (supports innerHTML).
```
--------------------------------
### Basic KTDropdown HTML Structure
Source: https://github.com/keenthemes/ktui/blob/main/skills/ktui/SKILL.md
Sets up the HTML for a dropdown component, including a toggle button and a menu container. The menu will be hidden by default.
```html
```
--------------------------------
### Toast with Different Sizes
Source: https://github.com/keenthemes/ktui/blob/main/examples/toast/example.html
Demonstrates how to display toasts with predefined size variants. Ensure the corresponding buttons exist in your HTML.
```javascript
sizes.forEach(size => {
const btn = document.getElementById(`toast-size-${size}`);
if (btn) {
btn.addEventListener('click', () => {
KTToast.show({
message: `${size.toUpperCase()} size`,
variant: 'success',
size
});
});
}
});
```
--------------------------------
### Initialize KTRangeSlider
Source: https://github.com/keenthemes/ktui/blob/main/skills/ktui/SKILL.md
HTML structure for initializing the KTRangeSlider component. Set minimum and maximum values using data attributes.
```html
```
--------------------------------
### Initialize KTInputNumber
Source: https://github.com/keenthemes/ktui/blob/main/skills/ktui/SKILL.md
HTML structure for initializing the KTInputNumber component. Configure min, max, and step values using data attributes.
```html
```
--------------------------------
### Global Configuration
Source: https://github.com/keenthemes/ktui/blob/main/skills/ktui-select/SKILL.md
Configure default settings for all KTSelect instances. This method should be called before initializing any instances if you want to apply global defaults.
```APIDOC
## Global Config
Set defaults for all future instances:
```ts
KTSelect.config({
enableSearch: true,
searchPlaceholder: 'Type to search...',
dropdownZindex: 9999,
height: 300,
closeOnEnter: true,
closeOnOtherOpen: true,
searchAutofocus: true,
dispatchGlobalEvents: true,
});
```
### Parameters
- **opts** (object) - Optional - An object containing configuration options to set as global defaults.
- **enableSearch** (boolean) - Optional - Enables or disables the search input within the dropdown.
- **searchPlaceholder** (string) - Optional - Sets the placeholder text for the search input.
- **dropdownZindex** (number) - Optional - Sets the z-index for the dropdown.
- **height** (number) - Optional - Sets the height of the dropdown.
- **closeOnEnter** (boolean) - Optional - Determines if the dropdown closes when Enter is pressed.
- **closeOnOtherOpen** (boolean) - Optional - Determines if the dropdown closes when another dropdown opens.
- **searchAutofocus** (boolean) - Optional - Automatically focuses the search input when the dropdown opens.
- **dispatchGlobalEvents** (boolean) - Optional - Determines if global events are dispatched.
```
--------------------------------
### KTModal Instance Methods
Source: https://github.com/keenthemes/ktui/blob/main/skills/ktui/SKILL.md
Provides details on the methods available for interacting with a `KTModal` instance programmatically.
```APIDOC
## KTModal Instance Methods
### Methods
- **`instance.show()`**
- **Description**: Displays the modal.
- **Returns**: void
- **`instance.hide()`**
- **Description**: Hides the modal.
- **Returns**: void
- **`instance.toggle()`**
- **Description**: Toggles the visibility of the modal (shows if hidden, hides if shown).
- **Returns**: void
- **`instance.isOpen()`**
- **Description**: Checks if the modal is currently visible.
- **Returns**: `boolean` - `true` if the modal is open, `false` otherwise.
- **`instance.dispose()`**
- **Description**: Destroys the modal instance, removing its event listeners and cleanup.
- **Returns**: void
```
--------------------------------
### Include All Assets
Source: https://github.com/keenthemes/ktui/blob/main/README.md
Ensure all necessary assets, including fonts, styles, and the KTUI JavaScript file, are included in your HTML.
```html
...
...
....
```
--------------------------------
### Component Event System
Source: https://github.com/keenthemes/ktui/blob/main/skills/ktui/SKILL.md
Explains how to handle events emitted by KTUI components, both through direct callback registration using `on`/`off` methods and via standard DOM events.
```APIDOC
## Component Event System
### Event Handling Methods
- **`instance.on(eventName, callback)`**
- **Description**: Registers a callback function to be executed when a specific event is triggered by the component instance. Returns an event ID for later removal.
- **Parameters**:
- `eventName` (string): The name of the event to listen for (e.g., 'show', 'hide').
- `callback` (function): The function to execute when the event fires. It receives a `payload` object.
- **Returns**: `eventId` (number) - An identifier for the registered event.
- **`instance.off(eventName, eventId)`**
- **Description**: Removes a previously registered event listener.
- **Parameters**:
- `eventName` (string): The name of the event to unregister.
- `eventId` (number): The ID of the event listener to remove, obtained from `instance.on()`.
- **Returns**: void
### Custom DOM Events
Components also emit standard DOM events that bubble up the DOM tree. These can be listened to using `addEventListener`.
- **`element.addEventListener(eventName, (e) => { ... })`**
- **Description**: Listens for DOM events dispatched by the component.
- **Parameters**:
- `eventName` (string): The name of the DOM event (e.g., 'show', 'hide').
- `e` (Event): The event object. `e.detail.payload` contains the event payload. Call `e.preventDefault()` to cancel cancelable events.
### Event Lifecycle Examples
- **Toggle to Show**: `toggle` → `show` → `shown` (after transition)
- **Toggle to Hide**: `toggle` → `hide` → `hidden` (after transition)
### Event Payload
For cancelable events, the payload object may contain a `cancel` property. Setting `payload.cancel = true` will prevent the default action of the event.
Example payload for cancelable events: `{ cancel: false }`.
```
--------------------------------
### Initialize KTSticky Components
Source: https://github.com/keenthemes/ktui/blob/main/examples/sticky/test-sticky-positioning.html
Initializes all sticky elements on the page when the DOM is loaded. It also sets up a scroll event listener to update a scroll indicator and log the position of the active sticky element.
```javascript
document.addEventListener('DOMContentLoaded', function() {
// Initialize all sticky elements if (window.KTSticky) {
window.KTSticky.init();
}
// Update scroll indicator
window.addEventListener('scroll', function() {
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
document.getElementById('scrollIndicator').textContent = `Scroll: ${scrollTop}px`;
// Update position indicator
const activeSticky = document.querySelector('[data-kt-sticky-initialized].active');
if (activeSticky) {
const name = activeSticky.getAttribute('data-kt-sticky-name');
const computedStyle = window.getComputedStyle(activeSticky);
const position = {
top: computedStyle.top,
bottom: computedStyle.bottom,
left: computedStyle.left,
right: computedStyle.right,
insetBlockStart: computedStyle.insetBlockStart,
insetInlineStart: computedStyle.insetInlineStart,
insetInlineEnd: computedStyle.insetInlineEnd
};
document.getElementById('positionIndicator').innerHTML = ` Active: ${name} Top: ${position.top} Bottom: ${position.bottom} Left: ${position.left} Right: ${position.right} InsetBlockStart: ${position.insetBlockStart} InsetInlineStart: ${position.insetInlineStart} InsetInlineEnd: ${position.insetInlineEnd} `;
} else {
document.getElementById('positionIndicator').textContent = 'No active sticky elements';
}
});
});
```
--------------------------------
### Open Test Runner in Browser
Source: https://github.com/keenthemes/ktui/blob/main/examples/sticky/README.md
Command to open the automated test runner HTML file in your web browser.
```bash
open examples/sticky/test-runner.html
```
--------------------------------
### Basic KTTooltip HTML Structure
Source: https://github.com/keenthemes/ktui/blob/main/skills/ktui/SKILL.md
Shows the HTML for a tooltip component, where hovering over the element displays the content specified in the `data-kt-tooltip-content` attribute.
```html
```
--------------------------------
### Run Sticky Test Suite Programmatically
Source: https://github.com/keenthemes/ktui/blob/main/examples/sticky/README.md
JavaScript code to import and run the StickyTestSuite directly in the browser's developer console.
```javascript
import StickyTestSuite from './examples/sticky/test-sticky-logic.js';
const testSuite = new StickyTestSuite();
await testSuite.runAllTests();
```
--------------------------------
### Initialize Modal and Select Components
Source: https://github.com/keenthemes/ktui/blob/main/examples/select/modal.html
Ensures that modal and select components are initialized after the DOM is fully loaded. This script should be included in your project to enable the functionality of these components.
```javascript
document.addEventListener('DOMContentLoaded', function() {
if (window.KTModal) {
KTModal.init();
}
if (window.KTSelect) {
KTSelect.init();
}
});
```
--------------------------------
### KTTooltip
Source: https://github.com/keenthemes/ktui/blob/main/skills/ktui/SKILL.md
Adds tooltips to elements, displaying informative text on hover or interaction.
```APIDOC
## KTTooltip
### Description
Adds tooltips to elements, displaying informative text on hover or interaction.
### Usage
```html
```
```