Files
goodgo-platform/apps/web/components/neighborhood/neighborhood-poi-map.tsx
Ho Ngoc Hai 0fc6516880
Some checks failed
Security Scanning / Trivy Filesystem Scan (push) Failing after 31s
Security Scanning / Security Gate (push) Failing after 2s
CI / Lint → Typecheck → Test → Build (22) (push) Failing after 13s
Deploy / Build API Image (push) Failing after 36s
Deploy / Build Web Image (push) Failing after 12s
Deploy / Build AI Services Image (push) Failing after 12s
Security Scanning / Trivy Scan — API Image (push) Failing after 1m5s
CI / E2E Tests (push) Has been skipped
CodeQL Analysis / CodeQL (javascript-typescript) (push) Failing after 1m24s
E2E Tests / Playwright E2E (push) Failing after 20s
Security Scanning / Dependency Audit (pnpm) (push) Failing after 3s
Deploy / Deploy to Production (push) Has been cancelled
Deploy / Deploy to Staging (push) Has been cancelled
Deploy / Smoke Test Staging (push) Has been cancelled
Deploy / Rollback Staging (push) Has been cancelled
Deploy / Smoke Test Production (push) Has been cancelled
Deploy / Rollback Production (push) Has been cancelled
Security Scanning / Trivy Scan — AI Services Image (push) Has been cancelled
Security Scanning / Trivy Scan — Web Image (push) Has been cancelled
feat(maps): dark/light Mapbox theme + fix empty Image src & missing keys
Mapbox theming
--------------
- New hook `lib/mapbox-style.ts` returning streets-v12 (light) or
  dark-v11 (dark) from the app's useTheme().
- Six map components now initialise with the themed style and
  `map.setStyle(...)` on theme change: project-map, park-map,
  listing-map, district-heatmap (plus re-adding its heatmap source
  after style.load), neighborhood-poi-map, valuation/comparables-map.
- Marker / popup DOM styles swapped from hard-coded white/#666/#green
  to shadcn CSS tokens (--card, --card-foreground, --muted-foreground,
  --primary, --border). Global Mapbox popup + control + attribution
  skins added in app/globals.css.
- POI filter pills on neighborhood-poi-map were hard-coded `bg-white`
  which rendered same-colour text on white in dark mode — switched to
  `bg-card`/`bg-card/60` for proper contrast.
- Extend the MockMap in comparables-map.spec.tsx with setStyle/on
  so the new theme-sync effect doesn't blow up in tests.

Detail client normaliser (du-an-server)
---------------------------------------
- Project media from the backend is a `string[]` (raw URLs) or richer
  `{url,...}` objects. Handle both shapes and drop entries without
  a URL so we never feed "" to <Image src>.
- Amenities are `string[]` in the DB but the frontend type expects
  `{id,name,icon,category}`; normalise strings into objects so the
  AmenitiesTab has stable keys and a displayable name.

Resolves three classes of runtime warnings on /du-an/<slug>:
"Image is missing required 'src' property", "ReactDOM.preload ...
empty href", and "Each child in a list should have a unique 'key'
prop" (AmenitiesTab).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 14:12:28 +07:00

255 lines
7.8 KiB
TypeScript

'use client';
/* eslint-disable import-x/no-named-as-default-member */
import mapboxgl from 'mapbox-gl';
import * as React from 'react';
import 'mapbox-gl/dist/mapbox-gl.css';
import { useMapboxStyle } from '@/lib/mapbox-style';
import { cn } from '@/lib/utils';
import { type POIItem, type POICategory, POI_CATEGORY_CONFIG } from './types';
interface NeighborhoodPOIMapProps {
center: { lat: number; lng: number };
pois: POIItem[];
zoom?: number;
height?: string;
className?: string;
}
export function NeighborhoodPOIMap({
center,
pois,
zoom = 14,
height = '400px',
className,
}: NeighborhoodPOIMapProps) {
const mapContainerRef = React.useRef<HTMLDivElement>(null);
const mapRef = React.useRef<mapboxgl.Map | null>(null);
const markersRef = React.useRef<mapboxgl.Marker[]>([]);
const mapStyle = useMapboxStyle();
const [activeCategories, setActiveCategories] = React.useState<Set<POICategory>>(
() => new Set(Object.keys(POI_CATEGORY_CONFIG) as POICategory[]),
);
const toggleCategory = React.useCallback((category: POICategory) => {
setActiveCategories((prev) => {
const next = new Set(prev);
if (next.has(category)) {
next.delete(category);
} else {
next.add(category);
}
return next;
});
}, []);
// Initialize map
React.useEffect(() => {
if (!mapContainerRef.current) return;
const token = process.env['NEXT_PUBLIC_MAPBOX_TOKEN'];
if (!token) return;
mapboxgl.accessToken = token;
const map = new mapboxgl.Map({
container: mapContainerRef.current,
style: mapStyle,
center: [center.lng, center.lat],
zoom,
attributionControl: false,
});
map.addControl(new mapboxgl.NavigationControl(), 'top-right');
map.addControl(
new mapboxgl.AttributionControl({ compact: true }),
'bottom-right',
);
mapRef.current = map;
return () => {
map.remove();
mapRef.current = null;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Sync style changes with theme
React.useEffect(() => {
const map = mapRef.current;
if (!map) return;
map.setStyle(mapStyle);
}, [mapStyle]);
// Update center when prop changes
React.useEffect(() => {
mapRef.current?.flyTo({ center: [center.lng, center.lat], zoom });
}, [center, zoom]);
// Render POI markers based on active categories
React.useEffect(() => {
const map = mapRef.current;
if (!map) return;
// Clear existing markers
markersRef.current.forEach((m) => m.remove());
markersRef.current = [];
const visiblePois = pois.filter((poi) => activeCategories.has(poi.category));
visiblePois.forEach((poi) => {
const config = POI_CATEGORY_CONFIG[poi.category];
const el = document.createElement('div');
el.className = 'poi-marker';
el.style.cssText = `
width: 28px;
height: 28px;
border-radius: 50%;
background: ${config.color};
border: 2px solid white;
box-shadow: 0 2px 6px rgba(0,0,0,0.25);
display: flex;
align-items: center;
justify-content: center;
font-size: 14px;
cursor: pointer;
transition: transform 0.15s;
`;
el.textContent = config.icon;
el.title = `${poi.name} (${config.label})`;
el.addEventListener('mouseenter', () => {
el.style.transform = 'scale(1.3)';
});
el.addEventListener('mouseleave', () => {
el.style.transform = 'scale(1)';
});
const popup = new mapboxgl.Popup({ offset: 20, closeButton: false })
.setHTML(
`<div style="font-family:system-ui,sans-serif;background:hsl(var(--card));color:hsl(var(--card-foreground));padding:8px;border-radius:6px;">
<p style="font-weight:600;font-size:13px;margin:0 0 2px;">${config.icon} ${poi.name}</p>
<p style="font-size:12px;color:hsl(var(--muted-foreground));margin:0;">${config.label}${poi.distance ? ` · ${poi.distance}m` : ''}</p>
</div>`,
);
const marker = new mapboxgl.Marker({ element: el, anchor: 'center' })
.setLngLat([poi.lng, poi.lat])
.setPopup(popup)
.addTo(map);
markersRef.current.push(marker);
});
}, [pois, activeCategories]);
// Add property center marker
React.useEffect(() => {
const map = mapRef.current;
if (!map) return;
const el = document.createElement('div');
el.style.cssText = `
width: 16px;
height: 16px;
border-radius: 50%;
background: hsl(var(--primary));
border: 3px solid hsl(var(--card));
box-shadow: 0 0 0 2px hsl(var(--primary)), 0 2px 8px rgba(0,0,0,0.3);
`;
const marker = new mapboxgl.Marker({ element: el, anchor: 'center' })
.setLngLat([center.lng, center.lat])
.addTo(map);
return () => {
marker.remove();
};
}, [center]);
const hasToken = typeof process !== 'undefined' && process.env['NEXT_PUBLIC_MAPBOX_TOKEN'];
const allCategories = Object.entries(POI_CATEGORY_CONFIG) as [
POICategory,
(typeof POI_CATEGORY_CONFIG)[POICategory],
][];
return (
<div className={cn('relative overflow-hidden rounded-lg border', className)}>
<div ref={mapContainerRef} style={{ height }} className="w-full" />
{/* Layer toggle controls */}
<div className="absolute left-3 top-3 flex flex-col gap-1.5">
{allCategories.map(([key, config]) => {
const isActive = activeCategories.has(key);
const poiCount = pois.filter((p) => p.category === key).length;
return (
<button
key={key}
type="button"
onClick={() => toggleCategory(key)}
className={cn(
'flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-medium shadow-sm transition-all',
isActive
? 'bg-card text-card-foreground ring-1 ring-inset ring-border'
: 'bg-card/60 text-muted-foreground line-through ring-1 ring-inset ring-transparent',
)}
title={`${isActive ? 'Ẩn' : 'Hiện'} ${config.label}`}
>
<span>{config.icon}</span>
<span>{config.label}</span>
{poiCount > 0 && (
<span
className={cn(
'ml-0.5 inline-flex h-4 min-w-4 items-center justify-center rounded-full px-1 text-[10px] font-bold',
isActive
? 'bg-primary/10 text-primary'
: 'bg-muted text-muted-foreground',
)}
>
{poiCount}
</span>
)}
</button>
);
})}
</div>
{/* Fallback when no Mapbox token */}
{!hasToken && (
<div
className="absolute inset-0 flex items-center justify-center bg-gradient-to-b from-blue-50 to-green-50"
style={{ height }}
>
<div className="text-center">
<svg
className="mx-auto mb-2 h-10 w-10 text-muted-foreground"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={1.5}
d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"
/>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={1.5}
d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"
/>
</svg>
<p className="text-sm text-muted-foreground">
Thiết lập NEXT_PUBLIC_MAPBOX_TOKEN đ hiển thị bản đ POI
</p>
</div>
</div>
)}
</div>
);
}