feat(listings-frontend): add create/edit form, detail page, and listing components

- Multi-step wizard for listing creation (basic info, location, details, pricing, images)
- Listing detail page with image gallery, property specs, seller/agent info, stats
- Listings index page with filters (transaction type, property type) and pagination
- Edit page with tab-based form (read-only until backend PATCH endpoint available)
- Drag & drop image upload component with preview and multi-file support
- Dashboard layout with navigation bar
- New UI primitives: textarea, select, badge, tabs
- Listings API client with typed endpoints matching backend contract
- Zod validation schemas for all form steps
- Status badges with Vietnamese labels for all listing states
- Responsive design across all pages

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Ho Ngoc Hai
2026-04-08 01:54:08 +07:00
parent 8a33aae026
commit 207a2013f3
18 changed files with 1834 additions and 8 deletions

View File

@@ -0,0 +1,84 @@
'use client';
import * as React from 'react';
import { cn } from '@/lib/utils';
import type { PropertyMedia } from '@/lib/listings-api';
interface ImageGalleryProps {
media: PropertyMedia[];
className?: string;
}
export function ImageGallery({ media, className }: ImageGalleryProps) {
const images = media.filter((m) => m.type === 'image').sort((a, b) => a.order - b.order);
const [selectedIndex, setSelectedIndex] = React.useState(0);
if (images.length === 0) {
return (
<div
className={cn(
'flex aspect-video items-center justify-center rounded-lg bg-muted text-muted-foreground',
className,
)}
>
Chưa hình nh
</div>
);
}
return (
<div className={cn('space-y-3', className)}>
{/* Main image */}
<div className="relative aspect-video overflow-hidden rounded-lg bg-muted">
<img
src={images[selectedIndex]?.url}
alt={images[selectedIndex]?.caption || `Ảnh ${selectedIndex + 1}`}
className="h-full w-full object-cover"
/>
{images.length > 1 && (
<>
<button
onClick={() => setSelectedIndex((i) => (i > 0 ? i - 1 : images.length - 1))}
className="absolute left-2 top-1/2 -translate-y-1/2 rounded-full bg-black/50 p-2 text-white transition-colors hover:bg-black/70"
aria-label="Ảnh trước"
>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m15 18-6-6 6-6"/></svg>
</button>
<button
onClick={() => setSelectedIndex((i) => (i < images.length - 1 ? i + 1 : 0))}
className="absolute right-2 top-1/2 -translate-y-1/2 rounded-full bg-black/50 p-2 text-white transition-colors hover:bg-black/70"
aria-label="Ảnh tiếp"
>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m9 18 6-6-6-6"/></svg>
</button>
</>
)}
<div className="absolute bottom-2 right-2 rounded bg-black/60 px-2 py-1 text-xs text-white">
{selectedIndex + 1} / {images.length}
</div>
</div>
{/* Thumbnails */}
{images.length > 1 && (
<div className="flex gap-2 overflow-x-auto pb-1">
{images.map((img, index) => (
<button
key={img.id}
onClick={() => setSelectedIndex(index)}
className={cn(
'h-16 w-16 flex-shrink-0 overflow-hidden rounded-md border-2 transition-colors',
index === selectedIndex ? 'border-primary' : 'border-transparent opacity-70 hover:opacity-100',
)}
>
<img
src={img.url}
alt={img.caption || `Thumbnail ${index + 1}`}
className="h-full w-full object-cover"
/>
</button>
))}
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,167 @@
'use client';
import * as React from 'react';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
interface ImageFile {
file: File;
preview: string;
}
interface ImageUploadProps {
images: ImageFile[];
onChange: (images: ImageFile[]) => void;
maxFiles?: number;
className?: string;
}
export function ImageUpload({ images, onChange, maxFiles = 20, className }: ImageUploadProps) {
const inputRef = React.useRef<HTMLInputElement>(null);
const [isDragging, setIsDragging] = React.useState(false);
const addFiles = React.useCallback(
(files: FileList | File[]) => {
const newImages: ImageFile[] = [];
const allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
const maxSize = 10 * 1024 * 1024; // 10MB
Array.from(files).forEach((file) => {
if (!allowedTypes.includes(file.type)) return;
if (file.size > maxSize) return;
if (images.length + newImages.length >= maxFiles) return;
newImages.push({
file,
preview: URL.createObjectURL(file),
});
});
if (newImages.length > 0) {
onChange([...images, ...newImages]);
}
},
[images, onChange, maxFiles],
);
const removeImage = React.useCallback(
(index: number) => {
const updated = [...images];
URL.revokeObjectURL(updated[index]!.preview);
updated.splice(index, 1);
onChange(updated);
},
[images, onChange],
);
const handleDragOver = React.useCallback((e: React.DragEvent) => {
e.preventDefault();
setIsDragging(true);
}, []);
const handleDragLeave = React.useCallback((e: React.DragEvent) => {
e.preventDefault();
setIsDragging(false);
}, []);
const handleDrop = React.useCallback(
(e: React.DragEvent) => {
e.preventDefault();
setIsDragging(false);
if (e.dataTransfer.files.length > 0) {
addFiles(e.dataTransfer.files);
}
},
[addFiles],
);
React.useEffect(() => {
return () => {
images.forEach((img) => URL.revokeObjectURL(img.preview));
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<div className={cn('space-y-4', className)}>
<div
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
onClick={() => inputRef.current?.click()}
className={cn(
'flex cursor-pointer flex-col items-center justify-center rounded-lg border-2 border-dashed p-8 transition-colors',
isDragging
? 'border-primary bg-primary/5'
: 'border-muted-foreground/25 hover:border-primary/50',
)}
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="40"
height="40"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
className="mb-3 text-muted-foreground"
>
<rect width="18" height="18" x="3" y="3" rx="2" ry="2" />
<circle cx="9" cy="9" r="2" />
<path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21" />
</svg>
<p className="text-sm font-medium">Kéo thả nh vào đây hoặc nhấp đ chọn</p>
<p className="mt-1 text-xs text-muted-foreground">
JPG, PNG, WebP - Tối đa {maxFiles} nh, mỗi nh 10MB
</p>
<input
ref={inputRef}
type="file"
accept="image/jpeg,image/png,image/webp"
multiple
className="hidden"
onChange={(e) => {
if (e.target.files) addFiles(e.target.files);
e.target.value = '';
}}
/>
</div>
{images.length > 0 && (
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4">
{images.map((img, index) => (
<div key={img.preview} className="group relative aspect-square overflow-hidden rounded-lg border">
<img
src={img.preview}
alt={`Ảnh ${index + 1}`}
className="h-full w-full object-cover"
/>
<div className="absolute inset-0 flex items-center justify-center bg-black/40 opacity-0 transition-opacity group-hover:opacity-100">
<Button
type="button"
variant="destructive"
size="sm"
onClick={(e) => {
e.stopPropagation();
removeImage(index);
}}
>
Xóa
</Button>
</div>
{index === 0 && (
<span className="absolute left-1.5 top-1.5 rounded bg-primary px-1.5 py-0.5 text-[10px] font-semibold text-primary-foreground">
nh bìa
</span>
)}
</div>
))}
</div>
)}
</div>
);
}
export type { ImageFile };

View File

@@ -0,0 +1,249 @@
'use client';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Select } from '@/components/ui/select';
import {
TRANSACTION_TYPES,
PROPERTY_TYPES,
DIRECTIONS,
} from '@/lib/validations/listings';
import type { UseFormRegister, FieldErrors } from 'react-hook-form';
import type { CreateListingFormData } from '@/lib/validations/listings';
interface StepProps {
register: UseFormRegister<CreateListingFormData>;
errors: FieldErrors<CreateListingFormData>;
}
function FieldError({ message }: { message?: string }) {
if (!message) return null;
return <p 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" {...register('transactionType')}>
<option value="">-- Chọn --</option>
{TRANSACTION_TYPES.map((t) => (
<option key={t.value} value={t.value}>
{t.label}
</option>
))}
</Select>
<FieldError message={errors.transactionType?.message} />
</div>
<div>
<Label htmlFor="propertyType">Loại bất đng sản *</Label>
<Select id="propertyType" {...register('propertyType')}>
<option value="">-- Chọn --</option>
{PROPERTY_TYPES.map((t) => (
<option key={t.value} value={t.value}>
{t.label}
</option>
))}
</Select>
<FieldError 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} />
</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..."
{...register('description')}
/>
<FieldError message={errors.description?.message} />
</div>
</div>
);
}
// ─── Step 2: Location ────────────────────────────────────
export function StepLocation({ register, errors }: StepProps) {
return (
<div className="space-y-4">
<h3 className="text-lg font-semibold">Vị trí</h3>
<div>
<Label htmlFor="address">Đa chỉ *</Label>
<Input id="address" placeholder="Số nhà, tên đường" {...register('address')} />
<FieldError 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} />
</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} />
</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} />
</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"
{...register('latitude')}
/>
<FieldError message={errors.latitude?.message} />
</div>
<div>
<Label htmlFor="longitude">Kinh đ</Label>
<Input
id="longitude"
type="number"
step="any"
placeholder="VD: 106.7009"
{...register('longitude')}
/>
<FieldError message={errors.longitude?.message} />
</div>
</div>
<div className="rounded-lg border border-dashed p-6 text-center text-sm text-muted-foreground">
Bản đ chọn vị trí sẽ đưc tích hợp trong phiên bản tiếp theo
</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" {...register('areaM2')} />
<FieldError 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>
</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" {...register('priceVND')} />
<FieldError 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>
);
}

View File

@@ -0,0 +1,12 @@
import { Badge } from '@/components/ui/badge';
import { LISTING_STATUSES } from '@/lib/validations/listings';
import type { ListingStatus } from '@/lib/listings-api';
interface ListingStatusBadgeProps {
status: ListingStatus;
}
export function ListingStatusBadge({ status }: ListingStatusBadgeProps) {
const config = LISTING_STATUSES[status] ?? { label: status, variant: 'outline' as const };
return <Badge variant={config.variant}>{config.label}</Badge>;
}

View File

@@ -0,0 +1,33 @@
import * as React from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils';
const badgeVariants = cva(
'inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
{
variants: {
variant: {
default: 'border-transparent bg-primary text-primary-foreground',
secondary: 'border-transparent bg-secondary text-secondary-foreground',
destructive: 'border-transparent bg-destructive text-destructive-foreground',
outline: 'text-foreground',
success: 'border-transparent bg-green-100 text-green-800',
warning: 'border-transparent bg-yellow-100 text-yellow-800',
info: 'border-transparent bg-blue-100 text-blue-800',
},
},
defaultVariants: {
variant: 'default',
},
},
);
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return <div className={cn(badgeVariants({ variant }), className)} {...props} />;
}
export { Badge, badgeVariants };

View File

@@ -0,0 +1,24 @@
import * as React from 'react';
import { cn } from '@/lib/utils';
export interface SelectProps extends React.SelectHTMLAttributes<HTMLSelectElement> {}
const Select = React.forwardRef<HTMLSelectElement, SelectProps>(
({ className, children, ...props }, ref) => {
return (
<select
className={cn(
'flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
className,
)}
ref={ref}
{...props}
>
{children}
</select>
);
},
);
Select.displayName = 'Select';
export { Select };

View File

@@ -0,0 +1,90 @@
'use client';
import * as React from 'react';
import { cn } from '@/lib/utils';
interface TabsContextValue {
value: string;
onValueChange: (value: string) => void;
}
const TabsContext = React.createContext<TabsContextValue | null>(null);
function useTabs() {
const context = React.useContext(TabsContext);
if (!context) throw new Error('Tabs components must be used within <Tabs>');
return context;
}
interface TabsProps extends React.HTMLAttributes<HTMLDivElement> {
value: string;
onValueChange: (value: string) => void;
}
function Tabs({ value, onValueChange, className, ...props }: TabsProps) {
return (
<TabsContext.Provider value={{ value, onValueChange }}>
<div className={cn('w-full', className)} {...props} />
</TabsContext.Provider>
);
}
const TabsList = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
'inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground',
className,
)}
{...props}
/>
),
);
TabsList.displayName = 'TabsList';
interface TabsTriggerProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
value: string;
}
const TabsTrigger = React.forwardRef<HTMLButtonElement, TabsTriggerProps>(
({ className, value, ...props }, ref) => {
const { value: selectedValue, onValueChange } = useTabs();
return (
<button
ref={ref}
className={cn(
'inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50',
selectedValue === value
? 'bg-background text-foreground shadow-sm'
: 'hover:bg-background/50',
className,
)}
onClick={() => onValueChange(value)}
{...props}
/>
);
},
);
TabsTrigger.displayName = 'TabsTrigger';
interface TabsContentProps extends React.HTMLAttributes<HTMLDivElement> {
value: string;
}
const TabsContent = React.forwardRef<HTMLDivElement, TabsContentProps>(
({ className, value, ...props }, ref) => {
const { value: selectedValue } = useTabs();
if (selectedValue !== value) return null;
return (
<div
ref={ref}
className={cn('mt-2 ring-offset-background focus-visible:outline-none', className)}
{...props}
/>
);
},
);
TabsContent.displayName = 'TabsContent';
export { Tabs, TabsList, TabsTrigger, TabsContent };

View File

@@ -0,0 +1,22 @@
import * as React from 'react';
import { cn } from '@/lib/utils';
export interface TextareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
({ className, ...props }, ref) => {
return (
<textarea
className={cn(
'flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
className,
)}
ref={ref}
{...props}
/>
);
},
);
Textarea.displayName = 'Textarea';
export { Textarea };