add: add address page

This commit is contained in:
Mahyar Khanbolooki
2025-08-08 19:41:29 +03:30
parent 40f4ec6449
commit 95a21b84ab
15 changed files with 1021 additions and 16 deletions
+57
View File
@@ -18,6 +18,8 @@
"@tanstack/react-query": "^5.81.5",
"@tanstack/react-query-devtools": "^5.81.5",
"@tanstack/react-table": "^8.21.3",
"@types/leaflet": "^1.9.20",
"@types/lodash": "^4.17.20",
"axios": "^1.10.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
@@ -26,6 +28,8 @@
"i18next": "^25.3.2",
"i18next-resources-to-backend": "^1.2.1",
"iconsax-react": "^0.0.8",
"leaflet": "^1.9.4",
"lodash": "^4.17.21",
"lucide-react": "^0.525.0",
"next": "15.3.4",
"next-i18n-router": "^5.5.3",
@@ -35,6 +39,7 @@
"react-day-picker": "^9.8.0",
"react-dom": "^19.0.0",
"react-i18next": "^15.6.1",
"react-leaflet": "^5.0.0",
"react-virtualized": "^9.22.6",
"tailwind-merge": "^3.3.1",
"use-long-press": "^3.3.0",
@@ -2749,6 +2754,17 @@
"version": "1.1.1",
"license": "MIT"
},
"node_modules/@react-leaflet/core": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/@react-leaflet/core/-/core-3.0.0.tgz",
"integrity": "sha512-3EWmekh4Nz+pGcr+xjf0KNyYfC3U2JjnkWsh0zcqaexYqmmB5ZhH37kz41JXGmKzpaMZCnPofBBm64i+YrEvGQ==",
"license": "Hippocratic-2.1",
"peerDependencies": {
"leaflet": "^1.9.0",
"react": "^19.0.0",
"react-dom": "^19.0.0"
}
},
"node_modules/@rollup/plugin-babel": {
"version": "5.3.1",
"resolved": "https://registry.npmjs.org/@rollup/plugin-babel/-/plugin-babel-5.3.1.tgz",
@@ -3247,6 +3263,12 @@
"dev": true,
"license": "MIT"
},
"node_modules/@types/geojson": {
"version": "7946.0.16",
"resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz",
"integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==",
"license": "MIT"
},
"node_modules/@types/glob": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/@types/glob/-/glob-7.2.0.tgz",
@@ -3266,6 +3288,21 @@
"dev": true,
"license": "MIT"
},
"node_modules/@types/leaflet": {
"version": "1.9.20",
"resolved": "https://registry.npmjs.org/@types/leaflet/-/leaflet-1.9.20.tgz",
"integrity": "sha512-rooalPMlk61LCaLOvBF2VIf9M47HgMQqi5xQ9QRi7c8PkdIe0WrIi5IxXUXQjAdL0c+vcQ01mYWbthzmp9GHWw==",
"license": "MIT",
"dependencies": {
"@types/geojson": "*"
}
},
"node_modules/@types/lodash": {
"version": "4.17.20",
"resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.20.tgz",
"integrity": "sha512-H3MHACvFUEiujabxhaI/ImO6gUrd8oOurg7LQtS7mbwIXA/cUqWrvBsaeJ23aZEPk1TAYkurjfMbSELfoCXlGA==",
"license": "MIT"
},
"node_modules/@types/minimatch": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-5.1.2.tgz",
@@ -6470,6 +6507,12 @@
"node": ">=0.10"
}
},
"node_modules/leaflet": {
"version": "1.9.4",
"resolved": "https://registry.npmjs.org/leaflet/-/leaflet-1.9.4.tgz",
"integrity": "sha512-nxS1ynzJOmOlHp+iL3FyWqK89GtNL8U8rvlMOsQdTTssxZwCXh8N2NB3GDQOL+YR3XnWyZAxwQixURb+FA74PA==",
"license": "BSD-2-Clause"
},
"node_modules/leven": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz",
@@ -7650,6 +7693,20 @@
"version": "16.13.1",
"license": "MIT"
},
"node_modules/react-leaflet": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/react-leaflet/-/react-leaflet-5.0.0.tgz",
"integrity": "sha512-CWbTpr5vcHw5bt9i4zSlPEVQdTVcML390TjeDG0cK59z1ylexpqC6M1PJFjV8jD7CF+ACBFsLIDs6DRMoLEofw==",
"license": "Hippocratic-2.1",
"dependencies": {
"@react-leaflet/core": "^3.0.0"
},
"peerDependencies": {
"leaflet": "^1.9.0",
"react": "^19.0.0",
"react-dom": "^19.0.0"
}
},
"node_modules/react-lifecycles-compat": {
"version": "3.0.4",
"license": "MIT"
+5
View File
@@ -19,6 +19,8 @@
"@tanstack/react-query": "^5.81.5",
"@tanstack/react-query-devtools": "^5.81.5",
"@tanstack/react-table": "^8.21.3",
"@types/leaflet": "^1.9.20",
"@types/lodash": "^4.17.20",
"axios": "^1.10.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
@@ -27,6 +29,8 @@
"i18next": "^25.3.2",
"i18next-resources-to-backend": "^1.2.1",
"iconsax-react": "^0.0.8",
"leaflet": "^1.9.4",
"lodash": "^4.17.21",
"lucide-react": "^0.525.0",
"next": "15.3.4",
"next-i18n-router": "^5.5.3",
@@ -36,6 +40,7 @@
"react-day-picker": "^9.8.0",
"react-dom": "^19.0.0",
"react-i18next": "^15.6.1",
"react-leaflet": "^5.0.0",
"react-virtualized": "^9.22.6",
"tailwind-merge": "^3.3.1",
"use-long-press": "^3.3.0",
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 608 B

+1 -1
View File
File diff suppressed because one or more lines are too long
@@ -0,0 +1,267 @@
'use client';
import { useSearchParams } from 'next/navigation';
import React, { useState, useEffect } from 'react';
import type { Icon } from 'leaflet';
import dynamic from 'next/dynamic';
import AnimatedBottomSheet from '@/components/bottomsheet/AnimatedBottomSheet';
import Button from '@/components/button/PrimaryButton';
import InputField from '@/components/input/InputField';
import { Skeleton } from '@/components/ui/skeleton';
const CustomMap = dynamic(
() => import('@/components/map/CustomMap'),
{ ssr: false } // Leaflet requires browser APIs
);
export interface MarkerData {
position: [number, number];
title: string;
icon?: Icon;
}
export interface NominatimReverseGeocodingResponse {
place_id: number
licence: string
osm_type: string
osm_id: number
lat: string
lon: string
class: string
type: string
place_rank: number
importance: number
addresstype: string
name: string
display_name: string
address: NominatimReverseGeocodingResponseAddress
boundingbox: string[]
}
export interface NominatimReverseGeocodingResponseAddress {
road: string
neighbourhood: string
suburb: string
city: string
district: string
county: string
province: string
"ISO3166-2-lvl4": string
postcode: string
country: string
state: string
country_code: string
}
function OrderTrackingPage() {
const params = useSearchParams();
const [selectedPosition, setSelectedPosition] = useState<[number, number] | null>(null);
const [selectedAddress, setSelectedAddress] = useState<NominatimReverseGeocodingResponse | null>(null);
const [markers, setMarkers] = useState<MarkerData[]>([]);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [mapCenter, setMapCenter] = useState<[number, number]>([Number(params?.get('lon')) || 35.6892, Number(params?.get('lon')) || 51.3890]);
const [bottomSheet1State, setBottomSheet1State] = useState<boolean>(false);
const [bottomSheet2State, setBottomSheet2State] = useState<boolean>(false);
// Example initial position (Tehran)
const initialPosition = React.useMemo<[number, number]>(() => [35.6892, 51.3890], []);
useEffect(() => {
// Initialize markers on the client side
const initializeMarkers = async () => {
// Dynamic import of Leaflet on the client side
const L = (await import('leaflet')).default;
setMarkers([
{
position: initialPosition,
title: 'Restaurant Location',
icon: new L.Icon({
iconUrl: '/icons/restaurant-marker.png',
iconSize: [25, 41],
iconAnchor: [12, 41],
popupAnchor: [1, -34],
})
}
]);
};
initializeMarkers();
}, [initialPosition]);
const handlePositionSelect = (position: [number, number]) => {
setSelectedPosition((prev) => {
if(prev === position) {
return prev;
}
setSelectedAddress(null);
return position;
});
setBottomSheet1State(position && true);
setBottomSheet2State(false);
// You can handle the selected position here
console.log('Selected position:', position);
};
const handleZoomChange = (zoom: number) => {
console.log('Zoom level:', zoom);
};
const handleMapClick = (e: L.LeafletMouseEvent) => {
console.log('Map clicked at:', e.latlng);
};
const toggleBottomSheet1 = () => {
setBottomSheet1State((prev) => !prev);
}
const toggleBottomSheet2 = async () => {
if (!selectedPosition) {
setBottomSheet1State(false);
setBottomSheet2State(false);
return;
}
setBottomSheet1State(false);
setBottomSheet2State((prev) => !prev);
if (!bottomSheet2State) {
const address = await fetchAddressFromCoordinates(selectedPosition[0], selectedPosition[1]);
setSelectedAddress(address);
}
}
const fetchAddressFromCoordinates = async (lat: unknown, lon: unknown) => {
try {
const response = await fetch(
`https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lon}&format=json&addressdetails=1&accept-language=fa`
);
const data = await response.json();
return data; // Full formatted address
} catch (error) {
console.error('Error fetching address:', error);
return null;
}
};
const submitAddressAction = () => {
}
return (
<div className="fixed inset-0 bg-gray-50">
<div className="absolute inset-0">
<CustomMap
initialPosition={mapCenter}
zoom={14}
markers={markers}
onPositionSelect={handlePositionSelect}
onZoomChange={handleZoomChange}
onClick={handleMapClick}
/>
</div>
{/* {selectedPosition && (
<div className="selected-location-indicator">
<p className="font-iran">موقعیت انتخاب شده: {selectedPosition[0].toFixed(4)}, {selectedPosition[1].toFixed(4)}</p>
</div>
)} */}
<div className="absolute bottom-0 left-0 right-0 z-[1000]">
<div className='relative w-full h-full' >
<AnimatedBottomSheet
bgOpacity={0}
inDuration={0}
blurOpacity={null}
noBlur
visible={bottomSheet1State}
showCloseButton={false}
showTitle={false}
overrideClassName='!pt-6'
>
<div className='grid grid-cols-2 gap-4 px-4'>
<Button
onClick={toggleBottomSheet2}
>
انتخاب
</Button>
<Button
onClick={toggleBottomSheet1}
className='bg-disabled! text-primary!'
>
انصراف
</Button>
</div>
</AnimatedBottomSheet>
<AnimatedBottomSheet
bgOpacity={0}
inDuration={0}
blurOpacity={null}
noBlur
visible={bottomSheet2State}
title='آدرس'
onClick={toggleBottomSheet2}
>
<form action={submitAddressAction}>
<div className='px-4'>
<div className='px-4 mt-2 bg-container'>
<span className='text-sm'>
{!selectedAddress ?
<Skeleton
className='h-6 w-full'
/>
:
[
selectedAddress.address.state ?? selectedAddress.address.province,
selectedAddress.address.city,
selectedAddress.address.neighbourhood,
!selectedAddress.address.road.startsWith('میدان') &&
!selectedAddress.address.road.startsWith('بلوار') &&
!selectedAddress.address.road.startsWith('خیابان') &&
!selectedAddress.address.road.startsWith('کوچه') ?
selectedAddress.type === 'secondary' ? `بلوار ${selectedAddress.address.road}` :
selectedAddress.type === 'tertiary' ? `خیابان ${selectedAddress.address.road}` :
selectedAddress.type === 'residential' ? `کوچه ${selectedAddress.address.road}` :
selectedAddress.address.road : selectedAddress.address.road
].filter(x => x).join('، ')
}
</span>
<hr className='border border-border mt-3 mb-10 ' />
<InputField
htmlFor={'addressTitle'}
labelText={'عنوان آدرس'}
placeholder='مثال: منزل، محل کار ...'
className='bg-inherit'
onChange={() => { }}
/>
<InputField
htmlFor={'addressDetails'}
labelText={'جزئیات آدرس'}
placeholder='میدان باغ ملی، مجتمع آسمان، واحد 12، پلاک 1234567890'
className='bg-inherit mt-8'
onChange={() => { }}
/>
</div>
<div className='grid grid-cols-2 gap-4 mt-16'>
<Button
type='submit'>
تایید
</Button>
<Button
type='button'
onClick={toggleBottomSheet2}
className='bg-disabled! text-primary!'
>
انصراف
</Button>
</div>
</div>
</form>
</AnimatedBottomSheet>
</div>
</div>
</div>
);
}
export default OrderTrackingPage;
@@ -5,10 +5,14 @@ import CloseIcon from '../icons/CloseIcon'
import { motion, PanInfo, Variants } from 'framer-motion'
type Props = {
title: string
title?: string,
showCloseButton?: boolean,
showTitle?: boolean,
blurOpacity?: string | number | null,
overrideClassName?: string,
} & BlurredOverlayContainerProps
const AnimatedBottomSheet = (props: Props) => {
const AnimatedBottomSheet = ({ blurOpacity = 64, overrideClassName = '', showTitle = true, showCloseButton = true, ...props }: Props) => {
const closeRef: React.Ref<HTMLDivElement> | undefined = useRef(null);
const variants: Variants = {
@@ -43,18 +47,26 @@ const AnimatedBottomSheet = (props: Props) => {
onDragEnd={onDrag}
data-visible={props.visible}
className={clsx(
'absolute left-0 w-full bg-white/64 rounded-t-4xl pt-[39px] pb-6',
'bottom-0'
overrideClassName ?? '',
'absolute left-0 w-full rounded-t-4xl pt-[39px] pb-6',
'bottom-0',
blurOpacity ? `bg-container/${blurOpacity}` : 'bg-container'
)}
initial="hidden"
animate={props.visible ? 'visible' : 'hidden'}
variants={variants}
>
<div className="ps-[31px] pe-[33px] flex justify-between">
<div className='text-lg font-medium text-black leading-8 mt-2.5'>{props.title}</div>
{showTitle &&
<div className='text-lg font-medium text-black leading-8 mt-2.5'>
{props.title}
</div>
}
{showCloseButton &&
<div ref={closeRef} onClick={props.onClick} className="bg-white/38 w-8 h-8 rounded-full p-1.5">
<CloseIcon size={20} />
</div>
}
</div>
{props.children}
</motion.div>
+69
View File
@@ -0,0 +1,69 @@
'use client';
import { useState } from 'react';
import { Skeleton } from '@/components/ui/skeleton';
import SearchBox from './SearchBox';
interface ActiveSearchboxProps extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'results'> {
onSearch?: (value: string) => void;
results?: Array<{ id: string; title: string }>;
isLoading?: boolean;
onResultSelect?: (result: { id: string; title: string }) => void;
}
export function ActiveSearchbox({
className,
onSearch,
results = [],
isLoading = false,
onResultSelect,
...props
}: ActiveSearchboxProps) {
const [isOpen, setIsOpen] = useState(false);
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
onSearch?.(value);
setIsOpen(true);
};
return (
<div className="map-search-container">
<SearchBox
className={className}
onFocus={() => setIsOpen(true)}
onChange={handleInputChange}
{...props}
/>
{isOpen && (isLoading || results.length > 0) && (
<div className="map-search-results">
{isLoading ? (
<>
<div className="p-4">
<Skeleton className="h-4 w-3/4 mb-2" />
<Skeleton className="h-4 w-1/2" />
</div>
<div className="p-4 border-t border-gray-100">
<Skeleton className="h-4 w-3/4 mb-2" />
<Skeleton className="h-4 w-1/2" />
</div>
</>
) : (
results.map((result) => (
<button
key={result.id}
className="map-search-result-item"
onClick={() => {
onResultSelect?.(result);
setIsOpen(false);
}}
>
{result.title}
</button>
))
)}
</div>
)}
</div>
);
}
-1
View File
@@ -6,7 +6,6 @@ type Props = {
htmlFor: string;
labelText?: React.ReactNode;
value?: string;
onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
valid?: boolean
} & Omit<React.InputHTMLAttributes<HTMLInputElement>, "id">;
+9 -5
View File
@@ -1,22 +1,26 @@
import React from 'react';
import SearchIcon from '../icons/SearchIcon';
import clsx from 'clsx';
type Props = {
value: string;
interface SearchboxProps extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'results'> {
placeholder?: string;
onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
};
export default function SearchBox({ value, placeholder = '', onChange }: Props) {
export default function SearchBox({ className, value, placeholder = '', onChange, ...props }: SearchboxProps) {
return (
<div className="bg-white inline-flex rounded-xl px-4 h-10 w-full items-center content-center">
<div className={clsx(
"bg-white inline-flex rounded-xl px-4 h-10 w-full items-center content-center",
className
)}>
<SearchIcon stroke="#8C90A3" />
<input
onChange={onChange}
value={value}
placeholder={placeholder}
className="text-[#8C90A3] block outline-none border-none focus:ring-0 focus:outline-none text-sm px-[7px] h-full items-center w-full"
type="text"
type="search"
{...props}
/>
</div>
);
+269
View File
@@ -0,0 +1,269 @@
.map-google-style {
background-color: #f8f9fa;
font-family: 'irancell', system-ui, -apple-system, sans-serif;
}
/* Map tiles styling */
.map-google-style .leaflet-tile-pane {
filter: saturate(0.95) contrast(0.95) brightness(1.02);
}
/* Base font for all map elements */
.map-google-style,
.map-google-style .leaflet-container {
font-family: 'irancell', system-ui, -apple-system, sans-serif !important;
}
/* Improve tile loading appearance */
.map-google-style .leaflet-tile-loading {
opacity: 0;
transition: opacity 0.2s ease-in-out;
}
/* Custom popup style */
.map-google-style .leaflet-popup-content-wrapper {
border-radius: 16px;
padding: 0;
box-shadow: 0 4px 16px rgba(0,0,0,0.08),
0 2px 4px rgba(0,0,0,0.05);
border: 1px solid rgba(0,0,0,0.08);
backdrop-filter: blur(8px);
background: rgba(255, 255, 255, 0.95);
}
.map-google-style .leaflet-popup-content {
margin: 16px 20px;
line-height: 1.6;
font-size: 14px;
color: #1f2937;
font-weight: 500;
text-align: right;
}
.map-google-style .leaflet-popup-tip {
background: rgba(255, 255, 255, 0.95);
backdrop-filter: blur(8px);
box-shadow: 0 4px 16px rgba(0,0,0,0.08);
border: 1px solid rgba(0,0,0,0.08);
}
.map-google-style .leaflet-popup-close-button {
padding: 12px !important;
color: #6b7280 !important;
opacity: 0.7;
transition: opacity 0.2s ease;
}
.map-google-style .leaflet-popup-close-button:hover {
opacity: 1;
}
/* Marker styles */
.map-google-style .leaflet-marker-icon,
.map-google-style .leaflet-marker-shadow {
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
transform-origin: bottom center;
}
.map-google-style .leaflet-marker-icon {
filter: drop-shadow(0 2px 4px rgba(0,0,0,0.1));
}
.map-google-style .leaflet-marker-icon:hover {
transform: scale(1.1) translateY(-4px);
filter: drop-shadow(0 4px 6px rgba(0,0,0,0.15));
}
.map-google-style .leaflet-marker-icon:hover + .leaflet-marker-shadow {
transform: scale(1.1) translateY(-4px);
opacity: 0.6;
}
/* Attribution styling */
.map-google-style .leaflet-control-attribution {
display: none;
/* background: rgba(255,255,255,0.9) !important;
backdrop-filter: blur(8px);
padding: 6px 12px !important;
border-radius: 12px;
margin: 8px !important;
font-size: 11px !important;
color: #4b5563 !important;
box-shadow: 0 2px 8px rgba(0,0,0,0.05);
border: 1px solid rgba(0,0,0,0.08); */
}
/* Zoom controls */
.map-zoom-controls {
position: absolute;
right: 20px;
bottom: 40px;
background: rgba(255, 255, 255, 0.95);
border-radius: 16px;
box-shadow: 0 4px 16px rgba(0,0,0,0.08),
0 2px 4px rgba(0,0,0,0.05);
border: 1px solid rgba(0,0,0,0.08);
overflow: hidden;
backdrop-filter: blur(8px);
z-index: 1000;
}
.zoom-button {
width: 44px;
height: 44px;
display: flex;
align-items: center;
justify-content: center;
background: transparent;
border: none;
cursor: pointer;
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
color: #4b5563;
font-size: 22px;
font-weight: 500;
-webkit-tap-highlight-color: transparent;
}
.zoom-button:first-child {
border-bottom: 1px solid rgba(0,0,0,0.08);
}
.zoom-button:hover {
background-color: rgba(59, 130, 246, 0.05);
color: #2563eb;
}
.zoom-button:active {
background-color: rgba(59, 130, 246, 0.1);
}
/* Selected location indicator */
.selected-location-indicator {
position: fixed;
bottom: 24px;
left: 50%;
transform: translateX(-50%);
background: rgba(255, 255, 255, 0.95);
backdrop-filter: blur(8px);
padding: 14px 24px;
border-radius: 16px;
box-shadow: 0 4px 16px rgba(0,0,0,0.08),
0 2px 4px rgba(0,0,0,0.05);
border: 1px solid rgba(0,0,0,0.08);
color: #1f2937;
font-size: 14px;
font-weight: 500;
line-height: 1.6;
max-width: 90%;
width: auto;
text-align: center;
z-index: 1000;
animation: slideUp 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
@keyframes slideUp {
from {
transform: translate(-50%, 100%);
opacity: 0;
}
to {
transform: translate(-50%, 0);
opacity: 1;
}
}
/* Loading state */
.map-loading {
position: absolute;
inset: 0;
background: rgba(255, 255, 255, 0.9);
backdrop-filter: blur(4px);
z-index: 1000;
display: flex;
align-items: center;
justify-content: center;
}
/* Container styling */
.map-container {
position: relative;
width: 100%;
height: 100%;
background: linear-gradient(to bottom, #e5e7eb 0%, #f3f4f6 100%);
}
/* Search box styling */
.map-search-container {
position: absolute;
top: 20px;
left: 50%;
transform: translateX(-50%);
width: 90%;
max-width: 480px;
z-index: 1000;
}
.map-search-input {
width: 100%;
padding: 14px 20px;
background: rgba(255, 255, 255, 0.95);
border: 1px solid rgba(0,0,0,0.08);
border-radius: 16px;
box-shadow: 0 4px 16px rgba(0,0,0,0.08),
0 2px 4px rgba(0,0,0,0.05);
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
font-size: 15px;
font-weight: 500;
text-align: right;
backdrop-filter: blur(8px);
color: #1f2937;
}
.map-search-input:focus {
box-shadow: 0 6px 24px rgba(0,0,0,0.12),
0 2px 8px rgba(0,0,0,0.08);
border-color: rgba(59, 130, 246, 0.5);
background: rgba(255, 255, 255, 0.98);
}
.map-search-input::placeholder {
color: #6b7280;
font-weight: 400;
}
.map-search-results {
margin-top: 12px;
background: rgba(255, 255, 255, 0.95);
border-radius: 16px;
box-shadow: 0 4px 20px rgba(0,0,0,0.1),
0 2px 8px rgba(0,0,0,0.05);
overflow: hidden;
border: 1px solid rgba(0,0,0,0.08);
backdrop-filter: blur(8px);
}
.map-search-result-item {
padding: 14px 20px;
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
border-bottom: 1px solid rgba(0,0,0,0.05);
font-size: 13px;
font-weight: 400;
color: #1f2937;
cursor: pointer;
display: block;
width: 100%;
text-align: right;
}
.map-search-result-item:last-child {
border-bottom: none;
}
.map-search-result-item:hover {
background-color: rgba(59, 130, 246, 0.05);
color: #2563eb;
}
.map-search-result-item:active {
background-color: rgba(59, 130, 246, 0.1);
}
+305
View File
@@ -0,0 +1,305 @@
'use client';
import React, { useEffect, useState } from 'react';
import { MapContainer, TileLayer, Marker, Popup, useMap, useMapEvents } from 'react-leaflet';
import L from 'leaflet';
import { Skeleton } from '@/components/ui/skeleton';
import 'leaflet/dist/leaflet.css';
import './CustomMap.css';
import { ActiveSearchbox } from '../input/ActiveSearchbox';
// Define types for our props
interface CustomMapProps {
initialPosition: [number, number];
zoom?: number;
markers?: Array<{
position: [number, number];
title: string;
icon?: L.Icon;
}>;
onPositionSelect?: (position: [number, number]) => void;
onZoomChange?: (zoom: number) => void;
onClick?: (event: L.LeafletMouseEvent) => void;
}
// Component to handle map events and position updates
function MapEvents({
onZoomChange,
onClick,
center,
setMapRef
}: Pick<CustomMapProps, 'onZoomChange' | 'onClick'> & {
center: [number, number];
setMapRef: (map: L.Map) => void;
}) {
const map = useMapEvents({
zoom: () => {
onZoomChange?.(map.getZoom());
},
click: (e) => {
onClick?.(e);
},
});
// Update map center when center prop changes
React.useEffect(() => {
map.setView(center, map.getZoom(), {
animate: true,
duration: 1
});
}, [map, center]);
// Set map reference
React.useEffect(() => {
setMapRef(map);
}, [map, setMapRef]);
return null;
}
// Component to handle marker updates on zoom
function MarkerUpdater({ markers }: { markers?: CustomMapProps['markers'] }) {
const map = useMap();
useEffect(() => {
// You can implement custom marker scaling or clustering logic here
const zoom = map.getZoom();
// Example: Scale markers based on zoom level
markers?.forEach(marker => {
const element = document.querySelector(`[title="${marker.title}"]`);
if (element) {
const scale = Math.min(1 + (zoom / 20), 1.5);
(element as HTMLElement).style.transform = `scale(${scale})`;
}
});
}, [map, markers]);
return null;
}
const CustomMap: React.FC<CustomMapProps> = ({
initialPosition,
zoom = 13,
markers = [],
onPositionSelect,
onZoomChange,
onClick,
}) => {
const [selectedPosition, setSelectedPosition] = useState<[number, number] | null>(null);
const [mapInstance, setMapInstance] = useState<L.Map | null>(null);
const [isSearching, setIsSearching] = useState(false);
const [searchResults, setSearchResults] = useState<Array<{ id: string; title: string; position: [number, number] }>>([]);
const [isMapLoading, setIsMapLoading] = useState(true);
// Handle map load complete
useEffect(() => {
const checkTiles = () => {
if (mapInstance) {
const container = document.querySelector('.leaflet-tile-container');
if (container && container.children.length > 0) {
setIsMapLoading(false);
} else {
setTimeout(checkTiles, 100);
}
}
};
checkTiles();
}, [mapInstance]);
// Initialize default icon on client side only
useEffect(() => {
// Dynamic import of Leaflet on the client side
// Fix for default marker icon in Next.js
delete ((L.Icon.Default.prototype) as { _getIconUrl?: unknown })._getIconUrl;
L.Icon.Default.mergeOptions({
iconRetinaUrl: '/marker-icon-2x.png',
iconUrl: '/marker-icon.png',
shadowUrl: '/marker-shadow.png',
});
}, []);
const handleMapClick = (e: L.LeafletMouseEvent) => {
const newPosition: [number, number] = [e.latlng.lat, e.latlng.lng];
setSelectedPosition(newPosition);
onPositionSelect?.(newPosition);
onClick?.(e);
};
const [searchTimeout, setSearchTimeout] = useState<NodeJS.Timeout>();
const handleSearch = async (value: string) => {
if (!value || value.trim().length === 0) {
setSearchResults([]);
return;
}
// Clear previous timeout
if (searchTimeout) {
clearTimeout(searchTimeout);
}
setIsSearching(true);
// Set new timeout
const timeout = setTimeout(async () => {
try {
// Iran's bounding box coordinates (roughly)
const viewbox = '44.0,25.0,63.0,40.0'; // [min lon, min lat, max lon, max lat]
const response = await fetch(
`https://nominatim.openstreetmap.org/search?` +
`format=json&` +
`q=${encodeURIComponent(value)}&` +
`countrycodes=ir&` + // Prioritize Iran
`viewbox=${viewbox}&` +
`bounded=0&` + // Allow results outside viewbox but prioritize inside
`limit=10&` + // Limit results to 10
`namedetails=1&` + // Get native names
`accept-language=fa` // Request Persian results
, {
headers: {
'Accept-Language': 'fa,en;q=0.9' // Prefer Persian, fallback to English
}
});
interface SearchResult {
place_id: string;
display_name: string;
lat: string;
lon: string;
namedetails?: {
name?: string;
'name:fa'?: string;
alt_name?: string;
'alt_name:fa'?: string;
};
}
const data: SearchResult[] = await response.json();
setSearchResults(data.map((item) => ({
id: item.place_id,
// Use Persian name if available, fallback to display_name
title: /* item.namedetails?.['name:fa'] ||
item.namedetails?.name ||
item.namedetails?.['alt_name:fa'] ||
item.namedetails?.alt_name || */
item.display_name,
position: [parseFloat(item.lat), parseFloat(item.lon)] as [number, number]
})));
} catch (error) {
console.error('Search error:', error);
setSearchResults([]);
} finally {
setIsSearching(false);
}
}, 500); // Wait 500ms after last keystroke
setSearchTimeout(timeout);
};
const handleSearchResultSelect = (result: { id: string; title: string; position: [number, number] }) => {
console.log(result);
setSelectedPosition(result.position);
if (mapInstance) {
mapInstance.setView(result.position, mapInstance.getZoom());
}
};
return (
<div className="w-full h-full relative">
<ActiveSearchbox
placeholder="جستجو"
onSearch={handleSearch}
isLoading={isSearching}
results={searchResults}
onResultSelect={(v) => {
// Find the full result object with position
const result = searchResults.find(r => r.id === v.id && r.title === v.title);
if (result) {
handleSearchResultSelect(result);
}
}}
/>
<div className="map-zoom-controls">
<button
onClick={(e) => {
e.stopPropagation();
if (mapInstance) {
const center = selectedPosition || mapInstance.getCenter();
mapInstance.setZoomAround(center, mapInstance.getZoom() + 1);
}
}}
className="zoom-button"
aria-label="بزرگنمایی"
>
+
</button>
<button
onClick={(e) => {
e.stopPropagation();
if (mapInstance) {
const center = selectedPosition || mapInstance.getCenter();
mapInstance.setZoomAround(center, mapInstance.getZoom() - 1);
}
}}
className="zoom-button"
aria-label="کوچک نمایی"
>
</button>
</div>
{isMapLoading && (
<div className="absolute inset-0 bg-zinc-50/80 backdrop-blur-sm z-[400]">
<div className="grid grid-cols-3 gap-4 p-8 h-full">
<Skeleton className="h-full" />
<Skeleton className="h-full" />
<Skeleton className="h-full" />
</div>
</div>
)}
<MapContainer
center={initialPosition}
zoom={zoom}
className="map-google-style"
style={{ height: '100%', width: '100%' }}
zoomControl={false} // Disable default zoom control
>
<TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
{/* Custom markers */}
{markers.map((marker, index) => (
<Marker
key={`${marker.position}-${index}`}
position={marker.position}
icon={marker.icon}
>
<Popup>
<div className="text-sm">{marker.title}</div>
</Popup>
</Marker>
))}
{/* Selected position marker */}
{selectedPosition && (
<Marker position={selectedPosition}>
<Popup>
<div className="text-sm px-2">موقعیت انتخاب شده</div>
</Popup>
</Marker>
)}
{/* Event handlers */}
<MapEvents
onZoomChange={onZoomChange}
onClick={handleMapClick}
center={initialPosition}
setMapRef={setMapInstance}
/>
{/* Marker updater for zoom effects */}
<MarkerUpdater markers={markers} />
</MapContainer>
</div>
);
};
export default CustomMap;
@@ -13,6 +13,7 @@ export type BlurredOverlayContainerProps = {
inDuration?: number
outDuration?: number
children: ReactNode
noBlur?: boolean
} & React.ComponentProps<typeof motion.div>
const BlurredOverlayContainer = ({
@@ -26,6 +27,7 @@ const BlurredOverlayContainer = ({
children,
className,
onClick,
noBlur = false,
...props
}: BlurredOverlayContainerProps) => {
const [loaded, setLoaded] = useState(visible)
@@ -69,10 +71,11 @@ const BlurredOverlayContainer = ({
<motion.div
data-visible={visible}
data-loaded={loaded}
data-blur={!noBlur}
className={clsx(
className,
visible || loaded ? 'z-50' : !visible && !loaded ? '-z-50' : 'z-0',
'absolute inset-0 flex items-center justify-center h-full w-full backdrop-blur-sm',
'absolute inset-0 flex items-center justify-center h-full w-full data-[blur=true]:backdrop-blur-sm',
)}
style={{
backgroundColor: `rgba(0, 0, 0, ${bgOpacity / 100})`,
+15
View File
@@ -0,0 +1,15 @@
import { cn } from "@/lib/utils"
function Skeleton({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) {
return (
<div
className={cn("animate-pulse rounded-md bg-zinc-200/70", className)}
{...props}
/>
)
}
export { Skeleton }