svelecte

repository·master·Indexed 20 days ago

https://github.com/mskocik/svelecte

A flexible autocomplete and select component for Svelte, inspired by Selectize.js. It supports single and multiselect modes, remote data fetching, virtualized lists for large datasets, and custom item rendering. Svelecte can be used as a standard Svelte component or registered as a Web Custom Element for use in non-Svelte environments. Version 5 is compatible with Svelte 5, while Version 4 is for Svelte 4 projects.

Tokens
14.7K
Snippets
50
Records
56
Agent score
69%

What's inside svelecte

  1. Overview of Svelecte features

    master

    Svelecte is a highly customizable autocomplete/select component for Svelte with the following capabilities:

    • Selection Modes: Searchable, multiselect (with a configurable limit on max selected items), and support for both simple arrays and complex objects.
    • Data Handling: Remote data fetching, virtual list support for large datasets, and lazy dropdown rendering.
    • Customization: Custom item renderers (formatters), customizable styling, and the ability to create/edit new items.
    • Compatibility: SSR support, client-side validation support (e.g., with sveltekit-superforms), and usable as a custom element.
    • Accessibility & UX: i18n, basic ARIA support, and integration with svelte-dnd-action for drag-and-drop.
  2. Key features of Svelecte

    master

    Svelecte is a fully featured and customizable select, multiselect, and autocomplete component. Key capabilities include:

    • Selection Modes: Supports single select, multiselect (with a maximum item limit), and autocomplete.
    • Data Handling: Accepts simple arrays or complex objects as items; supports remote data fetching and creating new items on the fly.
    • Rendering & UI: Custom item rendering via multiple snippets, virtual list support for large datasets, and drag & drop support.
    • Compatibility: Supports SSR (Server-Side Rendering), i18n (internationalization), and a11y (accessibility).
    • Extensibility: Can be used as a custom element and is themable using CSS variables.
  3. Use a native <select> as an anchor for Svelecte

    master

    You can use a native <select> element as an "anchor element". The Svelecte component will serve as the UI layer for the underlying native element.

    In this mode:

    • Svelecte inherits required, multiple, and disabled properties from the <select> element.
    • If the options property is not explicitly set on the Svelecte component, it will automatically extract the option list from the <option> elements within the anchor <select>.
    <select id="my_select" name="form_select" required>
      <option>Option 1</option>
      <option>Option 2</option>
    </select>
    <el-svelecte placeholder="Pick an item"></el-svelecte>
  4. Configure remote fetching modes

    master

    Svelecte supports two remote fetching modes determined by the fetch property:

    1. Query Mode: Triggered when the user types. Enable this by including the [query] placeholder in the fetch URL. The placeholder is replaced by the user's input.
    2. Init Mode: Triggered when the component is mounted. This is the default behavior if the [query] placeholder is absent.

    Note: Since v4.0, you cannot provide a custom fetch function; use the fetch and fetchProps properties instead.

    <!-- Query mode: triggered on user input -->
    <Svelecte fetch="https://example.com/url?search=[query]">
    
    <!-- Init mode: triggered on mount -->
    <Svelecte fetch="https://example.com/url">
  5. Customize rendering with Render Functions

    master

    Render functions (renderers) are functions that return a string which is rendered via {@html}. They are ideal for simple HTML customization and work even when using Svelecte as a custom element outside of Svelte. Highlighting is handled automatically unless you choose to handle it manually using the inputValue parameter.

    Renderer Signature:

    /**
     * @param {object} item - The current option object
     * @param {boolean} [selectionSection] - True if the option is being rendered in the control (selection area), false if in the dropdown
     * @param {string} [inputValue] - The current search/input value (use this if you want to handle highlighting manually)
     * @returns {string} - HTML string to render
     */
    function renderer(item, selectionSection, inputValue) {}

    Usage Patterns:

    • Global Registration: Use addRenderer(name, renderer) to make a renderer available by name via the renderer prop.
    • Local Usage: Pass the function directly to the renderer prop.

    Note: If you use inputValue to manually highlight text, you are responsible for escaping HTML tags to prevent XSS.

    import Svelecte, { addRenderer } from 'svelecte';
    
    // 1. Define the renderer
    function colorRenderer(item, _isSelection, _inputValue) {
      return _isSelection
        ? `<div style="width:16px; height: 16px; background-color: ${item.hex};"></div>${item.text}`
        : `${item.text} (#${item.hex})`;
    }
    
    // 2. Register globally
    addRenderer('color', colorRenderer);
    
    // 3. Use it
    // Via name:
    <Svelecte renderer="color" options={options} />
    
    // Or via function directly:
    <Svelecte renderer={colorRenderer} options={options} />
  6. Search nested properties in Svelecte

    master

    To search within nested object properties (e.g., internal.id), you must perform two steps:

    1. Set fields to the dot-notated path (e.g., 'internal.id').
    2. Set nesting: true in your searchProps object.

    Without nesting: true, the component will not correctly traverse the object structure for the specified field.

    let searchProps = {
      fields: 'internal.id',
      nesting: true
    };
  7. Configure searching and filtering with searchProps

    master

    Svelecte supports filtering available options based on user input. This functionality is enabled by default via the searchable property (which defaults to true).

    To customize how searching behaves, pass a searchProps object to the Svelecte component. This allows you to control which fields are searched, how results are sorted, and how word boundaries or nesting are handled.

    <Svelecte 
      {options} 
      {searchProps} 
      {placeholder} 
    />
  8. Migrate Svelecte from v3 to v4

    master

    Version 4 was a major rewrite. Key changes include:

    Export Changes

    • addFormatter is now addRenderer.
    • TAB_SELECT_NAVIGATE is removed; use the string 'select-navigate' for the selectOnTab property.

    Property Changes

    • fetch: Now accepts only strings (URLs). To customize request headers or other Fetch API options, use the fetchProps property.
    • collapseSelection: Now accepts 'blur', 'always', or null instead of a boolean.
    • createFilter: Now accepts a single parameter inputValue: string and returns a boolean.
    • createTransform: Renamed to createHandler. It now accepts a single object argument and can be async.

    Removed Properties

    • controlItem and dropdownItem: Replaced by selection and option slots/snippets.
    • alwaysCollapsed: Merged into collapseSelection (use 'always').
    • searchField, sortField, disableSifter: Replaced by extended search settings.
    • style: Use CSS variables for theming.
    • labelAsValue: Removed. Simple arrays are now automatically converted to {value: 'string', text: 'string'} objects.
    <script>
      // v3 style fetch (no longer supported)
      // function myFetch(query) { ... }
    
      // v4 style fetch
      const fetchProps = { headers: { Authorization: 'bearer token' } };
    </script>
    
    <Svelecte 
      fetch="/api?query=[query]" 
      fetchProps={fetchProps} 
    />
  9. Configure global settings with the config object

    master

    Svelecte allows you to set application-wide defaults using the config object exported from $lib. Because config is an export from a <script module>, any changes made to it before initializing <Svelecte /> instances will apply to all components in your application. This includes both functional settings and internationalization (i18n) settings.

    import { config } from '$lib';
    
    // Change defaults for the entire app
    config.clearable = true;
    config.searchable = false;
  10. Fetch initial values on mount

    master

    Since v4.0, Svelecte automatically fetches the initial value on mount regardless of whether you are in init or query mode. Svelecte appends an init parameter to the request containing the current value.

    • For single values, it sends ?init=my-value.
    • For multiple values (using the multiple prop), it sends a comma-separated list like ?init=one,two,three.
    <!-- Single value init fetch -->
    <Svelecte
      bind:value
      fetch="https://example.com/url"
    />
    
    <!-- Multiselect init fetch -->
    <Svelecte
      bind:value={multiValue}
      fetch="https://example.com/url?search[query]"
      multiple
    />