# Label

Label form dengan gaya konsisten serta penanda wajib atau opsional yang dibacakan screen reader dengan benar.

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

## Kapan dipakai

Label untuk kontrol form yang tidak merender label sendiri, atau untuk kontrol kustom dan grup kolom.

- Selalu hubungkan label ke kontrol lewat for dan id, atau bungkus kontrol di dalam label
- Tetap pasang atribut required di kontrolnya; penanda di label hanya tampilan dan teks yang dibacakan
- Dalam satu form tandai kolom wajib atau kolom opsional saja, pilih kelompok yang lebih sedikit

## Kode

### Blade

Simpan di `resources/views/components/markas/label.blade.php`. Tanpa dependensi tambahan.

```blade
@props([
    'required' => false,
    'optional' => false,
    'requiredLabel' => 'required',
    'optionalLabel' => 'Optional',
])

@php
    $base = 'text-sm font-medium text-ink';
    $marker = 'ms-0.5 text-danger';
    $srOnly = 'sr-only';
    $optionalClass = 'font-normal text-muted';
@endphp

<label {{ $attributes->class([$base]) }}>{{ $slot }}@if ($required)<span aria-hidden="true" class="{{ $marker }}">*</span>{{ ' ' }}<span class="{{ $srOnly }}">{{ $requiredLabel }}</span>@elseif ($optional){{ ' ' }}<span class="{{ $optionalClass }}">{{ $optionalLabel }}</span>@endif</label>
```

```blade
<x-markas.label for="full_name" required required-label="wajib">Nama lengkap</x-markas.label>
<input id="full_name" name="full_name" required />

<x-markas.label for="company" optional optional-label="Opsional">Perusahaan</x-markas.label>
<input id="company" name="company" />
```

### React

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

```tsx
import type { ComponentProps } from "react";

const base = "text-sm font-medium text-ink";
const marker = "ms-0.5 text-danger";
const srOnly = "sr-only";
const optionalClass = "font-normal text-muted";
const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");

export type LabelProps = ComponentProps<"label"> & {
  required?: boolean;
  optional?: boolean;
  requiredLabel?: string;
  optionalLabel?: string;
};

export function Label({
  required = false,
  optional = false,
  requiredLabel = "required",
  optionalLabel = "Optional",
  className,
  children,
  ...props
}: LabelProps) {
  return (
    <label className={cx(base, className)} {...props}>
      {children}
      {required ? (
        <>
          <span aria-hidden="true" className={marker}>
            *
          </span>{" "}
          <span className={srOnly}>{requiredLabel}</span>
        </>
      ) : optional ? (
        <>
          {" "}
          <span className={optionalClass}>{optionalLabel}</span>
        </>
      ) : null}
    </label>
  );
}
```

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

<Label htmlFor="full_name" required requiredLabel="wajib">Nama lengkap</Label>
<input id="full_name" name="full_name" required />

<Label htmlFor="company" optional optionalLabel="Opsional">Perusahaan</Label>
<input id="company" name="company" />
```

### Vue

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

```vue
<script setup lang="ts">
const props = withDefaults(
  defineProps<{
    required?: boolean;
    optional?: boolean;
    requiredLabel?: string;
    optionalLabel?: string;
  }>(),
  {
    required: false,
    optional: false,
    requiredLabel: "required",
    optionalLabel: "Optional",
  },
);

const base = "text-sm font-medium text-ink";
const marker = "ms-0.5 text-danger";
const srOnly = "sr-only";
const optionalClass = "font-normal text-muted";
</script>

<template>
  <label :class="base"
    ><slot /><template v-if="props.required"
      ><span aria-hidden="true" :class="marker">*</span>{{ " "
      }}<span :class="srOnly">{{ props.requiredLabel }}</span></template
    ><template v-else-if="props.optional"
      >{{ " "
      }}<span :class="optionalClass">{{ props.optionalLabel }}</span></template
    ></label
  >
</template>
```

```vue
<script setup lang="ts">
import Label from "@/components/markas/Label.vue";
</script>

<template>
  <Label for="full_name" required required-label="wajib">Nama lengkap</Label>
  <input id="full_name" name="full_name" required />

  <Label for="company" optional optional-label="Opsional">Perusahaan</Label>
  <input id="company" name="company" />
</template>
```

### Svelte

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

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

  const base = "text-sm font-medium text-ink";
  const marker = "ms-0.5 text-danger";
  const srOnly = "sr-only";
  const optionalClass = "font-normal text-muted";

  type Props = HTMLLabelAttributes & {
    required?: boolean;
    optional?: boolean;
    requiredLabel?: string;
    optionalLabel?: string;
    children?: Snippet;
  };

  let {
    required = false,
    optional = false,
    requiredLabel = "required",
    optionalLabel = "Optional",
    class: className,
    children,
    ...rest
  }: Props = $props();
</script>

<label class={[base, className]} {...rest}
  >{@render children?.()}{#if required}<span aria-hidden="true" class={marker}
      >*</span
    >{" "}<span class={srOnly}>{requiredLabel}</span
    >{:else if optional}{" "}<span class={optionalClass}>{optionalLabel}</span
    >{/if}</label
>
```

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

<Label for="full_name" required requiredLabel="wajib">Nama lengkap</Label>
<input id="full_name" name="full_name" required />

<Label for="company" optional optionalLabel="Opsional">Perusahaan</Label>
<input id="company" name="company" />
```

### Astro

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

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

const base = "text-sm font-medium text-ink";
const marker = "ms-0.5 text-danger";
const srOnly = "sr-only";
const optionalClass = "font-normal text-muted";

type Props = HTMLAttributes<"label"> & {
  required?: boolean;
  optional?: boolean;
  requiredLabel?: string;
  optionalLabel?: string;
};

const {
  required = false,
  optional = false,
  requiredLabel = "required",
  optionalLabel = "Optional",
  class: className,
  ...rest
} = Astro.props;
---

<label class:list={[base, className]} {...rest}><slot />{required ? <Fragment><span aria-hidden="true" class={marker}>*</span>{" "}<span class={srOnly}>{requiredLabel}</span></Fragment> : optional ? <Fragment>{" "}<span class={optionalClass}>{optionalLabel}</span></Fragment> : null}</label>
```

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

<Label for="full_name" required requiredLabel="wajib">Nama lengkap</Label>
<input id="full_name" name="full_name" required />

<Label for="company" optional optionalLabel="Opsional">Perusahaan</Label>
<input id="company" name="company" />
```

### Angular

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

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

const base = "text-sm font-medium text-ink";
const marker = "ms-0.5 text-danger";
const srOnly = "sr-only";
const optionalClass = "font-normal text-muted";

/**
 * Attribute selector on the native label: for, id, and the user's class stay on the label
 * itself, so nothing has to be forwarded.
 */
@Component({
  selector: "label[markas-label]",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { "[class]": "base" },
  // Kept on one line: formatting would add whitespace text around the marker and the optional text.
  // prettier-ignore
  template: `<ng-content />@if (required()) {<span aria-hidden="true" [class]="marker">*</span>{{ " " }}<span [class]="srOnly">{{ requiredLabel() }}</span>} @else if (optional()) {{{ " " }}<span [class]="optionalClass">{{ optionalLabel() }}</span>}`,
})
export class Label {
  readonly required = input(false, { transform: booleanAttribute });
  readonly optional = input(false, { transform: booleanAttribute });
  /** Screen reader text after the required marker. */
  readonly requiredLabel = input("required");
  /** Visible text after an optional label. */
  readonly optionalLabel = input("Optional");

  protected readonly base = base;
  protected readonly marker = marker;
  protected readonly srOnly = srOnly;
  protected readonly optionalClass = optionalClass;
}
```

```ts
import { Component } from "@angular/core";
import { Label } from "./markas/label.component";

@Component({
  selector: "app-profile-form",
  imports: [Label],
  template: `
    <label markas-label for="full_name" required requiredLabel="wajib"
      >Nama lengkap</label
    >
    <input id="full_name" name="full_name" required />

    <label markas-label for="company" optional optionalLabel="Opsional"
      >Perusahaan</label
    >
    <input id="company" name="company" />
  `,
})
export class ProfileForm {}
```

Di Angular, Label adalah atribut pada `<label>` native, jadi `for`, `id`, dan `class` tetap di elemen itu.

## Props

| Nama | Tipe | Default | Keterangan |
| --- | --- | --- | --- |
| `for / htmlFor` | `string` | - | Id kontrol form yang diberi nama oleh label ini. React memakai htmlFor. Di Angular, Label adalah atribut pada label native (<label markas-label for="...">). |
| `required` | `boolean` | false | Menampilkan tanda bintang merah (disembunyikan dari screen reader) dan teks khusus screen reader dari requiredLabel. Lebih diutamakan daripada optional. |
| `optional` | `boolean` | false | Menampilkan teks redup dari optionalLabel setelah teks label. |
| `requiredLabel` | `string` | required | Teks screen reader untuk kolom wajib. Isi misalnya "wajib". |
| `optionalLabel` | `string` | Optional | Teks terlihat untuk kolom opsional. Isi misalnya "Opsional". |

## Aksesibilitas

- Merender elemen label native, jadi mengekliknya memfokuskan atau mengubah kontrol yang terhubung.
- Tanda bintang memakai aria-hidden; status wajib dibacakan lewat teks khusus screen reader.
- Teks opsional adalah bagian label, jadi ikut masuk nama aksesibel kontrol.

## Catatan

- Label tidak butuh JavaScript. Atribut tambahan dan `class` jatuh ke elemen `<label>`, dan class Anda ditaruh paling akhir.
- Checkbox atau radio juga bisa dibungkus langsung di dalam label tanpa `for`: `<Label class="flex items-center gap-2"><input type="checkbox" />Ingat saya</Label>`.
- Tanda bintang disembunyikan dari screen reader. Screen reader membacakan "Nama lengkap wajib" dari `requiredLabel`. Kalau `required` dan `optional` sama-sama aktif, `required` yang dipakai.
- Teks bawaan berbahasa Inggris: `requiredLabel` (default "required") dan `optionalLabel` (default "Optional"). Isi keduanya untuk situs berbahasa Indonesia.
