Toggleable

The Toggleable class is a building block for toggling a set of properties on specific events.


Example: Cancellable

Let’s implement an improved button that toggles a data-active attribute on when clicked, and off as soon as either the click is released or the pointer leaves the target element.

From a user perspective, this button would better confers the “cancellability” of a click. We can implement this class by extending the Toggleable as follows:

import { Toggleable } from "chocobytes/blocks/toggleable.svelte.js";

export class Cancellable extends Toggleable<"button"> {
  constructor(options?: { active: boolean }) {
    const active = options?.active ?? false;
    super({
      initial: { "data-active": active },
      active,
      on: "pointerdown",
      off: ["pointerup", "pointerleave"],
    });
  }
}

The Toggleable constructor takes a few parameters:

  • initial is a record of booleanish attributes that will be toggled on the element
  • active labels this initial state as either the active or inactive state. Can be bound with a getter / setter pair (see API)
  • on event(s) triggering the active state
  • off event(s) triggering the inactive state
  • toggle event(s) toggling the state

A Cancellable element styled using this data-active attribute instead of the CSS :active pseudo class would then better confer the “cancelability” of a click. Try clicking these buttons and move the pointer outside the element while the pointer is down:

{
  "data-active": false
}

Relation to other classes

Almost everything is a toggleable, from the Toggle and Switch buttons to Tabs and Disclosures, carousels etc.

These classes are specialized Toggleable:


API

Constructor

initial?: Record<string, Booleanish>
Record of Booleanish attributes to toggle
Default: {}
active: boolean | () => boolean
Boolean or getter labelling the state as active or not. Can be bound
Default: false
setActive?: (v: boolean) => void
Setter allowing to bind the active state value
toggle?: EventName | EventName[]
Event(s) toggling the state
on?: EventName | EventName[]
Event(s) triggering the active state
off?: EventName | EventName[]
Event(s) triggering the inactive state