2.1.1 • Published 1 year ago

vue-combo-blocks v2.1.1

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

Vue Combo Blocks 🧱

Provides all the building blocks needed for accessible autocomplete, combobox, or typeahead component.

A very Downshift like autocomplete solution for Vue

Downshift for Vue.js

size gzip size downloads

The problem

You want to build an autocomplete/combobox component, and it needs to be accessible, lightweight and you don't really want extra dependencies or styling you would not use, or you'd have to hack around to to make it your own.

The solution

This library provides you the state and the controls for your combobox. You provide the elements and styles to build the thing you need.

Installation

For vue 3.x use npm i vue-combo-blocks For vue 2.x use npm i vue-combo-blocks@vue2

Usage

Try it out in codesandbox

<template>
  <vue-combo-blocks
    v-model="selected"
    :itemToString="itemToString"
    :items="filteredList"
    @input-value-change="updateList"
    v-slot:default="{
      getInputProps,
      getInputEventListeners,
      hoveredIndex,
      isOpen,
      getMenuProps,
      getMenuEventListeners,
      getItemProps,
      getItemEventListeners,
      getComboboxProps,
      reset,
    }"
  >
    <div v-bind="getComboboxProps()">
      <button @click="reset">reset</button>
      <input
        v-bind="getInputProps()"
        v-on="getInputEventListeners()"
        placeholder="Search"
      />
      <ul
        v-show="isOpen"
        v-bind="getMenuProps()"
        v-on="getMenuEventListeners()"
      >
        <li
          v-for="(item, index) in filteredList"
          :key="item.id"
          :style="{
            backgroundColor: hoveredIndex === index ? 'lightgray' : 'white',
            fontWeight: selected === item ? 'bold' : 'normal',
          }"
          v-bind="getItemProps({ item, index })"
          v-on="getItemEventListeners({ item, index })"
        >
          {{ item.value }}
        </li>
      </ul>
    </div>
  </vue-combo-blocks>
</template>

<script>
import VueComboBlocks from 'vue-combo-blocks';

// This list could come from an external api
const list = [
  { value: 'Gretsch', id: '1' },
  { value: 'Ludwig', id: '2' },
  { value: 'Mapex', id: '3' },
  { value: 'Pearl', id: '4' },
  { value: 'Sonor', id: '5' },
  { value: 'Tama', id: '6' },
  { value: 'Zildjian', id: '7' },
];
export default {
  components: {
    VueComboBlocks,
  },
  data() {
    return {
      selected: null,
      filteredList: list,
    };
  },
  methods: {
    itemToString(item) {
      return item ? item.value : '';
    },
    // This could be a call to an api that returns the options
    updateList(text) {
      this.filteredList = list.filter((item) =>
        item.value.toLowerCase().includes(text.toLowerCase()),
      );
    },
  },
};
</script>

Props

NameTypeDefaultdescription
itemsArrayrequired
itemToStringFunction(item) => (item ? String(item) : '')
modelValue (value in Vue2)AnynullSets the selected item. Prop part of v-model
stateReducerFunction(state: object, actionAndChanges: object)optionalVery handy feature that gives you a complete control of the vue-combo-blocks state. Read more about it in the State Reducer section
scrollIntoViewBooleantrueControls whether or not the hovered item is scrolled into view when navigating with up and down keys. Note: the menu (ul) element must be positioned either relative or absolute for it to work
circularBooleantrueControls what happens when navigation with arrow keys and list bottom or top is reached
inputIdStringgenerated IDUsed for aria attributes and the id prop of the element (input)
labelIdStringgenerated IDUsed for aria attributes and the id prop of the element (label)
menuIdStringgenerated IDUsed for aria attributes and the id prop of the element (ul)
getItemIdFunction(index)optionaldefaults to a function that generates an ID based on the index

Events

Emitted events return 2 parameters. First is the new value, and second is the state change type.

NameTypeDescription
selectselectedItem: Any, type: stateChangeTypeEmitted when the item is selected
changeselectedItem: Any, type: stateChangeTypeEmitted when the selected item changes
input-value-changeinputValue: String, type: stateChangeTypeEmitted when the input value changes
is-open-changeisOpen: Boolean, type: stateChangeTypeEmitted when the isOpen value changes
hovered-index-changehoveredIndex: Number, type: stateChangeTypeEmitted when the hoveredIndex value changes
state-changestate:Object, type: stateChangeTypeEmitted when the state changes. Contains all the changes

Default Slot & returned props

Default slot's scope contains: prop getters, event listeners, component state and actions.

Prop getters

Bind the prop getters to their elements with v-bind and event listeners with v-on. You can add your own event listeners to these elements too and any other props needed.

<input v-bind="getInputProps()" v-on="getInputEventListeners()" />
NameTypeDescription
getComboboxPropsfunction()returns the props you should apply to an element that wraps the input element that you render.
getInputPropsfunction()returns the props you should apply to the input element that you render.
getLabelPropsfunction()returns the props you should apply to the label element that you render.
getItemPropsfunction({ item: any, index: number, disabled: boolean })returns the props you should apply to any menu item elements you render. item property is required!
getMenuPropsfunction()returns the props you should apply to the ul element (or root of your menu) that you render.

Event listeners

NameTypeDescription
getInputEventListenersfunction({ blur?: (e: Event) => void, input?: (e: Event) => void, keydown?: (e: Event) => void, keyup?: (e: Event) => void })Bind these to the input element.
getItemEventListenersfunction({ item: any, index?: number, disabled?: boolean, mousemove?: (e: Event) => void, mousedown?: (e: Event) => void, click?: (e: Event) => void })Bind these to the li element. item property is required!
getMenuEventListenersfunction({ mouseleave?: (e: Event) => void, mousedown?: (e: Event) => void })Bind these to the ul element.

Custom Event Listeners

(New in 1.1.0)

You can add custom event listers with default event listeners. Your custom event listener will run before vue-combo-blocks internal event listener:

<vue-combo-blocks
  v-slot:default="{
    getInputProps,
    getInputEventListeners,
  }"
>
  <input v-bind="getInputProps()" v-on="getInputEventListeners()" @input="myInput" />
</vue-combo-blocks>

You can also override, or just prevent the default event by providing you custom event listener as an argument:

<vue-combo-blocks
  v-slot:default="{
    getInputProps,
    getInputEventListeners,
  }"
>
    <input v-bind="getInputProps()" v-on="getInputEventListeners({ input: myInput })" />
  </vue-combo-blocks>

State

NameTypeDescription
isOpenBooleanthe list open state
selectedItemAnythe currently selected item
hoveredIndexNumberthe currently hovered item
inputValueStringthe value in the input

Actions

NameTypeDescription
resetfunction()Clears the selected item, and reset the input value
selectfunction(item: any)Selects an item
setInputValuefunction(inputValue: string)Sets the input value
openMenufunction()Opens the menu
closeMenufunction()Closes the menu

State Reducer

function(state: object, actionAndChanges: object This function is called each time vue-combo-blocks sets its internal state. It gives you the current state and the state that will be set, and you return the state that you want to set.

  • state: The full current state of vue-combo-blocks.
  • actionAndChanges: Object that contains the action type, props needed to return a new state based on that type and the changes suggested by the vue-combo-blocks default reducer. About the type property you can learn more about in the stateChangeTypes section.

In this example, we want to keep the menu open after the item is selected, and keep the input value empty

<template>
  <vue-combo-blocks :stateReducer="stateReducer" ****>
    ****
  </vue-combo-blocks>
</template>
  methods: {
    stateReducer(oldState, { changes, type }) {
      switch (type) {
        case VueComboBlocks.stateChangeTypes.InputKeyUpEnter:
        case VueComboBlocks.stateChangeTypes.ItemClick:
          return {
            ...changes,
            isOpen: true,
            inputValue: '',
          };
        default:
          return changes;
      }
    },
  }

stateChangeTypes

The list of all possible values this type property can take is defined in this file and is as follows:

  • VueComboBlocks.stateChangeTypes.InputKeyDownArrowDown
  • VueComboBlocks.stateChangeTypes.InputKeyDownArrowUp
  • VueComboBlocks.stateChangeTypes.InputKeyDownTab
  • VueComboBlocks.stateChangeTypes.InputKeyUpEscape
  • VueComboBlocks.stateChangeTypes.InputKeyUpEnter
  • VueComboBlocks.stateChangeTypes.InputChange
  • VueComboBlocks.stateChangeTypes.InputBlur
  • VueComboBlocks.stateChangeTypes.MenuMouseLeave
  • VueComboBlocks.stateChangeTypes.ItemMouseMove
  • VueComboBlocks.stateChangeTypes.ItemClick
  • VueComboBlocks.stateChangeTypes.FunctionOpenMenu
  • VueComboBlocks.stateChangeTypes.FunctionCloseMenu
  • VueComboBlocks.stateChangeTypes.FunctionSelectItem
  • VueComboBlocks.stateChangeTypes.FunctionSetInputValue
  • VueComboBlocks.stateChangeTypes.FunctionReset
  • VueComboBlocks.stateChangeTypes.ControlledPropUpdatedSelectedItem
1.1.1

1 year ago

2.1.1

1 year ago

2.1.0

2 years ago

1.1.0

2 years ago

1.0.1

3 years ago

1.0.0

3 years ago

2.0.0

3 years ago

0.4.1

3 years ago

0.3.0

3 years ago

0.4.0

3 years ago

0.2.96

3 years ago

0.2.95

4 years ago

0.2.85

4 years ago

0.2.84

4 years ago

0.2.83

4 years ago

0.2.82

4 years ago

0.2.81

4 years ago

0.2.8

4 years ago

0.2.71

4 years ago

0.2.7

4 years ago

0.2.62

4 years ago

0.2.61

4 years ago

0.2.6

4 years ago

0.2.5

4 years ago

0.2.4

4 years ago

0.2.3

4 years ago

0.2.2

4 years ago

0.2.1

4 years ago

0.2.0

4 years ago

0.1.8

4 years ago

0.1.81

4 years ago

0.1.82

4 years ago

0.1.7

4 years ago

0.1.6

4 years ago

0.1.5

4 years ago

0.1.4

4 years ago