# ixfx-radial-input

A rotary dial input component inspired by music production interfaces (Ableton Live, synthesiser knobs). Renders as a flattened arc SVG and responds to drag and keyboard input.

---

## Basic Usage

```html
<ixfx-radial-input min="0" max="1" value="0.5"></ixfx-radial-input>
```

The component defaults to `100px` wide. Set width (and optionally height) via CSS:

```html
<ixfx-radial-input min="0" max="100" value="50" style="width: 120px;"></ixfx-radial-input>
```

To fill a container:

```html
<div style="width: 80px; height: 80px;">
  <ixfx-radial-input min="0" max="1" value="0.5" style="width: 100%; height: 100%;"></ixfx-radial-input>
</div>
```

---

## Attributes & Properties

| Attribute / Property | Type | Default | Description |
|---|---|---|---|
| `value` | `number` | `0` | Current value, within `min`…`max` |
| `min` | `number` | `0` | Minimum value |
| `max` | `number` | `100` | Maximum value |
| `step` | `number` | `undefined` | Keyboard step size. If unset, defaults to 10% of range |
| `stops` | `number` | `undefined` | Quantise to N discrete positions. Also sets keyboard step size |
| `value-mode` | `"range"` \| `"bipolar"` \| `"unipolar"` | `"range"` | Controls how the value arc is drawn (see [Value Modes](#value-modes)) |
| `marker-style` | `"needle"` \| `"dot"` \| `"none"` | `"needle"` | Visual style of the value indicator |
| `flatten` | `number` | `0.3` | Proportion of circle to hide at the top (0 = full circle, 0.5 = semicircle, 1 = nothing). Controls vertical footprint |
| `radius` | `number` | `45` | Dial radius in viewBox units (10–50). Clamped automatically |
| `wedge` | `boolean` | `false` | Enable a filled pie-slice behind the arc |
| `disabled` | `boolean` | `false` | Disables all interaction. Reflected as attribute |

### Sizing

Size via CSS `width`/`height`. The component's height adapts automatically to the `flatten` value to minimise whitespace — it tracks how much of the circle is visible and subtracts the hidden portion. You can override the height directly.

```html
<!-- Small -->
<ixfx-radial-input style="width: 60px;" min="0" max="1" value="0.4"></ixfx-radial-input>

<!-- Large -->
<ixfx-radial-input style="width: 200px;" min="0" max="1" value="0.4"></ixfx-radial-input>
```

### Disabled state

```html
<ixfx-radial-input disabled min="0" max="1" value="0.7"></ixfx-radial-input>
```

---

## Interaction

**Mouse / touch:** drag vertically. Dragging upward increases the value. Full min-to-max range spans `2×` the component's rendered height.

**Shift + drag:** fine control — sensitivity reduced to 1/10th (`KEY_STEP_DIVISOR = 10`).

**Keyboard** (when focused):

| Key | Action |
|---|---|
| `ArrowUp` / `ArrowRight` | Increase by step |
| `ArrowDown` / `ArrowLeft` | Decrease by step |
| `Home` | Set to minimum |
| `End` | Set to maximum |
| `Shift` + arrows | Fine step (÷10) |

Step size priority: `stops` > explicit `step` > 10% of range.

---

## Value Modes

### `range` (default)

Arc sweeps from the minimum position clockwise to the current value. Classic knob/potentiometer behaviour.

```html
<ixfx-radial-input value-mode="range" min="0" max="1" value="0.7"></ixfx-radial-input>
```

### `bipolar`

Arc pivots from the top-centre (midpoint). Values below the midpoint of `min`…`max` sweep left; values above sweep right. A midpoint marker is drawn at the top. Suited for pan, pitch, or any centred parameter.

```html
<ixfx-radial-input value-mode="bipolar" min="-1" max="1" value="0.5"></ixfx-radial-input>
```

### `unipolar`

Arc spreads symmetrically from the top-centre in both directions. Suited for width or intensity parameters where the visual weight is centred. A midpoint marker is drawn at the top.

```html
<ixfx-radial-input value-mode="unipolar" min="0" max="1" value="0.6"></ixfx-radial-input>
```

---

## Stepping & Quantisation

`step` controls keyboard navigation step size:

```html
<ixfx-radial-input min="0" max="1" value="0.5" step="0.2"></ixfx-radial-input>
```

`stops` quantises the value to N equally-spaced positions. Drag and keyboard input both snap:

```html
<!-- 5 discrete stops: 0, 0.25, 0.5, 0.75, 1.0 -->
<ixfx-radial-input min="0" max="1" value="0.5" stops="5"></ixfx-radial-input>

<!-- 10 stops across 0-100: snaps to 0, 10, 20 … 100 -->
<ixfx-radial-input min="0" max="100" value="50" stops="10"></ixfx-radial-input>
```

When `stops` is set it also governs the keyboard step (one stop per keypress).

---

## Events

Both events bubble and are `composed` (cross shadow-DOM boundaries).

### `input`

Fired continuously during user interaction (every pointer/key event that changes the value). Use for live updates.

```ts
import type { RadialInputInputEvent } from 'ixfx-radial-input/types';

dial.addEventListener('input', (e: RadialInputInputEvent) => {
  const { value, valueRelative } = e.detail;
  // value: number in min..max range
  // valueRelative: number 0..1
});
```

### `change`

Fired after the user finishes interacting (debounced 150 ms). Equivalent to the native `<input type="range">` change semantics. Also fires immediately for programmatic value changes.

```ts
import type { RadialInputChangeEvent } from 'ixfx-radial-input/types';

dial.addEventListener('change', (e: RadialInputChangeEvent) => {
  const { value, valueRelative, previousValue } = e.detail;
});
```

**Note:** `input` fires only for user-initiated changes. Programmatic `dial.value = x` triggers only `change`.

---

## CSS Custom Properties

### Dial outline

| Variable | Default | Description |
|---|---|---|
| `--dial-border-color` | `var(--surface-4)` | Colour of the track border arc |
| `--dial-border-width` | `2` | Stroke width of the border arc (SVG units) |
| `--dial-fill` | `transparent` | Fill colour of the dial face |

### Lanes

Lanes are arcs drawn around the dial. The built-in lanes are `track` (the grey background arc) and `value` (the accent-coloured progress arc).

| Variable | Default | Description |
|---|---|---|
| `--lane-track-color` | `var(--surface-4)` | Colour of the `track` lane |
| `--lane-value-color` | `var(--accent)` | Colour of the `value` lane |
| `--lane-color` | `var(--accent)` | Fallback colour for custom lanes |
| `--lane-<key>-color` | — | Per-lane colour override (e.g. `--lane-sweep-color`) |
| `--lane-<key>-width` | — | Per-lane width override |
| `--lane-dasharray` | `none` | SVG `stroke-dasharray` applied to all lanes |
| `--lane-dashoffset` | `0` | SVG `stroke-dashoffset` — animate for a marching-ants effect |

Dashed lanes:

```html
<!-- 8px dashes, 4px gaps -->
<ixfx-radial-input style="--lane-dasharray: 8 4;" min="0" max="1" value="0.6"></ixfx-radial-input>

<!-- Dotted -->
<ixfx-radial-input style="--lane-dasharray: 2 4;" min="0" max="1" value="0.6"></ixfx-radial-input>
```

### Marker (value indicator)

| Variable | Default | Description |
|---|---|---|
| `--marker-color` | `var(--accent)` | Colour of the needle line or dot fill |
| `--marker-thickness` | `0.15` | Relative thickness (fraction of radius) |
| `--marker-length` | `0.8` | Needle length as fraction of radius |
| `--marker-offset` | `0.2` | Needle start offset from centre (needle), or radial position multiplier (dot) |
| `--marker-border-width` | `0` | Border halo thickness around needle/dot |
| `--marker-border-color` | `transparent` | Border halo colour |
| `--marker-dasharray` | `none` | Dashed needle pattern |
| `--marker-dashoffset` | `0` | Dashed needle offset |

### Midpoint marker (bipolar/unipolar modes)

| Variable | Default | Description |
|---|---|---|
| `--midpoint-color` | `var(--surface-muted-text)` | Colour of the top-centre tick/dot |
| `--midpoint-thickness` | `1px` (needle) / `0.08` (dot) | Tick line width or dot size |
| `--midpoint-border-color` | `transparent` | Dot border colour (dot style only) |
| `--midpoint-border-width` | `0` | Dot border width (dot style only) |
| `--midpoint-length` | `0.15` | Tick line length as fraction of radius (needle style) |
| `--midpoint-offset` | `0.85` | Tick start offset from centre (needle style) |

### Wedge

| Variable | Default | Description |
|---|---|---|
| `--wedge-fill` | `var(--accent)` | Wedge fill colour |
| `--wedge-fill-opacity` | `0.25` | Wedge fill opacity |
| `--wedge-border-color` | `var(--accent)` | Wedge border/stroke colour |
| `--wedge-border-width` | `0` | Wedge border stroke width |
| `--wedge-border-opacity` | `1` | Wedge border opacity |

### Dynamic value variable

The component sets `--value-relative` (a number 0…1) on the host element as the value changes. Use it inside `calc()` to create value-reactive styles entirely in CSS:

```html
<!-- Needle colour shifts from purple to pink as value increases -->
<ixfx-radial-input
  min="0" max="1" value="0.6"
  style="--marker-color: hsl(calc((1 - var(--value-relative)) * 280), 80%, 55%);"
></ixfx-radial-input>

<!-- Wedge hue follows value -->
<ixfx-radial-input
  wedge min="0" max="1" value="0.5"
  style="--wedge-fill: hsl(calc(var(--value-relative) * 280), 80%, 50%); --wedge-fill-opacity: 0.4;"
></ixfx-radial-input>

<!-- Border thickens and changes colour -->
<ixfx-radial-input
  min="0" max="1" value="0.5"
  style="
    --dial-border-width: calc(1 + var(--value-relative) * 5);
    --dial-border-color: hsl(calc(var(--value-relative) * 280), 80%, 55%);
  "
></ixfx-radial-input>

<!-- Needle width grows with value (1px thin → 9px thick) -->
<ixfx-radial-input
  marker-style="needle" min="0" max="1" value="0.5"
  style="--marker-thickness: calc(0.01 + var(--value-relative) * 0.2);"
></ixfx-radial-input>
```

---

## Marker Styles

### `needle` (default)

A line from `--marker-offset` outward to `--marker-length` (both as fractions of radius).

```html
<ixfx-radial-input marker-style="needle" min="0" max="1" value="0.6"></ixfx-radial-input>
```

Thin minimalist look:

```html
<ixfx-radial-input
  marker-style="needle" min="0" max="1" value="0.6"
  style="--marker-thickness: 0.05; --marker-color: var(--surface-muted-text); --marker-length: 0.9; --marker-offset: 0.5;"
></ixfx-radial-input>
```

With a border halo (useful for contrast on filled dials):

```html
<ixfx-radial-input
  marker-style="needle" min="0" max="1" value="0.6"
  style="--marker-thickness: 0.1; --marker-border-width: 0.02; --marker-border-color: white;"
></ixfx-radial-input>
```

### `dot`

A filled circle placed at the perimeter at the value's angular position. `--marker-offset` moves it radially (1.0 = on the arc, <1.0 = toward centre, >1.0 = outside arc).

```html
<!-- Dot on the arc -->
<ixfx-radial-input marker-style="dot" min="0" max="1" value="0.6" style="--marker-offset: 1;"></ixfx-radial-input>

<!-- Dot inside perimeter -->
<ixfx-radial-input marker-style="dot" min="0" max="1" value="0.6" style="--marker-offset: 0.5;"></ixfx-radial-input>
```

Dot with dynamic border:

```html
<ixfx-radial-input
  marker-style="dot" min="0" max="1" value="0.6"
  style="
    --marker-offset: 0.8;
    --marker-thickness: 0.12;
    --marker-color: var(--surface-1);
    --marker-border-width: 0.05;
    --marker-border-color: hsl(calc(var(--value-relative) * 280), 80%, 60%);
  "
></ixfx-radial-input>
```

### `none`

No marker rendered. Useful when the wedge or lanes carry the visual.

---

## Wedge Visualisation

The `wedge` attribute renders a filled pie-slice sector behind the lane arcs. It follows the active `value-mode`.

```html
<!-- Basic -->
<ixfx-radial-input wedge min="0" max="1" value="0.5"></ixfx-radial-input>

<!-- With border -->
<ixfx-radial-input wedge min="0" max="1" value="0.5"
  style="--wedge-fill-opacity: 0.2; --wedge-border-width: 1;">
</ixfx-radial-input>

<!-- Temperature gauge (blue→red) -->
<ixfx-radial-input wedge min="0" max="1" value="0.3"
  style="--wedge-fill: hsl(calc((1 - var(--value-relative)) * 240), 80%, 50%); --wedge-fill-opacity: 0.4;">
</ixfx-radial-input>

<!-- Bipolar wedge -->
<ixfx-radial-input wedge value-mode="bipolar" min="-1" max="1" value="0.7"
  style="--wedge-fill: hsl(120, 70%, 50%); --wedge-fill-opacity: 0.35;">
</ixfx-radial-input>
```

---

## Flatten

`flatten` hides a fraction of the top of the circle, converting the full-circle dial into a horseshoe shape. The component height adjusts automatically to remove the dead space.

| Value | Arc visible | Degrees |
|---|---|---|
| `0` | 100% | 360° full circle |
| `0.3` (default) | 70% | 252° |
| `0.5` | 50% | 180° semicircle |
| `0.7` | 30% | 108° |

```html
<ixfx-radial-input flatten="0.5" min="0" max="1" value="0.75"></ixfx-radial-input>
```

---

## Data Lanes (programmatic API)

Lanes are additional arcs drawn around the dial. The two built-in lanes are `track` (grey background) and `value` (accent progress arc). You can add custom lanes at runtime.

### Lane types

| Type | Behaviour |
|---|---|
| `value` | Arc sweeps from origin to `lane.value` (same logic as the main value arc) |
| `fixed` | Always shows the full track arc — useful for static reference rings |
| `anchored` | Arc is centred on the current dial value; `lane.value` controls its width (0..1 of total arc) |

### API

```ts
import type { RadialInputElement } from 'ixfx-radial-input';

const dial = document.querySelector('ixfx-radial-input') as RadialInputElement;

// Wait for the element to be ready
await customElements.whenDefined('ixfx-radial-input');
await dial.updateComplete;

// Add a fixed reference ring at a different radial offset
dial.addLane('target', {
  type: 'fixed',
  offset: 0.2,   // 20% closer to centre
  width: 0.05,   // thin line
});

// Add an animated value lane (e.g. a running average)
dial.addLane('average', {
  type: 'value',
  value: 0.4,    // initial 0..1 position
});

// Add an anchored tolerance band centred on the current value
dial.addLane('tolerance', {
  type: 'anchored',
  value: 0.15,   // band spans ±15% of total arc width
});

// Update a lane's value (0..1)
dial.setLaneValue('average', 0.6);

// Remove a lane
dial.removeLane('target');

// Read lane state
const lane = dial.getLane('average');
const allLanes = dial.getLanes(); // ReadonlyMap<string, LaneData>
```

Style lanes via CSS variables using the lane key:

```css
ixfx-radial-input {
  --lane-average-color: hsl(120, 70%, 50%);
  --lane-tolerance-color: hsl(180, 80%, 50%);
  --lane-sweep-width: 0.06;
}
```

### Live lane animation example

From the demo — a sweep lane that oscillates between 0 and the current dial value:

```ts
let sweepPhase = 0;
setInterval(() => {
  sweepPhase += 0.08;
  const sineValue = (Math.sin(sweepPhase) + 1) / 2;
  const currentValue = (dial.value - dial.min) / (dial.max - dial.min);
  dial.setLaneValue('sweep', sineValue * currentValue);
}, 50);
```

---

## Tooltip Integration

Set `data-tooltip` and `data-tooltip-live` to wire up a live tooltip that updates as the user drags:

```html
<ixfx-radial-input
  min="0" max="1" value="0.5"
  data-tooltip="50%"
  data-tooltip-anchor="top"
  data-tooltip-live="input"
></ixfx-radial-input>
```

When `data-tooltip-live` is present the component automatically updates `data-tooltip` to the current percentage (e.g. `"63%"`) on every `input` event.

To format the text yourself (e.g. a time position), set the `tooltipFormatter` property: `el.tooltipFormatter = (value, relative) => formatTime(value)`. `value` is in min..max units, `relative` is 0..1. It is a property only (no attribute); the default is the rounded percentage.

---

## CSS Parts

Lane arcs are exposed as CSS shadow parts for styling from outside the shadow DOM:

```css
ixfx-radial-input::part(lane) { … }          /* all lanes */
ixfx-radial-input::part(lane-track) { … }    /* track lane specifically */
ixfx-radial-input::part(lane-value) { … }    /* value lane specifically */
ixfx-radial-input::part(lane-sweep) { … }    /* custom "sweep" lane */
ixfx-radial-input::part(value-marker) { … }  /* needle or dot group */
ixfx-radial-input::part(midpoint-marker) { … } /* bipolar/unipolar centre tick */
```

---

## Styling Recipes

### Purple theme

```css
#my-dial {
  --lane-value-color: hsl(280, 100%, 60%);
  --lane-track-color: hsl(280, 30%, 30%);
  --marker-thickness: 0.3;
}
```

### Animated marching-ants track

```css
@keyframes march {
  to { --lane-dashoffset: -30; }
}
#my-dial {
  --lane-dasharray: 20 10;
  animation: march 1s linear infinite;
}
```

---

## Implementation Notes

These are lessons learned from building the component — useful context when building a similar thing from scratch.

### SVG in a fixed 100×100 viewBox

All geometry is computed in a fixed `100×100` viewBox coordinate space with the circle centred at `{x: 50, y: 50}`. `radius` is a property clamped to 10–50 to prevent the dial from clipping the viewBox edges. This makes every calculation coordinate-system-agnostic — the SVG `viewBox` attribute takes care of scaling to the actual DOM pixels.

### Flatten changes the viewBox height

A flat-bottomed dial is achieved by cutting off the top portion of the arc. The full circle sits in a `100×100` box, but showing only the bottom `(1 - flatten) × 100` rows means the top of the box is empty space. Rather than cropping with `overflow: hidden`, the component dynamically narrows the SVG `viewBox` height (and sets a matching `--dial-height` CSS variable on the host) after first render and whenever `flatten` changes. This removes the dead space and makes the component's physical footprint match its visual content without requiring the consumer to manually set a height.

### Pointer capture, not window listeners… except for edge cases

The intended approach is `svg.setPointerCapture(event.pointerId)` on `pointerdown` so that `pointermove` events continue to reach the element even when the pointer leaves it. However, `pointermove` and `pointerup` are also attached to `window` as a belt-and-suspenders fallback, and removed again in `pointerup`/`pointercancel`. This handles edge cases where pointer capture is not available or fails silently (e.g. in some sandboxed environments).

### Drag sensitivity tied to rendered height

Full min-to-max range = `2 × clientHeight` of drag distance. This means a 100 px dial needs 200 px of vertical drag to sweep its full range — comfortable but precise. The sensitivity scales automatically as the component is resized. `Shift` divides sensitivity by 10 (`KEY_STEP_DIVISOR`), matching the fine-control convention used across other components in this library.

### Value stored in domain units; relative value (0..1) computed on demand

`this.value` is always in `min`…`max` domain units. Relative values are computed when needed with `scale(value, min, max, 0, 1)`. This avoids double-state and keeps the public API matching `<input type="range">` conventions.

### `input` vs `change` event semantics mirror native inputs

`input` fires on every user-driven value change (live, high frequency). `change` is debounced (150 ms) and fires once after the user stops interacting — identical to native `<input>` semantics. Programmatic writes bypass the `input` event entirely and fire `change` immediately (not debounced). This distinction matters to consumers: bind live UI feedback to `input`, persist/process to `change`.

### Lane rendering uses `part` + per-lane CSS variable patterns

Each lane path has `part="lane lane-<key>"` and reads its colour from `var(--lane-<key>-color, var(--lane-color))`. This two-tier fallback means a single `--lane-color` styles all custom lanes, while individual lanes can still be overridden by name. The same pattern is used for widths. The SVG `stroke-width` is expressed as a `calc()` over `--lane-<key>-width * radius%` so lane thickness scales proportionally with dial size.

### `--value-relative` as a CSS custom property bridge

Because CSS custom properties are live (they cascade and recompute continuously), updating `--value-relative` on the host element during every render cycle lets any CSS expression that references `var(--value-relative)` update purely in the browser's style engine — no JS event listener needed by the consumer. The component also has a `#getCssVar()` helper that evaluates `calc(…var(--value-relative)…)` expressions when reading back CSS variables (e.g. for `--marker-thickness`), so CSS-driven geometry works even for SVG attributes that must be set as numbers.

### Quantisation happens at the set-value boundary

`#quantise()` is called in `#setValueFromRelative()`, the single internal entry point for all value changes. Snapping to stops is therefore universal — drag, keyboard, and programmatic writes all go through the same path.

### `willUpdate` initialises the value lane before the first render

The `value` lane's internal `value` field is a 0..1 relative value, not a domain value. It must be in sync before the first paint. This is done in `willUpdate()` (not the constructor) because `@property` values set from HTML attributes are not yet parsed at construction time.

### `disconnectedCallback` cleans up timers and global listeners

The debounce timer and window pointer listeners are both cleaned up in `disconnectedCallback`. The pointer cleanup is achieved by calling `#onPointerUp()` directly, which also resets `#dragging`. Forgetting this causes a memory leak and a stuck-dragging bug if an element is removed mid-drag.
