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 elementactive
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 stateoff
event(s) triggering the inactive statetoggle
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:
<script lang="ts">
import { choco } from "chocobytes";
import { Cancellable } from "./cancellable.svelte.js";
const btn = new Cancellable();
</script>
<div class="my-10 flex justify-center gap-2">
<button class="py-2 px-4 data-[active=true]:scale-95" use:choco={btn}>Improved button</button>
<button class="active:bg-coral py-2 px-4 active:scale-95">Standard button</button>
</div>
<pre>{JSON.stringify(btn.attributes, null, 2)}</pre>
<style>
button {
border-radius: var(--radius-sm);
transition: all 200ms ease-out;
cursor: pointer;
&:hover {
background: var(--color-coral);
}
}
</style>
{ "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
:
Cancellable
Triggerable
Hoverable
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