Files
goodgo-platform/apps/web/components/listings/listing-form-steps.tsx
Ho Ngoc Hai d7961e297c 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>
2026-04-24 10:33:54 +07:00

484 lines
18 KiB
TypeScript

'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';
import { Select } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import {
TRANSACTION_TYPES,
PROPERTY_TYPES,
DIRECTIONS,
FURNISHING_OPTIONS,
PROPERTY_CONDITION_OPTIONS,
type CreateListingFormData,
} from '@/lib/validations/listings';
// Mapbox picker is client-only + imports `mapbox-gl` which pulls WebGL
// utilities — dynamic-import with ssr:false to keep it out of the server
// bundle.
const LocationPicker = dynamic(
() => import('@/components/map/location-picker').then((m) => m.LocationPicker),
{
ssr: false,
loading: () => (
<div className="flex h-[320px] items-center justify-center rounded-lg border bg-muted text-sm text-muted-foreground">
Đang tải bản đ...
</div>
),
},
);
interface StepProps {
register: UseFormRegister<CreateListingFormData>;
errors: FieldErrors<CreateListingFormData>;
}
interface StepLocationProps extends StepProps {
/** Optional — when provided, StepLocation renders the Mapbox picker and
* writes latitude/longitude (+ auto-fills address/ward/district/city on
* geocoder pick) into the form state. */
setValue?: UseFormSetValue<CreateListingFormData>;
watch?: UseFormWatch<CreateListingFormData>;
}
function FieldError({ id, message }: { id: string; message?: string }) {
if (!message) return null;
return (
<p id={id} role="alert" className="mt-1 text-xs text-destructive">
{message}
</p>
);
}
// ─── Step 1: Basic Info ──────────────────────────────────
export function StepBasicInfo({ register, errors }: StepProps) {
return (
<div className="space-y-4">
<h3 className="text-lg font-semibold">Thông tin bản</h3>
<div className="grid gap-4 sm:grid-cols-2">
<div>
<Label htmlFor="transactionType">Loại giao dịch *</Label>
<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}>
{t.label}
</option>
))}
</Select>
<FieldError id="transactionType-error" message={errors.transactionType?.message} />
</div>
<div>
<Label htmlFor="propertyType">Loại bất đng sản *</Label>
<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}>
{t.label}
</option>
))}
</Select>
<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"
aria-invalid={!!errors.title}
aria-describedby={errors.title ? 'title-error' : undefined}
{...register('title')}
/>
<FieldError id="title-error" message={errors.title?.message} />
</div>
<div>
<Label htmlFor="description"> tả chi tiết *</Label>
<Textarea
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 id="description-error" message={errors.description?.message} />
</div>
</div>
);
}
// ─── Step 2: Location ────────────────────────────────────
export function StepLocation({ register, errors, setValue, watch }: StepLocationProps) {
// Watch lat/lng so the picker stays in sync when the user edits the text
// inputs manually.
const latStr = watch?.('latitude') ?? '';
const lngStr = watch?.('longitude') ?? '';
const latNum = latStr ? Number(latStr) : null;
const lngNum = lngStr ? Number(lngStr) : null;
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}
lng={lngValid ? lngNum : null}
onChange={(coords, resolved) => {
setValue('latitude', coords.lat.toFixed(6), { shouldValidate: true, shouldDirty: true });
setValue('longitude', coords.lng.toFixed(6), { shouldValidate: true, shouldDirty: true });
if (resolved) {
if (resolved.address) setValue('address', resolved.address, { shouldDirty: true });
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"
/>
)}
<div>
<Label htmlFor="address">Đa chỉ *</Label>
<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ã"
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"
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ố"
aria-invalid={!!errors.city}
aria-describedby={errors.city ? 'city-error' : undefined}
{...register('city')}
/>
<FieldError id="city-error" message={errors.city?.message} />
</div>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div>
<Label htmlFor="latitude"> đ</Label>
<Input
id="latitude"
type="number"
step="any"
placeholder="VD: 10.7769"
aria-invalid={!!errors.latitude}
aria-describedby={errors.latitude ? 'latitude-error' : undefined}
{...register('latitude')}
/>
<FieldError id="latitude-error" message={errors.latitude?.message} />
</div>
<div>
<Label htmlFor="longitude">Kinh đ</Label>
<Input
id="longitude"
type="number"
step="any"
placeholder="VD: 106.7009"
aria-invalid={!!errors.longitude}
aria-describedby={errors.longitude ? 'longitude-error' : undefined}
{...register('longitude')}
/>
<FieldError id="longitude-error" message={errors.longitude?.message} />
</div>
</div>
</div>
);
}
// ─── Step 3: Details ─────────────────────────────────────
export function StepDetails({ register, errors }: StepProps) {
return (
<div className="space-y-4">
<h3 className="text-lg font-semibold">Thông số chi tiết</h3>
<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"
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>
<Input id="usableAreaM2" type="number" step="0.1" {...register('usableAreaM2')} />
</div>
<div>
<Label htmlFor="bedrooms">Phòng ngủ</Label>
<Input id="bedrooms" type="number" min="0" {...register('bedrooms')} />
</div>
<div>
<Label htmlFor="bathrooms">Phòng tắm</Label>
<Input id="bathrooms" type="number" min="0" {...register('bathrooms')} />
</div>
<div>
<Label htmlFor="floors">Số tầng</Label>
<Input id="floors" type="number" min="0" {...register('floors')} />
</div>
<div>
<Label htmlFor="floor">Tầng số</Label>
<Input id="floor" type="number" min="0" {...register('floor')} />
</div>
<div>
<Label htmlFor="totalFloors">Tổng số tầng tòa nhà</Label>
<Input id="totalFloors" type="number" min="0" {...register('totalFloors')} />
</div>
<div>
<Label htmlFor="direction">Hướng nhà</Label>
<Select id="direction" {...register('direction')}>
<option value="">-- Không chọn --</option>
{DIRECTIONS.map((d) => (
<option key={d.value} value={d.value}>
{d.label}
</option>
))}
</Select>
</div>
<div>
<Label htmlFor="yearBuilt">Năm xây dựng</Label>
<Input id="yearBuilt" type="number" placeholder="VD: 2020" {...register('yearBuilt')} />
</div>
</div>
<div>
<Label htmlFor="legalStatus">Pháp </Label>
<Input id="legalStatus" placeholder="VD: Sổ hồng, sổ đỏ..." {...register('legalStatus')} />
</div>
<div>
<Label htmlFor="projectName">Tên dự án</Label>
<Input id="projectName" placeholder="VD: Vinhomes Central Park" {...register('projectName')} />
</div>
<div>
<Label htmlFor="amenities">Tiện ích (cách nhau bởi dấu phẩy)</Label>
<Input id="amenities" placeholder="VD: Hồ bơi, Gym, Công viên" {...register('amenities')} />
</div>
<fieldset className="space-y-4 rounded-lg border p-4">
<legend className="px-2 text-sm font-semibold">Nội thất & điều kiện</legend>
<div className="grid gap-4 sm:grid-cols-2 md:grid-cols-3">
<div>
<Label htmlFor="furnishing">Nội thất</Label>
<Select id="furnishing" {...register('furnishing')}>
<option value="">-- Không chọn --</option>
{FURNISHING_OPTIONS.map((o) => (
<option key={o.value} value={o.value}>
{o.label}
</option>
))}
</Select>
</div>
<div>
<Label htmlFor="propertyCondition">Tình trạng</Label>
<Select id="propertyCondition" {...register('propertyCondition')}>
<option value="">-- Không chọn --</option>
{PROPERTY_CONDITION_OPTIONS.map((o) => (
<option key={o.value} value={o.value}>
{o.label}
</option>
))}
</Select>
</div>
<div>
<Label htmlFor="balconyDirection">Hướng ban công</Label>
<Select id="balconyDirection" {...register('balconyDirection')}>
<option value="">-- Không chọn --</option>
{DIRECTIONS.map((d) => (
<option key={d.value} value={d.value}>
{d.label}
</option>
))}
</Select>
</div>
<div>
<Label htmlFor="maintenanceFeeVND">Phí quản / tháng (VNĐ)</Label>
<Input
id="maintenanceFeeVND"
type="text"
inputMode="numeric"
placeholder="VD: 2500000"
{...register('maintenanceFeeVND')}
/>
</div>
<div>
<Label htmlFor="parkingSlots">Chỗ đ xe</Label>
<Input id="parkingSlots" type="number" min="0" {...register('parkingSlots')} />
</div>
<div>
<Label htmlFor="petFriendly">Cho phép thú cưng</Label>
<Select id="petFriendly" {...register('petFriendly')}>
<option value="">-- Không chọn --</option>
<option value="true"></option>
<option value="false">Không</option>
</Select>
</div>
</div>
<div>
<Label htmlFor="viewType">View (cách nhau bởi dấu phẩy)</Label>
<Input
id="viewType"
placeholder="VD: Sông, Thành phố, Công viên"
{...register('viewType')}
/>
</div>
<div>
<Label htmlFor="suitableFor">Phù hợp với (cách nhau bởi dấu phẩy)</Label>
<Input
id="suitableFor"
placeholder="VD: Gia đình có con nhỏ, Người đi làm xa"
{...register('suitableFor')}
/>
</div>
<div>
<Label htmlFor="whyThisLocation"> sao khu vực này phù hợp</Label>
<Textarea
id="whyThisLocation"
rows={3}
placeholder="Mô tả ngắn lý do khu vực này phù hợp với người mua..."
{...register('whyThisLocation')}
/>
</div>
</fieldset>
</div>
);
}
// ─── Step 4: Pricing ─────────────────────────────────────
export function StepPricing({ register, errors }: StepProps) {
return (
<div className="space-y-4">
<h3 className="text-lg font-semibold">Giá & Hoa hồng</h3>
<div>
<Label htmlFor="priceVND">Giá bán (VNĐ) *</Label>
<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>
<div className="grid gap-4 sm:grid-cols-2">
<div>
<Label htmlFor="rentPriceMonthly">Giá thuê/tháng (VNĐ)</Label>
<Input id="rentPriceMonthly" placeholder="Chỉ áp dụng cho thuê" {...register('rentPriceMonthly')} />
</div>
<div>
<Label htmlFor="commissionPct">Hoa hồng (%)</Label>
<Input
id="commissionPct"
type="number"
step="0.1"
min="0"
max="100"
placeholder="VD: 2.5"
{...register('commissionPct')}
/>
</div>
</div>
</div>
);
}