vael-ui v0.5.7

Used with a component · Knob

useKnob

The headless engine behind <Knob>: a value on a 270° sweep, from −135° to +135° with the gap at the bottom. Dragging reads the pointer's angle around the dial's center, so the value follows your finger around the circle instead of a straight-line distance. The arrow keys step, Page Up and Page Down jump 10 steps, and Home and End go to the bounds. It renders nothing: bind rootStyle on your root and draw the dial from --ui-knob-angle and --ui-knob-fraction. The KNOB_SWEEP_* constants give the arc in degrees, for drawing a track that matches.

Install

import { useKnob, KNOB_SWEEP_START_DEG, KNOB_SWEEP_DEG, KNOB_SWEEP_END_DEG } from 'vael-ui'

Examples

<script setup lang="ts">
import { ref, useTemplateRef } from 'vue'
import { useKnob } from 'vael-ui'

const volume = ref(40)
const dialEl = useTemplateRef<HTMLElement>('dial')
const { rootStyle, onDialPointerdown, onDialKeydown } = useKnob(volume, {
  dialEl,
  min: 0,
  max: 100,
  onCommit: () => console.log('saved', volume.value),
})
</script>

<template>
  <div
    ref="dial"
    class="my-knob"
    role="slider"
    tabindex="0"
    aria-label="Volume"
    aria-valuemin="0"
    aria-valuemax="100"
    :aria-valuenow="volume"
    :style="rootStyle"
    @pointerdown="onDialPointerdown"
    @keydown="onDialKeydown"
  >
    <span class="my-knob-pointer" />
  </div>
</template>

<style>
.my-knob-pointer {
  rotate: var(--ui-knob-angle);
}
</style>

Parameters

NameTypeDescription
modelRef<number>The value. It updates on every drag frame and key press, clamped and snapped to step.
dialElRef<HTMLElement | null>The round element. Pointer angles are measured around its center.
min / maxMaybeRefOrGetter<number>The range. The sweep always spans all of it. Default 0 and 100.
stepMaybeRefOrGetter<number>The step values snap to, without float drift such as 0.30000000000000004. Default 1.
disabledMaybeRefOrGetter<boolean>Ignores pointer and keyboard input.
onCommit() => voidFires once per settled interaction: on release, or after each key press. <Knob> re-emits it as change.

Returns

NameTypeDescription
isDraggingRef<boolean>true from pointer down to release.
rootStyleComputedRef<Record<string, string>>Bind it on your root: --ui-knob-angle (−135deg to 135deg) and --ui-knob-fraction (0 to 1). Draw the pointer's rotation and the fill arc from them in CSS.
onDialPointerdown(event: PointerEvent) => voidBind it on the dial. It tracks the drag on the window until release, so leaving the dial mid-drag keeps it going.
onDialKeydown(event: KeyboardEvent) => voidBind it on the focusable element: the arrow keys, Page Up, Page Down, Home and End.