SingleSelectAPIMixin

Exposes a public API for single selection on a list-like element

Overview

Purpose: Provides a public API for setting and retrieving the selected item.

This mixin works in the middle of the Elix render pipeline:

events → methodssetState → render DOM → post-render

Expects the component to provide:

  • items state member representing the items that can be selected. This is usually provided by ContentItemsMixin.
  • currentIndex state member indicating the current item, which the mixin will interpret as the selected item. This is typically defined via ItemsCursorMixin.

Provides the component with:

  • selectedIndex and selectedItem properties to read or manipulate the selected index.
  • selected-index-changed event.

Usage

import ContentItemsMixin from "elix/src/base/ContentItemsMixin.js";
import ItemsCursorMixin from "elix/src/base/ItemsCursorMixin.js";
import SingleSelectAPIMixin from "elix/src/base/SingleSelectAPIMixin.js";

class MyElement extends ContentItemsMixin(
  ItemsCursorMixin(SingleSelectAPIMixin(HTMLElement))
) {}

SingleSelectAPIMixin is designed to support components that let the user select a single thing at a time. This is generally done to let the user select a value (e.g., as the target of an action, or in configuring something), or as a navigation construct (where only one page/mode is visible at a time).

Examples:

  • List boxes such as ListBox.
  • Dropdown lists and combo boxes
  • Carousels such as Carousel.
  • Slideshows
  • Tab UIs (including top-level navigation toolbars that behave like tabs) such as Tabs.

Example

// A sample element that supports single-selection on its children.
class SimpleList extends SingleSelectAPIMixin(ReactiveMixin(HTMLElement)) {
  get items() {
    return this.children;
  }
}

const list = new SimpleList();
list.innerHTML = `
  <div>Zero</div>
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
  <div>Four</div>
`;
list.selectedIndex = 0; // Select the first item
list.selectedItem; // <div>Zero</div>
list.selectedItem = list.items.indexOf(list.items[1]);
list.selectedIndex; // 1

The following is a slightly expanded demo of the above, adding the ability to click an item to select it, and styling to highlight the selected item with color:

One
Two
Three
Four
Five
Demo: SingleSelectAPIMixin applied to HTMLElement

Here, the currently-selected item is tracked with SingleSelectAPIMixin.