Slim Select

repository·master·Indexed 23 days ago

https://github.com/brianvoe/slim-select

A lightweight, dependency-free replacement for the native HTML <select> element. Version 4.0.7 supports single and multi-select, remote API search, optgroups, and full theming via CSS variables. It is available as a vanilla JS library with official wrappers for Vue 3 and React.

Tokens
8.6K
Snippets
11
Records
36
Agent score
76%

What's inside slim-select

  1. Theme Slim Select with CSS variables

    master

    Slim Select uses CSS custom properties (variables) for styling. You can apply a theme globally by setting them on :root, or scoped to a specific container by setting them on a wrapper element.

    Common variables include:

    • --ss-primary-color
    • --ss-bg-color
    • --ss-font-color
    • --ss-border-color
    • --ss-border-radius
    • --ss-main-height

    Example usage:

    .my-form {
      --ss-primary-color: #2563eb;
      --ss-bg-color: #ffffff;
      --ss-font-color: #1e293b;
      --ss-border-color: #e2e8f0;
      --ss-border-radius: 8px;
      --ss-main-height: 44px;
    }
  2. Quick start with Slim Select

    master

    To initialize Slim Select on a native <select> element, import the library and its styles, then instantiate SlimSelect targeting your element's ID.

    HTML:

    <select id="selectElement">
      <option value="value1">Value 1</option>
    </select>

    JavaScript:

    import SlimSelect from 'slim-select'
    import 'slim-select/styles' // or: import 'slim-select/scss'
    
    new SlimSelect({
      select: '#selectElement'
    })
  3. Use Slim Select in Vue 3

    master

    Slim Select provides an official Vue 3 component that supports v-model.

    Note: Pass options via the :data prop. Native <option> slot children are not supported in the Vue wrapper.

    Installation:

    npm install slim-select

    Usage:

    <script lang="ts">
    import SlimSelect from 'slim-select/vue'
    import 'slim-select/styles'
    
    export default {
      components: { SlimSelect },
      data() {
        return {
          selected: 'value2',
          options: [
            { text: 'Value 1', value: 'value1' },
            { text: 'Value 2', value: 'value2' },
            { text: 'Value 3', value: 'value3' }
          ]
        }
      }
    }
    </script>
    
    <template>
      <SlimSelect v-model="selected" :data="options" />
    </template>
  4. Use Slim Select in React

    master

    Slim Select provides an official React component with hooks and ref access to the underlying instance.

    Note: Pass options via the data prop. Native <option> children are not supported in the React wrapper.

    Installation:

    npm install slim-select

    Basic Usage:

    import { useState } from 'react'
    import SlimSelect from 'slim-select/react'
    import 'slim-select/styles'
    
    function MyComponent() {
      const [selected, setSelected] = useState('value2')
      const options = [
        { text: 'Value 1', value: 'value1' },
        { text: 'Value 2', value: 'value2' },
        { text: 'Value 3', value: 'value3' }
      ]
    
      return <SlimSelect data={options} value={selected} onChange={setSelected} />
    }

    Accessing the underlying instance via Ref: To call methods like .open() or .close() directly, use useRef with the SlimSelectRef type.

    import { useRef } from 'react'
    import SlimSelect, { SlimSelectRef } from 'slim-select/react'
    import 'slim-select/styles'
    
    function MyComponent() {
      const slimRef = useRef<SlimSelectRef>(null)
    
      return (
        <>
          <SlimSelect ref={slimRef} data={options} />
          <button onClick={() => slimRef.current?.slimSelect?.open()}>Open</button>
        </>
      )
    }
  5. Install Slim Select

    master

    You can install Slim Select via npm or use a CDN for direct browser integration.

    NPM Installation:

    npm install slim-select

    CDN Integration: Include the following tags in your HTML:

    <script src="https://unpkg.com/slim-select@latest/dist/slimselect.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/slim-select@latest/dist/slimselect.css" />
  6. Understand SlimSelect lifecycle states

    master

    SlimSelect operates as a state machine to manage the dropdown's visibility and animations. The LifecycleState can be one of:

    • closed: The dropdown is hidden.
    • opening: The dropdown is currently transitioning to open.
    • open: The dropdown is fully visible and interactive.
    • closing: The dropdown is currently transitioning to closed.

    Two helper properties are available to check the state:

    • isOpen: Returns true if the state is opening or open.
    • isFullOpen: Returns true only when the state is exactly open (after animations have completed).
  7. Configure Slim Select settings

    master

    The settings object allows you to customize the behavior and appearance of the dropdown. All fields are optional. Key settings include:

    • showSearch: Enables/disables the search bar.
    • searchPlaceholder: Text for the search input.
    • modal: Controls mobile/modal behavior ('off' | 'on' | 'mobile').
    • allowDeselect: Enables/disables clearing the selection.
    • minSelected / maxSelected: Limits for multi-select.
    • contentPosition: 'absolute' | 'relative' | 'fixed'.
    • closeOnSelect: Boolean.

    Example Configuration:

    new SlimSelect({
      select: '#selectElement',
    
      settings: {
        disabled: false,
        alwaysOpen: false,
        showSearch: true,
        focusSearch: true,
        keepSearch: false,
        ariaLabel: 'Combobox',
        searchPlaceholder: 'Search...',
        searchText: 'No Results',
        searchingText: 'Searching...',
        resultsText: '{count} results available',
        deselectText: 'Clear',
        removeText: 'Remove',
        searchHighlight: false,
        closeOnSelect: true,
        contentLocation: document.body,
        contentPosition: 'absolute',
        contentWidth: '',
        openPosition: 'auto',
        placeholderText: 'Select Value',
        allowDeselect: false,
        hideSelected: false,
        multiString: false,
        keepOrder: false,
        showOptionTooltips: false,
        minSelected: 0,
        maxSelected: 1000,
        timeoutDelay: 200,
        maxValuesShown: 20,
        maxValuesMessage: '{number} selected',
        addableText: 'Press "Enter" to add {value}',
        modal: 'mobile',
        modalTitle: ''
      }
    })
  8. Manage selection data with the Store class

    master

    The Store class is the central authority for managing the lifecycle of options, groups, and selections. It handles data validation, filtering, and selection state.

    Key Capabilities:

    • Data Management: Set new data via setData(), add single options via addOption(), and retrieve data via getData() or getDataOptions().
    • Selection Control: Programmatically select items using setSelectedBy(), or retrieve current selections via getSelected(), getSelectedValues(), or getSelectedOptions().
    • Searching and Filtering: Perform searches using search() or custom predicate filtering using filter().
    • Data Integrity: Use validateDataArray() to ensure provided data conforms to the expected Option or Optgroup structures.
  9. Understand the SlimSelect synchronization pipeline

    master

    SlimSelect uses a SyncCoordinator to manage updates between the internal data store, the native <select> element, and the custom UI. This centralized pipeline ensures that changes (from the API, user UI interactions, or native DOM mutations) are batched and coalesced to prevent redundant renders and infinite loops.

    Change Sources

    Updates can originate from three sources:

    • native: Changes made directly to the native <select> element (e.g., via browser developer tools or other scripts).
    • ui: Changes triggered by user interactions with the SlimSelect custom UI.
    • api: Changes triggered via the SlimSelect public API (e.g., setData, setSelected).

    Synchronization Logic

    • Batching: Native mutations are coalesced into a single microtask to ensure the UI only re-renders once per frame.
    • Coalescing: If multiple structure updates (like setData) arrive in a single batch, only the last one is applied. Selection changes are also collapsed to the most recent state.
    • Search Results: When using API-based search, results are treated as ephemeral. They update the UI and store but do not overwrite the underlying catalog or the native <select> options, preventing search hits from polluting the form data unexpectedly.
  10. Define Option and Optgroup data structures

    master

    Slim Select uses two primary data structures to manage selection data: Option and Optgroup.

    Option

    Represents a single selectable item.

    • id: Unique identifier (auto-generated if not provided).
    • value: The underlying value of the option.
    • text: The display text.
    • html: Optional HTML content for the option.
    • selected: Boolean indicating if the option is currently selected.
    • disabled: Boolean indicating if the option is unselectable.
    • data: A dictionary of custom data attributes.
    • class / style: CSS classes or inline styles applied to the option.

    Optgroup

    Represents a grouping of options.

    • id: Unique identifier.
    • label: The display name for the group.
    • selectAll: Boolean indicating if the group supports selecting all children.
    • closable: Controls group behavior ('off' | 'open' | 'close').
    • options: An array of Option objects belonging to this group.
  11. Use the SlimSelect React component

    master

    The SlimSelect component is a React wrapper around the core SlimSelect library. It supports both controlled and uncontrolled modes.

    Controlled Mode

    Pass both value and onChange props to let React manage the selection state. This behaves like a native <select> element.

    Uncontrolled Mode

    Omit the value prop. SlimSelect will manage the selection internally, and you can access the instance via a ref.

    Important Data Handling

    • Data Source: Options are provided via the data prop (an array of Option or Optgroup objects), not via <option> children.
    • Immutability: When updating options, you must provide a new array reference for the data prop. In-place mutation of the existing array will not trigger a sync.
  12. Initialize SlimSelect with Config

    master

    To use SlimSelect, instantiate the SlimSelect class by passing a Config object. You can target a <select> element using either a CSS selector string or the element itself. You can also provide initial data, custom settings, and event handlers during initialization.

    import SlimSelect from 'slim-select';
    
    const select = new SlimSelect({
      select: '#my-select',
      data: [
        { text: 'Option 1', value: '1' },
        { text: 'Option 2', value: '2' }
      ],
      settings: {
        // custom settings
      },
      events: {
        // custom events
      }
    });