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

42
public/src/App.css Normal file
View File

@@ -0,0 +1,42 @@
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}

25
public/src/App.tsx Normal file
View File

@@ -0,0 +1,25 @@
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { Login } from './components/auth/Login';
import { ProtectedRoute } from './components/auth/ProtectedRoute';
import { Dashboard } from './pages/Dashboard';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/login" element={<Login />} />
<Route
path="/"
element={
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
}
/>
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</BrowserRouter>
);
}
export default App;

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

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>
);
}

56
public/src/index.css Normal file
View File

@@ -0,0 +1,56 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
/* Leaflet CSS will be imported in main.tsx */
/* Custom Leaflet marker styles */
.custom-marker {
background: transparent !important;
border: none !important;
display: flex;
align-items: center;
justify-content: center;
}
.custom-marker div {
filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.3));
}
/* Device marker icons */
.custom-device-marker {
background: transparent !important;
border: none !important;
}
.device-icon {
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
background: white;
border-radius: 50%;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
border: 3px solid;
}
.device-icon svg {
width: 24px;
height: 24px;
}
.switch-icon {
border-color: #8B5CF6;
color: #8B5CF6;
}
.ap-indoor-icon {
border-color: #10B981;
color: #10B981;
}
.ap-outdoor-icon {
border-color: #F59E0B;
color: #F59E0B;
}

10
public/src/main.tsx Normal file
View File

@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)

View File

@@ -0,0 +1,20 @@
import { useState } from 'react';
import { Layout } from '../components/layout/Layout';
import { MapListSidebar } from '../components/map/MapListSidebar';
import { MapView } from '../components/map/MapView';
export function Dashboard() {
const [selectedMapId, setSelectedMapId] = useState<string | null>(null);
return (
<Layout>
<div className="flex h-full">
<MapListSidebar
onSelectMap={setSelectedMapId}
selectedMapId={selectedMapId}
/>
<MapView mapId={selectedMapId} />
</div>
</Layout>
);
}

View File

@@ -0,0 +1,38 @@
import axios from 'axios';
const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:8000';
export const apiClient = axios.create({
baseURL: API_URL,
headers: {
'Content-Type': 'application/json',
},
});
// Request interceptor to add auth token
apiClient.interceptors.request.use(
(config) => {
const token = localStorage.getItem('access_token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
// Response interceptor to handle 401 errors
apiClient.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
// Clear tokens and redirect to login
localStorage.removeItem('access_token');
localStorage.removeItem('refresh_token');
window.location.href = '/login';
}
return Promise.reject(error);
}
);

View File

@@ -0,0 +1,32 @@
import { apiClient } from './api';
import type { LoginRequest, TokenResponse, User } from '../types/auth';
export const authService = {
async login(credentials: LoginRequest): Promise<TokenResponse> {
const response = await apiClient.post<TokenResponse>('/api/auth/login', credentials);
return response.data;
},
async getCurrentUser(): Promise<User> {
const response = await apiClient.get<User>('/api/auth/me');
return response.data;
},
logout() {
localStorage.removeItem('access_token');
localStorage.removeItem('refresh_token');
},
saveTokens(tokens: TokenResponse) {
localStorage.setItem('access_token', tokens.access_token);
localStorage.setItem('refresh_token', tokens.refresh_token);
},
getAccessToken(): string | null {
return localStorage.getItem('access_token');
},
isAuthenticated(): boolean {
return !!this.getAccessToken();
},
};

View File

@@ -0,0 +1,28 @@
import { apiClient } from './api';
import type { MapItem, MapItemCreate, MapItemUpdate } from '../types/mapItem';
export const mapItemService = {
async getMapItems(mapId: string): Promise<MapItem[]> {
const response = await apiClient.get<MapItem[]>(`/api/maps/${mapId}/items`);
return response.data;
},
async getMapItem(mapId: string, itemId: string): Promise<MapItem> {
const response = await apiClient.get<MapItem>(`/api/maps/${mapId}/items/${itemId}`);
return response.data;
},
async createMapItem(mapId: string, data: MapItemCreate): Promise<MapItem> {
const response = await apiClient.post<MapItem>(`/api/maps/${mapId}/items`, data);
return response.data;
},
async updateMapItem(mapId: string, itemId: string, data: MapItemUpdate): Promise<MapItem> {
const response = await apiClient.patch<MapItem>(`/api/maps/${mapId}/items/${itemId}`, data);
return response.data;
},
async deleteMapItem(mapId: string, itemId: string): Promise<void> {
await apiClient.delete(`/api/maps/${mapId}/items/${itemId}`);
},
};

View File

@@ -0,0 +1,38 @@
import { apiClient } from './api';
import type { Map, MapCreate, MapUpdate } from '../types/map';
export const mapService = {
async getUserMaps(): Promise<Map[]> {
const response = await apiClient.get<Map[]>('/api/maps');
return response.data;
},
async getMap(mapId: string): Promise<Map> {
const response = await apiClient.get<Map>(`/api/maps/${mapId}`);
return response.data;
},
async getPublicMap(): Promise<Map> {
const response = await apiClient.get<Map>('/api/maps/public');
return response.data;
},
async createMap(data: MapCreate): Promise<Map> {
const response = await apiClient.post<Map>('/api/maps', data);
return response.data;
},
async updateMap(mapId: string, data: MapUpdate): Promise<Map> {
const response = await apiClient.patch<Map>(`/api/maps/${mapId}`, data);
return response.data;
},
async deleteMap(mapId: string): Promise<void> {
await apiClient.delete(`/api/maps/${mapId}`);
},
async setDefaultPublic(mapId: string): Promise<Map> {
const response = await apiClient.post<Map>(`/api/maps/${mapId}/set-default-public`);
return response.data;
},
};

View File

@@ -0,0 +1,60 @@
import { create } from 'zustand';
import type { User } from '../types/auth';
import { authService } from '../services/authService';
interface AuthState {
user: User | null;
isAuthenticated: boolean;
isLoading: boolean;
error: string | null;
login: (username: string, password: string) => Promise<void>;
logout: () => void;
loadUser: () => Promise<void>;
clearError: () => void;
}
export const useAuthStore = create<AuthState>((set) => ({
user: null,
isAuthenticated: authService.isAuthenticated(),
isLoading: false,
error: null,
login: async (username, password) => {
set({ isLoading: true, error: null });
try {
const tokens = await authService.login({ username, password });
authService.saveTokens(tokens);
const user = await authService.getCurrentUser();
set({ user, isAuthenticated: true, isLoading: false });
} catch (error: any) {
const message = error.response?.data?.detail || 'Login failed';
set({ error: message, isLoading: false, isAuthenticated: false });
throw error;
}
},
logout: () => {
authService.logout();
set({ user: null, isAuthenticated: false });
},
loadUser: async () => {
if (!authService.isAuthenticated()) {
set({ isAuthenticated: false, user: null });
return;
}
set({ isLoading: true });
try {
const user = await authService.getCurrentUser();
set({ user, isAuthenticated: true, isLoading: false });
} catch (error) {
authService.logout();
set({ user: null, isAuthenticated: false, isLoading: false });
}
},
clearError: () => set({ error: null }),
}));

View File

@@ -0,0 +1,35 @@
import { create } from 'zustand';
import type { DrawingTool } from '../types/mapItem';
interface DrawingState {
activeTool: DrawingTool;
isDrawing: boolean;
drawingPoints: [number, number][];
setActiveTool: (tool: DrawingTool) => void;
setIsDrawing: (isDrawing: boolean) => void;
addDrawingPoint: (point: [number, number]) => void;
clearDrawingPoints: () => void;
resetDrawing: () => void;
}
export const useDrawingStore = create<DrawingState>((set) => ({
activeTool: 'select',
isDrawing: false,
drawingPoints: [],
setActiveTool: (tool) => set({ activeTool: tool, isDrawing: false, drawingPoints: [] }),
setIsDrawing: (isDrawing) => set({ isDrawing }),
addDrawingPoint: (point) => set((state) => ({
drawingPoints: [...state.drawingPoints, point],
})),
clearDrawingPoints: () => set({ drawingPoints: [] }),
resetDrawing: () => set({
isDrawing: false,
drawingPoints: [],
}),
}));

View File

@@ -0,0 +1,49 @@
import { create } from 'zustand';
import type { Map } from '../types/map';
interface MapState {
maps: Map[];
currentMap: Map | null;
isLoading: boolean;
error: string | null;
setMaps: (maps: Map[]) => void;
setCurrentMap: (map: Map | null) => void;
addMap: (map: Map) => void;
updateMap: (mapId: string, updates: Partial<Map>) => void;
removeMap: (mapId: string) => void;
setLoading: (isLoading: boolean) => void;
setError: (error: string | null) => void;
clearError: () => void;
}
export const useMapStore = create<MapState>((set) => ({
maps: [],
currentMap: null,
isLoading: false,
error: null,
setMaps: (maps) => set({ maps }),
setCurrentMap: (map) => set({ currentMap: map }),
addMap: (map) => set((state) => ({ maps: [map, ...state.maps] })),
updateMap: (mapId, updates) => set((state) => ({
maps: state.maps.map((m) => (m.id === mapId ? { ...m, ...updates } : m)),
currentMap: state.currentMap?.id === mapId
? { ...state.currentMap, ...updates }
: state.currentMap,
})),
removeMap: (mapId) => set((state) => ({
maps: state.maps.filter((m) => m.id !== mapId),
currentMap: state.currentMap?.id === mapId ? null : state.currentMap,
})),
setLoading: (isLoading) => set({ isLoading }),
setError: (error) => set({ error }),
clearError: () => set({ error: null }),
}));

25
public/src/types/auth.ts Normal file
View File

@@ -0,0 +1,25 @@
export interface User {
id: string;
username: string;
email: string;
is_admin: boolean;
created_at: string;
updated_at: string;
}
export interface LoginRequest {
username: string;
password: string;
}
export interface TokenResponse {
access_token: string;
refresh_token: string;
token_type: string;
}
export interface UserWithToken extends User {
access_token: string;
refresh_token: string;
token_type: string;
}

19
public/src/types/map.ts Normal file
View File

@@ -0,0 +1,19 @@
export interface Map {
id: string;
name: string;
description: string | null;
owner_id: string;
is_default_public: boolean;
created_at: string;
updated_at: string;
}
export interface MapCreate {
name: string;
description?: string | null;
}
export interface MapUpdate {
name?: string;
description?: string | null;
}

View File

@@ -0,0 +1,75 @@
export type MapItemType = 'cable' | 'switch' | 'indoor_ap' | 'outdoor_ap' | 'wireless_mesh';
export type CableType = 'fiber' | 'cat6' | 'cat6_poe';
export interface MapItem {
id: string;
map_id: string;
type: MapItemType;
geometry: GeoJSON.Geometry;
properties: Record<string, any>;
created_at: string;
updated_at: string;
created_by: string | null;
updated_by: string | null;
}
export interface CableProperties {
cable_type: CableType;
name?: string;
notes?: string;
length_meters?: number;
start_device_id?: string | null;
end_device_id?: string | null;
}
export interface DeviceProperties {
name?: string;
notes?: string;
port_count?: number;
connections?: Array<{
cable_id: string;
port_number: number;
}>;
}
export interface WirelessMeshProperties {
name?: string;
notes?: string;
start_ap_id?: string;
end_ap_id?: string;
}
export interface MapItemCreate {
type: MapItemType;
geometry: GeoJSON.Geometry;
properties: Record<string, any>;
}
export interface MapItemUpdate {
type?: MapItemType;
geometry?: GeoJSON.Geometry;
properties?: Record<string, any>;
}
export type DrawingTool =
| 'select'
| 'fiber'
| 'cat6'
| 'cat6_poe'
| 'switch'
| 'indoor_ap'
| 'outdoor_ap'
| 'wireless_mesh';
export const CABLE_COLORS: Record<CableType, string> = {
fiber: '#3B82F6', // Blue
cat6: '#F97316', // Orange
cat6_poe: '#EF4444', // Red
};
export const CABLE_LABELS: Record<CableType, string> = {
fiber: 'Fiber Cable',
cat6: 'Cat6 Cable',
cat6_poe: 'Cat6 PoE Cable',
};