# Scale menu

> A menu that picks a root and a scale and turns the scale on or off, in parts you place beside items of your own.

```tsx
import { useState } from "react";
import { DropdownMenuSeparator } from "@/components/ui/dropdown-menu";
import { inScale, type Scale } from "@/lib/engine/pitch";
import { Piano } from "@/components/audio-ui/piano";
import {
  ScaleMenu,
  ScaleMenuContent,
  ScaleMenuName,
  ScaleMenuRoot,
  ScaleMenuToggle,
  ScaleMenuTrigger,
} from "@/components/audio-ui/scale-menu";

const MIN_PITCH = 48;
const MAX_PITCH = 72;
const PITCHES = Array.from(
  { length: MAX_PITCH - MIN_PITCH + 1 },
  (_, index) => MIN_PITCH + index
);

/** Pick a root and a scale: the keys in it light up. */
export function ScaleMenuDemo() {
  const [enabled, setEnabled] = useState(true);
  const [scale, setScale] = useState<Scale>({ name: "major", root: 2 });
  const marked = enabled
    ? PITCHES.filter((pitch) => inScale(pitch, scale))
    : [];

  return (
    <div className="flex w-full flex-col items-center gap-4">
      <ScaleMenu
        enabled={enabled}
        onEnabledChange={setEnabled}
        onScaleChange={setScale}
        scale={scale}
      >
        <ScaleMenuTrigger />
        <ScaleMenuContent align="center">
          <ScaleMenuToggle>Light the scale</ScaleMenuToggle>
          <DropdownMenuSeparator />
          <ScaleMenuRoot />
          <ScaleMenuName />
        </ScaleMenuContent>
      </ScaleMenu>
      <Piano
        activeNotes={marked}
        aria-label="Piano"
        // The keys stay white and black in every theme, the primary color does not: the scale takes its hue at a lightness of its own, light on a white key, mid on a black one, so a key in it reads whatever the theme.
        className="[&_[data-selected][data-color=black]]:bg-[oklch(from_var(--primary)_0.55_c_h)] [&_[data-selected][data-color=white]]:bg-[oklch(from_var(--primary)_0.85_c_h)]"
        maxPitch={MAX_PITCH}
        minPitch={MIN_PITCH}
      />
    </div>
  );
}
```

## Installation

**CLI**

```bash
npx shadcn@latest add @audio-ui/scale-menu
```

**Manual**

**1. Copy and paste the following code into your project.**

```tsx title="components/audio-ui/scale-menu.tsx"
import {
  type ComponentProps,
  createContext,
  type ReactNode,
  use,
  useCallback,
  useMemo,
} from "react";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuCheckboxItem,
  DropdownMenuContent,
  DropdownMenuGroup,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuSub,
  DropdownMenuSubContent,
  DropdownMenuSubTrigger,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  detectKeys,
  type KeyNote,
  SCALES,
  type Scale,
  type ScaleName,
} from "@/lib/engine/pitch";
import { cn } from "@/lib/utils";
import { pitchClassName } from "@/components/audio-ui/pitch";

/** Each scale's name, as the menu writes it. */
export const SCALE_LABELS: Record<ScaleName, string> = {
  blues: "Blues",
  chromatic: "Chromatic",
  dorian: "Dorian",
  "harmonic-minor": "Harmonic minor",
  locrian: "Locrian",
  lydian: "Lydian",
  major: "Major",
  "pentatonic-major": "Major pentatonic",
  "melodic-minor": "Melodic minor",
  minor: "Minor",
  "pentatonic-minor": "Minor pentatonic",
  mixolydian: "Mixolydian",
  phrygian: "Phrygian",
  whole: "Whole tone",
};
const SCALE_NAMES = Object.keys(SCALES) as ScaleName[];
const ROOTS = Array.from({ length: 12 }, (_, root) => root);

/** "D Dorian": a scale's root and its name. */
export const scaleLabel = (scale: Scale) =>
  `${pitchClassName(scale.root)} ${SCALE_LABELS[scale.name]}`;

interface ScaleMenuContextValue {
  enabled: boolean;
  onEnabledChange: (enabled: boolean) => void;
  onScaleChange: (scale: Scale) => void;
  scale: Scale;
}

const ScaleMenuContext = createContext<ScaleMenuContextValue | null>(null);

function useScaleMenu() {
  const context = use(ScaleMenuContext);
  if (!context) {
    throw new Error("ScaleMenu parts must be placed inside a ScaleMenu.");
  }
  return context;
}

interface ScaleMenuProps {
  children: ReactNode;
  /** Whether the scale is in use, such as marked on a roll's rows. */
  enabled: boolean;
  onEnabledChange: (enabled: boolean) => void;
  /** Picking a root or a scale also turns it on. */
  onScaleChange: (scale: Scale) => void;
  /** The root and the scale, kept while the scale is off. */
  scale: Scale;
}

/** A menu that picks a root and a scale, and turns the scale on or off. */
function ScaleMenu({
  children,
  enabled,
  onEnabledChange,
  onScaleChange,
  scale,
}: ScaleMenuProps) {
  const value = useMemo(
    () => ({ enabled, onEnabledChange, onScaleChange, scale }),
    [enabled, onEnabledChange, onScaleChange, scale]
  );
  return (
    <ScaleMenuContext value={value}>
      <DropdownMenu>{children}</DropdownMenu>
    </ScaleMenuContext>
  );
}

/** The button that opens the menu: filled and named after the scale when it is on, "Scale" when off. */
function ScaleMenuTrigger(
  props: Omit<ComponentProps<typeof Button>, "children" | "variant">
) {
  const { enabled, scale } = useScaleMenu();
  return (
    <DropdownMenuTrigger
      render={
        <Button
          aria-label={`Scale: ${enabled ? scaleLabel(scale) : "off"}`}
          data-part="scale-menu-trigger"
          variant={enabled ? "default" : "outline"}
          {...props}
        />
      }
    >
      {enabled ? scaleLabel(scale) : "Scale"}
    </DropdownMenuTrigger>
  );
}

function ScaleMenuContent({
  align = "end",
  className,
  ...props
}: ComponentProps<typeof DropdownMenuContent>) {
  return (
    <DropdownMenuContent
      align={align}
      className={cn("w-auto min-w-48", className)}
      data-part="scale-menu-content"
      {...props}
    />
  );
}

/** A checkbox item that turns the scale on or off. Its children are the label. */
function ScaleMenuToggle({
  children = "Mark the scale",
  ...props
}: Omit<
  ComponentProps<typeof DropdownMenuCheckboxItem>,
  "checked" | "onCheckedChange"
>) {
  const { enabled, onEnabledChange } = useScaleMenu();
  return (
    <DropdownMenuCheckboxItem
      checked={enabled}
      data-part="scale-menu-toggle"
      onCheckedChange={onEnabledChange}
      {...props}
    >
      {children}
    </DropdownMenuCheckboxItem>
  );
}

/** A submenu of the twelve roots. */
function ScaleMenuRoot() {
  const { onEnabledChange, onScaleChange, scale } = useScaleMenu();
  const changeRoot = useCallback(
    (root: number) => {
      onScaleChange({ ...scale, root });
      onEnabledChange(true);
    },
    [onEnabledChange, onScaleChange, scale]
  );
  return (
    <DropdownMenuSub>
      <DropdownMenuSubTrigger data-part="scale-menu-root">
        Root: {pitchClassName(scale.root)}
      </DropdownMenuSubTrigger>
      <DropdownMenuSubContent>
        <DropdownMenuRadioGroup onValueChange={changeRoot} value={scale.root}>
          {ROOTS.map((root) => (
            <DropdownMenuRadioItem key={root} value={root}>
              {pitchClassName(root)}
            </DropdownMenuRadioItem>
          ))}
        </DropdownMenuRadioGroup>
      </DropdownMenuSubContent>
    </DropdownMenuSub>
  );
}

/** A submenu of the scales, by name. */
function ScaleMenuName() {
  const { onEnabledChange, onScaleChange, scale } = useScaleMenu();
  const changeName = useCallback(
    (name: ScaleName) => {
      onScaleChange({ ...scale, name });
      onEnabledChange(true);
    },
    [onEnabledChange, onScaleChange, scale]
  );
  return (
    <DropdownMenuSub>
      <DropdownMenuSubTrigger data-part="scale-menu-name">
        Scale: {SCALE_LABELS[scale.name]}
      </DropdownMenuSubTrigger>
      <DropdownMenuSubContent>
        <DropdownMenuRadioGroup onValueChange={changeName} value={scale.name}>
          {SCALE_NAMES.map((name) => (
            <DropdownMenuRadioItem key={name} value={name}>
              {SCALE_LABELS[name]}
            </DropdownMenuRadioItem>
          ))}
        </DropdownMenuRadioGroup>
      </DropdownMenuSubContent>
    </DropdownMenuSub>
  );
}

/** One key the notes may be in, as an item of the menu. */
function ScaleMenuDetected({
  onPick,
  scale,
}: {
  onPick: (scale: Scale) => void;
  scale: Scale;
}) {
  const pick = useCallback(() => onPick(scale), [onPick, scale]);
  return (
    <DropdownMenuItem onClick={pick}>{scaleLabel(scale)}</DropdownMenuItem>
  );
}

/**
 * The keys the notes are likeliest in, three at most, likeliest first: one
 * picked sets the root and the scale and turns it on. Pass every part of the
 * song, not one: a single part is often ambiguous.
 */
function ScaleMenuDetect({
  audio,
  count = 3,
  notes,
}: {
  /** How many keys it offers. @default 3 */
  count?: number;
  /** The sound of recordings to read it from too: a weight per pitch class, C to B, in the unit of the notes' lengths. */
  audio?: readonly number[];
  /** The notes to read the key from. */
  notes: readonly KeyNote[];
}) {
  const { onEnabledChange, onScaleChange } = useScaleMenu();
  const keys = useMemo(
    () => detectKeys(notes, count, audio),
    [audio, count, notes]
  );
  const pick = useCallback(
    (picked: Scale) => {
      onScaleChange(picked);
      onEnabledChange(true);
    },
    [onEnabledChange, onScaleChange]
  );
  return (
    <DropdownMenuGroup data-part="scale-menu-detect">
      <DropdownMenuLabel>Detected</DropdownMenuLabel>
      {keys.length === 0 ? (
        <DropdownMenuItem disabled>Nothing to read</DropdownMenuItem>
      ) : (
        keys.map((item) => (
          <ScaleMenuDetected
            key={`${item.root} ${item.name}`}
            onPick={pick}
            scale={item}
          />
        ))
      )}
    </DropdownMenuGroup>
  );
}

export {
  ScaleMenu,
  ScaleMenuContent,
  ScaleMenuDetect,
  ScaleMenuName,
  ScaleMenuRoot,
  ScaleMenuToggle,
  ScaleMenuTrigger,
};
```

**2. Update the import paths to match your project setup.**

**Agent**

Paste this prompt to your agent. It does the rest: it installs the skill, adds the component and wires it to your audio.

```text
Install the audio/ui skill with `npx skills add ouestlabs/audio-ui`, then follow it to add the scale menu from audio/ui to my project and wire it to my audio code. Read the docs at https://www.audio-ui.dev/llms.txt first.
```

To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents).

## Anatomy

```tsx
<ScaleMenu>
  <ScaleMenuTrigger />
  <ScaleMenuContent>
    <ScaleMenuToggle />
    <ScaleMenuRoot />
    <ScaleMenuName />
  </ScaleMenuContent>
</ScaleMenu>
```

## Usage

```tsx
import type { Scale } from "@/lib/engine/pitch";
import {
  ScaleMenu,
  ScaleMenuContent,
  ScaleMenuName,
  ScaleMenuRoot,
  ScaleMenuToggle,
  ScaleMenuTrigger,
} from "@/components/audio-ui/scale-menu";
import { DropdownMenuSeparator } from "@/components/ui/dropdown-menu";

const [enabled, setEnabled] = useState(false);
const [scale, setScale] = useState<Scale>({ name: "major", root: 0 });

<ScaleMenu
  enabled={enabled}
  onEnabledChange={setEnabled}
  onScaleChange={setScale}
  scale={scale}
>
  <ScaleMenuTrigger />
  <ScaleMenuContent>
    <ScaleMenuToggle />
    <DropdownMenuSeparator />
    <ScaleMenuRoot />
    <ScaleMenuName />
  </ScaleMenuContent>
</ScaleMenu>;
```

A scale is `{ root, name }`: `root` is a pitch class, 0 for C to 11 for B, and `name` one of the scales in `SCALES` from `@/lib/engine/pitch` (`"major"`, `"minor"`, `"dorian"`, `"blues"`…). The menu keeps the scale while it is off, so turning it back on brings back the last one; picking a root or a scale turns it on.

Pass `enabled ? scale : null` to whatever marks the scale: a [Piano roll](/docs/components/base/piano-roll)'s `scale` marks its rows, and `inScale(pitch, scale)` from `@/lib/engine/pitch` tells whether any pitch is in it.

### Items of your own

`ScaleMenuContent` is a dropdown menu's content, so any item goes beside the parts. The piano roll block adds a checkbox that folds the roll onto the scale's rows, and shows each item's key:

```tsx
<ScaleMenuContent>
  <ScaleMenuToggle>
    Mark the scale
    <DropdownMenuShortcut>K</DropdownMenuShortcut>
  </ScaleMenuToggle>
  <DropdownMenuCheckboxItem checked={folded} onCheckedChange={setFolded}>
    Only its rows
    <DropdownMenuShortcut>G</DropdownMenuShortcut>
  </DropdownMenuCheckboxItem>
  <DropdownMenuSeparator />
  <ScaleMenuRoot />
  <ScaleMenuName />
</ScaleMenuContent>
```

### Detect the key

`ScaleMenuDetect` offers the keys some notes are likeliest in, three at most, likeliest first: picking one sets the root and the scale, major or minor, and turns it on. Each pitch class is weighed by how long it sounds and matched against the major and minor key profiles of `@audio/mir-key` (Krumhansl-Schmuckler).

```tsx
<ScaleMenuContent>
  <ScaleMenuRoot />
  <ScaleMenuName />
  <DropdownMenuSeparator />
  <ScaleMenuDetect notes={notes} />
</ScaleMenuContent>
```

Pass every part of the song, not one. On 60 loops of known key, a single bass or guitar part named its key 21 times in 60 (39 times in its first three); the parts of each song together named it 8 times in 10. One part alone is often ambiguous: a bass line in E minor reads as well in C major.

Recordings count too: `audio` takes a weight per pitch class, C to B, in the unit of the notes' lengths, such as the `audioChroma(channels, sampleRate)` of each recording (from [`@/lib/engine/analysis`](/docs/engine/analysis#a-recording-as-it-comes-in), `@audio/mir-chroma` on its windows that are not silence) times the seconds it plays. The audio of the same songs, guitar and bass together, had the key first 6 times in 10 and in its first three 9 times in 10. `detectKeys(notes, count, audio)`, from [`@/lib/engine/pitch`](/docs/engine/pitch#keys), gives the same keys without the menu.

## API reference

### ScaleMenu

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `scale` | `{ root, name }` |  | The root and the scale, kept while the scale is off. |
| `onScaleChange` | `(scale) => void` |  | A root or a scale was picked. Picking one also turns the scale on. |
| `enabled` | `boolean` |  | Whether the scale is in use. |
| `onEnabledChange` | `(enabled) => void` |  | The scale was turned on or off. |

### Parts

**Components**

| Name | Description |
| --- | --- |
| `ScaleMenuTrigger` | The button that opens the menu: filled and named after the scale ("D Dorian") when it is on, outlined and named "Scale" when off. Takes the button's props. |
| `ScaleMenuContent` | The menu. Aligned to the trigger's end unless given `align`. |
| `ScaleMenuToggle` | A checkbox item that turns the scale on or off. Its children are the label, "Mark the scale" when left out. |
| `ScaleMenuRoot` | A submenu of the twelve roots. |
| `ScaleMenuName` | A submenu of the scales. |
| `ScaleMenuDetect` | The keys `notes` (each `{ pitch, length, muted? }`) and `audio` (a weight per pitch class) are likeliest in, `count` at most (3), under a "Detected" label. One picked sets the scale and turns it on. |

The file also exports `SCALE_LABELS`, each scale's name as the menu writes it, and `scaleLabel(scale)`, which writes a scale as "D Dorian"; the keys `ScaleMenuDetect` offers are `detectKeys(notes, count, audio)` of `@/lib/engine/pitch`.
