APG Patterns
English GitHub
English GitHub

Radio Group

一度に1つだけチェックできる、チェック可能なボタンのセット。

🤖 AI Implementation Guide

デモ

基本的な Radio Group

矢印キーで移動と選択を行います。Tab キーでグループの内外にフォーカスを移動します。

デフォルト値を含む Radio Group

defaultValue プロパティを使用して事前に選択されたオプション。

無効なオプションを含む Radio Group

無効なオプションは、キーボードナビゲーション中にスキップされます。

水平方向の Radio Group

orientation="horizontal" による水平レイアウト。

Native HTML

Use Native HTML First

Before using this custom component, consider using native <input type="radio"> elements with <fieldset> and <legend>. They provide built-in accessibility, work without JavaScript, and require no ARIA attributes.

<fieldset>
  <legend>Favorite color</legend>
  <label><input type="radio" name="color" value="red" /> Red</label>
  <label><input type="radio" name="color" value="blue" /> Blue</label>
  <label><input type="radio" name="color" value="green" /> Green</label>
</fieldset>

Use custom implementations when you need consistent cross-browser keyboard behavior or custom styling that native elements cannot provide.

Use Case Native HTML Custom Implementation
Basic form input Recommended Not needed
JavaScript disabled support Works natively Requires fallback
Arrow key navigation Browser-dependent* Consistent behavior
Custom styling Limited (browser-dependent) Full control
Form submission Built-in Requires hidden input

*Native radio keyboard behavior varies between browsers. Some browsers may not support all APG keyboard interactions (like Home/End) out of the box.

アクセシビリティ

WAI-ARIA ロール

ロール 要素 説明
radiogroup コンテナ要素 ラジオボタンをグループ化します。aria-label または aria-labelledby によるアクセシブルな名前が必須です。
radio 各オプション要素 要素をラジオボタンとして識別します。グループ内で一度に1つのラジオのみが選択可能です。

この実装では、クロスブラウザでの一貫したキーボード動作のため、カスタムの role="radiogroup"role="radio" を使用しています。ネイティブの <input type="radio"> はこれらのロールを暗黙的に提供します。

WAI-ARIA ステート

aria-checked

ラジオボタンの現在のチェック状態を示します。グループ内で1つのラジオのみが aria-checked="true" を持つべきです。

true | false
必須 はい(各ラジオボタンに)
変更トリガー クリック、Space、矢印キー

aria-disabled

ラジオボタンがインタラクティブでなく、選択できないことを示します。

true(無効時のみ)
必須 いいえ(無効時のみ)
効果 矢印キーナビゲーション中はスキップされ、選択できません

WAI-ARIA プロパティ

aria-orientation

ラジオグループの方向を示します。垂直がデフォルトです。

horizontal | vertical(デフォルト)
必須 いいえ(水平方向時のみ設定)
注記 この実装では、方向に関わらずすべての矢印キーをサポートします

キーボードサポート

キー アクション
Tab グループにフォーカスを移動(選択されたラジオまたは最初のラジオへ)
Shift + Tab グループからフォーカスを移動
Space フォーカスされたラジオを選択(選択解除はしない)
Arrow Down / Right 次のラジオに移動して選択(最初にラップ)
Arrow Up / Left 前のラジオに移動して選択(最後にラップ)
Home 最初のラジオに移動して選択
End 最後のラジオに移動して選択

注記: チェックボックスとは異なり、矢印キーはフォーカス移動と選択変更の両方を行います。無効化されたラジオはナビゲーション中にスキップされます。

フォーカス管理(ローヴィングタブインデックス)

ラジオグループはローヴィングタブインデックスを使用してフォーカスを管理します。グループ内で一度に1つのラジオのみがタブ可能です:

  • 選択されたラジオtabindex="0" を持ちます
  • 何も選択されていない場合、最初の有効なラジオが tabindex="0" を持ちます
  • 他のすべてのラジオtabindex="-1" を持ちます
  • 無効なラジオ は常に tabindex="-1" を持ちます

アクセシブルな名前付け

ラジオグループと個々のラジオの両方にアクセシブルな名前が必要です:

  • ラジオグループ - コンテナに aria-label または aria-labelledby を使用します
  • 個々のラジオ - 各ラジオは aria-labelledby を介して可視テキストコンテンツでラベル付けされます
  • ネイティブの代替 - グループのラベル付けには <fieldset><legend> を使用します

ビジュアルデザイン

この実装は、状態を示すために色のみに依存しないことで WCAG 1.4.1(色の使用)に従っています:

  • 塗りつぶされた円 - 選択状態を示します
  • 空の円 - 未選択状態を示します
  • 不透明度の低下 - 無効状態を示します
  • 強制カラーモード - Windows ハイコントラストモードでのアクセシビリティのためシステムカラーを使用します

References

ソースコード

RadioGroup.vue
<template>
  <div
    role="radiogroup"
    :aria-label="ariaLabel"
    :aria-labelledby="ariaLabelledby"
    :aria-orientation="orientation === 'horizontal' ? 'horizontal' : undefined"
    :class="['apg-radio-group', props.class]"
  >
    <!-- Hidden input for form submission -->
    <input type="hidden" :name="name" :value="selectedValue" />

    <div
      v-for="option in options"
      :key="option.id"
      :ref="(el) => setRadioRef(option.value, el as HTMLDivElement | null)"
      role="radio"
      :aria-checked="selectedValue === option.value"
      :aria-disabled="option.disabled || undefined"
      :aria-labelledby="`${instanceId}-label-${option.id}`"
      :tabindex="getTabIndex(option)"
      :class="[
        'apg-radio',
        selectedValue === option.value && 'apg-radio--selected',
        option.disabled && 'apg-radio--disabled',
      ]"
      @click="handleClick(option)"
      @keydown="(e) => handleKeyDown(e, option.value)"
    >
      <span class="apg-radio-control" aria-hidden="true">
        <span class="apg-radio-indicator" />
      </span>
      <span :id="`${instanceId}-label-${option.id}`" class="apg-radio-label">
        {{ option.label }}
      </span>
    </div>
  </div>
</template>

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

export interface RadioOption {
  id: string;
  label: string;
  value: string;
  disabled?: boolean;
}

export interface RadioGroupProps {
  /** Radio options */
  options: RadioOption[];
  /** Group name for form submission */
  name: string;
  /** Accessible label for the group */
  ariaLabel?: string;
  /** Reference to external label */
  ariaLabelledby?: string;
  /** Controlled value (for v-model) */
  modelValue?: string;
  /** Initially selected value (uncontrolled) */
  defaultValue?: string;
  /** Orientation of the group */
  orientation?: 'horizontal' | 'vertical';
  /** Additional CSS class */
  class?: string;
}

const props = withDefaults(defineProps<RadioGroupProps>(), {
  ariaLabel: undefined,
  ariaLabelledby: undefined,
  modelValue: undefined,
  defaultValue: '',
  orientation: 'vertical',
  class: undefined,
});

const emit = defineEmits<{
  'update:modelValue': [value: string];
  valueChange: [value: string];
}>();

// Generate unique ID for this instance
const instanceId = `radio-group-${Math.random().toString(36).slice(2, 9)}`;

// Filter enabled options
const enabledOptions = computed(() => props.options.filter((opt) => !opt.disabled));

// Check if controlled mode (v-model provided)
const isControlled = computed(() => props.modelValue !== undefined);

// Find initial value
const getInitialValue = () => {
  // If controlled, use modelValue
  if (props.modelValue !== undefined) {
    const option = props.options.find((opt) => opt.value === props.modelValue);
    if (option && !option.disabled) {
      return props.modelValue;
    }
  }
  // Otherwise use defaultValue
  if (props.defaultValue) {
    const option = props.options.find((opt) => opt.value === props.defaultValue);
    if (option && !option.disabled) {
      return props.defaultValue;
    }
  }
  return '';
};

const internalValue = ref(getInitialValue());

// Computed value that respects controlled/uncontrolled mode
const selectedValue = computed(() => {
  if (isControlled.value) {
    return props.modelValue ?? '';
  }
  return internalValue.value;
});

// Watch for external modelValue changes in controlled mode
watch(
  () => props.modelValue,
  (newValue) => {
    if (newValue !== undefined) {
      internalValue.value = newValue;
    }
  }
);

// Refs for focus management
const radioRefs = new Map<string, HTMLDivElement>();

const setRadioRef = (value: string, el: HTMLDivElement | null) => {
  if (el) {
    radioRefs.set(value, el);
  } else {
    radioRefs.delete(value);
  }
};

// Get the tabbable radio value
const getTabbableValue = () => {
  if (
    selectedValue.value &&
    enabledOptions.value.some((opt) => opt.value === selectedValue.value)
  ) {
    return selectedValue.value;
  }
  return enabledOptions.value[0]?.value || '';
};

const getTabIndex = (option: RadioOption): number => {
  if (option.disabled) return -1;
  return option.value === getTabbableValue() ? 0 : -1;
};

// Focus a radio by value
const focusRadio = (value: string) => {
  const radioEl = radioRefs.get(value);
  radioEl?.focus();
};

// Select a radio
const selectRadio = (value: string) => {
  const option = props.options.find((opt) => opt.value === value);
  if (option && !option.disabled) {
    internalValue.value = value;
    emit('update:modelValue', value);
    emit('valueChange', value);
  }
};

// Get enabled index of a value
const getEnabledIndex = (value: string) => {
  return enabledOptions.value.findIndex((opt) => opt.value === value);
};

// Navigate and select
const navigateAndSelect = (direction: 'next' | 'prev' | 'first' | 'last', currentValue: string) => {
  if (enabledOptions.value.length === 0) return;

  let targetIndex: number;
  const currentIndex = getEnabledIndex(currentValue);

  switch (direction) {
    case 'next':
      targetIndex = currentIndex >= 0 ? (currentIndex + 1) % enabledOptions.value.length : 0;
      break;
    case 'prev':
      targetIndex =
        currentIndex >= 0
          ? (currentIndex - 1 + enabledOptions.value.length) % enabledOptions.value.length
          : enabledOptions.value.length - 1;
      break;
    case 'first':
      targetIndex = 0;
      break;
    case 'last':
      targetIndex = enabledOptions.value.length - 1;
      break;
  }

  const targetOption = enabledOptions.value[targetIndex];
  if (targetOption) {
    focusRadio(targetOption.value);
    selectRadio(targetOption.value);
  }
};

const handleKeyDown = (event: KeyboardEvent, optionValue: string) => {
  const { key } = event;

  switch (key) {
    case 'ArrowDown':
    case 'ArrowRight':
      event.preventDefault();
      navigateAndSelect('next', optionValue);
      break;

    case 'ArrowUp':
    case 'ArrowLeft':
      event.preventDefault();
      navigateAndSelect('prev', optionValue);
      break;

    case 'Home':
      event.preventDefault();
      navigateAndSelect('first', optionValue);
      break;

    case 'End':
      event.preventDefault();
      navigateAndSelect('last', optionValue);
      break;

    case ' ':
      event.preventDefault();
      selectRadio(optionValue);
      break;
  }
};

const handleClick = (option: RadioOption) => {
  if (!option.disabled) {
    focusRadio(option.value);
    selectRadio(option.value);
  }
};
</script>

使い方

使用例
<script setup>
import { RadioGroup } from './RadioGroup.vue';

const options = [
  { id: 'red', label: 'Red', value: 'red' },
  { id: 'blue', label: 'Blue', value: 'blue' },
  { id: 'green', label: 'Green', value: 'green' },
];

const handleChange = (value) => {
  console.log('Selected:', value);
};
</script>

<template>
  <RadioGroup
    :options="options"
    name="color"
    aria-label="Favorite color"
    default-value="blue"
    @value-change="handleChange"
  />
</template>

API

RadioGroupProps

プロパティ デフォルト 説明
options RadioOption[] 必須 ラジオオプションの配列
name string 必須 フォーム送信用のグループ名
aria-label string - グループのアクセシブルなラベル
aria-labelledby string - ラベリング要素の ID
default-value string "" 初期選択値
orientation 'horizontal' | 'vertical' 'vertical' レイアウトの方向
class string - 追加の CSS クラス

イベント

イベント ペイロード 説明
update:modelValue string v-model バインディング用に発行されます
valueChange string 選択が変更されたときに発行されます

RadioOption

型定義
interface RadioOption {
  id: string;
  label: string;
  value: string;
  disabled?: boolean;
}

テスト

テストは、キーボード操作、ARIA属性、フォーカス管理、アクセシビリティ要件全般にわたるAPG準拠を検証します。

テストカテゴリ

高優先度: APG ARIA 属性

テスト 説明
role="radiogroup" コンテナがradiogroupロールを持つ
role="radio" 各オプションがradioロールを持つ
aria-checked 選択されたラジオが aria-checked="true" を持つ
aria-disabled 無効なラジオが aria-disabled="true" を持つ
aria-orientation 水平方向時のみ設定される(垂直がデフォルト)
accessible name グループとラジオがアクセシブルな名前を持つ

高優先度: APG キーボード操作

テスト 説明
Tab focus Tabで選択されたラジオ(または何もなければ最初)にフォーカス
Tab exit Tab/Shift+Tabでグループから退出
Space select Spaceでフォーカスされたラジオを選択
Space no unselect Spaceは既に選択されたラジオの選択を解除しない
ArrowDown/Right 次へ移動して選択
ArrowUp/Left 前へ移動して選択
Home 最初へ移動して選択
End 最後へ移動して選択
Arrow wrap 最後から最初へ、またはその逆にラップ
Disabled skip ナビゲーション中に無効なラジオをスキップ

高優先度: フォーカス管理(ローヴィングタブインデックス)

テスト 説明
tabindex="0" 選択されたラジオがtabindex="0"を持つ
tabindex="-1" 非選択のラジオがtabindex="-1"を持つ
Disabled tabindex 無効なラジオがtabindex="-1"を持つ
First tabbable 何も選択されていない場合、最初の有効なラジオがタブ可能
Single tabbable グループ内で常に1つのみがtabindex="0"

中優先度: フォーム統合

テスト 説明
hidden input フォーム送信用の非表示inputが存在する
name attribute 非表示inputが正しいnameを持つ
value sync 非表示inputの値が選択を反映する

中優先度: アクセシビリティ

テスト 説明
axe violations WCAG 2.1 AA違反がない(jest-axeによる)
selected axe 選択された値での違反がない
disabled axe 無効なオプションでの違反がない

低優先度: Props と動作

テスト 説明
onValueChange 選択変更時にコールバックが発火する
defaultValue defaultValueからの初期選択
className カスタムクラスがコンテナに適用される

テストツール

詳細は testing-strategy.md (opens in new tab) を参照してください。

リソース