KtUI (Keenthemes Tailwind UI)

repository·main·Indexed 40 days ago

https://github.com/keenthemes/ktui

An open-source Tailwind CSS component library providing interactive UI components with declarative data-attribute and programmatic JS API interfaces. Features include a robust DataTable with remote data support, sticky positioning with RTL compatibility, and a customizable theme system using CSS variables and Tailwind CSS. Version 1.2.7.

Tokens
32.2K
Snippets
111
Records
172
Agent score
100%

What's inside KtUI

  1. Understand the KTDataTable Lifecycle

    main

    Understanding the data update lifecycle is critical for debugging DOM-related issues. Every data update follows this sequence:

    1. _updateData(): Fetches data from the DOM (local) or API (remote).
    2. _draw():
      • _cleanupForRedraw(): Cleans up listeners and DOM artifacts.
      • _updateTable(): Re-renders <tbody> rows.
      • _updatePagination(): Re-renders pagination controls.
      • afterDraw layoutPlugin hook.
      • _saveState(): Persists state to localStorage.
    3. _finalize():
      • _checkbox.init(): Re-queries DOM and reapplies checked states.
      • _sortHandler.initSort(): Re-attaches sort listeners.
      • searchHandler.attach(): Re-attaches search listeners.
      • KTComponents.init(): Re-initializes other components.
      • spinner.hide(): Hides loading indicator.
      • Update _contentChecksum: This MUST be the last step. Any DOM modifications made in _finalize() must be reflected in the checksum.
    4. Emit update event.

    Critical Note: If the _contentChecksum is updated before _finalize() completes, the internal state may become stale, leading to issues like empty pagination after checkbox selection.

  2. Handle KTSelect Events

    main

    KTSelect supports two event channels: Internal callbacks via .on() and DOM CustomEvents dispatched on both the element and the document (if dispatchGlobalEvents is enabled).

    Event Names

    show, close, change, enabled, disabled, updated, updateError, reloadStart, reloadComplete, reloadError, refreshed, refreshError.

    Event Detail Shape

    When listening to a CustomEvent, the event.detail object contains:

    • instance: The KTSelect instance.
    • element: The root HTMLElement.
    • payload: Event-specific data.

    Usage Examples

    Listening on the document (Global):

    document.addEventListener('kt-select:change', (e) => {
      console.log(e.detail.instance.getSelectedOptions());
    });

    Listening on a specific element:

    el.addEventListener('change', (e) => {
      console.log(e.detail.instance.getSelectedOptions());
    });
  3. Understand KTUI configuration priority

    main

    KTUI components resolve configuration using a specific hierarchy. When multiple configuration sources are provided, the one with the higher priority wins.

    Priority Order (Lowest to Highest):

    1. window.KTGlobalComponentsConfig[component] (Global window object)
    2. Component class _defaultConfig (Internal defaults)
    3. Static .config() (Per-component static configuration)
    4. data-kt-{component}-* (HTML data attributes)
    5. --kt-{component}-{option} (CSS custom properties)
    6. Constructor config argument (Direct instantiation)
  4. Configure RTL (Right-to-Left) Support

    main

    KTUI supports RTL layouts using logical CSS properties.

    Global Setup

    Add the dir="rtl" attribute to your <html> element:

    <html dir="rtl">
    </html>

    Usage

    1. Logical Properties: Use classes like text-start and ps-5 (padding-start) instead of text-left or pl-5. These automatically adjust based on the text direction.
    2. RTL Modifier: For specific overrides, use the rtl:* Tailwind modifier:
    <div class="text-left pl-5 rtl:text-right rtl:pr-5">
        Example text
    </div>
    <!-- Setup rtl mode -->
    <html dir="rtl">
        <!-- HTML markup -->
    </html>
    
    <!-- Using logical properties -->
    <div class="text-start ps-5">
        Example text
    </div>
    
    <!-- Using rtl modifier -->
    <div class="text-left pl-5 rtl:text-right rtl:pr-5">
        Example text
    </div>
  5. Understand the KtUI source code structure

    main

    The KtUI library is organized into a core module and a collection of specialized component modules:

    • index.ts: The main entry point containing primary exports and the KTComponents.init() method.
    • init-all.ts: Handles automatic initialization on the DOMContentLoaded event.
    • helpers/: Contains internal utilities including KTDom (DOM utilities), KTData (WeakMap data store), KTEventHandler (delegated events), and KTUtils (general utilities).
    • components/: Contains the implementation for all UI components. Notable complex components include:
      • datatable: Supports local/remote providers, sorting, searching, and pagination.
      • dropdown: Utilizes @popperjs/core for positioning.
      • select: Includes modules for search, remote data, tags, and combobox functionality.
      • toast: Provides a static API for notifications.
    ktui/src/
    ├── index.ts                    # Main exports + KTComponents.init()
    ├── init-all.ts                 # Auto-init on DOMContentLoaded
    ├── types.ts                    # Shared types
    ├── legacy.ts                   # Legacy compatibility
    ├── helpers/
    │   ├── dom.ts                  # KTDom
    │   ├── data.ts                 # KTData
    │   ├── event-handler.ts        # KTEventHandler
    │   └── utils.ts                # KTUtils
    └── components/
        ├── component.ts            # KTComponent (Base class)
        ├── accordion/
        ├── datatable/
        ├── dropdown/
        ├── select/
        └── toast/
        ... (other components)
  6. Theming with CSS Variables

    main

    KTUI uses a Shadcn-inspired CSS variable convention. You can define your theme in your Tailwind entry file using :root.

    Naming Convention:

    • Background colors: Omit the -background suffix. Example: bg-primary uses var(--primary).
    • Foreground colors: Use the -foreground suffix. Example: text-primary-foreground uses var(--primary-foreground).

    Semantic Classes:

    • bg-background, text-foreground
    • bg-primary, text-primary-foreground
    • bg-card, text-card
    • kt-btn, kt-card, kt-input
    :root {
      --background: oklch(1 0 0);
      --foreground: oklch(14.1% 0.005 285.823);
      --primary: oklch(62.3% 0.214 259.815);
      --primary-foreground: oklch(1 0 0);
      --radius: 0.5rem;
      /* ... other variables */
    }
  7. RTL Support in KTUI

    main

    KTUI has built-in support for Right-to-Left (RTL) layouts:

    • KTDom.isRTL() can be used to check if the document has dir="rtl" on the <html> element.
    • Dropdowns automatically adjust their placement based on the placementRtl configuration.
    • It is recommended to use CSS logical properties (e.g., inset-inline-start instead of left) for custom styling to ensure compatibility.
  8. Configure Tailwind CSS for KtUI

    main

    To ensure Tailwind CSS scans and generates the necessary utility classes used by KtUI, add the KtUI source paths to your tailwind.config.js content array.

    // tailwind.config.js
    module.exports = {
      content: [
        './node_modules/@keenthemes/ktui/src/**/*.{ts,js}',
        // your app files...
      ],
    };
  9. Implement Remote Data in KTSelect

    main

    To load options from an external API, set data-kt-select-remote="true" and provide the endpoint via data-kt-select-remote-url="...". For APIs that support paginated results, add data-kt-select-pagination="true" to enable a "Load More" button.

    <select data-kt-select="true"
            data-kt-select-remote="true"
            data-kt-select-remote-url="https://api.example.com/options"
            data-kt-select-pagination="true">
    </select>
  10. Import KTUI Styles and Assets

    main

    To use KTUI components, you must import its styles and include its JavaScript bundle in your project.

    1. Import Styles

    In your Tailwind entry file (style.css), import the KTUI styles:

    @import "./node_modules/@keenthemes/ktui/dist/styles.css";

    2. Include JavaScript

    Include the minified KTUI script in your HTML (usually before the closing </body> tag):

    <script src="./node_modules/@keenthemes/ktui/dist/ktui.min.js"></script>

    3. Fonts (Optional)

    If you want to use a specific font like 'Inter', define it in your @theme block in style.css and include the font via a <link> tag in your HTML <head>.

  11. Basic Usage of KTDataTable

    main

    To use the KTDataTable component, mark a container element with the data-kt-datatable="true" attribute. Inside, include a standard HTML <table> with <thead> and <tbody>. Use data-kt-datatable-column="[name]" on <th> elements to map columns to your data keys.

    To interact with the table in TypeScript, use KTDataTable.getInstance(tableEl) to retrieve the instance associated with the element.

    <div data-kt-datatable="true">
      <table>
        <thead>
          <tr>
            <th data-kt-datatable-column="name">Name</th>
            <th data-kt-datatable-column="email">Email</th>
          </tr>
        </thead>
        <tbody></tbody>
      </table>
    </div>
    import { KTDataTable } from '@keenthemes/ktui';
    
    const dt = KTDataTable.getInstance(tableEl);
  12. Use the KTUI Sticky component positioning attributes

    main

    The KTUI Sticky component uses specific data-kt-sticky-* attributes to control positioning. It utilizes modern CSS logical properties (like inset-block-start) to ensure compatibility with both LTR and RTL layouts.

    Positioning Scenarios

    FeatureAttributeResulting CSS Logic
    Topdata-kt-sticky-top="20"inset-block-start: 20px
    Bottomdata-kt-sticky-bottom="20"inset-block-end: 20px
    Middle (Vertical Center)data-kt-sticky-middle="true"inset-block-start: 50%
    Center (Horizontal Center)data-kt-sticky-center="true"inset-inline-start: 50%
    Full Centeringdata-kt-sticky-middle="true" + data-kt-sticky-center="true"Both vertical and horizontal centering
    End (RTL Friendly)data-kt-sticky-end="20"inset-inline-end: 20px
    Auto Topdata-kt-sticky-top="auto"inset-block-start: 0px
    Auto Startdata-kt-sticky-start="auto"Calculated offset using KTDom.offset()

    Important Logic Rules

    • Exclusive Positioning: If conflicting properties are provided, precedence is applied. For example, if both top and bottom are set, only top is applied. Similarly, if both start and end are set, only start is applied.
    • RTL Support: Use start and end instead of left and right to ensure the component works correctly in right-to-left layouts. Ensure the dir="rtl" attribute is set on your <html> element.