3.16.1 • Published 1 year ago

mv-svelecte v3.16.1

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

Svelecte NPM version

svelecte

Flexible autocomplete/select component written in Svelte. Massively inspired by Selectize.js. Also usable as custom element (CE). Usable in forms, behaves very similar to standard <select> element.

See the latest changes on the Releases page.

📃 Features

  • searchable
  • multiselect with limit of max selected items
  • allow simple array or complex objects as items
  • custom item renderer (formatter)
  • allow creating new items (and possibly edit them)
  • remote data fetch
  • virtual list support
  • i18n support
  • SSR support
  • lazy dropdown rendering
  • usable as custom element
  • stylable
  • reordable multi selection with addition of svelte-dnd-action (example)
  • usable with svelte-use-form (example)

🔧 Installation

npm install svelecte --save

Minimalistic example

<script>
import Svelecte from 'svelecte';

const list = [{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2'}, ...];
let myValue = null;
</script>

<Svelecte options={list} bind:value={myValue}></Svelecte>
myValue = 2;

This would select item with id property 2.

Sometimes you want to work strictly with objects, like myValue = {id: 2, name: 'Item 2'}. You can set property valueAsObject which tells Svelecte to handle value property as object or array of object (if multiple is also set).

Property readSelection always returns selected object or object array no matter if valueAsObject is set or not.


👀 Examples

👉 Examples with more detailed documentation can be found at https://mskocik.github.io/svelecte/.

🛠 Configuration & API

Exposed properties:

PropertyTypeDefaultDescription
namestringnullcreate internal <select> element which you can use validatorAction on. Without name defined, no <select> is created
optionsarray[]Data array
valueAsObjectboolfalseSwitch whether Svelecte should expects from and return to bind:value objects or primitive value (usually string, number)
valueFieldstringnullProperty to be used as value (if not specified, will be selected automatically)
labelFieldstringnullProperty shown in dropdown (if not specified, will be selected automatically)
groupLabelFieldstringlabelProperty to be used as optgroup label
groupItemsFieldstringoptionsProperty holding optgroup option list
disabledFieldstring$disabledProperty to check, whether given options should be disabled and unselectable
requiredboolfalsemake sense only when name is defined
placeholderstringSelectInput placeholder
searchablebooltrueAllow search among items by typing
disabledboolfalseDisable component
rendererstring|functionnulldropdown and selection renderer function. More info in item rendering section
controlItemComponentItemItem component when item is selected. See Custom Items section for more details.
dropdownItemComponentItemItem component in dropdown. See Custom Items section for more details.
selectOnTabboolstringnullnullBased on value provided, it allows selecting currently active item by Tab AND (if value is 'select-navigate') also focus next input. The constant TAB_SELECT_NAVIGATE is exported from svelecte
resetOnBlurbooltrueControl if input value should be cleared on blur
resetOnSelectbooltrueControl if input value should be cleared on item selection. Note: applicable only with multiple
clearableboolfalseDisplay ✖ icon to clear whole selection
multipleboolfalseallow multiselection. Will be set automatically to true, if name property ends with [], like tags[]
closeAfterSelectboolfalsecloses dropdown after selection. Setting this to true is useful for multiple select only. For single select dropdown is always closed no matter the value this property has
maxnumber0Maximum allowed items selected, applicable only for multiselect
collapseSelectionboolfalsecollapse selection when multiple and not focused
alwaysCollapsedboolfalsekeep collapsed selection even when focused. Selected options are shown in dropdown on the top
inputIdstringnullallow targeting input using a html label.
creatableboolfalseAllow creating new item(s)
creatablePrefixstring*Prefix marking new item
allowEditingboolfalseWhen pressing Backspace switch to edit mode instead of removing newly created item. NOTE intended to be used with creatable property
keepCreatedbooltrueSwitch whether to add newly created option to option list or not
delimiterstring,split inserted text when pasting to create multiple items
createFilterfunctionnullFunction, that transform input string to custom value. It can serve as a filter, if value is valid or not. If you want to dismiss entered value, function should return '' (empty string). By default all input string is trimmed and all multiple spaces are removed. Function notation:createFilter(inputValue: string, dropdownOptions: array): string
createTransformfunctionnullCustom function transforming input string to option object. Default returns object with valueField and labelField properties, where labelField's value is input string prefixed with creatablePrefix property. Function notation:createTransform(inputValue: string, creatablePrefix: string, valueField: string, labelField: string): object
fetchstring|functionnullCheck "remote datasource" section for more details
fetchModestringautoWhen set to init options are fetched only when mounted, when searching it search in downloaded dataset
fetchCallbackfunctionnulloptional fetch callback
fetchResetOnBlurbooltruereset previous search results on empty input, related to resetOnBlur
minQuerynumber1Minimal amount of characters required to perform remote request. Usable with fetch property
lazyDropdownbooltruerender dropdown after first focus, not by default
virtualListboolfalseWhether use virtual list for dropdown items (useful for large datasets)
vlHeightnumbernullHeight of virtual list dropdown (if not specified, computed automatically)
vlItemSizenumbernullHeight of one row (if not specified, computed automatically)
searchFieldstring|arraynullSpecify item property that will be used to search by (if not specified all props except value prop will be used)
sortFieldstringnullSpecify sort property. If not specified, labelField will be used
disableSifterboolfalseDisable Sifter filtering & sorting. Can be useful in combination with fetch, when further filtering or sorting may be undesired
disableHighlightboolfalseDisable highlighting of input value in results. Can be useful with a renderer function that includes additional text or does its own highlighting
classstringsvelecte-controldefault css class
stylestringnullinline style
hasAnchorboolnullinternal: when passing also existing select (for CE)
i18nobjectnullI18n object overriding default settings
dndzonefunctionemptyPass dndzone from svelte-dnd-action, if you want to support selection reordering. See the example REPL
validatorActionarraynullBind validator action for inner <select> element. Designed to be used with svelte-use-form. See the example REPL. For this to work, name property MUST be defined

Custom items

If renderer property is not enough for you or you prefer Component syntax to HTML strings, you can use your own Components. Keep in mind that default Item component handles highlighting when searching, but the rest of features like styling should be inherited if you use proper css classes (the same as Item component)..

To make it easier to use your own Components, there are available actions, highlighting function and close button icon for you to use.

The simplest example can be found in this REPL.


Emitted events:

Eventargumentsdescription
fetchoptionsnewly fetched remote options
changeselectionselected objects. If anchor property is defined, change event is called also on it
createoptionoptionnewly created option object
blur-blur event
invalidValueinvalidValuetriggered when passed value is out of provided options items. Internal (and bound, if any) value is set to null or [] if multiple
enterKeyunderlying keyDown eventtriggered when natively it would cause form submit (dropdown is closed). This gives you ability to prevent it by calling event.detail.preventDefault()

Public API:

Nametypeargumentsdescription
focusfunction-focus input
getSelectionfunctionboolreturn selection, if true is passed, only values are returns, whole objects otherwise
setSelectionfunctionarrayset selection programmatically
configproperty-context property: global common config for all instances, you can override most properties here and also some additional, mainly i18n
addFormatterfunction-context function: with signature (name, formatFn) you can add additional item renderers (formatters)
<!-- clearByParentboolinternal for CE -->

I18n

This is default value of i18n property:

// config.i18n defaults:
{
  i18n: {
    empty: 'No options',
    nomatch: 'No matching options',    
    max: num => `Maximum items ${num} selected`,
    fetchBefore: 'Type to start searching',
    fetchQuery: (minQuery, inputLength) => `Type ${minQuery > 1 && minQuery > inputLength 
      ? `at least ${minQuery - inputLength} characters `
      : '' }to start searching`,
    fetchEmpty: 'No data related to your search',
    collapsedSelection: count => `${count} selected`,
    createRowLabel: value => `Create '${value}'`
  },
  collapseSelectionFn: function(selectionCount, selection) {
    return settings.i18n.collapsedSelection(selectionCount);
  }
}

You can override whole object or only items you are interested in. You can override it globally or on component level:

// global override
import Svelecte, { config } from 'svelecte';

config.i18n = {
    empty: '🚫',
    nomatch: '✋',
    max: num => '🙄',
    fetchBefore: '💻',
    fetchQuery: (minQuery, inputLength) => '🧮',
    fetchEmpty: '🚮',
    collapsedSelection: () => '🗃',
    createRowLabel: value => `📝 ${value}`
}

// local override (component-level)
const myI18n = {
    empty: `Empty list, can't you see?`
}

<Svelecte i18n={myI18n}></Svelecte>

Customizable Slots

There are different slots within the component that allow to insert custom code and icons.

Control.svelte (bubbled up to the Svelecte component)

  • icon This allows to insert custom code like e.g. an icon at the start/left of the Control.svelte
  • control-end This allows to insert custom code at the end/right of the Control.svelte. It is positioned AFTER the indicator icons.

🙏 Thanks to

License

MIT License

3.16.1

1 year ago

3.16.0

1 year ago

3.15.5

1 year ago

3.15.4

1 year ago

3.15.3

1 year ago

3.15.2

1 year ago