# Knob

A circular dial for a number in a range, with the value written inside: compact controls such as volume, gain or a thermostat.

- Package: [@vigdx/ui](https://www.npmjs.com/package/@vigdx/ui)
- Selectors: `vig-knob`
- Source: [libs/ui/src/lib/molecules/knob/knob.ts](https://github.com/bakyurekk/vigdx/blob/main/libs/ui/src/lib/molecules/knob/knob.ts)

```typescript title="Import"
import { Knob } from '@vigdx/ui/knob';
```

## Basic

Bind `[(value)]` to a `number | null` signal; `min`, `max` and `step` default to 0, 100 and 1. Drag around the dial or use the keyboard. An empty knob rests at `min`.

```typescript title="knob-basic.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { Knob } from '@vigdx/ui/knob';

@Component({
  selector: 'app-knob-basic',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Knob],
  template: `
    <vig-knob label="Volume" [(value)]="volume" />
    <p class="text-sm text-muted-foreground">Value: {{ volume() }}</p>
  `,
})
export class KnobBasicDemo {
  protected readonly volume = signal<number | null>(40);
}
```

## Formatting, steps and the wheel

`formatValue` is a function of the number that formats the text inside the dial and `aria-valuetext`; without it the number is formatted for the active locale. Unlike `vig-slider`'s `valueTemplate`, which also takes a `'{0} %'` string template, it is a function only: new components take functions, not string templates. `wheel` lets the mouse wheel turn a focused knob (a step per notch; trackpad gestures add up to steps), so scrolling the page never changes a value.

```typescript title="knob-format.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { Knob } from '@vigdx/ui/knob';

@Component({
  selector: 'app-knob-format',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Knob],
  template: `
    <div class="flex flex-wrap gap-8">
      <vig-knob label="Opacity" [formatValue]="percent" [(value)]="opacity" />
      <vig-knob
        label="Temperature"
        [min]="16"
        [max]="30"
        [step]="0.5"
        [formatValue]="celsius"
        [(value)]="temperature"
      />
      <vig-knob label="Gain" wheel hint="Focus it, then scroll." [(value)]="gain" />
    </div>
  `,
})
export class KnobFormatDemo {
  protected readonly opacity = signal<number | null>(75);
  protected readonly temperature = signal<number | null>(21.5);
  protected readonly gain = signal<number | null>(30);
  protected readonly percent = (value: number) => `${value}%`;
  private readonly degrees = new Intl.NumberFormat('en', { maximumFractionDigits: 1 });
  protected readonly celsius = (value: number) => `${this.degrees.format(value)} °C`;
}
```

## Sizes and states

`size` scales the dial with its font (`sm`, `md`, `lg`). `readonly` keeps it focusable but fixed; disabled knobs leave the tab order. Errors color the arc and show their message once touched.

```typescript title="knob-states.ts"
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { Knob } from '@vigdx/ui/knob';

@Component({
  selector: 'app-knob-states',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Knob],
  template: `
    <div class="flex flex-wrap items-start gap-8">
      <vig-knob label="Small" size="sm" [value]="20" />
      <vig-knob label="Large" size="lg" [value]="80" />
      <vig-knob label="Read-only" readonly [value]="30" />
      <vig-knob label="Disabled" disabled [value]="60" />
      <vig-knob
        label="Error"
        touched
        invalid
        [value]="95"
        [errors]="[{ kind: 'max', message: 'Keep it at 90 or below.' }]"
      />
    </div>
  `,
})
export class KnobStatesDemo {}
```

## Signal Forms

`vig-knob` implements `FormValueControl<number | null>`. Schema `min()` and `max()` rules set the dial's range.

```typescript title="knob-signal-forms.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { FormField, form, max, min } from '@angular/forms/signals';
import { Knob } from '@vigdx/ui/knob';

@Component({
  selector: 'app-knob-signal-forms',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [FormField, Knob],
  template: `
    <vig-knob label="Fan speed" hint="1 to 5" [formField]="settings.fan" />
    <p class="text-sm text-muted-foreground">
      Valid: {{ settings().valid() ? 'yes' : 'no' }} · {{ model().fan }}
    </p>
  `,
})
export class KnobSignalFormsDemo {
  protected readonly model = signal<{ fan: number | null }>({ fan: 3 });
  protected readonly settings = form(this.model, (path) => {
    // min() and max() also set the dial's range.
    min(path.fan, 1);
    max(path.fan, 5);
  });
}
```

## Reactive Forms

Import `VigValueAccessor` next to the component to use `formControlName`, `[formControl]` or `ngModel`.

```typescript title="knob-reactive-forms.ts"
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { VigValueAccessor } from '@vigdx/ui/core';
import { Knob } from '@vigdx/ui/knob';

@Component({
  selector: 'app-knob-reactive-forms',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [ReactiveFormsModule, Knob, VigValueAccessor],
  template: `
    <vig-knob label="Balance" [min]="-50" [max]="50" [formControl]="balance" />
    <p class="text-sm text-muted-foreground">
      {{ balance.value }} · {{ balance.dirty ? 'dirty' : 'pristine' }}
    </p>
  `,
})
export class KnobReactiveFormsDemo {
  protected readonly balance = new FormControl<number | null>(0);
}
```

## Styling hooks

Internal elements carry a stable `data-part` and the component's `data-scope`; both are public API, so removing one is a breaking change. Select a part by both, e.g. `[data-scope="knob"][data-part="label"] { … }`: the pair stays within this component when kit components nest, and also reaches parts in overlay panels, which render outside the host. State is exposed through `aria-*` and, where listed, a `data-state`; literal values are checked by the API gate, values computed from the component's state follow its documented types. Other `data-*` attributes listed below (such as `data-opening` while an overlay animates) are API too. See [Customizing](https://vigdx.com/docs/theming.md#customizing).

Scope: `[data-scope="knob"]`

| Part | Element | data-state |
| --- | --- | --- |
| `label` | The visible label (`aria-labelledby` of the control). |   |
| `control` | The `role="slider"` dial wrapper. |   |
| `dial` | The SVG of the dial. |   |
| `track` | The full arc, in the control-boundary color. |   |
| `range` | The arc up to the value. |   |
| `thumb` | The marker at the value. |   |
| `value` | The formatted value inside the dial. |   |
| `hint` | The `vig-hint` (a `display: contents` host; style its `text` part). |   |
| `disabled-reason` | The `vig-hint` with the disabled reason (`display: contents`). |   |
| `error` | The `vig-field-error` (a `display: contents` host; style its `message` part). |   |

## Accessibility

- A `role="slider"` named by its label: Right and Up raise the value, Left and Down lower it, Page Up and Page Down move by a tenth of the range, Home and End jump to `min` and `max`. Under RTL the dial fills counter-clockwise and Left and Right swap, like a mirrored slider.
- The text inside the dial is hidden from screen readers; the same text is announced through `aria-valuetext`, so put units in `formatValue`.
- Pointer drags use pointer capture and `touch-action: none` on the dial only, so a drag never scrolls the page while the rest of the page scrolls as usual.
- The value arc (`--color-primary`) holds 3:1 against the light track (`--color-muted`) and the track's `--color-border-control` border 3:1 against the page. Forced-colors mode draws the dial with system colors (Highlight on Canvas inside CanvasText). The focus outline follows the round dial.
- The slider role has no `aria-required`, so `required` adds a visually hidden "Required" to the description. For exact numbers offer a number input too: dials are hard to set precisely.

## API

### Knob

Selector: `vig-knob` · Kind: component

A circular dial for a number between `min` and `max`, in `step`s, with the value written inside (`formatValue`). Drag around the dial, or use the keyboard like a slider: arrows step (mirrored under RTL, where the dial fills counter-clockwise), Page Up/Down take ten steps' worth, Home and End jump to the ends. The mouse wheel is opt-in (`wheel`) and only turns a focused knob, so scrolling the page never changes a value.

**Example :**

```html
<vig-knob label="Volume" [(value)]="volume" [formatValue]="percent" />
```

Sized with the font (`size`), colored with the kit's tokens: the value arc is `--color-primary` on a `--color-muted` track inside a `--color-border-control` border. Works with Signal Forms and, through `VigValueAccessor`, with Reactive Forms and `ngModel`.

#### Inputs

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `dirty` | `boolean` | `false` | — |
| `disabled` | `boolean` | `false` | — |
| `disabledReasons` | `readonly WithOptionalFieldTree<DisabledReason>[]` | `[]` | — |
| `errorMessages` | `Record<string, string>` | — | — |
| `errors` | `readonly ValidationError.WithOptionalFieldTree[]` | `[]` | — |
| `formatValue` | `((value: number) => string) \| undefined` | `undefined` | Formats the value inside the dial and for `aria-valuetext`, e.g. `(n) => n + ' %'`; the locale-formatted number by default. |
| `hidden` | `boolean` | `false` | — |
| `hideLabel` | `boolean` | `false` | Keeps the label for assistive tech only. |
| `hint` | `string \| undefined` | `undefined` | — |
| `invalid` | `boolean` | `false` | — |
| `label` (required) | `string` | — | — |
| `labels` | `Partial<KnobLabels>` | — | Texts (i18n); locale defaults. |
| `max` | `number \| undefined` | `100` | — |
| `min` | `number \| undefined` | `0` | — |
| `name` | `string` | `''` | — |
| `pending` | `boolean` | `false` | — |
| `readonly` | `boolean` | `false` | — |
| `required` | `boolean` | `false` | — |
| `size` | `FieldSize` | `'md'` | — |
| `step` | `number` | `1` | — |
| `touched` | `boolean` | `false` | — |
| `value` (model) | `number \| null` | `null` | The value, `null` while empty; an empty knob rests at `min`. |
| `wheel` | `boolean` | `false` | Lets the mouse wheel turn the knob while it has focus. |

#### Outputs

| Name | Payload | Description |
| --- | --- | --- |
| `touch` | `void` | — |
| `valueChange` | `number \| null` | The value, `null` while empty; an empty knob rests at `min`. |

#### Methods

| Signature | Description |
| --- | --- |
| `focus(options?: FocusOptions): void` | Moves focus to the control's interactive element (the input, or the trigger of a popup control). Signal Forms calls it through `field().focusBoundControl()`; the host element itself cannot take focus. |
| `reset(): void` | Returns the control to its pristine look: drops in-progress text, closes an open popup, clears errors the component raised itself and the submitted state of `errorDisplay: 'interacted'`. Signal Forms calls it from `field().reset()`; `VigValueAccessor` from `control.reset()`. It never changes the value: the bound form owns that. |
