# Toggle Group

Grup tombol toggle bersegmen dengan pilihan tunggal atau ganda dan navigasi tombol panah antar item.

- Kategori: Form
- Status: stable
- Registry: https://markas.jenderalcorp.com/r/toggle-group.json
- CLI: `npx markasui@latest add toggle-group`

## Kapan dipakai

Mengganti tampilan atau pengaturan di antara beberapa opsi pendek, misalnya hari/minggu/bulan, daftar/grid, atau perataan dan format teks di toolbar.

- Batasi dua sampai lima item pendek, pakai Select untuk daftar panjang
- Pakai Tabs kalau setiap opsi menampilkan panel kontennya sendiri
- Selalu isi label agar grup punya nama

## Kode

### Blade

Simpan di `resources/views/components/markas/toggle-group.blade.php`. Dependensi: alpinejs.

```blade
@props([
    'items' => [],
    'type' => 'single',
    'value' => null,
    'label' => null,
])

@php
    $root = 'inline-flex items-center gap-1 rounded-lg bg-subtle p-1';
    $item = 'inline-flex h-8 items-center justify-center gap-2 rounded-md px-3 text-sm font-medium whitespace-nowrap text-muted transition-colors duration-150 ease-out hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary data-[state=on]:bg-surface data-[state=on]:text-ink motion-reduce:transition-none [&_svg]:size-4 [&_svg]:shrink-0';

    $values = array_map(fn ($entry) => (string) $entry['value'], $items);
    $selected = array_values(array_intersect($values, array_map('strval', (array) ($value ?? []))));
    if ($type !== 'multiple') {
        $selected = array_slice($selected, 0, 1);
    }
    $tabStop = $selected[0] ?? ($values[0] ?? null);
@endphp

<div
    role="group"
    x-data="{
        selected: @js($selected),
        focused: @js($tabStop),
        multiple: @js($type === 'multiple'),
        values: @js($values),
        {{-- Bound value for wire:model and x-model: a string (or null) for single, an array for multiple. --}}
        value: @js($type === 'multiple' ? $selected : ($selected[0] ?? null)),
        init() {
            this.$watch('value', (next) => {
                const list = (Array.isArray(next) ? next : next === null || next === '' ? [] : [next]).map(String);
                this.selected = this.values.filter((entry) => list.includes(entry));
            });
        },
        toggle(key) {
            this.focused = key;
            if (this.selected.includes(key)) {
                this.selected = this.selected.filter((entry) => entry !== key);
            } else {
                const next = this.multiple ? [...this.selected, key] : [key];
                this.selected = this.values.filter((entry) => next.includes(entry));
            }
            this.value = this.multiple ? [...this.selected] : (this.selected[0] ?? null);
        },
        move(step) {
            const buttons = Array.from($root.querySelectorAll(':scope > button'));
            const index = buttons.indexOf(document.activeElement);
            const target = buttons[(index + step + buttons.length) % buttons.length];
            if (!target) return;
            this.focused = target.dataset.value;
            target.focus();
        },
    }"
    x-modelable="value"
    x-on:keydown.right.prevent="move(1)"
    x-on:keydown.left.prevent="move(-1)"
    @if ($label) aria-label="{{ $label }}" @endif
    {{ $attributes->class([$root]) }}
>
    @foreach ($items as $entry)
        @php
            $key = (string) $entry['value'];
            $on = in_array($key, $selected, true);
        @endphp
        <button
            type="button"
            data-value="{{ $key }}"
            aria-pressed="{{ $on ? 'true' : 'false' }}"
            data-state="{{ $on ? 'on' : 'off' }}"
            tabindex="{{ $key === $tabStop ? '0' : '-1' }}"
            @isset($entry['ariaLabel']) aria-label="{{ $entry['ariaLabel'] }}" @endisset
            x-bind:aria-pressed="selected.includes(@js($key)) ? 'true' : 'false'"
            x-bind:data-state="selected.includes(@js($key)) ? 'on' : 'off'"
            x-bind:tabindex="focused === @js($key) ? 0 : -1"
            x-on:click="toggle(@js($key))"
            class="{{ $item }}"
        >{{ $__laravel_slots[$key] ?? $entry['label'] ?? '' }}</button>
    @endforeach
</div>
```

```blade
<x-markas.toggle-group
    label="Tampilan kalender"
    value="minggu"
    :items="[
        ['value' => 'hari', 'label' => 'Hari'],
        ['value' => 'minggu', 'label' => 'Minggu'],
        ['value' => 'bulan', 'label' => 'Bulan'],
    ]"
/>
```

Butuh Alpine.js. Ganti label dengan ikon lewat slot bernama sesuai value, misalnya `<x-slot:kiri>`, dan isi `ariaLabel` di item tersebut.

### Livewire

```blade
<x-markas.toggle-group label="View" wire:model.live="view" :items="$views" />
```

`wire:model` terhubung ke string (atau `null`) untuk `type="single"` dan array untuk `type="multiple"`.

### React

Simpan di `src/components/markas/ToggleGroup.tsx`. Tanpa dependensi tambahan.

```tsx
"use client";

import {
  useState,
  type ComponentProps,
  type KeyboardEvent,
  type ReactNode,
} from "react";

const root = "inline-flex items-center gap-1 rounded-lg bg-subtle p-1";
const item =
  "inline-flex h-8 items-center justify-center gap-2 rounded-md px-3 text-sm font-medium whitespace-nowrap text-muted transition-colors duration-150 ease-out hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary data-[state=on]:bg-surface data-[state=on]:text-ink motion-reduce:transition-none [&_svg]:size-4 [&_svg]:shrink-0";
const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");

const STEPS: Record<string, number> = { ArrowRight: 1, ArrowLeft: -1 };

export type ToggleGroupItem = {
  value: string;
  label: ReactNode;
  ariaLabel?: string;
};

type BaseProps = Omit<
  ComponentProps<"div">,
  "defaultValue" | "onChange" | "role"
> & {
  items: ToggleGroupItem[];
  label?: string;
};

export type ToggleGroupProps = BaseProps &
  (
    | {
        type?: "single";
        value?: string;
        defaultValue?: string;
        onValueChange?: (value: string) => void;
      }
    | {
        type: "multiple";
        value?: string[];
        defaultValue?: string[];
        onValueChange?: (value: string[]) => void;
      }
  );

const toArray = (value: string | string[] | undefined) =>
  Array.isArray(value) ? value : value ? [value] : [];

export function ToggleGroup(props: ToggleGroupProps) {
  const {
    items,
    label,
    type = "single",
    value,
    defaultValue,
    onValueChange,
    className,
    ...rest
  } = props;
  const [internal, setInternal] = useState(() => toArray(defaultValue));
  const [focused, setFocused] = useState<string>();
  const selected = value === undefined ? internal : toArray(value);
  const tabStop = focused ?? selected[0] ?? items[0]?.value;

  const toggle = (key: string) => {
    setFocused(key);
    const isOn = selected.includes(key);
    const wanted = isOn
      ? selected.filter((entry) => entry !== key)
      : type === "multiple"
        ? [...selected, key]
        : [key];
    const next = items
      .map((entry) => entry.value)
      .filter((entry) => wanted.includes(entry));
    setInternal(next);
    (onValueChange as ((value: string | string[]) => void) | undefined)?.(
      type === "multiple" ? next : (next[0] ?? ""),
    );
  };

  const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
    const step = STEPS[event.key];
    if (step === undefined) return;
    event.preventDefault();
    const buttons = Array.from(
      event.currentTarget.querySelectorAll<HTMLButtonElement>(
        ":scope > button",
      ),
    );
    const index = buttons.indexOf(document.activeElement as HTMLButtonElement);
    const target = buttons[(index + step + buttons.length) % buttons.length];
    if (!target) return;
    setFocused(target.dataset.value);
    target.focus();
  };

  return (
    <div
      role="group"
      aria-label={label}
      onKeyDown={handleKeyDown}
      className={cx(root, className)}
      {...rest}
    >
      {items.map((entry) => {
        const isOn = selected.includes(entry.value);
        return (
          <button
            key={entry.value}
            type="button"
            data-value={entry.value}
            aria-pressed={isOn}
            data-state={isOn ? "on" : "off"}
            tabIndex={entry.value === tabStop ? 0 : -1}
            aria-label={entry.ariaLabel}
            onClick={() => toggle(entry.value)}
            className={item}
          >
            {entry.label}
          </button>
        );
      })}
    </div>
  );
}
```

```tsx
import { ToggleGroup } from "@/components/markas/ToggleGroup";

<ToggleGroup
  label="Tampilan kalender"
  defaultValue="minggu"
  onValueChange={(value) => console.log(value)}
  items={[
    { value: "hari", label: "Hari" },
    { value: "minggu", label: "Minggu" },
    { value: "bulan", label: "Bulan" },
  ]}
/>;

<ToggleGroup
  type="multiple"
  label="Gaya teks"
  defaultValue={["tebal"]}
  items={[
    {
      value: "tebal",
      label: <BoldIcon aria-hidden="true" />,
      ariaLabel: "Tebal",
    },
    {
      value: "miring",
      label: <ItalicIcon aria-hidden="true" />,
      ariaLabel: "Miring",
    },
  ]}
/>;
```

### Vue

Simpan di `src/components/markas/ToggleGroup.vue`. Tanpa dependensi tambahan.

```vue
<script setup lang="ts">
import { computed, ref } from "vue";

export type ToggleGroupItem = {
  value: string;
  label: string;
  ariaLabel?: string;
};

const props = withDefaults(
  defineProps<{
    items: ToggleGroupItem[];
    type?: "single" | "multiple";
    defaultValue?: string | string[];
    label?: string;
  }>(),
  { type: "single", defaultValue: undefined, label: undefined },
);
const model = defineModel<string | string[]>();

const root = "inline-flex items-center gap-1 rounded-lg bg-subtle p-1";
const item =
  "inline-flex h-8 items-center justify-center gap-2 rounded-md px-3 text-sm font-medium whitespace-nowrap text-muted transition-colors duration-150 ease-out hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary data-[state=on]:bg-surface data-[state=on]:text-ink motion-reduce:transition-none [&_svg]:size-4 [&_svg]:shrink-0";

const STEPS: Record<string, number> = { ArrowRight: 1, ArrowLeft: -1 };

const toArray = (value: string | string[] | undefined) =>
  Array.isArray(value) ? value : value ? [value] : [];

const focused = ref<string>();
const selected = computed(() => toArray(model.value ?? props.defaultValue));
const tabStop = computed(
  () => focused.value ?? selected.value[0] ?? props.items[0]?.value,
);

function toggle(key: string) {
  focused.value = key;
  const isOn = selected.value.includes(key);
  const wanted = isOn
    ? selected.value.filter((entry) => entry !== key)
    : props.type === "multiple"
      ? [...selected.value, key]
      : [key];
  const next = props.items
    .map((entry) => entry.value)
    .filter((entry) => wanted.includes(entry));
  model.value = props.type === "multiple" ? next : (next[0] ?? "");
}

function onKeydown(event: KeyboardEvent) {
  const step = STEPS[event.key];
  if (step === undefined) return;
  event.preventDefault();
  const group = event.currentTarget as HTMLElement;
  const buttons = Array.from(
    group.querySelectorAll<HTMLButtonElement>(":scope > button"),
  );
  const index = buttons.indexOf(document.activeElement as HTMLButtonElement);
  const target = buttons[(index + step + buttons.length) % buttons.length];
  if (!target) return;
  focused.value = target.dataset.value;
  target.focus();
}
</script>

<template>
  <div
    role="group"
    :aria-label="props.label"
    :class="root"
    @keydown="onKeydown"
  >
    <button
      v-for="entry in props.items"
      :key="entry.value"
      type="button"
      :data-value="entry.value"
      :aria-pressed="selected.includes(entry.value) ? 'true' : 'false'"
      :data-state="selected.includes(entry.value) ? 'on' : 'off'"
      :tabindex="entry.value === tabStop ? 0 : -1"
      :aria-label="entry.ariaLabel"
      :class="item"
      @click="toggle(entry.value)"
    >
      <slot :name="entry.value">{{ entry.label }}</slot>
    </button>
  </div>
</template>
```

```vue
<script setup lang="ts">
import { ref } from "vue";
import ToggleGroup from "@/components/markas/ToggleGroup.vue";

const tampilan = ref("minggu");
</script>

<template>
  <ToggleGroup
    v-model="tampilan"
    label="Tampilan kalender"
    :items="[
      { value: 'hari', label: 'Hari' },
      { value: 'minggu', label: 'Minggu' },
      { value: 'bulan', label: 'Bulan' },
    ]"
  />
</template>
```

### Svelte

Simpan di `src/lib/components/markas/ToggleGroup.svelte`. Tanpa dependensi tambahan.

```svelte
<script module lang="ts">
  import type { Snippet } from "svelte";

  export type ToggleGroupItem = {
    value: string;
    /** Text, or a snippet for an icon (pass ariaLabel then). */
    label: string | Snippet;
    ariaLabel?: string;
  };
</script>

<script lang="ts">
  import type { HTMLAttributes } from "svelte/elements";

  const root = "inline-flex items-center gap-1 rounded-lg bg-subtle p-1";
  const item =
    "inline-flex h-8 items-center justify-center gap-2 rounded-md px-3 text-sm font-medium whitespace-nowrap text-muted transition-colors duration-150 ease-out hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary data-[state=on]:bg-surface data-[state=on]:text-ink motion-reduce:transition-none [&_svg]:size-4 [&_svg]:shrink-0";

  const STEPS: Record<string, number> = { ArrowRight: 1, ArrowLeft: -1 };

  type Props = Omit<HTMLAttributes<HTMLDivElement>, "role"> & {
    items: ToggleGroupItem[];
    label?: string;
    type?: "single" | "multiple";
    /** Pressed items, bindable with bind:value. A string for single, an array for multiple. */
    value?: string | string[];
  };

  let {
    items,
    label,
    type = "single",
    value = $bindable(),
    class: className,
    onkeydown,
    ...rest
  }: Props = $props();

  const toArray = (entry: string | string[] | undefined) =>
    Array.isArray(entry) ? entry : entry ? [entry] : [];

  let focused = $state<string>();
  const selected = $derived(toArray(value));
  const tabStop = $derived(focused ?? selected[0] ?? items[0]?.value);

  function toggle(key: string) {
    focused = key;
    const wanted = selected.includes(key)
      ? selected.filter((entry) => entry !== key)
      : type === "multiple"
        ? [...selected, key]
        : [key];
    const next = items
      .map((entry) => entry.value)
      .filter((entry) => wanted.includes(entry));
    value = type === "multiple" ? next : (next[0] ?? "");
  }

  function handleKeydown(
    event: KeyboardEvent & { currentTarget: EventTarget & HTMLDivElement },
  ) {
    onkeydown?.(event);
    const step = STEPS[event.key];
    if (step === undefined) return;
    event.preventDefault();
    const buttons = Array.from(
      event.currentTarget.querySelectorAll<HTMLButtonElement>(
        ":scope > button",
      ),
    );
    const index = buttons.indexOf(document.activeElement as HTMLButtonElement);
    const target = buttons[(index + step + buttons.length) % buttons.length];
    if (!target) return;
    focused = target.dataset.value;
    target.focus();
  }
</script>

<div
  role="group"
  aria-label={label}
  onkeydown={handleKeydown}
  class={[root, className]}
  {...rest}
>
  {#each items as entry (entry.value)}
    {@const isOn = selected.includes(entry.value)}
    <button
      type="button"
      data-value={entry.value}
      aria-pressed={isOn ? "true" : "false"}
      data-state={isOn ? "on" : "off"}
      tabindex={entry.value === tabStop ? 0 : -1}
      aria-label={entry.ariaLabel}
      onclick={() => toggle(entry.value)}
      class={item}
    >
      {#if typeof entry.label === "string"}{entry.label}{:else}{@render entry.label()}{/if}
    </button>
  {/each}
</div>
```

```svelte
<script lang="ts">
  import ToggleGroup from "$lib/components/markas/ToggleGroup.svelte";

  let view = $state("week");
</script>

{#snippet leftIcon()}
  <svg
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    stroke-width="1.5"
    aria-hidden="true"><path d="M4 6h16M4 12h10M4 18h14" /></svg
  >
{/snippet}

<ToggleGroup
  bind:value={view}
  label="Tampilan kalender"
  items={[
    { value: "day", label: "Hari" },
    { value: "week", label: "Minggu" },
    { value: "month", label: "Bulan" },
  ]}
/>

<ToggleGroup
  label="Perataan teks"
  value="left"
  items={[{ value: "left", label: leftIcon, ariaLabel: "Rata kiri" }]}
/>
```

### Astro

Simpan di `src/components/markas/ToggleGroup.astro`. Tanpa dependensi tambahan.

```astro
---
import type { HTMLAttributes } from "astro/types";

const root = "inline-flex items-center gap-1 rounded-lg bg-subtle p-1";
const item =
  "inline-flex h-8 items-center justify-center gap-2 rounded-md px-3 text-sm font-medium whitespace-nowrap text-muted transition-colors duration-150 ease-out hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary data-[state=on]:bg-surface data-[state=on]:text-ink motion-reduce:transition-none [&_svg]:size-4 [&_svg]:shrink-0";

type Item = { value: string; label: string; ariaLabel?: string };

type Props = Omit<HTMLAttributes<"div">, "role"> & {
  items: Item[];
  label?: string;
  type?: "single" | "multiple";
  value?: string | string[];
};

const {
  items,
  label,
  type = "single",
  value,
  class: className,
  ...rest
} = Astro.props;

const values = items.map((entry) => entry.value);
const wanted = Array.isArray(value) ? value : value ? [value] : [];
const selected = values
  .filter((entry) => wanted.includes(entry))
  .slice(0, type === "multiple" ? undefined : 1);
const tabStop = selected[0] ?? values[0];
// A slot named after an item value replaces its label, for example an icon.
const labels = await Promise.all(
  items.map((entry) =>
    Astro.slots.has(entry.value) ? Astro.slots.render(entry.value) : null,
  ),
);
---

<div
  role="group"
  aria-label={label}
  data-markas-toggle-group={type}
  class:list={[root, className]}
  {...rest}
>
  {
    items.map((entry, index) => {
      const isOn = selected.includes(entry.value);
      return (
        <button
          type="button"
          data-value={entry.value}
          aria-pressed={isOn ? "true" : "false"}
          data-state={isOn ? "on" : "off"}
          tabindex={entry.value === tabStop ? "0" : "-1"}
          aria-label={entry.ariaLabel}
          class={item}
        >
          {labels[index] === null ? entry.label : <Fragment set:html={labels[index]} />}
        </button>
      );
    })
  }
</div>

<script>
  // One set of listeners per page serves every toggle group, including markup added later.
  const STEPS: Record<string, number> = { ArrowRight: 1, ArrowLeft: -1 };

  const itemsOf = (group: Element) =>
    Array.from(group.querySelectorAll<HTMLButtonElement>(":scope > button"));

  const groupOf = (target: EventTarget | null) =>
    target instanceof Element
      ? target.closest<HTMLElement>("[data-markas-toggle-group]")
      : null;

  // Roving tabindex: only the last focused or clicked item is in the tab order.
  function rove(group: Element, current: HTMLButtonElement) {
    for (const button of itemsOf(group))
      button.tabIndex = button === current ? 0 : -1;
  }

  function press(button: HTMLButtonElement, pressed: boolean) {
    button.setAttribute("aria-pressed", String(pressed));
    button.dataset.state = pressed ? "on" : "off";
  }

  document.addEventListener("click", (event) => {
    const group = groupOf(event.target);
    const button = (event.target as Element).closest("button");
    if (!group || !button || button.parentElement !== group) return;
    const isOn = button.getAttribute("aria-pressed") === "true";
    if (!isOn && group.dataset.markasToggleGroup !== "multiple")
      for (const other of itemsOf(group)) press(other, false);
    press(button, !isOn);
    rove(group, button);
  });

  document.addEventListener("keydown", (event) => {
    const group = groupOf(event.target);
    const step = STEPS[event.key];
    if (!group || step === undefined) return;
    event.preventDefault();
    const buttons = itemsOf(group);
    const index = buttons.indexOf(document.activeElement as HTMLButtonElement);
    const target = buttons[(index + step + buttons.length) % buttons.length];
    if (!target) return;
    rove(group, target);
    target.focus();
  });
</script>
```

```astro
---
import ToggleGroup from "@/components/markas/ToggleGroup.astro";
---

<ToggleGroup
  label="Tampilan kalender"
  value="week"
  items={[
    { value: "day", label: "Hari" },
    { value: "week", label: "Minggu" },
    { value: "month", label: "Bulan" },
  ]}
/>
```

Ganti label dengan ikon lewat slot bernama sesuai value, misalnya `<Fragment slot="left">`. Script kecil di halaman menangani klik dan tombol panah.

### Angular

Simpan di `src/app/markas/toggle-group.component.ts`. Tanpa dependensi tambahan.

```ts
import { NgTemplateOutlet } from "@angular/common";
import {
  ChangeDetectionStrategy,
  Component,
  computed,
  contentChildren,
  Directive,
  inject,
  input,
  model,
  signal,
  TemplateRef,
} from "@angular/core";

const root = "inline-flex items-center gap-1 rounded-lg bg-subtle p-1";
const item =
  "inline-flex h-8 items-center justify-center gap-2 rounded-md px-3 text-sm font-medium whitespace-nowrap text-muted transition-colors duration-150 ease-out hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary data-[state=on]:bg-surface data-[state=on]:text-ink motion-reduce:transition-none [&_svg]:size-4 [&_svg]:shrink-0";

const STEPS: Record<string, number> = { ArrowRight: 1, ArrowLeft: -1 };

export type ToggleGroupItem = {
  value: string;
  label: string;
  ariaLabel?: string;
};

const toArray = (value: string | string[] | undefined) =>
  Array.isArray(value) ? value : value ? [value] : [];

/**
 * Replaces the label of the item with the same value, for example with an icon:
 * `<ng-template markasToggleGroupItem="left"><svg ...></svg></ng-template>`.
 */
@Directive({ selector: "ng-template[markasToggleGroupItem]" })
export class ToggleGroupItemTemplate {
  readonly value = input.required<string>({ alias: "markasToggleGroupItem" });
  readonly template = inject(TemplateRef);
}

/** Host stays out of layout (display: contents). class moves to the group. */
@Component({
  selector: "markas-toggle-group",
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [NgTemplateOutlet],
  host: { class: "contents", "[attr.label]": "null", "[attr.type]": "null" },
  template: `
    <div
      role="group"
      [attr.aria-label]="label() ?? null"
      [class]="rootClass()"
      (keydown)="handleKeydown($event)"
    >
      @for (entry of items(); track entry.value) {
        <button
          type="button"
          [attr.data-value]="entry.value"
          [attr.aria-pressed]="selected().includes(entry.value)"
          [attr.data-state]="selected().includes(entry.value) ? 'on' : 'off'"
          [tabIndex]="entry.value === tabStop() ? 0 : -1"
          [attr.aria-label]="entry.ariaLabel ?? null"
          [class]="item"
          (click)="toggle(entry.value)"
        >
          @if (templateFor(entry.value); as custom) {
            <ng-container [ngTemplateOutlet]="custom" />
          } @else {
            {{ entry.label }}
          }
        </button>
      }
    </div>
  `,
})
export class ToggleGroup {
  readonly items = input.required<ToggleGroupItem[]>();
  readonly label = input<string>();
  readonly type = input<"single" | "multiple">("single");
  readonly userClass = input("", { alias: "class" });
  /** Pressed items, two-way bindable with [(value)]. A string for single, an array for multiple. */
  readonly value = model<string | string[]>();

  protected readonly item = item;
  private readonly templates = contentChildren(ToggleGroupItemTemplate);
  private readonly focused = signal<string | undefined>(undefined);
  protected readonly selected = computed(() => toArray(this.value()));
  protected readonly tabStop = computed(
    () => this.focused() ?? this.selected()[0] ?? this.items()[0]?.value,
  );
  protected readonly rootClass = computed(() =>
    [root, this.userClass()].filter(Boolean).join(" "),
  );

  protected templateFor(value: string) {
    return this.templates().find((entry) => entry.value() === value)?.template;
  }

  protected toggle(key: string) {
    this.focused.set(key);
    const selected = this.selected();
    const wanted = selected.includes(key)
      ? selected.filter((entry) => entry !== key)
      : this.type() === "multiple"
        ? [...selected, key]
        : [key];
    const next = this.items()
      .map((entry) => entry.value)
      .filter((entry) => wanted.includes(entry));
    this.value.set(this.type() === "multiple" ? next : (next[0] ?? ""));
  }

  protected handleKeydown(event: KeyboardEvent) {
    const step = STEPS[event.key];
    if (step === undefined) return;
    event.preventDefault();
    const group = event.currentTarget as HTMLElement;
    const buttons = Array.from(
      group.querySelectorAll<HTMLButtonElement>(":scope > button"),
    );
    const index = buttons.indexOf(document.activeElement as HTMLButtonElement);
    const target = buttons[(index + step + buttons.length) % buttons.length];
    if (!target) return;
    this.focused.set(target.dataset["value"]);
    target.focus();
  }
}
```

```ts
import { Component, signal } from "@angular/core";
import {
  ToggleGroup,
  ToggleGroupItemTemplate,
} from "./markas/toggle-group.component";

@Component({
  selector: "app-kalender",
  imports: [ToggleGroup, ToggleGroupItemTemplate],
  template: `
    <markas-toggle-group
      [(value)]="view"
      label="Tampilan kalender"
      [items]="views"
    />
    <markas-toggle-group label="Perataan teks" value="left" [items]="align">
      <ng-template markasToggleGroupItem="left">
        <svg viewBox="0 0 24 24" aria-hidden="true">...</svg>
      </ng-template>
    </markas-toggle-group>
  `,
})
export class Kalender {
  readonly view = signal<string | string[]>("week");
  readonly views = [
    { value: "day", label: "Hari" },
    { value: "week", label: "Minggu" },
    { value: "month", label: "Bulan" },
  ];
  readonly align = [{ value: "left", label: "Kiri", ariaLabel: "Rata kiri" }];
}
```

## Props

| Nama | Tipe | Default | Keterangan |
| --- | --- | --- | --- |
| `items` | `{ value, label, ariaLabel? }[]` | [] | Tombol di dalam grup. ariaLabel wajib kalau label hanya ikon. Blade, Vue, dan Astro bisa mengganti label lewat slot bernama sesuai value, Svelte menerima snippet sebagai label, Angular memakai ng-template dengan markasToggleGroupItem berisi value. |
| `type` | `'single' \| 'multiple'` | 'single' | Single mengizinkan satu item ditekan, atau tidak ada. Multiple mengizinkan berapa pun. |
| `value / defaultValue / v-model / bind:value` | `string \| string[]` | - | Item yang ditekan. String untuk single (kosong kalau tidak ada) dan array untuk multiple. Blade dan Astro memakai value, React value atau defaultValue, Vue v-model atau defaultValue, Svelte bind:value, Angular value atau [(value)]. |
| `onValueChange` | `(value: string \| string[]) => void` | - | Khusus React. Dipanggil dengan nilai baru setiap kali berubah, urut sesuai item untuk multiple. |
| `label` | `string` | - | Nama aksesibel grup, dipasang sebagai aria-label. |

## Aksesibilitas

- Wadah memiliki role group dan aria-label dari label, setiap item adalah button dengan aria-pressed.
- Tab masuk ke grup sekali. Panah kiri dan kanan memindah fokus antar item (roving tabindex), Spasi dan Enter menekan item yang difokus.
- Item berisi ikon saja wajib diberi ariaLabel agar setiap tombol punya nama.

## Catatan

- Single menghasilkan string, kosong kalau item yang ditekan diklik lagi. Multiple menghasilkan array urut sesuai item.
- Value menjadi nama slot di Blade, Vue, dan Astro, jadi pakai hanya huruf kecil, angka, atau garis bawah.
- Komponen ini tidak punya teks bawaan. Isi `label` dan label item dalam Bahasa Indonesia.
