Kurs Next.js · Moduł 6: Formularze i Server Actions

Usability i accessibility w formularzach

19 min czytania ·
W tej lekcji7

Projektowanie formularzy, które są zarówno przyjazne dla użytkownika (usability), jak i dostępne dla osób z różnymi niepełnosprawnościami (accessibility), jest kluczowym aspektem tworzenia nowoczesnych aplikacji webowych. W tym module omówimy, jak tworzyć formularze, które są łatwe w użyciu dla wszystkich użytkowników, niezależnie od ich możliwości i urządzeń, z których korzystają.

Dlaczego usability i accessibility są ważne?

Korzyści biznesowe

  1. Zwiększenie konwersji - formularze, które są łatwe w użyciu, mają wyższe współczynniki konwersji
  2. Szerszy zasięg - dostępne formularze docierają do większej liczby użytkowników
  3. Zgodność prawna - w wielu krajach dostępność stron internetowych jest wymagana przez prawo (np. ADA w USA, WCAG w UE)
  4. Poprawa SEO - dostępne strony często mają lepsze pozycje w wynikach wyszukiwania

Korzyści dla użytkowników

  1. Lepsza wydajność - użytkownicy mogą szybciej i łatwiej wypełniać formularze
  2. Mniejsza frustracja - dobrze zaprojektowane formularze zmniejszają liczbę błędów i frustracji
  3. Większa niezależność - osoby z niepełnosprawnościami mogą samodzielnie korzystać z formularzy
  4. Spójne doświadczenie - dobrze zaprojektowane formularze działają spójnie na różnych urządzeniach i w różnych przeglądarkach

Podstawowe zasady użyteczności formularzy

1. Przejrzysta struktura

  • Grupuj powiązane pola - używaj <fieldset> i <legend> do grupowania pól
  • Logiczna kolejność - organizuj pola w intuicyjnej kolejności
  • Odpowiednie etykiety - każde pole powinno mieć jasną etykietę

2. Minimalizacja obciążenia poznawczego

  • Pytaj tylko o niezbędne informacje - każde dodatkowe pole zmniejsza konwersję
  • Podziel długie formularze na kroki - wieloetapowe formularze są łatwiejsze do przyswojenia
  • Pokazuj postęp - w wieloetapowych formularzach informuj użytkownika o postępie

3. Jasna komunikacja

  • Wyraźnie wymaganych pól - oznaczaj pola wymagane w sposób spójny i widoczny
  • Precyzyjne etykiety - etykiety powinny jasno komunikować, jakie informacje są oczekiwane
  • Podpowiedzi i przykłady - dla skomplikowanych pól dodawaj przykłady lub podpowiedzi

4. Efektywne przesyłanie danych

  • Walidacja w czasie rzeczywistym - informuj o błędach podczas wypełniania formularza
  • Zachowaj dane przy błędach - nie resetuj całego formularza po wystąpieniu błędu
  • Potwierdzaj akcje - informuj użytkownika o powodzeniu lub niepowodzeniu wysyłki formularza

Zasady dostępności formularzy

1. Strukturalne zasady HTML

  • Prawidłowe powiązanie etykiet z polami - używaj <label for="id"> powiązanego z id pola
  • Grupowanie pól - używaj <fieldset> i <legend> dla grup pól, zwłaszcza dla checkboxów i radio buttonów
  • Logiczna kolejność tabulacji - upewnij się, że kolejność tabulacji jest logiczna i intuicyjna

2. ARIA (Accessible Rich Internet Applications)

  • Atrybuty aria-label i aria-labelledby - do opisywania elementów bez widocznych etykiet
  • aria-describedby - do powiązania dodatkowych opisów z polami
  • aria-required - dla oznaczania pól wymaganych
  • aria-invalid - dla oznaczania pól z błędami
  • role="alert" - dla komunikatów błędów, które powinny być natychmiast odczytane

3. Kontrast i czytelność

  • Wystarczający kontrast - stosunek kontrastu między tekstem a tłem powinien wynosić co najmniej 4.5:1
  • Odpowiedni rozmiar tekstu - tekst powinien być czytelny bez powiększania
  • Responsywny projekt - formularze powinny być używalne na różnych rozmiarach ekranu

4. Obsługa klawiatury

  • Pełna obsługa klawiatury - wszystkie funkcje powinny być dostępne za pomocą klawiatury
  • Widoczny fokus - fokus klawiatury powinien być wyraźnie widoczny
  • Skróty klawiaturowe - dla zaawansowanych formularzy można dodać skróty klawiaturowe

Implementacja dostępnych formularzy w React

Podstawowy dostępny formularz

import { useState, FormEvent, ChangeEvent } from 'react';

export default function AccessibleForm() {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    phone: '',
    message: '',
    contactPreference: 'email',
    newsletter: false
  });

  const [errors, setErrors] = useState<Record<string, string>>({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isSuccess, setIsSuccess] = useState(false);

  const handleChange = (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value, type } = e.target;
    const checked = type === 'checkbox' ? (e.target as HTMLInputElement).checked : undefined;

    setFormData(prev => ({
      ...prev,
      [name]: checked !== undefined ? checked : value
    }));

    // Usuwanie błędu po edycji pola
    if (errors[name]) {
      setErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[name];
        return newErrors;
      });
    }
  };

  const validateForm = () => {
    const newErrors: Record<string, string> = {};

    if (!formData.name.trim()) {
      newErrors.name = 'Imię i nazwisko jest wymagane';
    }

    if (!formData.email.trim()) {
      newErrors.email = 'Email jest wymagany';
    } else if (!/^\S+@\S+\.\S+$/.test(formData.email)) {
      newErrors.email = 'Podaj prawidłowy adres email';
    }

    if (formData.contactPreference === 'phone' && !formData.phone.trim()) {
      newErrors.phone = 'Numer telefonu jest wymagany przy wyborze kontaktu telefonicznego';
    }

    if (!formData.message.trim()) {
      newErrors.message = 'Wiadomość jest wymagana';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    if (!validateForm()) {
      // Przesunięcie fokusu do pierwszego pola z błędem
      const firstErrorField = document.getElementById(Object.keys(errors)[0]);
      if (firstErrorField) {
        firstErrorField.focus();
      }
      return;
    }

    setIsSubmitting(true);

    try {
      // Symulacja wysyłki formularza
      await new Promise(resolve => setTimeout(resolve, 1500));
      console.log('Formularz wysłany:', formData);

      setIsSuccess(true);
      // Przesunięcie fokusu do komunikatu sukcesu
      const successMessage = document.getElementById('success-message');
      if (successMessage) {
        successMessage.focus();
      }

      // Resetowanie formularza
      setFormData({
        name: '',
        email: '',
        phone: '',
        message: '',
        contactPreference: 'email',
        newsletter: false
      });
    } catch (error) {
      setErrors({
        form: 'Wystąpił błąd podczas wysyłania formularza. Spróbuj ponownie później.'
      });
      // Przesunięcie fokusu do komunikatu błędu
      const errorMessage = document.getElementById('form-error');
      if (errorMessage) {
        errorMessage.focus();
      }
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="max-w-md mx-auto p-6 bg-white rounded-lg shadow-md">
      <h1 className="text-2xl font-bold mb-6">Skontaktuj się z nami</h1>

      {isSuccess && (
        <div
          id="success-message"
          className="mb-4 p-3 bg-green-100 border border-green-400 text-green-700 rounded"
          role="alert"
          tabIndex={-1} // Pozwala na otrzymanie fokusu
        >
          Dziękujemy za wysłanie formularza! Odpowiemy najszybciej jak to możliwe.
        </div>
      )}

      {errors.form && (
        <div
          id="form-error"
          className="mb-4 p-3 bg-red-100 border border-red-400 text-red-700 rounded"
          role="alert"
          tabIndex={-1} // Pozwala na otrzymanie fokusu
        >
          {errors.form}
        </div>
      )}

      <form onSubmit={handleSubmit} noValidate className="space-y-4">
        <div>
          <label htmlFor="name" className="block text-sm font-medium text-gray-700">
            Imię i nazwisko <span className="text-red-500" aria-hidden="true">*</span>
          </label>
          <input
            type="text"
            id="name"
            name="name"
            value={formData.name}
            onChange={handleChange}
            aria-required="true"
            aria-invalid={Boolean(errors.name)}
            aria-describedby={errors.name ? 'name-error' : undefined}
            className={`mt-1 block w-full rounded-md shadow-sm ${errors.name ? 'border-red-500' : 'border-gray-300'}`}
          />
          {errors.name && (
            <p id="name-error" className="mt-1 text-sm text-red-600" role="alert">
              {errors.name}
            </p>
          )}
        </div>

        <div>
          <label htmlFor="email" className="block text-sm font-medium text-gray-700">
            Email <span className="text-red-500" aria-hidden="true">*</span>
          </label>
          <input
            type="email"
            id="email"
            name="email"
            value={formData.email}
            onChange={handleChange}
            aria-required="true"
            aria-invalid={Boolean(errors.email)}
            aria-describedby={errors.email ? 'email-error' : undefined}
            className={`mt-1 block w-full rounded-md shadow-sm ${errors.email ? 'border-red-500' : 'border-gray-300'}`}
          />
          {errors.email && (
            <p id="email-error" className="mt-1 text-sm text-red-600" role="alert">
              {errors.email}
            </p>
          )}
        </div>

        <fieldset>
          <legend className="text-sm font-medium text-gray-700">Preferowana forma kontaktu</legend>
          <div className="mt-2 space-y-2">
            <div className="flex items-center">
              <input
                type="radio"
                id="email-contact"
                name="contactPreference"
                value="email"
                checked={formData.contactPreference === 'email'}
                onChange={handleChange}
                className="h-4 w-4 text-blue-600 border-gray-300 focus:ring-blue-500"
              />
              <label htmlFor="email-contact" className="ml-2 block text-sm text-gray-700">
                Email
              </label>
            </div>
            <div className="flex items-center">
              <input
                type="radio"
                id="phone-contact"
                name="contactPreference"
                value="phone"
                checked={formData.contactPreference === 'phone'}
                onChange={handleChange}
                className="h-4 w-4 text-blue-600 border-gray-300 focus:ring-blue-500"
              />
              <label htmlFor="phone-contact" className="ml-2 block text-sm text-gray-700">
                Telefon
              </label>
            </div>
          </div>
        </fieldset>

        <div className={formData.contactPreference === 'phone' ? 'block' : 'hidden'}>
          <label htmlFor="phone" className="block text-sm font-medium text-gray-700">
            Numer telefonu {formData.contactPreference === 'phone' && <span className="text-red-500" aria-hidden="true">*</span>}
          </label>
          <input
            type="tel"
            id="phone"
            name="phone"
            value={formData.phone}
            onChange={handleChange}
            aria-required={formData.contactPreference === 'phone'}
            aria-invalid={Boolean(errors.phone)}
            aria-describedby={errors.phone ? 'phone-error' : 'phone-hint'}
            className={`mt-1 block w-full rounded-md shadow-sm ${errors.phone ? 'border-red-500' : 'border-gray-300'}`}
          />
          <p id="phone-hint" className="mt-1 text-xs text-gray-500">
            Format: 123-456-789
          </p>
          {errors.phone && (
            <p id="phone-error" className="mt-1 text-sm text-red-600" role="alert">
              {errors.phone}
            </p>
          )}
        </div>

        <div>
          <label htmlFor="message" className="block text-sm font-medium text-gray-700">
            Wiadomość <span className="text-red-500" aria-hidden="true">*</span>
          </label>
          <textarea
            id="message"
            name="message"
            rows={4}
            value={formData.message}
            onChange={handleChange}
            aria-required="true"
            aria-invalid={Boolean(errors.message)}
            aria-describedby={errors.message ? 'message-error' : undefined}
            className={`mt-1 block w-full rounded-md shadow-sm ${errors.message ? 'border-red-500' : 'border-gray-300'}`}
          />
          {errors.message && (
            <p id="message-error" className="mt-1 text-sm text-red-600" role="alert">
              {errors.message}
            </p>
          )}
        </div>

        <div className="flex items-center">
          <input
            type="checkbox"
            id="newsletter"
            name="newsletter"
            checked={formData.newsletter}
            onChange={handleChange}
            className="h-4 w-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
          />
          <label htmlFor="newsletter" className="ml-2 block text-sm text-gray-700">
            Zapisz mnie do newslettera
          </label>
        </div>

        <div className="pt-2">
          <p className="text-xs text-gray-500">
            Pola oznaczone <span className="text-red-500" aria-hidden="true">*</span> są wymagane
          </p>
        </div>

        <button
          type="submit"
          disabled={isSubmitting}
          aria-disabled={isSubmitting}
          className="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50"
        >
          {isSubmitting ? 'Wysyłanie...' : 'Wyślij wiadomość'}
        </button>
      </form>
    </div>
  );
}

Kluczowe elementy dostępności w powyższym przykładzie:

  1. Prawidłowe powiązanie etykiet z polami - każda etykieta ma atrybut htmlFor powiązany z id pola
  2. Grupowanie z fieldset i legend - dla radio buttonów
  3. Atrybuty ARIA - aria-required, aria-invalid, aria-describedby
  4. Dynamiczna widoczność - pole telefonu pojawia się tylko wtedy, gdy jest potrzebne
  5. Komunikaty błędów z role="alert" - dla czytników ekranu
  6. Zarządzanie fokusem - przesuwanie fokusu do pierwszego błędu lub komunikatu sukcesu

Zaawansowane praktyki dla dostępnych formularzy

1. Zarządzanie fokusem

Prawidłowe zarządzanie fokusem jest kluczowe dla użytkowników klawiatury i czytników ekranu:

import { useRef, useEffect } from 'react';

function FocusManagementExample() {
  const firstInputRef = useRef<HTMLInputElement>(null);
  const errorMessageRef = useRef<HTMLDivElement>(null);
  const successMessageRef = useRef<HTMLDivElement>(null);

  // Autofokus na pierwsze pole formularza przy montażu
  useEffect(() => {
    if (firstInputRef.current) {
      firstInputRef.current.focus();
    }
  }, []);

  // Przykładowa funkcja do przenoszenia fokusu do pierwszego błędu
  const moveToFirstError = () => {
    if (errorMessageRef.current) {
      errorMessageRef.current.focus();
      errorMessageRef.current.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
  };

  // Przykładowa funkcja do przenoszenia fokusu do komunikatu sukcesu
  const moveToSuccessMessage = () => {
    if (successMessageRef.current) {
      successMessageRef.current.focus();
      successMessageRef.current.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
  };

  return (
    <form>
      {/* Komunikat błędu z możliwością otrzymania fokusu */}
      <div
        ref={errorMessageRef}
        tabIndex={-1}
        role="alert"
        className="bg-red-100 p-3 rounded"
        style={{ display: 'none' }} // Normalnie kontrolowane przez stan
      >
        Wystąpiły błędy w formularzu
      </div>

      {/* Pierwsze pole formularza */}
      <div>
        <label htmlFor="first-field">Imię</label>
        <input
          ref={firstInputRef}
          id="first-field"
          type="text"
        />
      </div>

      {/* Komunikat sukcesu */}
      <div
        ref={successMessageRef}
        tabIndex={-1}
        role="status"
        className="bg-green-100 p-3 rounded"
        style={{ display: 'none' }} // Normalnie kontrolowane przez stan
      >
        Formularz został wysłany pomyślnie!
      </div>

      {/* Przyciski do demonstracji przenoszenia fokusu */}
      <div className="mt-4 space-x-2">
        <button type="button" onClick={moveToFirstError}>
          Pokaż błąd
        </button>
        <button type="button" onClick={moveToSuccessMessage}>
          Pokaż sukces
        </button>
      </div>
    </form>
  );
}

2. Pola z auto-kompletacją

Dobrze zaimplementowane pola z auto-kompletacją mogą znacząco poprawić użyteczność formularzy:

import { useState, useRef, KeyboardEvent } from 'react';

interface Props {
  suggestions: string[];
  label: string;
  id: string;
  value: string;
  onChange: (value: string) => void;
}

function AccessibleAutocomplete({ suggestions, label, id, value, onChange }: Props) {
  const [filteredSuggestions, setFilteredSuggestions] = useState<string[]>([]);
  const [showSuggestions, setShowSuggestions] = useState(false);
  const [activeSuggestionIndex, setActiveSuggestionIndex] = useState(0);
  const suggestionsListRef = useRef<HTMLUListElement>(null);

  // Filtruj sugestie na podstawie aktualnego wprowadzenia
  const filterSuggestions = (input: string) => {
    const filtered = suggestions.filter(suggestion =>
      suggestion.toLowerCase().includes(input.toLowerCase())
    );
    setFilteredSuggestions(filtered);
    setShowSuggestions(true);
    setActiveSuggestionIndex(0);
  };

  // Obsługa zmiany wartości
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const userInput = e.target.value;
    onChange(userInput);
    filterSuggestions(userInput);
  };

  // Obsługa kliknięcia na sugestię
  const handleSuggestionClick = (suggestion: string) => {
    onChange(suggestion);
    setShowSuggestions(false);
    setActiveSuggestionIndex(0);
  };

  // Obsługa nawigacji za pomocą klawiatury
  const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
    // Strzałka w dół - przejście do następnej sugestii
    if (e.key === 'ArrowDown') {
      e.preventDefault();
      setActiveSuggestionIndex(prev =>
        prev < filteredSuggestions.length - 1 ? prev + 1 : prev
      );
    }
    // Strzałka w górę - przejście do poprzedniej sugestii
    else if (e.key === 'ArrowUp') {
      e.preventDefault();
      setActiveSuggestionIndex(prev => (prev > 0 ? prev - 1 : 0));
    }
    // Enter - wybór aktywnej sugestii
    else if (e.key === 'Enter' && showSuggestions) {
      e.preventDefault();
      if (filteredSuggestions[activeSuggestionIndex]) {
        handleSuggestionClick(filteredSuggestions[activeSuggestionIndex]);
      }
    }
    // Escape - zamknięcie listy sugestii
    else if (e.key === 'Escape') {
      setShowSuggestions(false);
    }
  };

  // ID dla listy sugestii (do powiązania z ARIA)
  const listId = `${id}-suggestions`;

  return (
    <div className="relative">
      <label htmlFor={id} className="block text-sm font-medium text-gray-700">
        {label}
      </label>
      <input
        type="text"
        id={id}
        value={value}
        onChange={handleInputChange}
        onKeyDown={handleKeyDown}
        onFocus={() => filterSuggestions(value)}
        onBlur={() => {
          // Opóźnienie, aby umożliwić kliknięcie sugestii
          setTimeout(() => setShowSuggestions(false), 200);
        }}
        aria-autocomplete="list"
        aria-controls={listId}
        aria-activedescendant={
          showSuggestions && filteredSuggestions.length > 0
            ? `${id}-suggestion-${activeSuggestionIndex}`
            : undefined
        }
        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
      />

      {/* Lista sugestii */}
      {showSuggestions && filteredSuggestions.length > 0 && (
        <ul
          id={listId}
          ref={suggestionsListRef}
          role="listbox"
          className="absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-md bg-white py-1 text-base shadow-lg ring-1 ring-black ring-opacity-5"
        >
          {filteredSuggestions.map((suggestion, index) => (
            <li
              key={index}
              id={`${id}-suggestion-${index}`}
              role="option"
              aria-selected={index === activeSuggestionIndex}
              onClick={() => handleSuggestionClick(suggestion)}
              className={`cursor-default select-none relative py-2 px-4 ${index === activeSuggestionIndex ? 'bg-blue-100' : ''}`}
            >
              {suggestion}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

Kluczowe elementy dostępności w auto-kompletacji:

  1. ARIA roles - aria-autocomplete="list", role="listbox", role="option"
  2. aria-activedescendant - do oznaczania aktywnej sugestii
  3. aria-controls - powiązanie pola z listą sugestii
  4. Obsługa klawiatury - strzałki, Enter, Escape

3. Data pickers i inputy z maskami

Pola daty i inne złożone inputy powinny być dostępne i łatwe w użyciu:

import { useState, useRef, ChangeEvent } from 'react';

function AccessibleDateInput() {
  const [date, setDate] = useState('');
  const inputRef = useRef<HTMLInputElement>(null);

  // Formatowanie daty w formacie DD-MM-YYYY
  const formatDate = (input: string) => {
    // Usunięcie wszystkich znaków innych niż cyfry
    const digitsOnly = input.replace(/\D/g, '');

    // Dodanie kresek w odpowiednich miejscach
    let formatted = '';
    for (let i = 0; i < digitsOnly.length && i < 8; i++) {
      if (i === 2 || i === 4) formatted += '-';
      formatted += digitsOnly[i];
    }

    return formatted;
  };

  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    const input = e.target.value;
    const formatted = formatDate(input);
    setDate(formatted);

    // Zachowanie pozycji kursora po formatowaniu
    if (inputRef.current) {
      const cursorPosition = e.target.selectionStart || 0;
      const diffLength = formatted.length - input.length;
      setTimeout(() => {
        inputRef.current?.setSelectionRange(cursorPosition + diffLength, cursorPosition + diffLength);
      }, 0);
    }
  };

  // Walidacja daty
  const validateDate = (date: string) => {
    // Sprawdzenie formatu DD-MM-YYYY
    if (!/^\d{2}-\d{2}-\d{4}$/.test(date)) return false;

    const [day, month, year] = date.split('-').map(Number);

    // Sprawdzenie zakresu miesiąca
    if (month < 1 || month > 12) return false;

    // Sprawdzenie liczby dni w miesiącu
    const daysInMonth = new Date(year, month, 0).getDate();
    if (day < 1 || day > daysInMonth) return false;

    return true;
  };

  // Generowanie instrukcji dla czytników ekranu
  const dateInstructions = 'Wprowadź datę w formacie DD-MM-RRRR, na przykład 01-06-2023 dla 1 czerwca 2023.';

  return (
    <div>
      <label htmlFor="date-input" className="block text-sm font-medium text-gray-700">
        Data
      </label>
      <input
        ref={inputRef}
        type="text"
        id="date-input"
        value={date}
        onChange={handleChange}
        aria-describedby="date-instructions"
        aria-invalid={date !== '' && !validateDate(date)}
        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm"
      />
      <p id="date-instructions" className="mt-1 text-xs text-gray-500">
        {dateInstructions}
      </p>
      {date !== '' && !validateDate(date) && (
        <p className="mt-1 text-sm text-red-600" role="alert">
          Wprowadzona data jest nieprawidłowa. {dateInstructions}
        </p>
      )}
    </div>
  );
}

4. Reużywalne komponenty dostępnych formularzy

Tworzenie biblioteki reużywalnych, dostępnych komponentów formularza może znacząco ułatwić budowanie spójnych i dostępnych formularzy w całej aplikacji:

// components/FormElements.tsx
import { InputHTMLAttributes, TextareaHTMLAttributes, ReactNode } from 'react';

// Komponent etykiety
interface LabelProps {
  htmlFor: string;
  children: ReactNode;
  required?: boolean;
}

export function FormLabel({ htmlFor, children, required }: LabelProps) {
  return (
    <label htmlFor={htmlFor} className="block text-sm font-medium text-gray-700">
      {children}
      {required && <span className="text-red-500 ml-1" aria-hidden="true">*</span>}
    </label>
  );
}

// Komponent pola tekstowego
interface TextInputProps extends InputHTMLAttributes<HTMLInputElement> {
  id: string;
  label: string;
  error?: string;
  hint?: string;
  required?: boolean;
}

export function TextInput({
  id,
  label,
  error,
  hint,
  required,
  ...props
}: TextInputProps) {
  const errorId = error ? `${id}-error` : undefined;
  const hintId = hint ? `${id}-hint` : undefined;
  const describedBy = [errorId, hintId].filter(Boolean).join(' ') || undefined;

  return (
    <div className="mb-4">
      <FormLabel htmlFor={id} required={required}>{label}</FormLabel>
      <input
        id={id}
        type="text"
        aria-invalid={Boolean(error)}
        aria-required={required}
        aria-describedby={describedBy}
        className={`mt-1 block w-full rounded-md ${error ? 'border-red-500' : 'border-gray-300'}`}
        {...props}
      />
      {hint && !error && (
        <p id={hintId} className="mt-1 text-xs text-gray-500">
          {hint}
        </p>
      )}
      {error && (
        <p id={errorId} className="mt-1 text-sm text-red-600" role="alert">
          {error}
        </p>
      )}
    </div>
  );
}

// Komponent pola tekstowego wieloliniowego
interface TextareaProps extends TextareaHTMLAttributes<HTMLTextAreaElement> {
  id: string;
  label: string;
  error?: string;
  hint?: string;
  required?: boolean;
}

export function Textarea({
  id,
  label,
  error,
  hint,
  required,
  ...props
}: TextareaProps) {
  const errorId = error ? `${id}-error` : undefined;
  const hintId = hint ? `${id}-hint` : undefined;
  const describedBy = [errorId, hintId].filter(Boolean).join(' ') || undefined;

  return (
    <div className="mb-4">
      <FormLabel htmlFor={id} required={required}>{label}</FormLabel>
      <textarea
        id={id}
        aria-invalid={Boolean(error)}
        aria-required={required}
        aria-describedby={describedBy}
        className={`mt-1 block w-full rounded-md ${error ? 'border-red-500' : 'border-gray-300'}`}
        {...props}
      />
      {hint && !error && (
        <p id={hintId} className="mt-1 text-xs text-gray-500">
          {hint}
        </p>
      )}
      {error && (
        <p id={errorId} className="mt-1 text-sm text-red-600" role="alert">
          {error}
        </p>
      )}
    </div>
  );
}

// Komponent grupy radio lub checkbox
interface OptionItem {
  id: string;
  value: string;
  label: string;
}

interface CheckboxOrRadioGroupProps {
  legend: string;
  name: string;
  options: OptionItem[];
  type: 'checkbox' | 'radio';
  values: string[];
  onChange: (value: string, checked: boolean) => void;
  error?: string;
  required?: boolean;
}

export function OptionGroup({
  legend,
  name,
  options,
  type,
  values,
  onChange,
  error,
  required
}: CheckboxOrRadioGroupProps) {
  const errorId = error ? `${name}-error` : undefined;

  return (
    <fieldset className="mb-4">
      <legend className="text-sm font-medium text-gray-700">
        {legend}
        {required && <span className="text-red-500 ml-1" aria-hidden="true">*</span>}
      </legend>

      <div className="mt-2 space-y-2" role={type === 'radio' ? 'radiogroup' : undefined} aria-required={required}>
        {options.map(option => (
          <div key={option.id} className="flex items-center">
            <input
              type={type}
              id={option.id}
              name={name}
              value={option.value}
              checked={type === 'radio' ? values[0] === option.value : values.includes(option.value)}
              onChange={(e) => onChange(option.value, e.target.checked)}
              aria-describedby={errorId}
              className="h-4 w-4 text-blue-600 border-gray-300 focus:ring-blue-500"
            />
            <label htmlFor={option.id} className="ml-2 block text-sm text-gray-700">
              {option.label}
            </label>
          </div>
        ))}
      </div>

      {error && (
        <p id={errorId} className="mt-1 text-sm text-red-600" role="alert">
          {error}
        </p>
      )}
    </fieldset>
  );
}

Przykład użycia reużywalnych komponentów:

import { useState } from 'react';
import { TextInput, Textarea, OptionGroup } from '../components/FormElements';

export default function SurveyForm() {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    feedback: '',
    satisfaction: '',
    interests: [] as string[]
  });

  const [errors, setErrors] = useState<Record<string, string>>({});

  const handleInputChange = (field: string, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));

    // Usunięcie błędu po edycji
    if (errors[field]) {
      setErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[field];
        return newErrors;
      });
    }
  };

  const handleCheckboxChange = (value: string, checked: boolean) => {
    setFormData(prev => {
      if (checked) {
        return { ...prev, interests: [...prev.interests, value] };
      } else {
        return { ...prev, interests: prev.interests.filter(item => item !== value) };
      }
    });

    // Usunięcie błędu po edycji
    if (errors.interests) {
      setErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors.interests;
        return newErrors;
      });
    }
  };

  const handleRadioChange = (value: string, checked: boolean) => {
    if (checked) {
      setFormData(prev => ({ ...prev, satisfaction: value }));

      // Usunięcie błędu po edycji
      if (errors.satisfaction) {
        setErrors(prev => {
          const newErrors = { ...prev };
          delete newErrors.satisfaction;
          return newErrors;
        });
      }
    }
  };

  const validateForm = () => {
    const newErrors: Record<string, string> = {};

    if (!formData.name.trim()) {
      newErrors.name = 'Imię jest wymagane';
    }

    if (!formData.email.trim()) {
      newErrors.email = 'Email jest wymagany';
    } else if (!/^\S+@\S+\.\S+$/.test(formData.email)) {
      newErrors.email = 'Podaj prawidłowy adres email';
    }

    if (!formData.feedback.trim()) {
      newErrors.feedback = 'Opinia jest wymagana';
    }

    if (!formData.satisfaction) {
      newErrors.satisfaction = 'Wybierz poziom zadowolenia';
    }

    if (formData.interests.length === 0) {
      newErrors.interests = 'Wybierz co najmniej jedną kategorię';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    if (validateForm()) {
      // Przesłanie formularza
      console.log('Dane formularza:', formData);
      alert('Formularz wysłany pomyślnie!');
    }
  };

  return (
    <div className="max-w-md mx-auto p-6 bg-white rounded-lg shadow-md">
      <h1 className="text-2xl font-bold mb-6">Ankieta użytkownika</h1>

      <form onSubmit={handleSubmit} noValidate>
        <TextInput
          id="name"
          label="Imię i nazwisko"
          required
          value={formData.name}
          onChange={(e) => handleInputChange('name', e.target.value)}
          error={errors.name}
        />

        <TextInput
          id="email"
          label="Email"
          type="email"
          required
          value={formData.email}
          onChange={(e) => handleInputChange('email', e.target.value)}
          error={errors.email}
          hint="Nigdy nie udostępnimy Twojego adresu email"
        />

        <Textarea
          id="feedback"
          label="Twoja opinia"
          required
          value={formData.feedback}
          onChange={(e) => handleInputChange('feedback', e.target.value)}
          error={errors.feedback}
          rows={4}
        />

        <OptionGroup
          legend="Poziom zadowolenia"
          name="satisfaction"
          type="radio"
          required
          values={formData.satisfaction ? [formData.satisfaction] : []}
          onChange={handleRadioChange}
          error={errors.satisfaction}
          options={[
            { id: 'satisfaction-very-satisfied', value: 'very-satisfied', label: 'Bardzo zadowolony' },
            { id: 'satisfaction-satisfied', value: 'satisfied', label: 'Zadowolony' },
            { id: 'satisfaction-neutral', value: 'neutral', label: 'Neutralny' },
            { id: 'satisfaction-dissatisfied', value: 'dissatisfied', label: 'Niezadowolony' },
            { id: 'satisfaction-very-dissatisfied', value: 'very-dissatisfied', label: 'Bardzo niezadowolony' }
          ]}
        />

        <OptionGroup
          legend="Zainteresowania"
          name="interests"
          type="checkbox"
          required
          values={formData.interests}
          onChange={handleCheckboxChange}
          error={errors.interests}
          options={[
            { id: 'interests-technology', value: 'technology', label: 'Technologia' },
            { id: 'interests-design', value: 'design', label: 'Wzornictwo' },
            { id: 'interests-business', value: 'business', label: 'Biznes' },
            { id: 'interests-health', value: 'health', label: 'Zdrowie' },
            { id: 'interests-education', value: 'education', label: 'Edukacja' }
          ]}
        />

        <div className="mt-6">
          <button
            type="submit"
            className="w-full py-2 px-4 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
          >
            Wyślij ankietę
          </button>
        </div>
      </form>
    </div>
  );
}

Testowanie dostępności formularzy

Samo zaimplementowanie dostępnych formularzy to tylko połowa sukcesu. Konieczne jest również ich testowanie:

1. Automatyczne testowanie dostępności

Możesz użyć narzędzi takich jak @axe-core/react do testowania dostępności w trakcie rozwoju:

// W pliku testowym (np. FormComponent.test.tsx)
import React from 'react';
import { render } from '@testing-library/react';
import { axe, toHaveNoViolations } from 'jest-axe';
import ContactForm from '../ContactForm';

// Dodaj matcher do Jest
expect.extend(toHaveNoViolations);

describe('ContactForm', () => {
  it('should not have accessibility violations', async () => {
    const { container } = render(<ContactForm />);
    const results = await axe(container);
    expect(results).toHaveNoViolations();
  });
});

2. Manualne testowanie dostępności

Automatyczne testy nie wychwycają wszystkich problemów. Konieczne jest również manualne testowanie:

  1. Testowanie nawigacji klawiaturą:

    • Czy można poruszać się po formularzu używając tylko klawiatury (Tab, Shift+Tab, Enter, spacja)?
    • Czy fokus jest wyraźnie widoczny na każdym polu?
    • Czy można aktywować przyciski i linki za pomocą klawiatury?
  2. Testowanie z czytnikami ekranu:

    • NVDA lub JAWS (Windows)
    • VoiceOver (macOS)
    • TalkBack (Android)
    • VoiceOver (iOS)
  3. Testowanie powiększenia:

    • Czy formularz jest używalny przy powiększeniu tekstu do 200%?
    • Czy układ formularza dostosowuje się do powiększenia?

3. Lista kontrolna dostępności formularzy

Przed wdrożeniem formularza, sprawdź go pod kątem następujących kryteriów:

  1. Strukturalne:

    • Czy wszystkie pola formularza mają powiązane etykiety?
    • Czy pola radio i checkbox są zgrupowane za pomocą <fieldset> i <legend>?
    • Czy atrybuty ARIA są użyte poprawnie?
  2. Interakcyjność:

    • Czy można poruszać się po formularzu za pomocą klawiatury?
    • Czy można aktywować wszystkie kontrolki za pomocą klawiatury?
    • Czy fokus klawiatury jest widoczny?
  3. Feedback:

    • Czy błędy walidacji są jasno komunikowane?
    • Czy komunikaty o błędach są powiązane z polami za pomocą aria-describedby?
    • Czy status wysyłki formularza jest jasno komunikowany?
  4. Wizualne:

    • Czy kontrast tekstu i tła jest wystarczający (minimum 4.5:1)?
    • Czy formularz jest używalny na różnych rozmiarach ekranu?
    • Czy wizualne wskaźniki (np. kolory) są uzupełnione innymi wskaźnikami?

Podsumowanie

Tworzenie użytecznych i dostępnych formularzy to kluczowy aspekt nowoczesnych aplikacji webowych. Prawidłowo zaprojektowane formularze przyczyniają się do zwiększenia konwersji, poprawy doświadczenia użytkownika i zapewniają dostęp do twoich usług szerszemu gronu odbiorców.

Główne zasady, o których należy pamiętać:

  1. Przejrzysta struktura - logiczna organizacja pól, jasne etykiety, grupowanie powiązanych pól
  2. Dostępność klawiatury - pełna obsługa klawiatury, widoczny fokus, logiczna kolejność tabulacji
  3. Poprawne ARIA - używanie atrybutów ARIA do poprawy doświadczenia użytkowników czytników ekranu
  4. Efektywna komunikacja - jasne etykiety, pomocnicze teksty, precyzyjne komunikaty błędów
  5. Walidacja - natychmiastowa informacja zwrotna, jasne instrukcje, walidacja zarówno na kliencie, jak i na serwerze
  6. Testowanie - zarówno automatyczne, jak i manualne, z różnymi urządzeniami wspierającymi

Budując formularze zgodnie z tymi zasadami, możesz stworzyć dostępne i przyjazne dla użytkownika doświadczenie, które będzie służyć wszystkim odwiedzającym Twoją aplikację.

Kod do tej lekcji: App.tsx
import React, { useState, useRef, useEffect } from 'react';

// Dostepnosc formularzy - ARIA, labels, focus management

interface A11yIssue {
  id: string;
  label: string;
  bad: string;
  good: string;
  description: string;
}

const a11yIssues: A11yIssue[] = [
  {
    id: 'labels',
    label: 'Label + htmlFor',
    bad: '<input placeholder="Email" />',
    good: '<label htmlFor="email">Email</label>\n<input id="email" />',
    description: 'Kazde pole musi miec powiazany label. Czytniki ekranu odczytuja label.',
  },
  {
    id: 'aria',
    label: 'aria-describedby',
    bad: '<input />\n<span>Min. 8 znakow</span>',
    good: '<input aria-describedby="hint" />\n<span id="hint">Min. 8 znakow</span>',
    description: 'aria-describedby laczy pole z opisem bledu lub wskazowka.',
  },
  {
    id: 'error',
    label: 'aria-invalid + role="alert"',
    bad: '<input style={{border:"red"}} />\n<span>Blad!</span>',
    good: '<input aria-invalid="true" />\n<span role="alert">Blad!</span>',
    description: 'aria-invalid i role="alert" informuja czytniki ekranu o bledach.',
  },
  {
    id: 'focus',
    label: 'Focus management',
    bad: '// Brak zarzadzania focusem\n// Uzytkownik nie wie gdzie jest blad',
    good: '// Po bledzie - focus na pierwszy bledny input\nfirstErrorRef.current?.focus()',
    description: 'Po bledzie walidacji przenies focus na pierwszy bledny element.',
  },
];

export default function AccessibilityDemo() {
  const [selected, setSelected] = useState<A11yIssue>(a11yIssues[0]);
  const [showDemo, setShowDemo] = useState(false);
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [errors, setErrors] = useState<Record<string, string>>({});
  const nameRef = useRef<HTMLInputElement>(null);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const errs: Record<string, string> = {};
    if (!name) errs.name = 'Imie jest wymagane';
    if (!email) errs.email = 'Email jest wymagany';
    else if (!/\S+@\S+\.\S+/.test(email)) errs.email = 'Nieprawidlowy email';
    setErrors(errs);

    // Focus management - przenies na pierwszy bledny input
    if (Object.keys(errs).length > 0 && errs.name) {
      nameRef.current?.focus();
    }
  };

  const inputStyle: React.CSSProperties = {
    width: '100%', padding: '10px', background: '#0d1117',
    border: '1px solid #333', borderRadius: 6, color: '#e0e0e0',
    fontFamily: 'monospace', fontSize: 13, boxSizing: 'border-box'
  };

  return (
    <div style={{ background: '#0f0f23', minHeight: '100vh', padding: 20, color: '#e0e0e0', fontFamily: 'monospace' }}>
      <h1 style={{ color: '#64ffda' }}>Dostepnosc formularzy (a11y)</h1>

      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 16 }}>
        {a11yIssues.map(issue => (
          <button key={issue.id} onClick={() => setSelected(issue)} style={{
            background: selected.id === issue.id ? '#1565c0' : '#1a2744',
            color: '#fff', border: `1px solid ${selected.id === issue.id ? '#64ffda' : '#333'}`,
            borderRadius: 6, padding: '6px 12px', cursor: 'pointer', fontSize: 11, fontFamily: 'monospace'
          }}>
            {issue.label}
          </button>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 16 }}>
        <div style={{ background: '#3e1010', borderRadius: 8, padding: 12, border: '1px solid #f44336' }}>
          <div style={{ color: '#f44336', fontSize: 12, marginBottom: 8 }}>Zle (niedostepne):</div>
          <pre style={{ color: '#ffcdd2', fontSize: 11, margin: 0, whiteSpace: 'pre-wrap' }}>{selected.bad}</pre>
        </div>
        <div style={{ background: '#0d2818', borderRadius: 8, padding: 12, border: '1px solid #4caf50' }}>
          <div style={{ color: '#4caf50', fontSize: 12, marginBottom: 8 }}>Dobrze (dostepne):</div>
          <pre style={{ color: '#c8e6c9', fontSize: 11, margin: 0, whiteSpace: 'pre-wrap' }}>{selected.good}</pre>
        </div>
      </div>
      <p style={{ color: '#aaa', fontSize: 13, marginBottom: 16 }}>{selected.description}</p>

      <button onClick={() => setShowDemo(!showDemo)} style={{
        background: '#9c27b0', color: '#fff', border: 'none', borderRadius: 6,
        padding: '8px 16px', cursor: 'pointer', fontFamily: 'monospace', marginBottom: 16
      }}>
        {showDemo ? 'Ukryj' : 'Pokaz'} dostepny formularz demo
      </button>

      {showDemo && (
        <form onSubmit={handleSubmit} style={{ maxWidth: 400 }} aria-label="Formularz rejestracji">
          <div style={{ marginBottom: 12 }}>
            <label htmlFor="a11y-name" style={{ color: '#64ffda', fontSize: 12, display: 'block', marginBottom: 4 }}>
              Imie *
            </label>
            <input
              ref={nameRef} id="a11y-name" value={name}
              onChange={e => setName(e.target.value)}
              aria-invalid={!!errors.name} aria-describedby={errors.name ? 'name-error' : undefined}
              style={{ ...inputStyle, borderColor: errors.name ? '#f44336' : '#333' }}
            />
            {errors.name && <div id="name-error" role="alert" style={{ color: '#f44336', fontSize: 11, marginTop: 4 }}>{errors.name}</div>}
          </div>

          <div style={{ marginBottom: 12 }}>
            <label htmlFor="a11y-email" style={{ color: '#64ffda', fontSize: 12, display: 'block', marginBottom: 4 }}>
              Email *
            </label>
            <input
              id="a11y-email" type="email" value={email}
              onChange={e => setEmail(e.target.value)}
              aria-invalid={!!errors.email} aria-describedby="email-hint"
              style={{ ...inputStyle, borderColor: errors.email ? '#f44336' : '#333' }}
            />
            <div id="email-hint" style={{ color: '#888', fontSize: 11, marginTop: 4 }}>
              {errors.email ? <span role="alert" style={{ color: '#f44336' }}>{errors.email}</span> : 'Format: nazwa@domena.pl'}
            </div>
          </div>

          <button type="submit" style={{
            background: '#4caf50', color: '#fff', border: 'none', borderRadius: 6,
            padding: '10px 20px', cursor: 'pointer', fontFamily: 'monospace', width: '100%'
          }}>
            Wyslij (z focus management)
          </button>
        </form>
      )}
    </div>
  );
}

Hasła z dokumentacji w tej lekcji

Widzisz błąd w tej lekcji?

Sprawdź się

Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.

  1. 1. Jaki jest zalecany wzorzec obsługi błędów w Server Actions w Next.js?

  2. 2. Hook useActionState (dawniej useFormState) w Server Actions służy do:

To 2 z 4 pytań do tej lekcji. Pozostałe rozwiążesz w grze.

Zadania praktyczne w grze

  • Edytor kodu

    Utwórz reusable custom hook useForm z validation, submission handling i error management

  • Edytor kodu

    Utwórz formularz do uploadu zdjęć z preview, drag&drop, progress bar i walidacją typu/rozmiaru

  • Edytor kodu

    Utwórz formularz gdzie pola pokazują się conditional na podstawie poprzednich wyborów (np. payment method -> different fields)

  • Układanie w pionie

    Ułóż elementy w prawidłowej kolejności: Setup provider → Create login → Protect

  • Klikanie w kolejności

    Kliknij elementy w kolejności, aby zbudować składnię <form action={serverAction}>

  • Klikanie w kolejności

    Kliknij elementy w kolejności, aby zbudować łańcuch walidacji Zod: z.string().email().min(5)

  1. PytanieWzorzec obsługi błędów w Server Actions
  2. PytanieHook useActionState w Server Actions
  3. Zadanie z kodemPraktyka: Utwórz reusable custom hook useForm z validation,
  4. PytanieFile uploads w formularzach wymagają:
  5. PytanieDebouncing w formularzach służy do:
  6. Zadanie z kodemPraktyka: Utwórz formularz do uploadu zdjęć z preview,
  7. Zadanie z kodemPraktyka: Utwórz formularz gdzie pola pokazują się
  8. Ułóż w kolejnościKolejność: Setup provider → Create login → Protect routes
  9. Kliknij w kolejnościSkładnia formularza z Server Action
  10. Kliknij w kolejnościŁańcuch walidacji Zod dla emaila

Przydatne artykuły