# Toggle

Tombol dua keadaan dengan aria-pressed untuk opsi seperti tebal atau tandai, dalam varian default dan outline serta tiga ukuran.

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

## Kapan dipakai

Satu opsi nyala/mati yang berperilaku seperti tombol, misalnya tebal di toolbar, bisukan, atau tandai.

- Pakai Switch untuk pengaturan di form dan Checkbox untuk nilai yang dikirim
- Label tetap sama di kedua keadaan, gaya ditekan yang menunjukkan keadaan
- Pakai Toggle group untuk sekumpulan toggle yang saling terkait

## Kode

### Blade

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

```blade
@props([
    'variant' => 'default',
    'size' => 'md',
    'pressed' => false,
])

@php
    $base = 'inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-subtle data-[state=on]:text-ink motion-reduce:transition-none [&_svg]:size-4 [&_svg]:shrink-0';
    $variants = [
        'default' => 'bg-transparent',
        'outline' => 'border border-line bg-surface',
    ];
    $sizes = [
        'sm' => 'h-8 min-w-8 px-2',
        'md' => 'h-9 min-w-9 px-2.5',
        'lg' => 'h-10 min-w-10 px-3',
    ];
@endphp

{{-- wire:model and x-model bind to the pressed state (x-modelable). --}}
<button
    x-data="{ pressed: @js((bool) $pressed) }"
    x-modelable="pressed"
    x-on:click="pressed = !pressed"
    x-bind:aria-pressed="pressed ? 'true' : 'false'"
    x-bind:data-state="pressed ? 'on' : 'off'"
    aria-pressed="{{ $pressed ? 'true' : 'false' }}"
    data-state="{{ $pressed ? 'on' : 'off' }}"
    {{ $attributes->merge(['type' => 'button'])->class([$base, $variants[$variant], $sizes[$size]]) }}
>
    {{ $slot }}
</button>
```

```blade
<x-markas.toggle aria-label="Tebal" pressed>
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7 5h6a3.5 3.5 0 0 1 0 7H7zm0 7h7a3.5 3.5 0 0 1 0 7H7z" /></svg>
</x-markas.toggle>
<x-markas.toggle variant="outline">Tandai</x-markas.toggle>
```

Butuh Alpine.js.

### Livewire

```blade
<x-markas.toggle wire:model.live="bold" aria-label="Bold">B</x-markas.toggle>
```

`wire:model` terhubung ke status ditekan sebagai boolean.

### React

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

```tsx
"use client";

import { useState, type ComponentProps, type MouseEvent } from "react";

const base =
  "inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-subtle data-[state=on]:text-ink motion-reduce:transition-none [&_svg]:size-4 [&_svg]:shrink-0";
const variants = {
  default: "bg-transparent",
  outline: "border border-line bg-surface",
};
const sizes = {
  sm: "h-8 min-w-8 px-2",
  md: "h-9 min-w-9 px-2.5",
  lg: "h-10 min-w-10 px-3",
};
const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");

export type ToggleProps = ComponentProps<"button"> & {
  variant?: keyof typeof variants;
  size?: keyof typeof sizes;
  pressed?: boolean;
  defaultPressed?: boolean;
  onPressedChange?: (pressed: boolean) => void;
};

export function Toggle({
  variant = "default",
  size = "md",
  pressed,
  defaultPressed = false,
  onPressedChange,
  onClick,
  className,
  type = "button",
  ...props
}: ToggleProps) {
  const [internal, setInternal] = useState(defaultPressed);
  const isPressed = pressed ?? internal;

  const handleClick = (event: MouseEvent<HTMLButtonElement>) => {
    onClick?.(event);
    if (event.defaultPrevented) return;
    setInternal(!isPressed);
    onPressedChange?.(!isPressed);
  };

  return (
    <button
      type={type}
      aria-pressed={isPressed}
      data-state={isPressed ? "on" : "off"}
      onClick={handleClick}
      className={cx(base, variants[variant], sizes[size], className)}
      {...props}
    />
  );
}
```

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

<Toggle aria-label="Tebal" defaultPressed onPressedChange={setTebal}>
  <BoldIcon aria-hidden="true" />
</Toggle>;
<Toggle variant="outline">Tandai</Toggle>;
```

### Vue

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

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

const variants = {
  default: "bg-transparent",
  outline: "border border-line bg-surface",
};
const sizes = {
  sm: "h-8 min-w-8 px-2",
  md: "h-9 min-w-9 px-2.5",
  lg: "h-10 min-w-10 px-3",
};

const props = withDefaults(
  defineProps<{
    variant?: keyof typeof variants;
    size?: keyof typeof sizes;
    defaultPressed?: boolean;
  }>(),
  { variant: "default", size: "md", defaultPressed: false },
);
const model = defineModel<boolean | undefined>({ default: undefined });

const base =
  "inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-subtle data-[state=on]:text-ink motion-reduce:transition-none [&_svg]:size-4 [&_svg]:shrink-0";

const isPressed = computed(() => model.value ?? props.defaultPressed);
</script>

<template>
  <button
    type="button"
    :aria-pressed="isPressed ? 'true' : 'false'"
    :data-state="isPressed ? 'on' : 'off'"
    :class="[base, variants[props.variant], sizes[props.size]]"
    @click="model = !isPressed"
  >
    <slot />
  </button>
</template>
```

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

const tebal = ref(true);
</script>

<template>
  <Toggle v-model="tebal" aria-label="Tebal">
    <BoldIcon aria-hidden="true" />
  </Toggle>
  <Toggle variant="outline">Tandai</Toggle>
</template>
```

### Svelte

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

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

  const base =
    "inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-subtle data-[state=on]:text-ink motion-reduce:transition-none [&_svg]:size-4 [&_svg]:shrink-0";
  const variants = {
    default: "bg-transparent",
    outline: "border border-line bg-surface",
  };
  const sizes = {
    sm: "h-8 min-w-8 px-2",
    md: "h-9 min-w-9 px-2.5",
    lg: "h-10 min-w-10 px-3",
  };

  type Props = HTMLButtonAttributes & {
    variant?: keyof typeof variants;
    size?: keyof typeof sizes;
    /** Pressed state, bindable with bind:pressed. */
    pressed?: boolean;
  };

  let {
    variant = "default",
    size = "md",
    pressed = $bindable(false),
    type = "button",
    class: className,
    onclick,
    children,
    ...rest
  }: Props = $props();

  function handleClick(
    event: MouseEvent & { currentTarget: EventTarget & HTMLButtonElement },
  ) {
    onclick?.(event);
    if (event.defaultPrevented) return;
    pressed = !pressed;
  }
</script>

<button
  {type}
  aria-pressed={pressed ? "true" : "false"}
  data-state={pressed ? "on" : "off"}
  onclick={handleClick}
  class={[base, variants[variant], sizes[size], className]}
  {...rest}
>
  {@render children?.()}
</button>
```

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

  let tebal = $state(true);
</script>

<Toggle bind:pressed={tebal} aria-label="Tebal">
  <svg
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    stroke-width="1.5"
    aria-hidden="true"
    ><path d="M7 5h6a3.5 3.5 0 0 1 0 7H7zm0 7h7a3.5 3.5 0 0 1 0 7H7z" /></svg
  >
</Toggle>
<Toggle variant="outline">Tandai</Toggle>
```

### Astro

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

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

const base =
  "inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-subtle data-[state=on]:text-ink motion-reduce:transition-none [&_svg]:size-4 [&_svg]:shrink-0";
const variants = {
  default: "bg-transparent",
  outline: "border border-line bg-surface",
};
const sizes = {
  sm: "h-8 min-w-8 px-2",
  md: "h-9 min-w-9 px-2.5",
  lg: "h-10 min-w-10 px-3",
};

type Props = HTMLAttributes<"button"> & {
  variant?: keyof typeof variants;
  size?: keyof typeof sizes;
  pressed?: boolean;
};

const {
  variant = "default",
  size = "md",
  pressed = false,
  type = "button",
  class: className,
  ...rest
} = Astro.props;
---

<button
  type={type}
  aria-pressed={pressed ? "true" : "false"}
  data-state={pressed ? "on" : "off"}
  data-markas-toggle
  class:list={[base, variants[variant], sizes[size], className]}
  {...rest}
>
  <slot />
</button>

<script>
  // One listener per page serves every toggle, including markup added later.
  document.addEventListener("click", (event) => {
    if (event.defaultPrevented || !(event.target instanceof Element)) return;
    const toggle = event.target.closest<HTMLElement>("[data-markas-toggle]");
    if (!toggle) return;
    const pressed = toggle.getAttribute("aria-pressed") !== "true";
    toggle.setAttribute("aria-pressed", String(pressed));
    toggle.dataset.state = pressed ? "on" : "off";
  });
</script>
```

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

<Toggle variant="outline" pressed>Tandai</Toggle>
```

Script kecil di halaman membalik `aria-pressed` dan `data-state` saat diklik.

### Angular

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

```ts
import {
  booleanAttribute,
  ChangeDetectionStrategy,
  Component,
  computed,
  input,
  linkedSignal,
  output,
} from "@angular/core";

const base =
  "inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-subtle data-[state=on]:text-ink motion-reduce:transition-none [&_svg]:size-4 [&_svg]:shrink-0";
const variants = {
  default: "bg-transparent",
  outline: "border border-line bg-surface",
};
const sizes = {
  sm: "h-8 min-w-8 px-2",
  md: "h-9 min-w-9 px-2.5",
  lg: "h-10 min-w-10 px-3",
};

export type ToggleVariant = keyof typeof variants;
export type ToggleSize = keyof typeof sizes;

/**
 * Attribute selector on the native button: disabled, aria-label, and the user's class stay on
 * the button itself.
 */
@Component({
  selector: "button[markas-toggle]",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    "[attr.type]": "type()",
    "[attr.aria-pressed]": "on() ? 'true' : 'false'",
    "[attr.data-state]": "on() ? 'on' : 'off'",
    "[class]": "classes()",
    "(click)": "toggle($event)",
  },
  template: `<ng-content />`,
})
export class Toggle {
  readonly variant = input<ToggleVariant>("default");
  readonly size = input<ToggleSize>("md");
  readonly type = input<"button" | "submit" | "reset">("button");
  readonly pressed = input(false, { transform: booleanAttribute });
  /** Emits the new state; together with `pressed` this enables `[(pressed)]`. */
  readonly pressedChange = output<boolean>();

  protected readonly on = linkedSignal(() => this.pressed());
  protected readonly classes = computed(
    () => `${base} ${variants[this.variant()]} ${sizes[this.size()]}`,
  );

  protected toggle(event: MouseEvent) {
    if (event.defaultPrevented) return;
    const next = !this.on();
    this.on.set(next);
    this.pressedChange.emit(next);
  }
}
```

```ts
import { Component, signal } from "@angular/core";
import { Toggle } from "./markas/toggle.component";

@Component({
  selector: "app-penyunting",
  imports: [Toggle],
  template: `
    <button markas-toggle [(pressed)]="tebal" aria-label="Tebal">B</button>
    <button markas-toggle variant="outline">Tandai</button>
  `,
})
export class Penyunting {
  readonly tebal = signal(true);
}
```

## Props

| Nama | Tipe | Default | Keterangan |
| --- | --- | --- | --- |
| `variant` | `'default' \| 'outline'` | 'default' | Tampilan toggle. Outline menambahkan border dan latar surface. |
| `size` | `'sm' \| 'md' \| 'lg'` | 'md' | Tinggi 32, 36, atau 40px. Lebar minimum sama dengan tinggi untuk toggle berisi ikon saja. |
| `pressed / defaultPressed / v-model / bind:pressed` | `boolean` | false | Keadaan ditekan. Blade dan Astro memakai pressed, React pressed atau defaultPressed, Vue v-model atau defaultPressed, Svelte bind:pressed, Angular pressed atau [(pressed)]. |
| `onPressedChange` | `(pressed: boolean) => void` | - | Khusus React. Dipanggil dengan keadaan baru setiap kali diklik. |
| `pressedChange` | `output<boolean>` | - | Khusus Angular. Memancarkan keadaan baru setiap kali diklik. |
| `disabled` | `boolean` | false | Menonaktifkan toggle. |

## Aksesibilitas

- Button native dengan aria-pressed, sehingga screen reader membacakannya sebagai tombol toggle yang ditekan atau tidak.
- Spasi dan Enter mengubah keadaan secara native.
- Toggle yang hanya berisi ikon wajib diberi aria-label, dan ikonnya aria-hidden.

## Catatan

- Toggle adalah `<button aria-pressed>`. Tampilannya mengikuti `data-state="on"` atau `"off"`.
- Ikon di dalamnya otomatis berukuran `size-4`. Toggle yang hanya berisi ikon wajib diberi `aria-label`.
- Komponen ini tidak punya teks bawaan. Cukup isi konten dan `aria-label` dalam Bahasa Indonesia.
