Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ Server-state lives in TanStack Query. The global `QueryClient` (`src/lib/tanstac

### Backend integration

- **Valhalla base URL**: `getBaseUrl()` in `src/utils/base-url.ts` reads `localStorage['valhalla_base_url']` first, then falls back to `VITE_VALHALLA_URL`. The settings panel lets users override and `testConnection()` validates by hitting `/status` and checking `available_actions` includes `route` and `isochrone`.
- **Valhalla base URL**: `getBaseUrl()` in `src/utils/base-url.ts` reads `localStorage['valhalla_base_url']` first, then falls back to `VITE_VALHALLA_URL`. The settings panel lets users override and `testConnection()` validates by hitting `/status` and checking `available_actions` includes `route` and `isochrone`. Every URL that passes `testConnection()` is also appended to `localStorage['valhalla_saved_base_urls']` (JSON array); `ServerSettings` (`src/components/settings-panel/server-settings.tsx`) exposes them as a dropdown on the URL input for quick switching (default always listed and not removable; removing the active URL falls back to the default).
- **Client ID header**: Valhalla requests to the **default** server send `X-Client-Id: ${VITE_CLIENT_ID}` (via `getValhallaHeaders()` in `src/utils/valhalla.ts`). Requests to any custom server send no custom headers and no `Content-Type`, so they stay CORS-"simple": a bare `valhalla_service` (e.g. `localhost:8002`) answers OPTIONS preflights with 405; production only works because nginx answers them. `src/index.tsx` warns at startup if it's unset or `unknown-web-app`. Production CI sets it to `public-web-app`.
- **Nominatim**: `src/utils/nominatim.ts`, base URL from `VITE_NOMINATIM_URL`.

Expand Down
149 changes: 124 additions & 25 deletions src/components/settings-panel/server-settings.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,39 @@
import { useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
InputGroup,
InputGroupAddon,
InputGroupButton,
InputGroupInput,
} from '@/components/ui/input-group';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
getBaseUrl,
setBaseUrl,
getDefaultBaseUrl,
getSavedBaseUrls,
saveBaseUrl,
removeSavedBaseUrl,
validateBaseUrl,
normalizeBaseUrl,
testConnection,
} from '@/utils/base-url';
import { CollapsibleSection } from '@/components/ui/collapsible-section';
import { Server, RotateCcw, Loader2 } from 'lucide-react';
import {
Server,
RotateCcw,
Loader2,
ChevronDown,
Check,
Trash2,
} from 'lucide-react';
import {
Field,
FieldLabel,
Expand All @@ -21,6 +43,9 @@ import {

export const ServerSettings = () => {
const [baseUrl, setBaseUrlState] = useState<string>(() => getBaseUrl());
const [savedUrls, setSavedUrls] = useState<string[]>(() =>
getSavedBaseUrls()
);
const [isOpen, setIsOpen] = useState(false);

const connectionMutation = useMutation({
Expand All @@ -29,7 +54,9 @@ export const ServerSettings = () => {
if (result.reachable) {
const normalizedUrl = normalizeBaseUrl(url);
setBaseUrl(normalizedUrl);
saveBaseUrl(normalizedUrl);
setBaseUrlState(normalizedUrl);
setSavedUrls(getSavedBaseUrls());
}
},
});
Expand Down Expand Up @@ -87,6 +114,31 @@ export const ServerSettings = () => {
connectionMutation.reset();
};

const handleSelectSavedUrl = (url: string) => {
setBaseUrlState(url);
connectionMutation.reset();

if (url === getDefaultBaseUrl()) {
setBaseUrl(url);
return;
}

connectionMutation.mutate(url);
};

const handleRemoveSavedUrl = (url: string) => {
const wasActive = url === getBaseUrl();
removeSavedBaseUrl(url);
setSavedUrls(getSavedBaseUrls());

if (wasActive) {
setBaseUrlState(getDefaultBaseUrl());
connectionMutation.reset();
}
};

const activeUrl = getBaseUrl();

return (
<CollapsibleSection
title="Server Settings"
Expand All @@ -98,32 +150,79 @@ export const ServerSettings = () => {
<Field data-invalid={!!errorMessage}>
<FieldLabel htmlFor="base-url-input">Base URL</FieldLabel>
<FieldDescription>
The Valhalla server URL for routing and isochrone requests
The Valhalla server URL for routing and isochrone requests. Working
URLs are saved for quick switching.
</FieldDescription>
<div className="flex gap-2">
<div className="flex-1 relative">
<Input
id="base-url-input"
type="url"
placeholder="https://valhalla.example.com"
value={baseUrl}
onChange={handleBaseUrlChange}
onBlur={handleBaseUrlBlur}
disabled={connectionMutation.isPending}
aria-invalid={!!errorMessage}
className={
errorMessage
? 'border-destructive focus-visible:ring-destructive/50'
: ''
}
/>
<InputGroup>
<InputGroupInput
id="base-url-input"
type="url"
placeholder="https://valhalla.example.com"
value={baseUrl}
onChange={handleBaseUrlChange}
onBlur={handleBaseUrlBlur}
disabled={connectionMutation.isPending}
aria-invalid={!!errorMessage}
/>
<InputGroupAddon align="inline-end">
{connectionMutation.isPending && (
<div className="absolute right-3 top-1/2 -translate-y-1/2">
<Loader2 className="size-4 animate-spin text-muted-foreground" />
</div>
<Loader2 className="size-4 animate-spin" />
)}
</div>
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<InputGroupButton
size="icon-xs"
aria-label="Saved servers"
disabled={connectionMutation.isPending}
>
<ChevronDown />
</InputGroupButton>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-72">
<DropdownMenuLabel>Saved servers</DropdownMenuLabel>
{savedUrls.map((url) => {
const isDefault = url === getDefaultBaseUrl();
return (
<DropdownMenuItem
key={url}
onSelect={() => handleSelectSavedUrl(url)}
onKeyDown={(e) => {
if (e.key === 'Delete' && !isDefault) {
handleRemoveSavedUrl(url);
}
}}
>
<Check
className={url === activeUrl ? '' : 'invisible'}
/>
<span className="flex-1 truncate" title={url}>
{url}
</span>
{isDefault ? (
<span className="text-muted-foreground text-xs">
default
</span>
) : (
<Button
variant="ghost"
size="icon-xs"
aria-label={`Remove ${url}`}
onClick={(e) => {
// keep the menu open and don't select the row
e.stopPropagation();
handleRemoveSavedUrl(url);
}}
>
<Trash2 />
</Button>
)}
</DropdownMenuItem>
);
})}
</DropdownMenuContent>
</DropdownMenu>
</InputGroupAddon>
</InputGroup>
<FieldError>{errorMessage}</FieldError>
</Field>
<Button
Expand Down
51 changes: 51 additions & 0 deletions src/utils/base-url.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ import {
getBaseUrl,
setBaseUrl,
getDefaultBaseUrl,
getSavedBaseUrls,
saveBaseUrl,
removeSavedBaseUrl,
validateBaseUrl,
normalizeBaseUrl,
testConnection,
Expand Down Expand Up @@ -65,6 +68,54 @@ describe('base-url', () => {
});
});

describe('saved base URLs', () => {
const OTHER_URL = 'https://other.valhalla.com';

it('should always list the default URL first', () => {
expect(getSavedBaseUrls()).toEqual([getDefaultBaseUrl()]);
});

it('should include the active URL even if it was never saved', () => {
localStorage.setItem(STORAGE_KEY, TEST_CUSTOM_URL);
expect(getSavedBaseUrls()).toEqual([
getDefaultBaseUrl(),
TEST_CUSTOM_URL,
]);
});

it('should save URLs in insertion order without duplicates', () => {
saveBaseUrl(TEST_CUSTOM_URL);
saveBaseUrl(OTHER_URL);
saveBaseUrl(TEST_CUSTOM_URL);
saveBaseUrl(getDefaultBaseUrl());
expect(getSavedBaseUrls()).toEqual([
getDefaultBaseUrl(),
TEST_CUSTOM_URL,
OTHER_URL,
]);
});

it('should ignore corrupt storage', () => {
localStorage.setItem('valhalla_saved_base_urls', '{not json');
expect(getSavedBaseUrls()).toEqual([getDefaultBaseUrl()]);
});

it('should remove a saved URL', () => {
saveBaseUrl(TEST_CUSTOM_URL);
saveBaseUrl(OTHER_URL);
removeSavedBaseUrl(TEST_CUSTOM_URL);
expect(getSavedBaseUrls()).toEqual([getDefaultBaseUrl(), OTHER_URL]);
});

it('should fall back to the default when removing the active URL', () => {
saveBaseUrl(TEST_CUSTOM_URL);
setBaseUrl(TEST_CUSTOM_URL);
removeSavedBaseUrl(TEST_CUSTOM_URL);
expect(getBaseUrl()).toBe(getDefaultBaseUrl());
expect(getSavedBaseUrls()).toEqual([getDefaultBaseUrl()]);
});
});

describe('validateBaseUrl', () => {
it('should return invalid for empty string', () => {
const result = validateBaseUrl('');
Expand Down
72 changes: 72 additions & 0 deletions src/utils/base-url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,78 @@ export function getDefaultBaseUrl(): string {
return DEFAULT_BASE_URL;
}

const SAVED_BASE_URLS_STORAGE_KEY = 'valhalla_base_urls';

const savedBaseUrlsSchema = z.array(z.string());

function readStoredBaseUrls(): string[] {
const stored = localStorage.getItem(SAVED_BASE_URLS_STORAGE_KEY);
if (!stored) {
return [];
}

try {
const parsed = savedBaseUrlsSchema.safeParse(JSON.parse(stored));
return parsed.success ? parsed.data : [];
} catch {
return [];
}
}

function writeStoredBaseUrls(urls: string[]): void {
if (urls.length === 0) {
localStorage.removeItem(SAVED_BASE_URLS_STORAGE_KEY);
} else {
localStorage.setItem(SAVED_BASE_URLS_STORAGE_KEY, JSON.stringify(urls));
}
}

/**
* All server URLs the user can pick from: the default first, then every
* user-saved URL. The active URL is always included, so a URL set before
* saved URLs existed still shows up.
*/
export function getSavedBaseUrls(): string[] {
if (typeof window === 'undefined') {
return [DEFAULT_BASE_URL];
}

return [
...new Set([DEFAULT_BASE_URL, ...readStoredBaseUrls(), getBaseUrl()]),
];
}

export function saveBaseUrl(url: string): void {
if (typeof window === 'undefined') {
return;
}

const trimmedUrl = url.trim();
const storedUrls = readStoredBaseUrls();

if (
trimmedUrl === '' ||
trimmedUrl === DEFAULT_BASE_URL ||
storedUrls.includes(trimmedUrl)
) {
return;
}

writeStoredBaseUrls([...storedUrls, trimmedUrl]);
}

export function removeSavedBaseUrl(url: string): void {
if (typeof window === 'undefined') {
return;
}

writeStoredBaseUrls(readStoredBaseUrls().filter((saved) => saved !== url));

if (getBaseUrl() === url) {
setBaseUrl(DEFAULT_BASE_URL);
}
}

export interface UrlValidationResult {
valid: boolean;
error?: string;
Expand Down