feat(a11y): add DialogContext auto-labelling with aria-labelledby/describedby

Introduce DialogContext using React.useId() that auto-wires aria-labelledby
and aria-describedby on DialogContent, with matching ids on DialogTitle and
DialogDescription. Adds role="dialog" and aria-modal="true". All 12+ existing
consumers get proper ARIA labels without any call-site changes.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Ho Ngoc Hai
2026-04-24 10:33:54 +07:00
parent f5118244b7
commit d7961e297c
3 changed files with 232 additions and 48 deletions

View File

@@ -1,6 +1,7 @@
'use client';
import dynamic from 'next/dynamic';
import { useEffect, useRef, useState } from 'react';
import type { UseFormRegister, UseFormSetValue, UseFormWatch, FieldErrors } from 'react-hook-form';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
@@ -43,9 +44,13 @@ interface StepLocationProps extends StepProps {
watch?: UseFormWatch<CreateListingFormData>;
}
function FieldError({ message }: { message?: string }) {
function FieldError({ id, message }: { id: string; message?: string }) {
if (!message) return null;
return <p className="mt-1 text-xs text-destructive">{message}</p>;
return (
<p id={id} role="alert" className="mt-1 text-xs text-destructive">
{message}
</p>
);
}
// ─── Step 1: Basic Info ──────────────────────────────────
@@ -58,7 +63,12 @@ export function StepBasicInfo({ register, errors }: StepProps) {
<div className="grid gap-4 sm:grid-cols-2">
<div>
<Label htmlFor="transactionType">Loại giao dịch *</Label>
<Select id="transactionType" {...register('transactionType')}>
<Select
id="transactionType"
aria-invalid={!!errors.transactionType}
aria-describedby={errors.transactionType ? 'transactionType-error' : undefined}
{...register('transactionType')}
>
<option value="">-- Chọn --</option>
{TRANSACTION_TYPES.map((t) => (
<option key={t.value} value={t.value}>
@@ -66,12 +76,17 @@ export function StepBasicInfo({ register, errors }: StepProps) {
</option>
))}
</Select>
<FieldError message={errors.transactionType?.message} />
<FieldError id="transactionType-error" message={errors.transactionType?.message} />
</div>
<div>
<Label htmlFor="propertyType">Loại bất đng sản *</Label>
<Select id="propertyType" {...register('propertyType')}>
<Select
id="propertyType"
aria-invalid={!!errors.propertyType}
aria-describedby={errors.propertyType ? 'propertyType-error' : undefined}
{...register('propertyType')}
>
<option value="">-- Chọn --</option>
{PROPERTY_TYPES.map((t) => (
<option key={t.value} value={t.value}>
@@ -79,14 +94,20 @@ export function StepBasicInfo({ register, errors }: StepProps) {
</option>
))}
</Select>
<FieldError message={errors.propertyType?.message} />
<FieldError id="propertyType-error" message={errors.propertyType?.message} />
</div>
</div>
<div>
<Label htmlFor="title">Tiêu đ tin đăng *</Label>
<Input id="title" placeholder="VD: Bán căn hộ 2PN tại Vinhomes Central Park" {...register('title')} />
<FieldError message={errors.title?.message} />
<Input
id="title"
placeholder="VD: Bán căn hộ 2PN tại Vinhomes Central Park"
aria-invalid={!!errors.title}
aria-describedby={errors.title ? 'title-error' : undefined}
{...register('title')}
/>
<FieldError id="title-error" message={errors.title?.message} />
</div>
<div>
@@ -95,9 +116,11 @@ export function StepBasicInfo({ register, errors }: StepProps) {
id="description"
rows={5}
placeholder="Mô tả chi tiết về bất động sản..."
aria-invalid={!!errors.description}
aria-describedby={errors.description ? 'description-error' : undefined}
{...register('description')}
/>
<FieldError message={errors.description?.message} />
<FieldError id="description-error" message={errors.description?.message} />
</div>
</div>
);
@@ -115,10 +138,35 @@ export function StepLocation({ register, errors, setValue, watch }: StepLocation
const latValid = latNum != null && Number.isFinite(latNum) && latNum >= -90 && latNum <= 90;
const lngValid = lngNum != null && Number.isFinite(lngNum) && lngNum >= -180 && lngNum <= 180;
// Live region message announced when the map geocoder resolves a location.
const [locationAnnouncement, setLocationAnnouncement] = useState('');
const announcementTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// Clear announcement after it has been read to avoid stale text being
// re-announced on re-render.
useEffect(() => {
if (locationAnnouncement) {
announcementTimerRef.current = setTimeout(() => setLocationAnnouncement(''), 3000);
}
return () => {
if (announcementTimerRef.current) clearTimeout(announcementTimerRef.current);
};
}, [locationAnnouncement]);
return (
<div className="space-y-4">
<h3 className="text-lg font-semibold">Vị trí</h3>
{/* Visually-hidden live region for map-picker location announcements */}
<div
role="status"
aria-live="polite"
aria-atomic="true"
className="sr-only"
>
{locationAnnouncement}
</div>
{setValue && (
<LocationPicker
lat={latValid ? latNum : null}
@@ -131,6 +179,11 @@ export function StepLocation({ register, errors, setValue, watch }: StepLocation
if (resolved.ward) setValue('ward', resolved.ward, { shouldDirty: true });
if (resolved.district) setValue('district', resolved.district, { shouldDirty: true });
if (resolved.city) setValue('city', resolved.city, { shouldDirty: true });
// Announce resolved location to screen reader users
const parts = [resolved.ward, resolved.district, resolved.city].filter(Boolean);
if (parts.length > 0) {
setLocationAnnouncement(`Đã cập nhật vị trí: ${parts.join(', ')}`);
}
}
}}
height="360px"
@@ -139,25 +192,49 @@ export function StepLocation({ register, errors, setValue, watch }: StepLocation
<div>
<Label htmlFor="address">Đa chỉ *</Label>
<Input id="address" placeholder="Số nhà, tên đường" {...register('address')} />
<FieldError message={errors.address?.message} />
<Input
id="address"
placeholder="Số nhà, tên đường"
aria-invalid={!!errors.address}
aria-describedby={errors.address ? 'address-error' : undefined}
{...register('address')}
/>
<FieldError id="address-error" message={errors.address?.message} />
</div>
<div className="grid gap-4 sm:grid-cols-3">
<div>
<Label htmlFor="ward">Phường/ *</Label>
<Input id="ward" placeholder="Phường/Xã" {...register('ward')} />
<FieldError message={errors.ward?.message} />
<Input
id="ward"
placeholder="Phường/Xã"
aria-invalid={!!errors.ward}
aria-describedby={errors.ward ? 'ward-error' : undefined}
{...register('ward')}
/>
<FieldError id="ward-error" message={errors.ward?.message} />
</div>
<div>
<Label htmlFor="district">Quận/Huyện *</Label>
<Input id="district" placeholder="Quận/Huyện" {...register('district')} />
<FieldError message={errors.district?.message} />
<Input
id="district"
placeholder="Quận/Huyện"
aria-invalid={!!errors.district}
aria-describedby={errors.district ? 'district-error' : undefined}
{...register('district')}
/>
<FieldError id="district-error" message={errors.district?.message} />
</div>
<div>
<Label htmlFor="city">Tỉnh/Thành phố *</Label>
<Input id="city" placeholder="Tỉnh/Thành phố" {...register('city')} />
<FieldError message={errors.city?.message} />
<Input
id="city"
placeholder="Tỉnh/Thành phố"
aria-invalid={!!errors.city}
aria-describedby={errors.city ? 'city-error' : undefined}
{...register('city')}
/>
<FieldError id="city-error" message={errors.city?.message} />
</div>
</div>
@@ -169,9 +246,11 @@ export function StepLocation({ register, errors, setValue, watch }: StepLocation
type="number"
step="any"
placeholder="VD: 10.7769"
aria-invalid={!!errors.latitude}
aria-describedby={errors.latitude ? 'latitude-error' : undefined}
{...register('latitude')}
/>
<FieldError message={errors.latitude?.message} />
<FieldError id="latitude-error" message={errors.latitude?.message} />
</div>
<div>
<Label htmlFor="longitude">Kinh đ</Label>
@@ -180,9 +259,11 @@ export function StepLocation({ register, errors, setValue, watch }: StepLocation
type="number"
step="any"
placeholder="VD: 106.7009"
aria-invalid={!!errors.longitude}
aria-describedby={errors.longitude ? 'longitude-error' : undefined}
{...register('longitude')}
/>
<FieldError message={errors.longitude?.message} />
<FieldError id="longitude-error" message={errors.longitude?.message} />
</div>
</div>
</div>
@@ -199,8 +280,16 @@ export function StepDetails({ register, errors }: StepProps) {
<div className="grid gap-4 sm:grid-cols-2 md:grid-cols-3">
<div>
<Label htmlFor="areaM2">Diện tích (m²) *</Label>
<Input id="areaM2" type="number" step="0.1" placeholder="VD: 75" {...register('areaM2')} />
<FieldError message={errors.areaM2?.message} />
<Input
id="areaM2"
type="number"
step="0.1"
placeholder="VD: 75"
aria-invalid={!!errors.areaM2}
aria-describedby={errors.areaM2 ? 'areaM2-error' : undefined}
{...register('areaM2')}
/>
<FieldError id="areaM2-error" message={errors.areaM2?.message} />
</div>
<div>
<Label htmlFor="usableAreaM2">Diện tích sử dụng (m²)</Label>
@@ -360,8 +449,14 @@ export function StepPricing({ register, errors }: StepProps) {
<div>
<Label htmlFor="priceVND">Giá bán (VNĐ) *</Label>
<Input id="priceVND" placeholder="VD: 5000000000" {...register('priceVND')} />
<FieldError message={errors.priceVND?.message} />
<Input
id="priceVND"
placeholder="VD: 5000000000"
aria-invalid={!!errors.priceVND}
aria-describedby={errors.priceVND ? 'priceVND-error' : undefined}
{...register('priceVND')}
/>
<FieldError id="priceVND-error" message={errors.priceVND?.message} />
<p className="mt-1 text-xs text-muted-foreground">Nhập số không dấu chấm hoặc dấu phẩy</p>
</div>

View File

@@ -68,4 +68,53 @@ describe('Dialog', () => {
await userEvent.click(screen.getByText('Stay Open'));
expect(onOpenChange).not.toHaveBeenCalled();
});
describe('a11y: DialogContext auto-labelling', () => {
it('renders DialogContent with role="dialog" and aria-modal', () => {
render(
<Dialog open={true} onOpenChange={() => {}}>
<DialogContent>
<DialogTitle>A11y Title</DialogTitle>
</DialogContent>
</Dialog>,
);
const dialog = screen.getByRole('dialog');
expect(dialog).toHaveAttribute('aria-modal', 'true');
});
it('auto-wires aria-labelledby from DialogTitle id', () => {
render(
<Dialog open={true} onOpenChange={() => {}}>
<DialogContent>
<DialogTitle>Auto Label</DialogTitle>
<DialogDescription>Auto Desc</DialogDescription>
</DialogContent>
</Dialog>,
);
const dialog = screen.getByRole('dialog');
const titleId = dialog.getAttribute('aria-labelledby');
const descId = dialog.getAttribute('aria-describedby');
expect(titleId).toBeTruthy();
expect(descId).toBeTruthy();
// The title element should carry the matching id
expect(screen.getByText('Auto Label')).toHaveAttribute('id', titleId);
expect(screen.getByText('Auto Desc')).toHaveAttribute('id', descId);
});
it('allows explicit id override on DialogTitle', () => {
render(
<Dialog open={true} onOpenChange={() => {}}>
<DialogContent>
<DialogTitle id="custom-title">Custom</DialogTitle>
</DialogContent>
</Dialog>,
);
expect(screen.getByText('Custom')).toHaveAttribute('id', 'custom-title');
});
});
});

View File

@@ -3,6 +3,23 @@
import * as React from 'react';
import { cn } from '@/lib/utils';
/* ------------------------------------------------------------------ */
/* DialogContext — auto-wires aria-labelledby / aria-describedby */
/* ------------------------------------------------------------------ */
interface DialogContextValue {
titleId: string;
descriptionId: string;
}
const DialogContext = React.createContext<DialogContextValue | null>(null);
function useDialogContext() {
return React.useContext(DialogContext);
}
/* ------------------------------------------------------------------ */
interface DialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
@@ -10,6 +27,10 @@ interface DialogProps {
}
function Dialog({ open, onOpenChange, children }: DialogProps) {
const reactId = React.useId();
const titleId = `${reactId}-dialog-title`;
const descriptionId = `${reactId}-dialog-desc`;
React.useEffect(() => {
if (open) {
document.body.style.overflow = 'hidden';
@@ -24,34 +45,43 @@ function Dialog({ open, onOpenChange, children }: DialogProps) {
if (!open) return null;
return (
<div className="fixed inset-0 z-50">
<div
className="fixed inset-0 bg-black/80 animate-in fade-in-0"
onClick={() => onOpenChange(false)}
/>
<div className="fixed inset-0 flex items-center justify-center p-4">
{children}
<DialogContext.Provider value={{ titleId, descriptionId }}>
<div className="fixed inset-0 z-50">
<div
className="fixed inset-0 bg-black/80 animate-in fade-in-0"
onClick={() => onOpenChange(false)}
/>
<div className="fixed inset-0 flex items-center justify-center p-4">
{children}
</div>
</div>
</div>
</DialogContext.Provider>
);
}
const DialogContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, children, ...props }, ref) => (
<div
ref={ref}
className={cn(
'relative z-50 w-full max-w-lg rounded-lg border bg-background p-6 shadow-lg animate-in fade-in-0 zoom-in-95',
className,
)}
onClick={(e) => e.stopPropagation()}
{...props}
>
{children}
</div>
));
>(({ className, children, ...props }, ref) => {
const ctx = useDialogContext();
return (
<div
ref={ref}
role="dialog"
aria-modal="true"
aria-labelledby={ctx?.titleId}
aria-describedby={ctx?.descriptionId}
className={cn(
'relative z-50 w-full max-w-lg rounded-lg border bg-background p-6 shadow-lg animate-in fade-in-0 zoom-in-95',
className,
)}
onClick={(e) => e.stopPropagation()}
{...props}
>
{children}
</div>
);
});
DialogContent.displayName = 'DialogContent';
function DialogHeader({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
@@ -60,15 +90,25 @@ function DialogHeader({ className, ...props }: React.HTMLAttributes<HTMLDivEleme
);
}
function DialogTitle({ className, ...props }: React.HTMLAttributes<HTMLHeadingElement>) {
function DialogTitle({ className, id, ...props }: React.HTMLAttributes<HTMLHeadingElement>) {
const ctx = useDialogContext();
return (
<h2 className={cn('text-lg font-semibold leading-none tracking-tight', className)} {...props} />
<h2
id={id ?? ctx?.titleId}
className={cn('text-lg font-semibold leading-none tracking-tight', className)}
{...props}
/>
);
}
function DialogDescription({ className, ...props }: React.HTMLAttributes<HTMLParagraphElement>) {
function DialogDescription({ className, id, ...props }: React.HTMLAttributes<HTMLParagraphElement>) {
const ctx = useDialogContext();
return (
<p className={cn('text-sm text-muted-foreground', className)} {...props} />
<p
id={id ?? ctx?.descriptionId}
className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
);
}