a working product with ugly ui

This commit is contained in:
2025-12-12 20:15:27 +05:00
parent e6d04f986f
commit 4d3085623a
77 changed files with 8750 additions and 0 deletions

View File

@@ -0,0 +1,78 @@
import { useState, FormEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuthStore } from '../../stores/authStore';
export function Login() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const { login, isLoading, error, clearError } = useAuthStore();
const navigate = useNavigate();
const handleSubmit = async (e: FormEvent) => {
e.preventDefault();
clearError();
try {
await login(username, password);
navigate('/');
} catch (err) {
// Error is handled by the store
}
};
return (
<div className="min-h-screen flex items-center justify-center bg-gray-100">
<div className="bg-white p-8 rounded-lg shadow-md w-full max-w-md">
<h1 className="text-2xl font-bold mb-6 text-center text-gray-800">
ISP Wiremap
</h1>
<form onSubmit={handleSubmit} className="space-y-4">
{error && (
<div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded">
{error}
</div>
)}
<div>
<label htmlFor="username" className="block text-sm font-medium text-gray-700 mb-1">
Username
</label>
<input
id="username"
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
disabled={isLoading}
/>
</div>
<div>
<label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-1">
Password
</label>
<input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
disabled={isLoading}
/>
</div>
<button
type="submit"
disabled={isLoading}
className="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
>
{isLoading ? 'Logging in...' : 'Login'}
</button>
</form>
</div>
</div>
);
}

View File

@@ -0,0 +1,31 @@
import { useEffect } from 'react';
import { Navigate } from 'react-router-dom';
import { useAuthStore } from '../../stores/authStore';
interface ProtectedRouteProps {
children: React.ReactNode;
}
export function ProtectedRoute({ children }: ProtectedRouteProps) {
const { isAuthenticated, loadUser, isLoading } = useAuthStore();
useEffect(() => {
if (isAuthenticated) {
loadUser();
}
}, [isAuthenticated, loadUser]);
if (isLoading) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-gray-600">Loading...</div>
</div>
);
}
if (!isAuthenticated) {
return <Navigate to="/login" replace />;
}
return <>{children}</>;
}

View File

@@ -0,0 +1,50 @@
import { ReactNode } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuthStore } from '../../stores/authStore';
interface LayoutProps {
children: ReactNode;
}
export function Layout({ children }: LayoutProps) {
const { user, logout } = useAuthStore();
const navigate = useNavigate();
const handleLogout = () => {
logout();
navigate('/login');
};
return (
<div className="h-screen flex flex-col">
<header className="bg-blue-600 text-white shadow-md">
<div className="px-4 py-3 flex items-center justify-between">
<h1 className="text-xl font-bold">ISP Wiremap</h1>
{user && (
<div className="flex items-center gap-4">
<span className="text-sm">
{user.username}
{user.is_admin && (
<span className="ml-2 px-2 py-0.5 bg-blue-500 rounded text-xs">
Admin
</span>
)}
</span>
<button
onClick={handleLogout}
className="px-3 py-1 bg-blue-700 hover:bg-blue-800 rounded text-sm"
>
Logout
</button>
</div>
)}
</div>
</header>
<main className="flex-1 overflow-hidden">
{children}
</main>
</div>
);
}

View File

@@ -0,0 +1,338 @@
import { useEffect, useState } from 'react';
import { useMapEvents, Polyline, Marker } from 'react-leaflet';
import L from 'leaflet';
import { useDrawingStore } from '../../stores/drawingStore';
import { mapItemService } from '../../services/mapItemService';
import { CABLE_COLORS, type CableType } from '../../types/mapItem';
interface DrawingHandlerProps {
mapId: string;
onItemCreated: () => void;
}
export function DrawingHandler({ mapId, onItemCreated }: DrawingHandlerProps) {
const { activeTool, isDrawing, drawingPoints, setIsDrawing, addDrawingPoint, resetDrawing, setActiveTool } =
useDrawingStore();
const [cursorPosition, setCursorPosition] = useState<[number, number] | null>(null);
const [allItems, setAllItems] = useState<any[]>([]);
const [startDeviceId, setStartDeviceId] = useState<string | null>(null);
const [endDeviceId, setEndDeviceId] = useState<string | null>(null);
const isCableTool = ['fiber', 'cat6', 'cat6_poe'].includes(activeTool);
const isDeviceTool = ['switch', 'indoor_ap', 'outdoor_ap'].includes(activeTool);
const isWirelessTool = activeTool === 'wireless_mesh';
// Load all map items for snapping
useEffect(() => {
const loadItems = async () => {
try {
const items = await mapItemService.getMapItems(mapId);
setAllItems(items);
} catch (error) {
console.error('Failed to load items for snapping:', error);
}
};
loadItems();
}, [mapId]);
// Find nearby device for snapping
const findNearbyDevice = (lat: number, lng: number, radiusMeters = 5): any | null => {
const devices = allItems.filter(item =>
['switch', 'indoor_ap', 'outdoor_ap'].includes(item.type) &&
item.geometry.type === 'Point'
);
for (const device of devices) {
const [deviceLng, deviceLat] = device.geometry.coordinates;
const distance = map.distance([lat, lng], [deviceLat, deviceLng]);
if (distance <= radiusMeters) {
return device;
}
}
return null;
};
// Check if device has available ports
const hasAvailablePorts = (device: any): boolean => {
const portCount = device.properties.port_count || 0;
const usedPorts = device.properties.connections?.length || 0;
return usedPorts < portCount;
};
// Count wireless mesh connections for an AP
const getWirelessMeshCount = (apId: string): number => {
const meshLinks = allItems.filter(item =>
item.type === 'wireless_mesh' &&
(item.properties.start_ap_id === apId || item.properties.end_ap_id === apId)
);
return meshLinks.length;
};
const map = useMapEvents({
click: async (e) => {
if (activeTool === 'select') return;
let { lat, lng } = e.latlng;
let clickedDevice = null;
// Check for nearby device when drawing cables
if (isCableTool && map) {
clickedDevice = findNearbyDevice(lat, lng);
if (clickedDevice) {
// Check if device has available ports
if (!hasAvailablePorts(clickedDevice)) {
const portCount = clickedDevice.properties.port_count || 0;
const usedPorts = clickedDevice.properties.connections?.length || 0;
const deviceName = clickedDevice.properties.name || clickedDevice.type;
alert(`${deviceName} has no available ports (${usedPorts}/${portCount} ports used). Please select a different device or increase the port count.`);
return;
}
// Snap to device center
const [deviceLng, deviceLat] = clickedDevice.geometry.coordinates;
lat = deviceLat;
lng = deviceLng;
// Track device connection
if (!isDrawing) {
setStartDeviceId(clickedDevice.id);
} else {
setEndDeviceId(clickedDevice.id);
}
}
}
// Device placement - single click
if (isDeviceTool) {
try {
await mapItemService.createMapItem(mapId, {
type: activeTool as any,
geometry: {
type: 'Point',
coordinates: [lng, lat],
},
properties: {
name: `${activeTool} at ${lat.toFixed(4)}, ${lng.toFixed(4)}`,
port_count: activeTool === 'switch' ? 5 : activeTool === 'outdoor_ap' ? 1 : 4,
connections: [],
},
});
onItemCreated();
// Reload items for snapping
const items = await mapItemService.getMapItems(mapId);
setAllItems(items);
} catch (error) {
console.error('Failed to create device:', error);
}
return;
}
// Cable drawing - multi-point
if (isCableTool) {
if (!isDrawing) {
setIsDrawing(true);
addDrawingPoint([lat, lng]);
} else {
addDrawingPoint([lat, lng]);
}
}
// Wireless mesh - connect AP to AP only
if (isWirelessTool) {
// Must click on an AP
const ap = findNearbyDevice(lat, lng, 5);
if (!ap || !['indoor_ap', 'outdoor_ap'].includes(ap.type)) {
alert('Wireless mesh can only connect between Access Points. Please click on an AP.');
return;
}
// Check wireless mesh connection limit (max 4 per AP)
const meshCount = getWirelessMeshCount(ap.id);
if (meshCount >= 4) {
const apName = ap.properties.name || ap.type;
alert(`${apName} already has the maximum of 4 wireless mesh connections. Please select a different AP.`);
return;
}
if (!isDrawing) {
// First AP clicked
setIsDrawing(true);
setStartDeviceId(ap.id);
const [apLng, apLat] = ap.geometry.coordinates;
addDrawingPoint([apLat, apLng]);
} else if (drawingPoints.length === 1) {
// Second AP clicked - check if it's different from first
if (ap.id === startDeviceId) {
alert('Cannot create wireless mesh to the same Access Point. Please select a different AP.');
return;
}
// Second AP clicked - finish immediately with both points
const [apLng, apLat] = ap.geometry.coordinates;
const secondPoint: [number, number] = [apLat, apLng];
await finishWirelessMesh(ap.id, secondPoint);
}
}
},
mousemove: (e) => {
// Update cursor position for preview line
if (isDrawing && (isCableTool || isWirelessTool)) {
setCursorPosition([e.latlng.lat, e.latlng.lng]);
}
},
contextmenu: async (e) => {
// Right-click to finish cable drawing
if (isCableTool && isDrawing && drawingPoints.length >= 2) {
e.originalEvent.preventDefault();
e.originalEvent.stopPropagation();
await finishCable();
return false;
}
if (!isDrawing) {
e.originalEvent.preventDefault();
}
},
});
useEffect(() => {
// Listen for Escape key globally
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape' && isDrawing) {
resetDrawing();
setCursorPosition(null);
}
};
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, [isDrawing, resetDrawing]);
const finishCable = async () => {
if (drawingPoints.length < 2) return;
try {
const cableType = activeTool as CableType;
await mapItemService.createMapItem(mapId, {
type: 'cable',
geometry: {
type: 'LineString',
coordinates: drawingPoints.map(([lat, lng]) => [lng, lat]),
},
properties: {
cable_type: cableType,
name: `${cableType} cable`,
start_device_id: startDeviceId,
end_device_id: endDeviceId,
},
});
onItemCreated();
resetDrawing();
setCursorPosition(null);
setStartDeviceId(null);
setEndDeviceId(null);
// Reload items
const items = await mapItemService.getMapItems(mapId);
setAllItems(items);
} catch (error) {
console.error('Failed to create cable:', error);
}
};
const finishWirelessMesh = async (endApId: string, secondPoint: [number, number]) => {
if (drawingPoints.length !== 1) {
console.error('Wireless mesh requires exactly 1 starting point');
return;
}
try {
// Create line with first point from state and second point from parameter
const coordinates = [
[drawingPoints[0][1], drawingPoints[0][0]], // First point: [lng, lat]
[secondPoint[1], secondPoint[0]], // Second point: [lng, lat]
];
await mapItemService.createMapItem(mapId, {
type: 'wireless_mesh',
geometry: {
type: 'LineString',
coordinates: coordinates,
},
properties: {
name: 'Wireless mesh link',
start_ap_id: startDeviceId,
end_ap_id: endApId,
},
});
onItemCreated();
// Reset drawing state but keep the wireless mesh tool active
resetDrawing();
setCursorPosition(null);
setStartDeviceId(null);
setEndDeviceId(null);
// Reload items
const items = await mapItemService.getMapItems(mapId);
setAllItems(items);
} catch (error) {
console.error('Failed to create wireless mesh:', error);
// Reset on error too
resetDrawing();
setCursorPosition(null);
setStartDeviceId(null);
setEndDeviceId(null);
}
};
// Render drawing preview
if (isDrawing && drawingPoints.length > 0) {
const color = isCableTool
? CABLE_COLORS[activeTool as CableType]
: isWirelessTool
? '#10B981'
: '#6B7280';
const dashArray = isWirelessTool ? '10, 10' : undefined;
// Create preview line from last point to cursor
const previewPositions = cursorPosition
? [...drawingPoints, cursorPosition]
: drawingPoints;
return (
<>
{/* Main line connecting all points */}
{drawingPoints.length > 1 && (
<Polyline
positions={drawingPoints}
color={color}
weight={3}
dashArray={dashArray}
opacity={0.8}
/>
)}
{/* Preview line from last point to cursor */}
{cursorPosition && drawingPoints.length > 0 && (
<Polyline
positions={[drawingPoints[drawingPoints.length - 1], cursorPosition]}
color={color}
weight={3}
dashArray="5, 5"
opacity={0.5}
/>
)}
{/* Markers at each point */}
{drawingPoints.map((point, idx) => (
<Marker key={idx} position={point} />
))}
</>
);
}
return null;
}

View File

@@ -0,0 +1,387 @@
import { useState, useEffect, useRef } from 'react';
import { mapItemService } from '../../services/mapItemService';
interface ItemContextMenuProps {
item: any;
position: { x: number; y: number };
onClose: () => void;
onUpdate: () => void;
}
export function ItemContextMenu({ item, position, onClose, onUpdate }: ItemContextMenuProps) {
const [showRenameDialog, setShowRenameDialog] = useState(false);
const [showNotesDialog, setShowNotesDialog] = useState(false);
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
const [showPortConfigDialog, setShowPortConfigDialog] = useState(false);
const [newName, setNewName] = useState(item.properties.name || '');
const [notes, setNotes] = useState(item.properties.notes || '');
const [imageData, setImageData] = useState<string | null>(item.properties.image || null);
const [portCount, setPortCount] = useState(item.properties.port_count || 5);
const [deleteConnectedCables, setDeleteConnectedCables] = useState(false);
const menuRef = useRef<HTMLDivElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const isSwitch = item.type === 'switch';
const isDevice = ['switch', 'indoor_ap', 'outdoor_ap'].includes(item.type);
const hasConnections = item.properties.connections && item.properties.connections.length > 0;
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
if (menuRef.current && !menuRef.current.contains(e.target as Node)) {
onClose();
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, [onClose]);
const handleDelete = async () => {
try {
// If device with connections and user wants to delete connected cables
if (isDevice && deleteConnectedCables && hasConnections) {
// First delete all connected cables
const { mapItemService: itemService } = await import('../../services/mapItemService');
const allItems = await itemService.getMapItems(item.map_id);
// Find all cables connected to this device
const connectedCableIds = item.properties.connections.map((conn: any) => conn.cable_id);
const cablesToDelete = allItems.filter((i: any) =>
i.type === 'cable' && connectedCableIds.includes(i.id)
);
// Delete each cable
for (const cable of cablesToDelete) {
await itemService.deleteMapItem(item.map_id, cable.id);
}
}
// Delete the device/item itself
await mapItemService.deleteMapItem(item.map_id, item.id);
onUpdate();
onClose();
} catch (error) {
console.error('Failed to delete item:', error);
alert('Failed to delete item');
}
};
const handleRename = async () => {
try {
await mapItemService.updateMapItem(item.map_id, item.id, {
properties: {
...item.properties,
name: newName,
},
});
onUpdate();
setShowRenameDialog(false);
onClose();
} catch (error) {
console.error('Failed to rename item:', error);
alert('Failed to rename item');
}
};
const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
// Check file size (max 2MB)
if (file.size > 2 * 1024 * 1024) {
alert('Image too large. Please use an image smaller than 2MB.');
return;
}
// Check file type
if (!file.type.startsWith('image/')) {
alert('Please select an image file.');
return;
}
const reader = new FileReader();
reader.onload = () => {
setImageData(reader.result as string);
};
reader.readAsDataURL(file);
};
const handleRemoveImage = () => {
setImageData(null);
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
};
const handleSaveNotes = async () => {
try {
await mapItemService.updateMapItem(item.map_id, item.id, {
properties: {
...item.properties,
notes: notes,
image: imageData,
},
});
onUpdate();
setShowNotesDialog(false);
onClose();
} catch (error) {
console.error('Failed to save notes:', error);
alert('Failed to save notes');
}
};
const handleSavePortConfig = async () => {
try {
await mapItemService.updateMapItem(item.map_id, item.id, {
properties: {
...item.properties,
port_count: portCount,
},
});
onUpdate();
setShowPortConfigDialog(false);
onClose();
} catch (error) {
console.error('Failed to save port configuration:', error);
alert('Failed to save port configuration');
}
};
if (showPortConfigDialog) {
return (
<div
ref={menuRef}
className="fixed bg-white rounded-lg shadow-xl border border-gray-200 p-4"
style={{ left: position.x, top: position.y, zIndex: 10000, minWidth: '250px' }}
>
<h3 className="font-semibold mb-2">Configure Ports</h3>
<label className="block text-sm text-gray-600 mb-2">
Total number of ports:
</label>
<input
type="number"
min="1"
max="96"
value={portCount}
onChange={(e) => setPortCount(parseInt(e.target.value) || 1)}
className="w-full px-3 py-2 border border-gray-300 rounded mb-3"
autoFocus
onKeyDown={(e) => {
if (e.key === 'Enter') handleSavePortConfig();
if (e.key === 'Escape') { setShowPortConfigDialog(false); onClose(); }
}}
/>
<div className="text-xs text-gray-500 mb-3">
Currently used: {item.properties.connections?.length || 0} ports
</div>
<div className="flex gap-2">
<button
onClick={handleSavePortConfig}
className="flex-1 px-3 py-1.5 bg-blue-600 text-white rounded hover:bg-blue-700"
>
Save
</button>
<button
onClick={() => { setShowPortConfigDialog(false); onClose(); }}
className="flex-1 px-3 py-1.5 bg-gray-300 text-gray-700 rounded hover:bg-gray-400"
>
Cancel
</button>
</div>
</div>
);
}
if (showDeleteDialog) {
return (
<div
ref={menuRef}
className="fixed bg-white rounded-lg shadow-xl border border-gray-200 p-4"
style={{ left: position.x, top: position.y, zIndex: 10000, minWidth: '300px' }}
>
<h3 className="font-semibold text-lg mb-2">Delete Item</h3>
<p className="text-gray-600 mb-4">
Are you sure you want to delete <span className="font-semibold">{item.properties.name || item.type}</span>?
{item.type === 'cable' && item.properties.start_device_id && (
<span className="block mt-2 text-sm">This will also remove the connection from the connected devices.</span>
)}
</p>
{/* Checkbox for deleting connected cables */}
{isDevice && hasConnections && (
<label className="flex items-center gap-2 mb-4 cursor-pointer">
<input
type="checkbox"
checked={deleteConnectedCables}
onChange={(e) => setDeleteConnectedCables(e.target.checked)}
className="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
/>
<span className="text-sm text-gray-700">
Also delete {item.properties.connections.length} connected cable{item.properties.connections.length !== 1 ? 's' : ''}
</span>
</label>
)}
<div className="flex gap-2">
<button
onClick={handleDelete}
className="flex-1 px-3 py-2 bg-red-600 text-white rounded hover:bg-red-700 font-medium"
>
Delete
</button>
<button
onClick={() => { setShowDeleteDialog(false); setDeleteConnectedCables(false); onClose(); }}
className="flex-1 px-3 py-2 bg-gray-300 text-gray-700 rounded hover:bg-gray-400"
>
Cancel
</button>
</div>
</div>
);
}
if (showRenameDialog) {
return (
<div
ref={menuRef}
className="fixed bg-white rounded-lg shadow-xl border border-gray-200 p-4"
style={{ left: position.x, top: position.y, zIndex: 10000, minWidth: '250px' }}
>
<h3 className="font-semibold mb-2">Rename Item</h3>
<input
type="text"
value={newName}
onChange={(e) => setNewName(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded mb-3"
placeholder="Enter new name"
autoFocus
onKeyDown={(e) => {
if (e.key === 'Enter') handleRename();
if (e.key === 'Escape') { setShowRenameDialog(false); onClose(); }
}}
/>
<div className="flex gap-2">
<button
onClick={handleRename}
className="flex-1 px-3 py-1.5 bg-blue-600 text-white rounded hover:bg-blue-700"
>
Save
</button>
<button
onClick={() => { setShowRenameDialog(false); onClose(); }}
className="flex-1 px-3 py-1.5 bg-gray-300 text-gray-700 rounded hover:bg-gray-400"
>
Cancel
</button>
</div>
</div>
);
}
if (showNotesDialog) {
return (
<div
ref={menuRef}
className="fixed bg-white rounded-lg shadow-xl border border-gray-200 p-4"
style={{ left: position.x, top: position.y, zIndex: 10000, minWidth: '350px', maxWidth: '400px' }}
>
<h3 className="font-semibold mb-2">Edit Notes</h3>
<textarea
value={notes}
onChange={(e) => setNotes(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded mb-3"
placeholder="Enter notes"
rows={4}
autoFocus
onKeyDown={(e) => {
if (e.key === 'Escape') { setShowNotesDialog(false); onClose(); }
}}
/>
{/* Image upload section */}
<div className="mb-3">
<label className="block text-sm font-medium text-gray-700 mb-2">
Attach Image (optional)
</label>
{imageData ? (
<div className="relative">
<img
src={imageData}
alt="Attached"
className="w-full rounded border border-gray-300 mb-2"
style={{ maxHeight: '200px', objectFit: 'contain' }}
/>
<button
onClick={handleRemoveImage}
className="absolute top-2 right-2 bg-red-600 text-white rounded-full w-6 h-6 flex items-center justify-center hover:bg-red-700"
>
×
</button>
</div>
) : (
<input
ref={fileInputRef}
type="file"
accept="image/*"
onChange={handleImageUpload}
className="w-full px-3 py-2 border border-gray-300 rounded text-sm"
/>
)}
<p className="text-xs text-gray-500 mt-1">Max size: 2MB</p>
</div>
<div className="flex gap-2">
<button
onClick={handleSaveNotes}
className="flex-1 px-3 py-1.5 bg-blue-600 text-white rounded hover:bg-blue-700"
>
Save
</button>
<button
onClick={() => { setShowNotesDialog(false); onClose(); }}
className="flex-1 px-3 py-1.5 bg-gray-300 text-gray-700 rounded hover:bg-gray-400"
>
Cancel
</button>
</div>
</div>
);
}
return (
<div
ref={menuRef}
className="fixed bg-white rounded-lg shadow-xl border border-gray-200 py-1"
style={{ left: position.x, top: position.y, zIndex: 10000, minWidth: '180px' }}
>
<button
onClick={() => setShowRenameDialog(true)}
className="w-full px-4 py-2 text-left text-sm hover:bg-gray-100"
>
Rename
</button>
<button
onClick={() => setShowNotesDialog(true)}
className="w-full px-4 py-2 text-left text-sm hover:bg-gray-100"
>
{item.properties.notes ? 'Edit Notes' : 'Add Notes'}
</button>
{isSwitch && (
<button
onClick={() => setShowPortConfigDialog(true)}
className="w-full px-4 py-2 text-left text-sm hover:bg-gray-100"
>
Configure Ports
</button>
)}
<div className="border-t border-gray-200 my-1"></div>
<button
onClick={() => setShowDeleteDialog(true)}
className="w-full px-4 py-2 text-left text-sm text-red-600 hover:bg-red-50"
>
Delete
</button>
</div>
);
}

View File

@@ -0,0 +1,71 @@
import { useState } from 'react';
interface LayerInfo {
name: string;
url: string;
attribution: string;
maxZoom: number;
maxNativeZoom?: number;
}
interface LayerSwitcherProps {
activeLayer: string;
onLayerChange: (layer: string) => void;
layers: Record<string, LayerInfo>;
}
export function LayerSwitcher({ activeLayer, onLayerChange, layers }: LayerSwitcherProps) {
const [isOpen, setIsOpen] = useState(false);
return (
<div className="relative">
<button
onClick={() => setIsOpen(!isOpen)}
className="bg-white shadow-md rounded-lg px-4 py-2 hover:bg-gray-50 flex items-center gap-2"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 20l-5.447-2.724A1 1 0 013 16.382V5.618a1 1 0 011.447-.894L9 7m0 13l6-3m-6 3V7m6 10l4.553 2.276A1 1 0 0021 18.382V7.618a1 1 0 00-.553-.894L15 4m0 13V4m0 0L9 7" />
</svg>
<span className="text-sm font-medium">
{layers[activeLayer]?.name || 'Map Layer'}
</span>
<svg
className={`w-4 h-4 transition-transform ${isOpen ? 'rotate-180' : ''}`}
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
</svg>
</button>
{isOpen && (
<div className="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg border border-gray-200 py-1">
{Object.entries(layers).map(([key, layer]) => (
<button
key={key}
onClick={() => {
onLayerChange(key);
setIsOpen(false);
}}
className={`w-full px-4 py-2 text-left text-sm hover:bg-gray-50 flex items-center justify-between ${
activeLayer === key ? 'bg-blue-50 text-blue-700' : 'text-gray-700'
}`}
>
<span>{layer.name}</span>
{activeLayer === key && (
<svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
<path
fillRule="evenodd"
d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
clipRule="evenodd"
/>
</svg>
)}
</button>
))}
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,422 @@
import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { Polyline, Marker, Popup, Circle, useMapEvents } from 'react-leaflet';
import L from 'leaflet';
import { mapItemService } from '../../services/mapItemService';
import { CABLE_COLORS, type MapItem, type CableType } from '../../types/mapItem';
import { ItemContextMenu } from './ItemContextMenu';
import { useDrawingStore } from '../../stores/drawingStore';
interface MapItemsLayerProps {
mapId: string;
refreshTrigger: number;
}
// Custom marker icons for devices using CSS
const switchIcon = new L.DivIcon({
html: `<div class="device-icon switch-icon">
<svg viewBox="0 0 24 24" fill="currentColor">
<rect x="2" y="4" width="20" height="16" rx="2" fill="none" stroke="currentColor" stroke-width="2"/>
<circle cx="6" cy="10" r="1.5"/>
<circle cx="10" cy="10" r="1.5"/>
<circle cx="14" cy="10" r="1.5"/>
<circle cx="18" cy="10" r="1.5"/>
<circle cx="6" cy="14" r="1.5"/>
<circle cx="10" cy="14" r="1.5"/>
<circle cx="14" cy="14" r="1.5"/>
<circle cx="18" cy="14" r="1.5"/>
</svg>
</div>`,
className: 'custom-device-marker',
iconSize: [40, 40],
iconAnchor: [20, 40],
});
const indoorApIcon = new L.DivIcon({
html: `<div class="device-icon ap-indoor-icon">
<svg viewBox="0 0 24 24" fill="currentColor">
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z" opacity="0.3"/>
<circle cx="12" cy="12" r="3"/>
<path d="M12 6c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm0 10c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4z"/>
</svg>
</div>`,
className: 'custom-device-marker',
iconSize: [40, 40],
iconAnchor: [20, 40],
});
const outdoorApIcon = new L.DivIcon({
html: `<div class="device-icon ap-outdoor-icon">
<svg viewBox="0 0 24 24" fill="currentColor">
<path d="M1 9l2 2c4.97-4.97 13.03-4.97 18 0l2-2C16.93 2.93 7.08 2.93 1 9z"/>
<path d="M9 17l3 3 3-3c-1.65-1.66-4.34-1.66-6 0z"/>
<path d="M5 13l2 2c2.76-2.76 7.24-2.76 10 0l2-2C15.14 9.14 8.87 9.14 5 13z"/>
</svg>
</div>`,
className: 'custom-device-marker',
iconSize: [40, 40],
iconAnchor: [20, 40],
});
export function MapItemsLayer({ mapId, refreshTrigger }: MapItemsLayerProps) {
const [items, setItems] = useState<MapItem[]>([]);
const [loading, setLoading] = useState(true);
const [contextMenu, setContextMenu] = useState<{
item: MapItem;
position: { x: number; y: number };
} | null>(null);
const { activeTool } = useDrawingStore();
// Check if we're in drawing mode (should suppress popups)
const isCableTool = ['fiber', 'cat6', 'cat6_poe'].includes(activeTool);
const isWirelessTool = activeTool === 'wireless_mesh';
const shouldSuppressPopups = isCableTool || isWirelessTool;
useEffect(() => {
loadItems();
}, [mapId, refreshTrigger]);
const loadItems = async () => {
try {
setLoading(true);
const data = await mapItemService.getMapItems(mapId);
console.log('Loaded items:', data);
// Log devices with their connections
data.forEach(item => {
if (['switch', 'indoor_ap', 'outdoor_ap'].includes(item.type)) {
console.log(`Device ${item.type} (${item.id}): ${item.properties.connections?.length || 0} / ${item.properties.port_count} ports`);
}
});
setItems(data);
} catch (error) {
console.error('Failed to load map items:', error);
} finally {
setLoading(false);
}
};
// Close context menu on any map click
useMapEvents({
click: () => setContextMenu(null),
contextmenu: () => {}, // Prevent default map context menu
});
const getDeviceIcon = (type: string) => {
switch (type) {
case 'switch':
return switchIcon;
case 'indoor_ap':
return indoorApIcon;
case 'outdoor_ap':
return outdoorApIcon;
default:
return undefined;
}
};
if (loading) return null;
return (
<>
{items.map((item) => {
// Render cables
if (item.type === 'cable' && item.geometry.type === 'LineString') {
const positions = item.geometry.coordinates.map(
([lng, lat]) => [lat, lng] as [number, number]
);
const cableType = item.properties.cable_type as CableType;
const color = CABLE_COLORS[cableType] || '#6B7280';
// Find connected devices
const startDevice = item.properties.start_device_id
? items.find(i => i.id === item.properties.start_device_id)
: null;
const endDevice = item.properties.end_device_id
? items.find(i => i.id === item.properties.end_device_id)
: null;
return (
<div key={item.id}>
<Polyline
positions={positions}
color={color}
weight={3}
opacity={0.8}
eventHandlers={{
contextmenu: (e) => {
L.DomEvent.stopPropagation(e);
setContextMenu({
item,
position: { x: e.originalEvent.clientX, y: e.originalEvent.clientY }
});
},
}}
>
{!shouldSuppressPopups && (
<Popup>
<div className="text-sm" style={{ minWidth: '200px' }}>
<div className="font-semibold">{item.properties.name || 'Cable'}</div>
<div className="text-gray-600">Type: {cableType}</div>
{startDevice && (
<div className="text-gray-600 mt-1">
From: {startDevice.properties.name || startDevice.type}
</div>
)}
{endDevice && (
<div className="text-gray-600">
To: {endDevice.properties.name || endDevice.type}
</div>
)}
{item.properties.notes && (
<div className="text-gray-600 mt-2 pt-2 border-t border-gray-200">
{item.properties.notes}
</div>
)}
{item.properties.image && (
<div className="mt-2">
<img
src={item.properties.image}
alt="Attachment"
className="w-full rounded border border-gray-200"
style={{ maxHeight: '150px', objectFit: 'contain' }}
/>
</div>
)}
</div>
</Popup>
)}
</Polyline>
{/* Show circles at cable bend points (not first/last) */}
{positions.slice(1, -1).map((pos, idx) => (
<Circle
key={`${item.id}-bend-${idx}`}
center={pos}
radius={1}
pathOptions={{
color: color,
fillColor: color,
fillOpacity: 0.3,
weight: 2,
}}
/>
))}
</div>
);
}
// Render wireless mesh
if (item.type === 'wireless_mesh' && item.geometry.type === 'LineString') {
const positions = item.geometry.coordinates.map(
([lng, lat]) => [lat, lng] as [number, number]
);
// Find connected APs
const startAp = item.properties.start_ap_id
? items.find(i => i.id === item.properties.start_ap_id)
: null;
const endAp = item.properties.end_ap_id
? items.find(i => i.id === item.properties.end_ap_id)
: null;
return (
<Polyline
key={item.id}
positions={positions}
color="#10B981"
weight={3}
opacity={0.8}
dashArray="10, 10"
eventHandlers={{
contextmenu: (e) => {
L.DomEvent.stopPropagation(e);
setContextMenu({
item,
position: { x: e.originalEvent.clientX, y: e.originalEvent.clientY }
});
},
}}
>
{!shouldSuppressPopups && (
<Popup>
<div className="text-sm" style={{ minWidth: '200px' }}>
<div className="font-semibold">{item.properties.name || 'Wireless Mesh'}</div>
{startAp && (
<div className="text-gray-600 mt-1">
From: {startAp.properties.name || startAp.type}
</div>
)}
{endAp && (
<div className="text-gray-600">
To: {endAp.properties.name || endAp.type}
</div>
)}
{item.properties.notes && (
<div className="text-gray-600 mt-2 pt-2 border-t border-gray-200">
{item.properties.notes}
</div>
)}
{item.properties.image && (
<div className="mt-2">
<img
src={item.properties.image}
alt="Attachment"
className="w-full rounded border border-gray-200"
style={{ maxHeight: '150px', objectFit: 'contain' }}
/>
</div>
)}
</div>
</Popup>
)}
</Polyline>
);
}
// Render devices
if (
['switch', 'indoor_ap', 'outdoor_ap'].includes(item.type) &&
item.geometry.type === 'Point'
) {
const [lng, lat] = item.geometry.coordinates;
const position: [number, number] = [lat, lng];
const icon = getDeviceIcon(item.type);
return (
<Marker
key={item.id}
position={position}
icon={icon}
eventHandlers={{
contextmenu: (e) => {
L.DomEvent.stopPropagation(e);
setContextMenu({
item,
position: { x: e.originalEvent.clientX, y: e.originalEvent.clientY }
});
},
}}
>
{!shouldSuppressPopups && (
<Popup>
<div className="text-sm" style={{ minWidth: '200px' }}>
<div className="font-semibold">{item.properties.name || item.type}</div>
<div className="text-gray-600">Type: {item.type}</div>
{item.properties.port_count && (
<div className="text-gray-600">
Ports: {item.properties.connections?.length || 0} / {item.properties.port_count}
</div>
)}
{/* Show port connections details */}
{item.properties.connections && item.properties.connections.length > 0 && (
<div className="mt-2 pt-2 border-t border-gray-200">
<div className="font-semibold text-gray-700 mb-1">Port Connections:</div>
{item.properties.connections
.sort((a: any, b: any) => a.port_number - b.port_number)
.map((conn: any) => {
const cable = items.find(i => i.id === conn.cable_id);
if (!cable) return null;
// Find the other device connected to this cable
const otherDeviceId = cable.properties.start_device_id === item.id
? cable.properties.end_device_id
: cable.properties.start_device_id;
const otherDevice = otherDeviceId
? items.find(i => i.id === otherDeviceId)
: null;
const cableType = cable.properties.cable_type;
return (
<div key={conn.cable_id} className="text-xs text-gray-600 ml-2">
Port {conn.port_number} {otherDevice
? `${otherDevice.properties.name || otherDevice.type} (${cableType})`
: `${cableType} cable`}
</div>
);
})}
</div>
)}
{/* Show wireless mesh count for APs */}
{['indoor_ap', 'outdoor_ap'].includes(item.type) && (
<div className="text-gray-600">
Wireless mesh: {items.filter(i =>
i.type === 'wireless_mesh' &&
(i.properties.start_ap_id === item.id || i.properties.end_ap_id === item.id)
).length} / 4
</div>
)}
{/* Show wireless mesh connections details for APs */}
{['indoor_ap', 'outdoor_ap'].includes(item.type) && (() => {
const meshLinks = items.filter(i =>
i.type === 'wireless_mesh' &&
(i.properties.start_ap_id === item.id || i.properties.end_ap_id === item.id)
);
if (meshLinks.length > 0) {
return (
<div className="mt-2 pt-2 border-t border-gray-200">
<div className="font-semibold text-gray-700 mb-1">Mesh Connections:</div>
{meshLinks.map((mesh) => {
const otherApId = mesh.properties.start_ap_id === item.id
? mesh.properties.end_ap_id
: mesh.properties.start_ap_id;
const otherAp = otherApId
? items.find(i => i.id === otherApId)
: null;
return (
<div key={mesh.id} className="text-xs text-gray-600 ml-2">
{otherAp ? (otherAp.properties.name || otherAp.type) : 'Unknown AP'}
</div>
);
})}
</div>
);
}
return null;
})()}
{item.properties.notes && (
<div className="text-gray-600 mt-2 pt-2 border-t border-gray-200">
{item.properties.notes}
</div>
)}
{item.properties.image && (
<div className="mt-2">
<img
src={item.properties.image}
alt="Attachment"
className="w-full rounded border border-gray-200"
style={{ maxHeight: '150px', objectFit: 'contain' }}
/>
</div>
)}
</div>
</Popup>
)}
</Marker>
);
}
return null;
})}
{/* Context menu rendered outside map using portal */}
{contextMenu && createPortal(
<ItemContextMenu
item={contextMenu.item}
position={contextMenu.position}
onClose={() => setContextMenu(null)}
onUpdate={loadItems}
/>,
document.body
)}
</>
);
}

View File

@@ -0,0 +1,142 @@
import { useState, useEffect } from 'react';
import { useMapStore } from '../../stores/mapStore';
import { mapService } from '../../services/mapService';
interface MapListSidebarProps {
onSelectMap: (mapId: string) => void;
selectedMapId: string | null;
}
export function MapListSidebar({ onSelectMap, selectedMapId }: MapListSidebarProps) {
const { maps, setMaps, addMap, removeMap, setLoading, setError } = useMapStore();
const [isCreating, setIsCreating] = useState(false);
const [newMapName, setNewMapName] = useState('');
useEffect(() => {
loadMaps();
}, []);
const loadMaps = async () => {
setLoading(true);
try {
const data = await mapService.getUserMaps();
setMaps(data);
} catch (error: any) {
setError(error.response?.data?.detail || 'Failed to load maps');
} finally {
setLoading(false);
}
};
const handleCreateMap = async () => {
if (!newMapName.trim()) return;
try {
const newMap = await mapService.createMap({ name: newMapName });
addMap(newMap);
setNewMapName('');
setIsCreating(false);
onSelectMap(newMap.id);
} catch (error: any) {
setError(error.response?.data?.detail || 'Failed to create map');
}
};
const handleDeleteMap = async (mapId: string) => {
if (!confirm('Are you sure you want to delete this map?')) return;
try {
await mapService.deleteMap(mapId);
removeMap(mapId);
} catch (error: any) {
setError(error.response?.data?.detail || 'Failed to delete map');
}
};
return (
<div className="w-80 bg-white border-r border-gray-200 flex flex-col">
<div className="p-4 border-b border-gray-200">
<h2 className="text-lg font-semibold mb-3">My Maps</h2>
{!isCreating ? (
<button
onClick={() => setIsCreating(true)}
className="w-full px-3 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
>
+ New Map
</button>
) : (
<div className="space-y-2">
<input
type="text"
value={newMapName}
onChange={(e) => setNewMapName(e.target.value)}
placeholder="Map name"
className="w-full px-3 py-2 border border-gray-300 rounded"
autoFocus
onKeyDown={(e) => e.key === 'Enter' && handleCreateMap()}
/>
<div className="flex gap-2">
<button
onClick={handleCreateMap}
className="flex-1 px-3 py-1 bg-green-600 text-white rounded hover:bg-green-700 text-sm"
>
Create
</button>
<button
onClick={() => {
setIsCreating(false);
setNewMapName('');
}}
className="flex-1 px-3 py-1 bg-gray-300 text-gray-700 rounded hover:bg-gray-400 text-sm"
>
Cancel
</button>
</div>
</div>
)}
</div>
<div className="flex-1 overflow-y-auto">
{maps.length === 0 ? (
<div className="p-4 text-center text-gray-500 text-sm">
No maps yet. Create your first map!
</div>
) : (
<div className="divide-y divide-gray-200">
{maps.map((map) => (
<div
key={map.id}
className={`p-4 cursor-pointer hover:bg-gray-50 ${
selectedMapId === map.id ? 'bg-blue-50 border-l-4 border-blue-600' : ''
}`}
onClick={() => onSelectMap(map.id)}
>
<div className="flex justify-between items-start">
<div className="flex-1">
<h3 className="font-medium text-gray-900">{map.name}</h3>
{map.description && (
<p className="text-sm text-gray-600 mt-1">{map.description}</p>
)}
<p className="text-xs text-gray-400 mt-1">
{new Date(map.updated_at).toLocaleDateString()}
</p>
</div>
<button
onClick={(e) => {
e.stopPropagation();
handleDeleteMap(map.id);
}}
className="text-red-600 hover:text-red-800 text-sm ml-2"
>
Delete
</button>
</div>
</div>
))}
</div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,113 @@
import { useState, useEffect } from 'react';
import { MapContainer, TileLayer, useMap } from 'react-leaflet';
import 'leaflet/dist/leaflet.css';
import { Toolbar } from './Toolbar';
import { LayerSwitcher } from './LayerSwitcher';
import { DrawingHandler } from './DrawingHandler';
import { MapItemsLayer } from './MapItemsLayer';
interface MapViewProps {
mapId: string | null;
}
type MapLayer = 'osm' | 'google' | 'esri';
const MAP_LAYERS = {
osm: {
name: 'OpenStreetMap',
url: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
maxZoom: 25,
},
google: {
name: 'Google Satellite',
url: 'https://mt1.google.com/vt/lyrs=s&x={x}&y={y}&z={z}',
attribution: '&copy; Google',
maxZoom: 25,
maxNativeZoom: 22,
},
esri: {
name: 'ESRI Satellite',
url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
attribution: 'Tiles &copy; Esri',
maxZoom: 25,
},
};
function MapController() {
const map = useMap();
useEffect(() => {
// Invalidate size when map becomes visible
setTimeout(() => {
map.invalidateSize();
}, 100);
}, [map]);
return null;
}
export function MapView({ mapId }: MapViewProps) {
const [activeLayer, setActiveLayer] = useState<MapLayer>('osm');
const [refreshTrigger, setRefreshTrigger] = useState(0);
const handleItemCreated = () => {
// Trigger refresh of map items
setRefreshTrigger((prev) => prev + 1);
};
if (!mapId) {
return (
<div className="flex-1 flex items-center justify-center bg-gray-100">
<div className="text-center">
<p className="text-gray-500 text-lg">Select a map from the sidebar to get started</p>
<p className="text-gray-400 text-sm mt-2">or create a new one</p>
</div>
</div>
);
}
const layer = MAP_LAYERS[activeLayer];
return (
<>
{/* Toolbar for drawing tools */}
<div style={{ position: 'fixed', left: '220px', top: '70px', zIndex: 9999 }}>
<Toolbar mapId={mapId} />
</div>
{/* Layer switcher */}
<div style={{ position: 'fixed', right: '20px', top: '70px', zIndex: 9999 }}>
<LayerSwitcher
activeLayer={activeLayer}
onLayerChange={setActiveLayer}
layers={MAP_LAYERS}
/>
</div>
<div className="flex-1 relative">
<MapContainer
center={[0, 0]}
zoom={2}
className="h-full w-full"
style={{ background: '#f0f0f0' }}
>
<MapController />
<TileLayer
key={activeLayer}
url={layer.url}
attribution={layer.attribution}
maxZoom={layer.maxZoom}
maxNativeZoom={layer.maxNativeZoom}
/>
{/* Drawing handler for creating new items */}
<DrawingHandler mapId={mapId} onItemCreated={handleItemCreated} />
{/* Render existing map items */}
<MapItemsLayer mapId={mapId} refreshTrigger={refreshTrigger} />
</MapContainer>
</div>
</>
);
}

View File

@@ -0,0 +1,99 @@
import { useDrawingStore } from '../../stores/drawingStore';
import type { DrawingTool } from '../../types/mapItem';
import { CABLE_COLORS, CABLE_LABELS } from '../../types/mapItem';
interface ToolbarProps {
mapId: string;
}
interface ToolButton {
id: DrawingTool;
label: string;
icon: string;
color?: string;
description: string;
}
const TOOLS: ToolButton[] = [
{
id: 'select',
label: 'Select',
icon: '👆',
description: 'Select and edit items',
},
{
id: 'fiber',
label: 'Fiber',
icon: '━',
color: CABLE_COLORS.fiber,
description: CABLE_LABELS.fiber,
},
{
id: 'cat6',
label: 'Cat6',
icon: '━',
color: CABLE_COLORS.cat6,
description: CABLE_LABELS.cat6,
},
{
id: 'cat6_poe',
label: 'Cat6 PoE',
icon: '━',
color: CABLE_COLORS.cat6_poe,
description: CABLE_LABELS.cat6_poe,
},
{
id: 'switch',
label: 'Switch',
icon: '⚡',
description: 'Network Switch',
},
{
id: 'indoor_ap',
label: 'Indoor AP',
icon: '📡',
description: 'Indoor Access Point',
},
{
id: 'outdoor_ap',
label: 'Outdoor AP',
icon: '📶',
description: 'Outdoor Access Point',
},
{
id: 'wireless_mesh',
label: 'Wireless',
icon: '⚡',
color: '#10B981',
description: 'Wireless Mesh Link',
},
];
export function Toolbar({ mapId }: ToolbarProps) {
const { activeTool, setActiveTool } = useDrawingStore();
return (
<div className="bg-white shadow-lg rounded-lg p-2 space-y-1" style={{ minWidth: '150px' }}>
{TOOLS.map((tool) => (
<button
key={tool.id}
onClick={() => setActiveTool(tool.id)}
className={`w-full px-3 py-2 rounded text-left flex items-center gap-2 transition-colors ${
activeTool === tool.id
? 'bg-blue-100 text-blue-700 font-medium'
: 'hover:bg-gray-100 text-gray-700'
}`}
title={tool.description}
>
<span
className="text-lg"
style={tool.color ? { color: tool.color } : undefined}
>
{tool.icon}
</span>
<span className="text-sm">{tool.label}</span>
</button>
))}
</div>
);
}