This commit is contained in:
vcoppe
2025-06-21 21:07:36 +02:00
parent f0230d4634
commit 1cc07901f6
803 changed files with 7937 additions and 6329 deletions

View File

@@ -26,6 +26,7 @@ Any help is greatly appreciated!
## Development
The code is split into two parts:
- `gpx`: a Typescript library for parsing and manipulating GPX files,
- `website`: the website itself, which is a [SvelteKit](https://kit.svelte.dev/) application.
@@ -57,10 +58,9 @@ This project has been made possible thanks to the following open source projects
- Development:
- [Svelte](https://github.com/sveltejs/svelte) and [SvelteKit](https://github.com/sveltejs/kit) — seamless development experience
- [MDsveX](https://github.com/pngwn/MDsveX) — allowing a Markdown-based documentation
- [svelte-i18n](https://github.com/kaisermann/svelte-i18n) — easy localization
- Design:
- [shadcn-svelte](https://github.com/huntabyte/shadcn-svelte) — beautiful components
- [lucide-svelte](https://github.com/lucide-icons/lucide/tree/main/packages/lucide-svelte) — beautiful icons
- [@lucide/svelte](https://github.com/lucide-icons/lucide/tree/main/packages/svelte) — beautiful icons
- [tailwindcss](https://github.com/tailwindlabs/tailwindcss) — easy styling
- [Chart.js](https://github.com/chartjs/Chart.js) — beautiful and fast charts
- Logic:

View File

@@ -1 +0,0 @@
package-lock.json

View File

@@ -1,7 +1,7 @@
{
"$schema": "https://next.shadcn-svelte.com/schema.json",
"tailwind": {
"css": "src/app.pcss",
"css": "src/app.css",
"baseColor": "slate"
},
"aliases": {
@@ -12,5 +12,5 @@
"lib": "$lib"
},
"typescript": true,
"registry": "https://tw3.shadcn-svelte.com/registry/default"
"registry": "https://next.shadcn-svelte.com/registry"
}

1464
website/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -5,8 +5,8 @@
"scripts": {
"dev": "vite dev",
"build": "vite build",
"prebuild": "npx tsx src/lib/pwa-manifest.ts",
"postbuild": "npx tsx src/lib/sitemap.ts",
"prebuild": "npx tsx src/lib/scripts/pwa-manifest.ts",
"postbuild": "npx tsx src/lib/scripts/sitemap.ts",
"preview": "vite preview",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
@@ -14,11 +14,12 @@
"format": "prettier --write ."
},
"devDependencies": {
"@lucide/svelte": "^0.482.0",
"@lucide/svelte": "^0.513.0",
"@sveltejs/adapter-static": "^3.0.8",
"@sveltejs/enhanced-img": "^0.6.0",
"@sveltejs/kit": "^2.21.2",
"@sveltejs/vite-plugin-svelte": "^5.1.0",
"@tailwindcss/vite": "^4.1.8",
"@types/eslint": "^9.6.1",
"@types/events": "^3.0.3",
"@types/file-saver": "^2.0.7",
@@ -30,8 +31,7 @@
"@types/sortablejs": "^1.15.8",
"@typescript-eslint/eslint-plugin": "^8.33.1",
"@typescript-eslint/parser": "^8.33.1",
"autoprefixer": "^10.4.21",
"bits-ui": "^1.8.0",
"bits-ui": "^2.5.0",
"eslint": "^9.28.0",
"eslint-config-prettier": "^10.1.5",
"eslint-plugin-svelte": "^3.9.1",
@@ -46,10 +46,11 @@
"prettier-plugin-svelte": "^3.4.0",
"svelte": "^5.33.18",
"svelte-check": "^4.0.0",
"svelte-sonner": "^0.3.28",
"tailwindcss": "^3.4.13",
"svelte-sonner": "^1.0.4",
"tailwindcss": "^4.1.8",
"tslib": "^2.8.1",
"tsx": "^4.19.1",
"tw-animate-css": "^1.3.4",
"typescript": "^5.8.3",
"vaul-svelte": "^1.0.0-next.7",
"vite": "^6.3.5",
@@ -76,8 +77,7 @@
"png.js": "^0.2.1",
"sanitize-html": "^2.17.0",
"sortablejs": "^1.15.6",
"tailwind-merge": "^2.5.2",
"tailwind-variants": "^0.2.1",
"tailwindcss-animate": "^1.0.7"
"tailwind-merge": "^3.3.0",
"tailwind-variants": "^1.0.0"
}
}

View File

@@ -1,6 +0,0 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};

122
website/src/app.css Normal file
View File

@@ -0,0 +1,122 @@
@import "tailwindcss";
@import "tw-animate-css";
@custom-variant dark (&:is(.dark *));
:root {
--background: hsl(0 0% 100%) /* <- Wrap in HSL */;
--foreground: hsl(240 10% 3.9%);
--muted: hsl(240 4.8% 95.9%);
--muted-foreground: hsl(240 3.8% 46.1%);
--popover: hsl(0 0% 100%);
--popover-foreground: hsl(240 10% 3.9%);
--card: hsl(0 0% 100%);
--card-foreground: hsl(240 10% 3.9%);
--border: hsl(240 5.9% 90%);
--input: hsl(240 5.9% 90%);
--primary: hsl(240 5.9% 10%);
--primary-foreground: hsl(0 0% 98%);
--secondary: hsl(240 4.8% 95.9%);
--secondary-foreground: hsl(240 5.9% 10%);
--accent: hsl(240 4.8% 95.9%);
--accent-foreground: hsl(240 5.9% 10%);
--destructive: hsl(0 72.2% 50.6%);
--destructive-foreground: hsl(0 0% 98%);
--ring: hsl(240 10% 3.9%);
--sidebar: hsl(0 0% 98%);
--sidebar-foreground: hsl(240 5.3% 26.1%);
--sidebar-primary: hsl(240 5.9% 10%);
--sidebar-primary-foreground: hsl(0 0% 98%);
--sidebar-accent: hsl(240 4.8% 95.9%);
--sidebar-accent-foreground: hsl(240 5.9% 10%);
--sidebar-border: hsl(220 13% 91%);
--sidebar-ring: hsl(217.2 91.2% 59.8%);
--support: rgb(220 15 130);
--link: rgb(0 110 180);
--radius: 0.5rem;
}
.dark {
--background: hsl(240 10% 3.9%);
--foreground: hsl(0 0% 98%);
--muted: hsl(240 3.7% 15.9%);
--muted-foreground: hsl(240 5% 64.9%);
--popover: hsl(240 10% 3.9%);
--popover-foreground: hsl(0 0% 98%);
--card: hsl(240 10% 3.9%);
--card-foreground: hsl(0 0% 98%);
--border: hsl(240 3.7% 15.9%);
--input: hsl(240 3.7% 15.9%);
--primary: hsl(0 0% 98%);
--primary-foreground: hsl(240 5.9% 10%);
--secondary: hsl(240 3.7% 15.9%);
--secondary-foreground: hsl(0 0% 98%);
--accent: hsl(240 3.7% 15.9%);
--accent-foreground: hsl(0 0% 98%);
--destructive: hsl(0 62.8% 30.6%);
--destructive-foreground: hsl(0 0% 98%);
--ring: hsl(240 4.9% 83.9%);
--sidebar: hsl(240 5.9% 10%);
--sidebar-foreground: hsl(240 4.8% 95.9%);
--sidebar-primary: hsl(224.3 76.3% 48%);
--sidebar-primary-foreground: hsl(0 0% 100%);
--sidebar-accent: hsl(240 3.7% 15.9%);
--sidebar-accent-foreground: hsl(240 4.8% 95.9%);
--sidebar-border: hsl(240 3.7% 15.9%);
--sidebar-ring: hsl(217.2 91.2% 59.8%);
--support: rgb(255 110 190);
--link: rgb(80 190 255);
}
@theme inline {
/* Radius (for rounded-*) */
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
/* Colors */
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-border: var(--border);
--color-input: var(--input);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-destructive-foreground: var(--destructive-foreground);
--color-ring: var(--ring);
--color-radius: var(--radius);
--color-sidebar: var(--sidebar);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring);
--color-support: var(--support);
--color-link: var(--link);
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
}
}

View File

@@ -1,86 +0,0 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 222.2 84% 4.9%;
--muted: 210 40% 96.1%;
--muted-foreground: 215.4 16.3% 45%;
--popover: 0 0% 100%;
--popover-foreground: 222.2 84% 4.9%;
--card: 0 0% 100%;
--card-foreground: 222.2 84% 4.9%;
--border: 214.3 31.8% 91.4%;
--input: 214.3 31.8% 91.4%;
--primary: 222.2 47.4% 11.2%;
--primary-foreground: 210 40% 98%;
--secondary: 210 40% 96.1%;
--secondary-foreground: 222.2 47.4% 11.2%;
--accent: 210 40% 92%;
--accent-foreground: 222.2 47.4% 11.2%;
--destructive: 0 72.2% 50.6%;
--destructive-foreground: 210 40% 98%;
--support: 220 15 130;
--link: 0 110 180;
--ring: 222.2 84% 4.9%;
--radius: 0.5rem;
}
.dark {
--background: 222.2 84% 4.9%;
--foreground: 210 40% 98%;
--muted: 217.2 32.6% 17.5%;
--muted-foreground: 215 20.2% 65.1%;
--popover: 222.2 84% 4.9%;
--popover-foreground: 210 40% 98%;
--card: 222.2 84% 4.9%;
--card-foreground: 210 40% 98%;
--border: 217.2 32.6% 17.5%;
--input: 217.2 32.6% 17.5%;
--primary: 210 40% 98%;
--primary-foreground: 222.2 47.4% 11.2%;
--secondary: 217.2 32.6% 17.5%;
--secondary-foreground: 210 40% 98%;
--accent: 217.2 32.6% 30%;
--accent-foreground: 210 40% 98%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 210 40% 98%;
--support: 255 110 190;
--link: 80 190 255;
--ring: hsl(212.7, 26.8%, 83.9);
}
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
}
}

View File

@@ -41,10 +41,12 @@ export async function handle({ event, resolve }) {
<link rel="alternate" hreflang="x-default" href="https://gpx.studio${getURLForLanguage('en', path)}" />
<link rel="manifest" href="/${language}.manifest.webmanifest" />`;
if (page !== '404') {
for (let lang of Object.keys(languages)) {
headTag += ` <link rel="alternate" hreflang="${lang}" href="https://gpx.studio${getURLForLanguage(lang, path)}" />
`;
}
}
const response = await resolve(event, {
transformPageChunk: ({ html }) =>

View File

@@ -29,7 +29,8 @@ import {
TriangleAlert,
Anchor,
Toilet,
} from 'lucide-svelte';
type IconProps,
} from '@lucide/svelte';
import {
Landmark as LandmarkSvg,
Shell as ShellSvg,
@@ -61,11 +62,11 @@ import {
Anchor as AnchorSvg,
Toilet as ToiletSvg,
} from 'lucide-static';
import type { ComponentType } from 'svelte';
import type { Component } from 'svelte';
export type Symbol = {
value: string;
icon?: ComponentType<Icon>;
icon?: Component<IconProps>;
iconSvg?: string;
};

View File

@@ -2,7 +2,11 @@
import docsearch from '@docsearch/js';
import '@docsearch/css';
import { onMount } from 'svelte';
import { _, locale, isLoadingLocale } from '$lib/i18n';
import { i18n } from '$lib/i18n.svelte';
let props: {
class?: string;
} = $props();
let mounted = false;
@@ -13,31 +17,31 @@
indexName: 'gpx',
container: '#docsearch',
searchParameters: {
facetFilters: ['lang:' + $locale],
facetFilters: ['lang:' + i18n.lang],
},
placeholder: $_('docs.search.search'),
placeholder: i18n._('docs.search.search'),
disableUserPersonalization: true,
translations: {
button: {
buttonText: $_('docs.search.search'),
buttonAriaLabel: $_('docs.search.search'),
buttonText: i18n._('docs.search.search'),
buttonAriaLabel: i18n._('docs.search.search'),
},
modal: {
searchBox: {
resetButtonTitle: $_('docs.search.clear'),
resetButtonAriaLabel: $_('docs.search.clear'),
cancelButtonText: $_('docs.search.cancel'),
cancelButtonAriaLabel: $_('docs.search.cancel'),
searchInputLabel: $_('docs.search.search'),
resetButtonTitle: i18n._('docs.search.clear'),
resetButtonAriaLabel: i18n._('docs.search.clear'),
cancelButtonText: i18n._('docs.search.cancel'),
cancelButtonAriaLabel: i18n._('docs.search.cancel'),
searchInputLabel: i18n._('docs.search.search'),
},
footer: {
selectText: $_('docs.search.to_select'),
navigateText: $_('docs.search.to_navigate'),
closeText: $_('docs.search.to_close'),
selectText: i18n._('docs.search.to_select'),
navigateText: i18n._('docs.search.to_navigate'),
closeText: i18n._('docs.search.to_close'),
},
noResultsScreen: {
noResultsText: $_('docs.search.no_results'),
suggestedQueryText: $_('docs.search.no_results_suggestion'),
noResultsText: i18n._('docs.search.no_results'),
suggestedQueryText: i18n._('docs.search.no_results_suggestion'),
},
},
},
@@ -48,13 +52,15 @@
mounted = true;
});
$: if (mounted && $locale && !$isLoadingLocale) {
$effect(() => {
if (mounted && i18n.lang && !i18n.isLoading) {
initDocsearch();
}
});
</script>
<svelte:head>
<link rel="preconnect" href="https://21XLD94PE3-dsn.algolia.net" crossorigin />
</svelte:head>
<div id="docsearch" {...$$restProps}></div>
<div id="docsearch" class={props.class ?? ''}></div>

View File

@@ -1,28 +1,36 @@
<script lang="ts">
import { Button } from '$lib/components/ui/button/index.js';
import * as Tooltip from '$lib/components/ui/tooltip/index.js';
import type { Builder } from 'bits-ui';
import type { Snippet } from 'svelte';
export let variant:
| 'default'
| 'secondary'
| 'link'
| 'destructive'
| 'outline'
| 'ghost'
| undefined = 'default';
export let label: string;
export let side: 'top' | 'right' | 'bottom' | 'left' = 'top';
export let builders: Builder[] = [];
const {
variant = 'default',
label,
side = 'top',
class: className = '',
children,
onclick,
}: {
variant?: 'default' | 'secondary' | 'link' | 'destructive' | 'outline' | 'ghost';
label: string;
side?: 'top' | 'right' | 'bottom' | 'left';
class?: string;
children: Snippet;
onclick?: (event: MouseEvent) => void;
} = $props();
</script>
<Tooltip.Provider>
<Tooltip.Root>
<Tooltip.Trigger asChild let:builder>
<Button builders={[...builders, builder]} {variant} {...$$restProps} on:click>
<slot />
<Tooltip.Trigger>
{#snippet child({ props })}
<Button {...props} {variant} class={className} {onclick}>
{@render children()}
</Button>
{/snippet}
</Tooltip.Trigger>
<Tooltip.Content {side}>
<span>{label}</span>
</Tooltip.Content>
</Tooltip.Root>
</Tooltip.Provider>

View File

@@ -1,18 +0,0 @@
<script lang="ts">
import { map } from '$lib/stores';
import { trackpointPopup } from '$lib/components/gpx-layer/GPXLayerPopup';
import { TrackPoint } from 'gpx';
$: if ($map) {
$map.on('contextmenu', (e) => {
trackpointPopup?.setItem({
item: new TrackPoint({
attributes: {
lat: e.lngLat.lat,
lon: e.lngLat.lng,
},
}),
});
});
}
</script>

View File

@@ -18,9 +18,9 @@
Check,
ChartNoAxesColumn,
Construction,
} from 'lucide-svelte';
} from '@lucide/svelte';
import { getSlopeColor, getSurfaceColor, getHighwayColor } from '$lib/assets/colors';
import { _, df } from '$lib/i18n';
import { _, df } from '$lib/i18n.svelte';
import {
getCadenceWithUnits,
getConvertedDistance,
@@ -120,17 +120,17 @@
marker.addTo($map);
}
}
return `${$_('quantities.elevation')}: ${getElevationWithUnits(point.y, false)}`;
return `${i18n._('quantities.elevation')}: ${getElevationWithUnits(point.y, false)}`;
} else if (context.datasetIndex === 1) {
return `${$velocityUnits === 'speed' ? $_('quantities.speed') : $_('quantities.pace')}: ${getVelocityWithUnits(point.y, false)}`;
return `${$velocityUnits === 'speed' ? i18n._('quantities.speed') : i18n._('quantities.pace')}: ${getVelocityWithUnits(point.y, false)}`;
} else if (context.datasetIndex === 2) {
return `${$_('quantities.heartrate')}: ${getHeartRateWithUnits(point.y)}`;
return `${i18n._('quantities.heartrate')}: ${getHeartRateWithUnits(point.y)}`;
} else if (context.datasetIndex === 3) {
return `${$_('quantities.cadence')}: ${getCadenceWithUnits(point.y)}`;
return `${i18n._('quantities.cadence')}: ${getCadenceWithUnits(point.y)}`;
} else if (context.datasetIndex === 4) {
return `${$_('quantities.temperature')}: ${getTemperatureWithUnits(point.y, false)}`;
return `${i18n._('quantities.temperature')}: ${getTemperatureWithUnits(point.y, false)}`;
} else if (context.datasetIndex === 5) {
return `${$_('quantities.power')}: ${getPowerWithUnits(point.y)}`;
return `${i18n._('quantities.power')}: ${getPowerWithUnits(point.y)}`;
}
},
afterBody: function (contexts: Chart.TooltipContext[]) {
@@ -152,31 +152,35 @@
let mtbScale = point.extensions.mtb_scale;
let labels = [
` ${$_('quantities.distance')}: ${getDistanceWithUnits(point.x, false)}`,
` ${$_('quantities.slope')}: ${slope.at} %${elevationFill === 'slope' ? ` (${slope.length} @${slope.segment} %)` : ''}`,
` ${i18n._('quantities.distance')}: ${getDistanceWithUnits(point.x, false)}`,
` ${i18n._('quantities.slope')}: ${slope.at} %${elevationFill === 'slope' ? ` (${slope.length} @${slope.segment} %)` : ''}`,
];
if (elevationFill === 'surface') {
labels.push(
` ${$_('quantities.surface')}: ${$_(`toolbar.routing.surface.${surface}`)}`
` ${i18n._('quantities.surface')}: ${i18n._(`toolbar.routing.surface.${surface}`)}`
);
}
if (elevationFill === 'highway') {
labels.push(
` ${$_('quantities.highway')}: ${$_(`toolbar.routing.highway.${highway}`)}${
` ${i18n._('quantities.highway')}: ${i18n._(`toolbar.routing.highway.${highway}`)}${
sacScale
? ` (${$_(`toolbar.routing.sac_scale.${sacScale}`)})`
? ` (${i18n._(`toolbar.routing.sac_scale.${sacScale}`)})`
: ''
}`
);
if (mtbScale) {
labels.push(` ${$_('toolbar.routing.mtb_scale')}: ${mtbScale}`);
labels.push(
` ${i18n._('toolbar.routing.mtb_scale')}: ${mtbScale}`
);
}
}
if (point.time) {
labels.push(` ${$_('quantities.time')}: ${$df.format(point.time)}`);
labels.push(
` ${i18n._('quantities.time')}: ${$df.format(point.time)}`
);
}
return labels;
@@ -357,7 +361,7 @@
// update data
chart.data.datasets[0] = {
label: $_('quantities.elevation'),
label: i18n._('quantities.elevation'),
data: data.local.points.map((point, index) => {
return {
x: getConvertedDistance(data.local.distance.total[index]),
@@ -552,15 +556,17 @@
{#if showControls}
<div class="absolute bottom-10 right-1.5">
<Popover.Root>
<Popover.Trigger asChild let:builder>
<Popover.Trigger>
{#snippet child({ props })}
<ButtonWithTooltip
label={$_('chart.settings')}
builders={[builder]}
{...props}
label={i18n._('chart.settings')}
variant="outline"
class="w-7 h-7 p-0 flex justify-center opacity-70 hover:opacity-100 transition-opacity duration-300 hover:bg-background"
>
<ChartNoAxesColumn size="18" />
</ButtonWithTooltip>
{/snippet}
</Popover.Trigger>
<Popover.Content
class="w-fit p-0 flex flex-col divide-y"
@@ -582,7 +588,7 @@
{/if}
</div>
<TriangleRight size="15" class="mr-1" />
{$_('quantities.slope')}
{i18n._('quantities.slope')}
</ToggleGroup.Item>
<ToggleGroup.Item
class="p-0 pr-1.5 h-6 w-full rounded flex justify-start data-[state=on]:bg-background data-[state=on]:hover:bg-accent hover:bg-accent hover:text-foreground"
@@ -595,7 +601,7 @@
{/if}
</div>
<BrickWall size="15" class="mr-1" />
{$_('quantities.surface')}
{i18n._('quantities.surface')}
</ToggleGroup.Item>
<ToggleGroup.Item
class="p-0 pr-1.5 h-6 w-full rounded flex justify-start data-[state=on]:bg-background data-[state=on]:hover:bg-accent hover:bg-accent hover:text-foreground"
@@ -608,7 +614,7 @@
{/if}
</div>
<Construction size="15" class="mr-1" />
{$_('quantities.highway')}
{i18n._('quantities.highway')}
</ToggleGroup.Item>
</ToggleGroup.Root>
<ToggleGroup.Root
@@ -627,8 +633,8 @@
</div>
<Zap size="15" class="mr-1" />
{$velocityUnits === 'speed'
? $_('quantities.speed')
: $_('quantities.pace')}
? i18n._('quantities.speed')
: i18n._('quantities.pace')}
</ToggleGroup.Item>
<ToggleGroup.Item
class="p-0 pr-1.5 h-6 w-full rounded flex justify-start data-[state=on]:bg-background data-[state=on]:hover:bg-accent hover:bg-accent hover:text-foreground"
@@ -640,7 +646,7 @@
{/if}
</div>
<HeartPulse size="15" class="mr-1" />
{$_('quantities.heartrate')}
{i18n._('quantities.heartrate')}
</ToggleGroup.Item>
<ToggleGroup.Item
class="p-0 pr-1.5 h-6 w-full rounded flex justify-start data-[state=on]:bg-background data-[state=on]:hover:bg-accent hover:bg-accent hover:text-foreground"
@@ -652,7 +658,7 @@
{/if}
</div>
<Orbit size="15" class="mr-1" />
{$_('quantities.cadence')}
{i18n._('quantities.cadence')}
</ToggleGroup.Item>
<ToggleGroup.Item
class="p-0 pr-1.5 h-6 w-full rounded flex justify-start data-[state=on]:bg-background data-[state=on]:hover:bg-accent hover:bg-accent hover:text-foreground"
@@ -664,7 +670,7 @@
{/if}
</div>
<Thermometer size="15" class="mr-1" />
{$_('quantities.temperature')}
{i18n._('quantities.temperature')}
</ToggleGroup.Item>
<ToggleGroup.Item
class="p-0 pr-1.5 h-6 w-full rounded flex justify-start data-[state=on]:bg-background data-[state=on]:hover:bg-accent hover:bg-accent hover:text-foreground"
@@ -676,7 +682,7 @@
{/if}
</div>
<SquareActivity size="15" class="mr-1" />
{$_('quantities.power')}
{i18n._('quantities.power')}
</ToggleGroup.Item>
</ToggleGroup.Root>
</Popover.Content>

View File

@@ -2,8 +2,8 @@
import { Button } from '$lib/components/ui/button';
import LanguageSelect from '$lib/components/LanguageSelect.svelte';
import Logo from '$lib/components/Logo.svelte';
import { AtSign, BookOpenText, Heart, Home, Map } from 'lucide-svelte';
import { _, locale } from '$lib/i18n';
import { AtSign, BookOpenText, Heart, Home, Map } from '@lucide/svelte';
import { i18n } from '$lib/i18n.svelte';
import { getURLForLanguage } from '$lib/utils';
</script>
@@ -24,42 +24,42 @@
</div>
<div class="grow max-w-2xl flex flex-row flex-wrap justify-between gap-x-10 gap-y-6">
<div class="flex flex-col items-start gap-1">
<span class="font-semibold">{$_('homepage.website')}</span>
<span class="font-semibold">{i18n._('homepage.website')}</span>
<Button
variant="link"
class="h-6 px-0 text-muted-foreground"
href={getURLForLanguage($locale, '/')}
href={getURLForLanguage(i18n.lang, '/')}
>
<Home size="16" class="mr-1" />
{$_('homepage.home')}
<Home size="16" />
{i18n._('homepage.home')}
</Button>
<Button
variant="link"
class="h-6 px-0 text-muted-foreground"
href={getURLForLanguage($locale, '/app')}
href={getURLForLanguage(i18n.lang, '/app')}
>
<Map size="16" class="mr-1" />
{$_('homepage.app')}
<Map size="16" />
{i18n._('homepage.app')}
</Button>
<Button
variant="link"
class="h-6 px-0 text-muted-foreground"
href={getURLForLanguage($locale, '/help')}
href={getURLForLanguage(i18n.lang, '/help')}
>
<BookOpenText size="16" class="mr-1" />
{$_('menu.help')}
<BookOpenText size="16" />
{i18n._('menu.help')}
</Button>
</div>
<div class="flex flex-col items-start gap-1" id="contact">
<span class="font-semibold">{$_('homepage.contact')}</span>
<span class="font-semibold">{i18n._('homepage.contact')}</span>
<Button
variant="link"
class="h-6 px-0 text-muted-foreground"
href="https://www.reddit.com/r/gpxstudio/"
target="_blank"
>
<Logo company="reddit" class="h-4 mr-1 fill-muted-foreground" />
{$_('homepage.reddit')}
<Logo company="reddit" class="h-4 fill-muted-foreground" />
{i18n._('homepage.reddit')}
</Button>
<Button
variant="link"
@@ -67,8 +67,8 @@
href="https://facebook.com/gpx.studio"
target="_blank"
>
<Logo company="facebook" class="h-4 mr-1 fill-muted-foreground" />
{$_('homepage.facebook')}
<Logo company="facebook" class="h-4 fill-muted-foreground" />
{i18n._('homepage.facebook')}
</Button>
<Button
variant="link"
@@ -76,8 +76,8 @@
href="https://x.com/gpxstudio"
target="_blank"
>
<Logo company="x" class="h-4 mr-1 fill-muted-foreground" />
{$_('homepage.x')}
<Logo company="x" class="h-4 fill-muted-foreground" />
{i18n._('homepage.x')}
</Button>
<Button
variant="link"
@@ -85,20 +85,20 @@
href="mailto:hello@gpx.studio"
target="_blank"
>
<AtSign size="16" class="mr-1" />
{$_('homepage.email')}
<AtSign size="16" />
{i18n._('homepage.email')}
</Button>
</div>
<div class="flex flex-col items-start gap-1">
<span class="font-semibold">{$_('homepage.contribute')}</span>
<span class="font-semibold">{i18n._('homepage.contribute')}</span>
<Button
variant="link"
class="h-6 px-0 text-muted-foreground"
href="https://ko-fi.com/gpxstudio"
target="_blank"
>
<Heart size="16" class="mr-1" />
{$_('menu.donate')}
<Heart size="16" />
{i18n._('menu.donate')}
</Button>
<Button
variant="link"
@@ -106,8 +106,8 @@
href="https://crowdin.com/project/gpxstudio"
target="_blank"
>
<Logo company="crowdin" class="h-4 mr-1 fill-muted-foreground" />
{$_('homepage.crowdin')}
<Logo company="crowdin" class="h-4 fill-muted-foreground" />
{i18n._('homepage.crowdin')}
</Button>
<Button
variant="link"
@@ -115,8 +115,8 @@
href="https://github.com/gpxstudio/gpx.studio"
target="_blank"
>
<Logo company="github" class="h-4 mr-1 fill-muted-foreground" />
{$_('homepage.github')}
<Logo company="github" class="h-4 fill-muted-foreground" />
{i18n._('homepage.github')}
</Button>
</div>
</div>

View File

@@ -3,9 +3,9 @@
import Tooltip from '$lib/components/Tooltip.svelte';
import WithUnits from '$lib/components/WithUnits.svelte';
import { MoveDownRight, MoveUpRight, Ruler, Timer, Zap } from 'lucide-svelte';
import { MoveDownRight, MoveUpRight, Ruler, Timer, Zap } from '@lucide/svelte';
import { _ } from '$lib/i18n';
import { i18n } from '$lib/i18n.svelte';
import type { GPXStatistics } from 'gpx';
import type { Writable } from 'svelte/store';
import { settings } from '$lib/db';
@@ -36,13 +36,13 @@
? 'flex-col justify-center'
: 'flex-row w-full justify-between'} gap-4 p-0"
>
<Tooltip label={$_('quantities.distance')}>
<Tooltip label={i18n._('quantities.distance')}>
<span class="flex flex-row items-center">
<Ruler size="16" class="mr-1" />
<WithUnits value={statistics.global.distance.total} type="distance" />
</span>
</Tooltip>
<Tooltip label={$_('quantities.elevation_gain_loss')}>
<Tooltip label={i18n._('quantities.elevation_gain_loss')}>
<span class="flex flex-row items-center">
<MoveUpRight size="16" class="mr-1" />
<WithUnits value={statistics.global.elevation.gain} type="elevation" />
@@ -54,8 +54,10 @@
<Tooltip
class={orientation === 'horizontal' ? 'hidden xs:block' : ''}
label="{$velocityUnits === 'speed'
? $_('quantities.speed')
: $_('quantities.pace')} ({$_('quantities.moving')} / {$_('quantities.total')})"
? i18n._('quantities.speed')
: i18n._('quantities.pace')} ({i18n._('quantities.moving')} / {i18n._(
'quantities.total'
)})"
>
<span class="flex flex-row items-center">
<Zap size="16" class="mr-1" />
@@ -72,7 +74,7 @@
{#if panelSize > 160 || orientation === 'horizontal'}
<Tooltip
class={orientation === 'horizontal' ? 'hidden md:block' : ''}
label="{$_('quantities.time')} ({$_('quantities.moving')} / {$_(
label="{i18n._('quantities.time')} ({i18n._('quantities.moving')} / {i18n._(
'quantities.total'
)})"
>

View File

@@ -1,6 +1,6 @@
<script lang="ts">
import { CircleHelp } from 'lucide-svelte';
import { _ } from '$lib/i18n';
import { CircleHelp } from '@lucide/svelte';
import { i18n } from '$lib/i18n.svelte';
export let link: string | undefined = undefined;
</script>
@@ -13,7 +13,7 @@
<slot />
{#if link}
<a href={link} target="_blank" class="text-sm text-link hover:underline">
{$_('menu.more')}
{i18n._('menu.more')}
</a>
{/if}
</div>

View File

@@ -1,37 +1,27 @@
<script lang="ts">
import { page } from '$app/stores';
import { page } from '$app/state';
import * as Select from '$lib/components/ui/select';
import { languages } from '$lib/languages';
import { getURLForLanguage } from '$lib/utils';
import { Languages } from 'lucide-svelte';
import { _, locale } from '$lib/i18n';
let selected = {
value: '',
label: '',
};
$: if ($locale) {
selected = {
value: $locale,
label: languages[$locale],
};
}
import { Languages } from '@lucide/svelte';
import { i18n } from '$lib/i18n.svelte';
</script>
<Select.Root bind:selected>
<Select.Trigger class="w-[180px] {$$props.class ?? ''}" aria-label={$_('menu.language')}>
<Select.Root type="single" value={i18n.lang}>
<Select.Trigger class="w-[180px] {$$props.class ?? ''}" aria-label={i18n._('menu.language')}>
<Languages size="16" />
<Select.Value class="ml-2 mr-auto" />
<span class="ml-2 mr-auto">
{languages[i18n.lang]}
</span>
</Select.Trigger>
<Select.Content>
{#each Object.entries(languages) as [lang, label]}
{#if $page.url.pathname.includes('404')}
{#if page.url.pathname.includes('404')}
<a href={getURLForLanguage(lang, '/')}>
<Select.Item value={lang}>{label}</Select.Item>
</a>
{:else}
<a href={getURLForLanguage(lang, $page.url.pathname)}>
<a href={getURLForLanguage(lang, page.url.pathname)}>
<Select.Item value={lang}>{label}</Select.Item>
</a>
{/if}
@@ -41,9 +31,9 @@
<!-- hidden links for svelte crawling -->
<div class="hidden">
{#if !$page.url.pathname.includes('404')}
{#if !page.url.pathname.includes('404')}
{#each Object.entries(languages) as [lang, label]}
<a href={getURLForLanguage(lang, $page.url.pathname)}>
<a href={getURLForLanguage(lang, page.url.pathname)}>
{label}
</a>
{/each}

View File

@@ -1,394 +0,0 @@
<script lang="ts">
import { onDestroy, onMount } from 'svelte';
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';
import MapboxGeocoder from '@mapbox/mapbox-gl-geocoder';
import '@mapbox/mapbox-gl-geocoder/dist/mapbox-gl-geocoder.css';
import { Button } from '$lib/components/ui/button';
import { map } from '$lib/stores';
import { settings } from '$lib/db';
import { _ } from '$lib/i18n';
import { PUBLIC_MAPBOX_TOKEN } from '$env/static/public';
import { page } from '$app/stores';
export let accessToken = PUBLIC_MAPBOX_TOKEN;
export let geolocate = true;
export let geocoder = true;
export let hash = true;
mapboxgl.accessToken = accessToken;
let webgl2Supported = true;
let embeddedApp = false;
let fitBoundsOptions: mapboxgl.FitBoundsOptions = {
maxZoom: 15,
linear: true,
easing: () => 1,
};
const { distanceUnits, elevationProfile, treeFileView, bottomPanelSize, rightPanelSize } =
settings;
let scaleControl = new mapboxgl.ScaleControl({
unit: $distanceUnits,
});
onMount(() => {
let gl = document.createElement('canvas').getContext('webgl2');
if (!gl) {
webgl2Supported = false;
return;
}
if (window.top !== window.self && !$page.route.id?.includes('embed')) {
embeddedApp = true;
return;
}
let language = $page.params.language;
if (language === 'zh') {
language = 'zh-Hans';
} else if (language?.includes('-')) {
language = language.split('-')[0];
} else if (language === '' || language === undefined) {
language = 'en';
}
let newMap = new mapboxgl.Map({
container: 'map',
style: {
version: 8,
sources: {},
layers: [],
imports: [
{
id: 'glyphs-and-sprite', // make Mapbox glyphs and sprite available to other styles
url: '',
data: {
version: 8,
sources: {},
layers: [],
glyphs: 'mapbox://fonts/mapbox/{fontstack}/{range}.pbf',
sprite: `https://api.mapbox.com/styles/v1/mapbox/outdoors-v12/sprite?access_token=${PUBLIC_MAPBOX_TOKEN}`,
},
},
{
id: 'basemap',
url: '',
},
{
id: 'overlays',
url: '',
data: {
version: 8,
sources: {},
layers: [],
},
},
],
},
projection: 'globe',
zoom: 0,
hash: hash,
language,
attributionControl: false,
logoPosition: 'bottom-right',
boxZoom: false,
});
newMap.on('load', () => {
$map = newMap; // only set the store after the map has loaded
window._map = newMap; // entry point for extensions
scaleControl.setUnit($distanceUnits);
});
newMap.addControl(
new mapboxgl.AttributionControl({
compact: true,
})
);
newMap.addControl(
new mapboxgl.NavigationControl({
visualizePitch: true,
})
);
if (geocoder) {
let geocoder = new MapboxGeocoder({
mapboxgl: mapboxgl,
enableEventLogging: false,
collapsed: true,
flyTo: fitBoundsOptions,
language,
localGeocoder: () => [],
localGeocoderOnly: true,
externalGeocoder: (query: string) =>
fetch(
`https://nominatim.openstreetmap.org/search?format=json&q=${query}&limit=5&accept-language=${language}`
)
.then((response) => response.json())
.then((data) => {
return data.map((result: any) => {
return {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [result.lon, result.lat],
},
place_name: result.display_name,
};
});
}),
});
let onKeyDown = geocoder._onKeyDown;
geocoder._onKeyDown = (e: KeyboardEvent) => {
// Trigger search on Enter key only
if (e.key === 'Enter') {
onKeyDown.apply(geocoder, [{ target: geocoder._inputEl }]);
} else if (geocoder._typeahead.data.length > 0) {
geocoder._typeahead.clear();
}
};
newMap.addControl(geocoder);
}
if (geolocate) {
newMap.addControl(
new mapboxgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true,
},
fitBoundsOptions,
trackUserLocation: true,
showUserHeading: true,
})
);
}
newMap.addControl(scaleControl);
newMap.on('style.load', () => {
newMap.addSource('mapbox-dem', {
type: 'raster-dem',
url: 'mapbox://mapbox.mapbox-terrain-dem-v1',
tileSize: 512,
maxzoom: 14,
});
if (newMap.getPitch() > 0) {
newMap.setTerrain({
source: 'mapbox-dem',
exaggeration: 1,
});
}
newMap.setFog({
color: 'rgb(186, 210, 235)',
'high-color': 'rgb(36, 92, 223)',
'horizon-blend': 0.1,
'space-color': 'rgb(156, 240, 255)',
});
newMap.on('pitch', () => {
if (newMap.getPitch() > 0) {
newMap.setTerrain({
source: 'mapbox-dem',
exaggeration: 1,
});
} else {
newMap.setTerrain(null);
}
});
});
});
onDestroy(() => {
if ($map) {
$map.remove();
$map = null;
}
});
$: if ($map && (!$treeFileView || !$elevationProfile || $bottomPanelSize || $rightPanelSize)) {
$map.resize();
}
</script>
<div {...$$restProps}>
<div id="map" class="h-full {webgl2Supported && !embeddedApp ? '' : 'hidden'}"></div>
<div
class="flex flex-col items-center justify-center gap-3 h-full {webgl2Supported &&
!embeddedApp
? 'hidden'
: ''} {embeddedApp ? 'z-30' : ''}"
>
{#if !webgl2Supported}
<p>{$_('webgl2_required')}</p>
<Button href="https://get.webgl.org/webgl2/" target="_blank">
{$_('enable_webgl2')}
</Button>
{:else if embeddedApp}
<p>The app cannot be embedded in an iframe.</p>
<Button href="https://gpx.studio/help/integration" target="_blank">
Learn how to create a map for your website
</Button>
{/if}
</div>
</div>
<style lang="postcss">
div :global(.mapboxgl-map) {
@apply font-sans;
}
div :global(.mapboxgl-ctrl-top-right > .mapboxgl-ctrl) {
@apply shadow-md;
@apply bg-background;
@apply text-foreground;
}
div :global(.mapboxgl-ctrl-icon) {
@apply dark:brightness-[4.7];
@apply dark:bg-white;
}
div :global(.mapboxgl-ctrl-geocoder) {
@apply flex;
@apply flex-row;
@apply w-fit;
@apply min-w-fit;
@apply items-center;
@apply shadow-md;
}
div :global(.suggestions) {
@apply shadow-md;
@apply bg-background;
@apply text-foreground;
}
div :global(.mapboxgl-ctrl-geocoder .suggestions > li > a) {
@apply text-foreground;
@apply hover:text-accent-foreground;
@apply hover:bg-accent;
}
div :global(.mapboxgl-ctrl-geocoder .suggestions > .active > a) {
@apply bg-background;
}
div :global(.mapboxgl-ctrl-geocoder--button) {
@apply bg-transparent;
@apply hover:bg-transparent;
}
div :global(.mapboxgl-ctrl-geocoder--icon) {
@apply fill-foreground;
@apply hover:fill-accent-foreground;
}
div :global(.mapboxgl-ctrl-geocoder--icon-search) {
@apply relative;
@apply top-0;
@apply left-0;
@apply my-2;
@apply w-[29px];
}
div :global(.mapboxgl-ctrl-geocoder--input) {
@apply relative;
@apply w-64;
@apply py-0;
@apply pl-2;
@apply focus:outline-none;
@apply transition-[width];
@apply duration-200;
@apply text-foreground;
}
div :global(.mapboxgl-ctrl-geocoder--collapsed .mapboxgl-ctrl-geocoder--input) {
@apply w-0;
@apply p-0;
}
div :global(.mapboxgl-ctrl-top-right) {
@apply z-40;
@apply flex;
@apply flex-col;
@apply items-end;
@apply h-full;
@apply overflow-hidden;
}
.horizontal :global(.mapboxgl-ctrl-bottom-left) {
@apply bottom-[42px];
}
.horizontal :global(.mapboxgl-ctrl-bottom-right) {
@apply bottom-[42px];
}
div :global(.mapboxgl-ctrl-attrib) {
@apply dark:bg-transparent;
}
div :global(.mapboxgl-compact-show.mapboxgl-ctrl-attrib) {
@apply dark:bg-background;
}
div :global(.mapboxgl-ctrl-attrib-button) {
@apply dark:bg-foreground;
}
div :global(.mapboxgl-compact-show .mapboxgl-ctrl-attrib-button) {
@apply dark:bg-foreground;
}
div :global(.mapboxgl-ctrl-attrib a) {
@apply text-foreground;
}
div :global(.mapboxgl-popup) {
@apply w-fit;
@apply z-50;
}
div :global(.mapboxgl-popup-content) {
@apply p-0;
@apply bg-transparent;
@apply shadow-none;
}
div :global(.mapboxgl-popup-anchor-top .mapboxgl-popup-tip) {
@apply border-b-background;
}
div :global(.mapboxgl-popup-anchor-top-left .mapboxgl-popup-tip) {
@apply border-b-background;
}
div :global(.mapboxgl-popup-anchor-top-right .mapboxgl-popup-tip) {
@apply border-b-background;
}
div :global(.mapboxgl-popup-anchor-bottom .mapboxgl-popup-tip) {
@apply border-t-background;
@apply drop-shadow-md;
}
div :global(.mapboxgl-popup-anchor-bottom-left .mapboxgl-popup-tip) {
@apply border-t-background;
@apply drop-shadow-md;
}
div :global(.mapboxgl-popup-anchor-bottom-right .mapboxgl-popup-tip) {
@apply border-t-background;
@apply drop-shadow-md;
}
div :global(.mapboxgl-popup-anchor-left .mapboxgl-popup-tip) {
@apply border-r-background;
}
div :global(.mapboxgl-popup-anchor-right .mapboxgl-popup-tip) {
@apply border-l-background;
}
</style>

View File

@@ -1,25 +0,0 @@
<svelte:options accessors />
<script lang="ts">
import { TrackPoint, Waypoint } from 'gpx';
import type { Writable } from 'svelte/store';
import WaypointPopup from '$lib/components/gpx-layer/WaypointPopup.svelte';
import TrackpointPopup from '$lib/components/gpx-layer/TrackpointPopup.svelte';
import OverpassPopup from '$lib/components/layer-control/OverpassPopup.svelte';
import type { PopupItem } from './MapPopup';
export let item: Writable<PopupItem | null>;
export let container: HTMLDivElement | null = null;
</script>
<div bind:this={container}>
{#if $item}
{#if $item.item instanceof Waypoint}
<WaypointPopup waypoint={$item} />
{:else if $item.item instanceof TrackPoint}
<TrackpointPopup trackpoint={$item} />
{:else}
<OverpassPopup poi={$item} />
{/if}
{/if}
</div>

View File

@@ -1,82 +0,0 @@
import { TrackPoint, Waypoint } from 'gpx';
import mapboxgl from 'mapbox-gl';
import { tick, mount } from 'svelte';
import { get, writable, type Writable } from 'svelte/store';
import MapPopupComponent from './MapPopup.svelte';
export type PopupItem<T = Waypoint | TrackPoint | any> = {
item: T;
fileId?: string;
hide?: () => void;
};
export class MapPopup {
map: mapboxgl.Map;
popup: mapboxgl.Popup;
item: Writable<PopupItem | null> = writable(null);
maybeHideBinded = this.maybeHide.bind(this);
constructor(map: mapboxgl.Map, options?: mapboxgl.PopupOptions) {
this.map = map;
this.popup = new mapboxgl.Popup(options);
let component = mount(MapPopupComponent, {
target: document.body,
props: {
item: this.item,
},
});
tick().then(() => this.popup.setDOMContent(component.container));
}
setItem(item: PopupItem | null) {
if (item) item.hide = () => this.hide();
this.item.set(item);
if (item === null) {
this.hide();
} else {
tick().then(() => this.show());
}
}
show() {
const i = get(this.item);
if (i === null) {
this.hide();
return;
}
this.popup.setLngLat(this.getCoordinates()).addTo(this.map);
this.map.on('mousemove', this.maybeHideBinded);
}
maybeHide(e: mapboxgl.MapMouseEvent) {
const i = get(this.item);
if (i === null) {
this.hide();
return;
}
if (this.map.project(this.getCoordinates()).dist(this.map.project(e.lngLat)) > 60) {
this.hide();
}
}
hide() {
this.popup.remove();
this.map.off('mousemove', this.maybeHideBinded);
}
remove() {
this.popup.remove();
}
getCoordinates() {
const i = get(this.item);
if (i === null) {
return new mapboxgl.LngLat(0, 0);
}
return i.item instanceof Waypoint || i.item instanceof TrackPoint
? i.item.getCoordinates()
: new mapboxgl.LngLat(i.item.lon, i.item.lat);
}
}

View File

@@ -43,21 +43,18 @@
BookOpenText,
ChartArea,
Maximize,
} from 'lucide-svelte';
import {
map,
triggerFileInput,
createFile,
loadFiles,
updateSelectionFromKey,
allHidden,
editMetadata,
editStyle,
exportState,
ExportState,
centerMapOnSelection,
} from '$lib/stores';
} from '@lucide/svelte';
import { map } from '$lib/components/map/utils.svelte';
import { editMetadata } from '$lib/components/file-list/metadata/utils.svelte';
import { editStyle } from '$lib/components/file-list/style/utils.svelte';
import { exportState, ExportState } from '$lib/components/export/utils.svelte';
// import {
// triggerFileInput,
// createFile,
// loadFiles,
// updateSelectionFromKey,
// allHidden,
// } from '$lib/stores';
import {
copied,
copySelection,
@@ -66,17 +63,17 @@
selectAll,
selection,
} from '$lib/components/file-list/Selection';
import { derived } from 'svelte/store';
import { canUndo, canRedo, dbUtils, fileObservers, settings } from '$lib/db';
import { anySelectedLayer } from '$lib/components/layer-control/utils';
// import { canUndo, canRedo, dbUtils, fileObservers, settings } from '$lib/db';
import { anySelectedLayer } from '$lib/components/map/layer-control/utils.svelte';
import { defaultOverlays } from '$lib/assets/layers';
import LayerControlSettings from '$lib/components/layer-control/LayerControlSettings.svelte';
// import LayerControlSettings from '$lib/components/map/layer-control/LayerControlSettings.svelte';
import { allowedPastes, ListFileItem, ListTrackItem } from '$lib/components/file-list/FileList';
import Export from '$lib/components/Export.svelte';
import Export from '$lib/components/export/Export.svelte';
import { mode, setMode } from 'mode-watcher';
import { _, locale } from '$lib/i18n';
import { i18n } from '$lib/i18n.svelte';
import { languages } from '$lib/languages';
import { getURLForLanguage } from '$lib/utils';
import { settings } from '$lib/logic/settings.svelte';
const {
distanceUnits,
@@ -94,119 +91,118 @@
routing,
} = settings;
let undoDisabled = derived(canUndo, ($canUndo) => !$canUndo);
let redoDisabled = derived(canRedo, ($canRedo) => !$canRedo);
// let undoDisabled = derived(canUndo, ($canUndo) => !$canUndo);
// let redoDisabled = derived(canRedo, ($canRedo) => !$canRedo);
function switchBasemaps() {
[$currentBasemap, $previousBasemap] = [$previousBasemap, $currentBasemap];
[currentBasemap.value, previousBasemap.value] = [
previousBasemap.value,
currentBasemap.value,
];
}
function toggleOverlays() {
if (anySelectedLayer($currentOverlays)) {
[$currentOverlays, $previousOverlays] = [defaultOverlays, $currentOverlays];
if (currentOverlays.value && anySelectedLayer(currentOverlays.value)) {
[currentOverlays.value, previousOverlays.value] = [
defaultOverlays,
currentOverlays.value,
];
} else {
[$currentOverlays, $previousOverlays] = [$previousOverlays, defaultOverlays];
[currentOverlays.value, previousOverlays.value] = [
previousOverlays.value,
defaultOverlays,
];
}
}
function toggle3D() {
if ($map) {
if ($map.getPitch() === 0) {
$map.easeTo({ pitch: 70 });
} else {
$map.easeTo({ pitch: 0 });
}
}
}
let layerSettingsOpen = false;
let layerSettingsOpen = $state(false);
</script>
<div class="absolute md:top-2 left-0 right-0 z-20 flex flex-row justify-center pointer-events-none">
<div
class="w-fit flex flex-row items-center justify-center p-1 bg-background rounded-b-md md:rounded-md pointer-events-auto shadow-md"
>
<a href={getURLForLanguage($locale, '/')} target="_blank" class="shrink-0">
<a href={getURLForLanguage(i18n.lang, '/')} target="_blank" class="shrink-0">
<Logo class="h-5 mt-0.5 mx-2 md:hidden" iconOnly={true} width="16" />
<Logo class="h-5 mt-0.5 mx-2 hidden md:block" width="96" />
</a>
<Menubar.Root class="border-none h-fit p-0">
<Menubar.Menu>
<Menubar.Trigger aria-label={$_('gpx.file')}>
<Menubar.Trigger aria-label={i18n._('gpx.file')}>
<File size="18" class="md:hidden" />
<span class="hidden md:block">{$_('gpx.file')}</span>
<span class="hidden md:block">{i18n._('gpx.file')}</span>
</Menubar.Trigger>
<Menubar.Content class="border-none">
<Menubar.Item on:click={createFile}>
<Menubar.Item onclick={createFile}>
<Plus size="16" class="mr-1" />
{$_('menu.new')}
{i18n._('menu.new')}
<Shortcut key="+" ctrl={true} />
</Menubar.Item>
<Menubar.Separator />
<Menubar.Item on:click={triggerFileInput}>
<Menubar.Item onclick={triggerFileInput}>
<FolderOpen size="16" class="mr-1" />
{$_('menu.open')}
{i18n._('menu.open')}
<Shortcut key="O" ctrl={true} />
</Menubar.Item>
<Menubar.Separator />
<Menubar.Item
on:click={dbUtils.duplicateSelection}
onclick={dbUtils.duplicateSelection}
disabled={$selection.size == 0}
>
<Copy size="16" class="mr-1" />
{$_('menu.duplicate')}
{i18n._('menu.duplicate')}
<Shortcut key="D" ctrl={true} />
</Menubar.Item>
<Menubar.Separator />
<Menubar.Item
on:click={dbUtils.deleteSelectedFiles}
onclick={dbUtils.deleteSelectedFiles}
disabled={$selection.size == 0}
>
<FileX size="16" class="mr-1" />
{$_('menu.close')}
{i18n._('menu.close')}
<Shortcut key="⌫" ctrl={true} />
</Menubar.Item>
<Menubar.Item
on:click={dbUtils.deleteAllFiles}
onclick={dbUtils.deleteAllFiles}
disabled={$fileObservers.size == 0}
>
<FileX size="16" class="mr-1" />
{$_('menu.close_all')}
{i18n._('menu.close_all')}
<Shortcut key="⌫" ctrl={true} shift={true} />
</Menubar.Item>
<Menubar.Separator />
<Menubar.Item
on:click={() => ($exportState = ExportState.SELECTION)}
onclick={() => (exportState.current = ExportState.SELECTION)}
disabled={$selection.size == 0}
>
<Download size="16" class="mr-1" />
{$_('menu.export')}
{i18n._('menu.export')}
<Shortcut key="S" ctrl={true} />
</Menubar.Item>
<Menubar.Item
on:click={() => ($exportState = ExportState.ALL)}
onclick={() => (exportState.current = ExportState.ALL)}
disabled={$fileObservers.size == 0}
>
<Download size="16" class="mr-1" />
{$_('menu.export_all')}
{i18n._('menu.export_all')}
<Shortcut key="S" ctrl={true} shift={true} />
</Menubar.Item>
</Menubar.Content>
</Menubar.Menu>
<Menubar.Menu>
<Menubar.Trigger aria-label={$_('menu.edit')}>
<Menubar.Trigger aria-label={i18n._('menu.edit')}>
<FilePen size="18" class="md:hidden" />
<span class="hidden md:block">{$_('menu.edit')}</span>
<span class="hidden md:block">{i18n._('menu.edit')}</span>
</Menubar.Trigger>
<Menubar.Content class="border-none">
<Menubar.Item on:click={dbUtils.undo} disabled={$undoDisabled}>
<Menubar.Item onclick={dbUtils.undo} disabled={$undoDisabled}>
<Undo2 size="16" class="mr-1" />
{$_('menu.undo')}
{i18n._('menu.undo')}
<Shortcut key="Z" ctrl={true} />
</Menubar.Item>
<Menubar.Item on:click={dbUtils.redo} disabled={$redoDisabled}>
<Menubar.Item onclick={dbUtils.redo} disabled={$redoDisabled}>
<Redo2 size="16" class="mr-1" />
{$_('menu.redo')}
{i18n._('menu.redo')}
<Shortcut key="Z" ctrl={true} shift={true} />
</Menubar.Item>
<Menubar.Separator />
@@ -219,10 +215,10 @@
item instanceof ListFileItem ||
item instanceof ListTrackItem
)}
on:click={() => ($editMetadata = true)}
onclick={() => (editMetadata.current = true)}
>
<Info size="16" class="mr-1" />
{$_('menu.metadata.button')}
{i18n._('menu.metadata.button')}
<Shortcut key="I" ctrl={true} />
</Menubar.Item>
<Menubar.Item
@@ -234,13 +230,13 @@
item instanceof ListFileItem ||
item instanceof ListTrackItem
)}
on:click={() => ($editStyle = true)}
onclick={() => (editStyle.current = true)}
>
<PaintBucket size="16" class="mr-1" />
{$_('menu.style.button')}
{i18n._('menu.style.button')}
</Menubar.Item>
<Menubar.Item
on:click={() => {
onclick={() => {
if ($allHidden) {
dbUtils.setHiddenToSelection(false);
} else {
@@ -251,67 +247,67 @@
>
{#if $allHidden}
<Eye size="16" class="mr-1" />
{$_('menu.unhide')}
{i18n._('menu.unhide')}
{:else}
<EyeOff size="16" class="mr-1" />
{$_('menu.hide')}
{i18n._('menu.hide')}
{/if}
<Shortcut key="H" ctrl={true} />
</Menubar.Item>
{#if $treeFileView}
{#if treeFileView.value}
{#if $selection.getSelected().some((item) => item instanceof ListFileItem)}
<Menubar.Separator />
<Menubar.Item
on:click={() =>
onclick={() =>
dbUtils.addNewTrack($selection.getSelected()[0].getFileId())}
disabled={$selection.size !== 1}
>
<Plus size="16" class="mr-1" />
{$_('menu.new_track')}
{i18n._('menu.new_track')}
</Menubar.Item>
{:else if $selection
.getSelected()
.some((item) => item instanceof ListTrackItem)}
<Menubar.Separator />
<Menubar.Item
on:click={() => {
onclick={() => {
let item = $selection.getSelected()[0];
dbUtils.addNewSegment(item.getFileId(), item.getTrackIndex());
}}
disabled={$selection.size !== 1}
>
<Plus size="16" class="mr-1" />
{$_('menu.new_segment')}
{i18n._('menu.new_segment')}
</Menubar.Item>
{/if}
{/if}
<Menubar.Separator />
<Menubar.Item on:click={selectAll} disabled={$fileObservers.size == 0}>
<Menubar.Item onclick={selectAll} disabled={$fileObservers.size == 0}>
<FileStack size="16" class="mr-1" />
{$_('menu.select_all')}
{i18n._('menu.select_all')}
<Shortcut key="A" ctrl={true} />
</Menubar.Item>
<Menubar.Item
on:click={() => {
onclick={() => {
if ($selection.size > 0) {
centerMapOnSelection();
}
}}
>
<Maximize size="16" class="mr-1" />
{$_('menu.center')}
{i18n._('menu.center')}
<Shortcut key="⏎" ctrl={true} />
</Menubar.Item>
{#if $treeFileView}
{#if treeFileView.value}
<Menubar.Separator />
<Menubar.Item on:click={copySelection} disabled={$selection.size === 0}>
<Menubar.Item onclick={copySelection} disabled={$selection.size === 0}>
<ClipboardCopy size="16" class="mr-1" />
{$_('menu.copy')}
{i18n._('menu.copy')}
<Shortcut key="C" ctrl={true} />
</Menubar.Item>
<Menubar.Item on:click={cutSelection} disabled={$selection.size === 0}>
<Menubar.Item onclick={cutSelection} disabled={$selection.size === 0}>
<Scissors size="16" class="mr-1" />
{$_('menu.cut')}
{i18n._('menu.cut')}
<Shortcut key="X" ctrl={true} />
</Menubar.Item>
<Menubar.Item
@@ -321,122 +317,119 @@
!allowedPastes[$copied[0].level].includes(
$selection.getSelected().pop()?.level
))}
on:click={pasteSelection}
onclick={pasteSelection}
>
<ClipboardPaste size="16" class="mr-1" />
{$_('menu.paste')}
{i18n._('menu.paste')}
<Shortcut key="V" ctrl={true} />
</Menubar.Item>
{/if}
<Menubar.Separator />
<Menubar.Item
on:click={dbUtils.deleteSelection}
disabled={$selection.size == 0}
>
<Menubar.Item onclick={dbUtils.deleteSelection} disabled={$selection.size == 0}>
<Trash2 size="16" class="mr-1" />
{$_('menu.delete')}
{i18n._('menu.delete')}
<Shortcut key="⌫" ctrl={true} />
</Menubar.Item>
</Menubar.Content>
</Menubar.Menu>
<Menubar.Menu>
<Menubar.Trigger aria-label={$_('menu.view')}>
<Menubar.Trigger aria-label={i18n._('menu.view')}>
<View size="18" class="md:hidden" />
<span class="hidden md:block">{$_('menu.view')}</span>
<span class="hidden md:block">{i18n._('menu.view')}</span>
</Menubar.Trigger>
<Menubar.Content class="border-none">
<Menubar.CheckboxItem bind:checked={$elevationProfile}>
<Menubar.CheckboxItem bind:checked={elevationProfile.value}>
<ChartArea size="16" class="mr-1" />
{$_('menu.elevation_profile')}
{i18n._('menu.elevation_profile')}
<Shortcut key="P" ctrl={true} />
</Menubar.CheckboxItem>
<Menubar.CheckboxItem bind:checked={$treeFileView}>
<Menubar.CheckboxItem bind:checked={treeFileView.value}>
<ListTree size="16" class="mr-1" />
{$_('menu.tree_file_view')}
{i18n._('menu.tree_file_view')}
<Shortcut key="L" ctrl={true} />
</Menubar.CheckboxItem>
<Menubar.Separator />
<Menubar.Item inset on:click={switchBasemaps}>
<Map size="16" class="mr-1" />{$_('menu.switch_basemap')}<Shortcut
<Menubar.Item inset onclick={switchBasemaps}>
<Map size="16" class="mr-1" />{i18n._('menu.switch_basemap')}<Shortcut
key="F1"
/>
</Menubar.Item>
<Menubar.Item inset on:click={toggleOverlays}>
<Layers2 size="16" class="mr-1" />{$_('menu.toggle_overlays')}<Shortcut
<Menubar.Item inset onclick={toggleOverlays}>
<Layers2 size="16" class="mr-1" />{i18n._('menu.toggle_overlays')}<Shortcut
key="F2"
/>
</Menubar.Item>
<Menubar.Separator />
<Menubar.CheckboxItem bind:checked={$distanceMarkers}>
<Coins size="16" class="mr-1" />{$_('menu.distance_markers')}<Shortcut
<Menubar.CheckboxItem bind:checked={distanceMarkers.value}>
<Coins size="16" class="mr-1" />{i18n._('menu.distance_markers')}<Shortcut
key="F3"
/>
</Menubar.CheckboxItem>
<Menubar.CheckboxItem bind:checked={$directionMarkers}>
<Milestone size="16" class="mr-1" />{$_('menu.direction_markers')}<Shortcut
key="F4"
/>
<Menubar.CheckboxItem bind:checked={directionMarkers.value}>
<Milestone size="16" class="mr-1" />{i18n._(
'menu.direction_markers'
)}<Shortcut key="F4" />
</Menubar.CheckboxItem>
<Menubar.Separator />
<Menubar.Item inset on:click={toggle3D}>
<Menubar.Item inset onclick={map.toggle3D}>
<Box size="16" class="mr-1" />
{$_('menu.toggle_3d')}
<Shortcut key="{$_('menu.ctrl')}+{$_('menu.drag')}" />
{i18n._('menu.toggle_3d')}
<Shortcut key="{i18n._('menu.ctrl')}+{i18n._('menu.drag')}" />
</Menubar.Item>
</Menubar.Content>
</Menubar.Menu>
<Menubar.Menu>
<Menubar.Trigger aria-label={$_('menu.settings')}>
<Menubar.Trigger aria-label={i18n._('menu.settings')}>
<Settings size="18" class="md:hidden" />
<span class="hidden md:block">
{$_('menu.settings')}
{i18n._('menu.settings')}
</span>
</Menubar.Trigger>
<Menubar.Content class="border-none">
<Menubar.Sub>
<Menubar.SubTrigger>
<Ruler size="16" class="mr-1" />{$_('menu.distance_units')}
<Ruler size="16" class="mr-1" />{i18n._('menu.distance_units')}
</Menubar.SubTrigger>
<Menubar.SubContent>
<Menubar.RadioGroup bind:value={$distanceUnits}>
<Menubar.RadioGroup bind:value={distanceUnits.value}>
<Menubar.RadioItem value="metric"
>{$_('menu.metric')}</Menubar.RadioItem
>{i18n._('menu.metric')}</Menubar.RadioItem
>
<Menubar.RadioItem value="imperial"
>{$_('menu.imperial')}</Menubar.RadioItem
>{i18n._('menu.imperial')}</Menubar.RadioItem
>
<Menubar.RadioItem value="nautical"
>{$_('menu.nautical')}</Menubar.RadioItem
>{i18n._('menu.nautical')}</Menubar.RadioItem
>
</Menubar.RadioGroup>
</Menubar.SubContent>
</Menubar.Sub>
<Menubar.Sub>
<Menubar.SubTrigger>
<Zap size="16" class="mr-1" />{$_('menu.velocity_units')}
<Zap size="16" class="mr-1" />{i18n._('menu.velocity_units')}
</Menubar.SubTrigger>
<Menubar.SubContent>
<Menubar.RadioGroup bind:value={$velocityUnits}>
<Menubar.RadioGroup bind:value={velocityUnits.value}>
<Menubar.RadioItem value="speed"
>{$_('quantities.speed')}</Menubar.RadioItem
>{i18n._('quantities.speed')}</Menubar.RadioItem
>
<Menubar.RadioItem value="pace"
>{$_('quantities.pace')}</Menubar.RadioItem
>{i18n._('quantities.pace')}</Menubar.RadioItem
>
</Menubar.RadioGroup>
</Menubar.SubContent>
</Menubar.Sub>
<Menubar.Sub>
<Menubar.SubTrigger>
<Thermometer size="16" class="mr-1" />{$_('menu.temperature_units')}
<Thermometer size="16" class="mr-1" />{i18n._('menu.temperature_units')}
</Menubar.SubTrigger>
<Menubar.SubContent>
<Menubar.RadioGroup bind:value={$temperatureUnits}>
<Menubar.RadioGroup bind:value={temperatureUnits.value}>
<Menubar.RadioItem value="celsius"
>{$_('menu.celsius')}</Menubar.RadioItem
>{i18n._('menu.celsius')}</Menubar.RadioItem
>
<Menubar.RadioItem value="fahrenheit"
>{$_('menu.fahrenheit')}</Menubar.RadioItem
>{i18n._('menu.fahrenheit')}</Menubar.RadioItem
>
</Menubar.RadioGroup>
</Menubar.SubContent>
@@ -445,10 +438,10 @@
<Menubar.Sub>
<Menubar.SubTrigger>
<Languages size="16" class="mr-1" />
{$_('menu.language')}
{i18n._('menu.language')}
</Menubar.SubTrigger>
<Menubar.SubContent>
<Menubar.RadioGroup value={$locale}>
<Menubar.RadioGroup value={i18n.lang}>
{#each Object.entries(languages) as [lang, label]}
<a href={getURLForLanguage(lang, '/app')}>
<Menubar.RadioItem value={lang}>{label}</Menubar.RadioItem>
@@ -464,19 +457,20 @@
{:else}
<Moon size="16" class="mr-1" />
{/if}
{$_('menu.mode')}
{i18n._('menu.mode')}
</Menubar.SubTrigger>
<Menubar.SubContent>
<Menubar.RadioGroup
value={mode.current ?? 'light'}
onValueChange={(value) => {
setMode(value);
setMode(value as 'light' | 'dark');
}}
>
<Menubar.RadioItem value="light"
>{$_('menu.light')}</Menubar.RadioItem
>{i18n._('menu.light')}</Menubar.RadioItem
>
<Menubar.RadioItem value="dark">{$_('menu.dark')}</Menubar.RadioItem
<Menubar.RadioItem value="dark"
>{i18n._('menu.dark')}</Menubar.RadioItem
>
</Menubar.RadioGroup>
</Menubar.SubContent>
@@ -485,22 +479,22 @@
<Menubar.Sub>
<Menubar.SubTrigger>
<PersonStanding size="16" class="mr-1" />
{$_('menu.street_view_source')}
{i18n._('menu.street_view_source')}
</Menubar.SubTrigger>
<Menubar.SubContent>
<Menubar.RadioGroup bind:value={$streetViewSource}>
<Menubar.RadioGroup bind:value={streetViewSource.value}>
<Menubar.RadioItem value="mapillary"
>{$_('menu.mapillary')}</Menubar.RadioItem
>{i18n._('menu.mapillary')}</Menubar.RadioItem
>
<Menubar.RadioItem value="google"
>{$_('menu.google')}</Menubar.RadioItem
>{i18n._('menu.google')}</Menubar.RadioItem
>
</Menubar.RadioGroup>
</Menubar.SubContent>
</Menubar.Sub>
<Menubar.Item on:click={() => (layerSettingsOpen = true)}>
<Menubar.Item onclick={() => (layerSettingsOpen = true)}>
<Layers size="16" class="mr-1" />
{$_('menu.layers')}
{i18n._('menu.layers')}
</Menubar.Item>
</Menubar.Content>
</Menubar.Menu>
@@ -511,11 +505,11 @@
href="./help"
target="_blank"
class="cursor-default h-fit rounded-sm px-3 py-0.5"
aria-label={$_('menu.help')}
aria-label={i18n._('menu.help')}
>
<BookOpenText size="18" class="md:hidden" />
<span class="hidden md:block">
{$_('menu.help')}
{i18n._('menu.help')}
</span>
</Button>
<Button
@@ -523,11 +517,11 @@
href="https://ko-fi.com/gpxstudio"
target="_blank"
class="cursor-default h-fit rounded-sm font-bold text-support hover:text-support px-3 py-0.5"
aria-label={$_('menu.donate')}
aria-label={i18n._('menu.donate')}
>
<HeartHandshake size="18" class="md:hidden" />
<span class="hidden md:flex flex-row items-center">
{$_('menu.donate')}
{i18n._('menu.donate')}
<Heart size="16" class="ml-1" fill="rgb(var(--support))" />
</span>
</Button>
@@ -536,7 +530,7 @@
</div>
<Export />
<LayerControlSettings bind:open={layerSettingsOpen} />
<!-- <LayerControlSettings bind:open={layerSettingsOpen} /> -->
<svelte:window
on:keydown={(e) => {
@@ -578,10 +572,10 @@
} else if ((e.key === 's' || e.key == 'S') && (e.metaKey || e.ctrlKey)) {
if (e.shiftKey) {
if ($fileObservers.size > 0) {
$exportState = ExportState.ALL;
exportState.current = ExportState.ALL;
}
} else if ($selection.size > 0) {
$exportState = ExportState.SELECTION;
exportState.current = ExportState.SELECTION;
}
e.preventDefault();
} else if ((e.key === 'z' || e.key == 'Z') && (e.metaKey || e.ctrlKey)) {
@@ -612,7 +606,7 @@
.getSelected()
.every((item) => item instanceof ListFileItem || item instanceof ListTrackItem)
) {
$editMetadata = true;
editMetadata.current = true;
}
e.preventDefault();
} else if (e.key === 'p' && (e.metaKey || e.ctrlKey)) {
@@ -669,6 +663,8 @@
/>
<style lang="postcss">
@reference "../../app.css";
div :global(button) {
@apply hover:bg-accent;
@apply px-3;

View File

@@ -1,19 +1,20 @@
<script lang="ts">
import { Button } from '$lib/components/ui/button';
import { Moon, Sun } from 'lucide-svelte';
import { Moon, Sun } from '@lucide/svelte';
import { mode, setMode } from 'mode-watcher';
import { _ } from '$lib/i18n';
import { i18n } from '$lib/i18n.svelte';
export let size = '20';
</script>
<Button
variant="ghost"
size="icon"
class="h-8 px-1.5 {$$props.class ?? ''}"
on:click={() => {
onclick={() => {
setMode(mode.current === 'light' ? 'dark' : 'light');
}}
aria-label={$_('menu.mode')}
aria-label={i18n._('menu.mode')}
>
{#if mode.current === 'light'}
<Sun {size} />

View File

@@ -3,28 +3,28 @@
import { Button } from '$lib/components/ui/button';
import AlgoliaDocSearch from '$lib/components/AlgoliaDocSearch.svelte';
import ModeSwitch from '$lib/components/ModeSwitch.svelte';
import { BookOpenText, Home, Map } from 'lucide-svelte';
import { _, locale } from '$lib/i18n';
import { BookOpenText, Home, Map } from '@lucide/svelte';
import { i18n } from '$lib/i18n.svelte';
import { getURLForLanguage } from '$lib/utils';
</script>
<nav class="w-full sticky top-0 bg-background z-50">
<div class="mx-6 py-2 flex flex-row items-center border-b gap-4 sm:gap-8">
<a href={getURLForLanguage($locale, '/')} class="shrink-0 translate-y-0.5">
<a href={getURLForLanguage(i18n.lang, '/')} class="shrink-0 translate-y-0.5">
<Logo class="h-8 sm:hidden" iconOnly={true} width="26" />
<Logo class="h-8 hidden sm:block" width="153" />
</a>
<Button variant="link" class="text-base px-0" href={getURLForLanguage($locale, '/')}>
<Home size="18" class="mr-1.5" />
{$_('homepage.home')}
<Button variant="link" class="text-base px-0" href={getURLForLanguage(i18n.lang, '/')}>
<Home size="18" />
{i18n._('homepage.home')}
</Button>
<Button variant="link" class="text-base px-0" href={getURLForLanguage($locale, '/app')}>
<Map size="18" class="mr-1.5" />
{$_('homepage.app')}
<Button variant="link" class="text-base px-0" href={getURLForLanguage(i18n.lang, '/app')}>
<Map size="18" />
{i18n._('homepage.app')}
</Button>
<Button variant="link" class="text-base px-0" href={getURLForLanguage($locale, '/help')}>
<BookOpenText size="18" class="mr-1.5" />
{$_('menu.help')}
<Button variant="link" class="text-base px-0" href={getURLForLanguage(i18n.lang, '/help')}>
<BookOpenText size="18" />
{i18n._('menu.help')}
</Button>
<AlgoliaDocSearch class="ml-auto" />
<ModeSwitch class="hidden xs:block" />

View File

@@ -1,9 +1,15 @@
<script lang="ts">
export let orientation: 'col' | 'row' = 'col';
export let after: number;
export let minAfter: number = 0;
export let maxAfter: number = Number.MAX_SAFE_INTEGER;
let {
orientation = 'col',
after = $bindable(),
minAfter = 0,
maxAfter = Number.MAX_SAFE_INTEGER,
}: {
orientation?: 'col' | 'row';
after: number;
minAfter?: number;
maxAfter?: number;
} = $props();
function handleMouseDown(event: PointerEvent) {
const startX = event.clientX;
@@ -33,10 +39,10 @@
}
</script>
<!-- svelte-ignore a11y-no-static-element-interactions -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="{orientation === 'col'
? 'w-1 h-full cursor-col-resize border-l'
: 'w-full h-1 cursor-row-resize border-t'} {orientation}"
on:pointerdown={handleMouseDown}
onpointerdown={handleMouseDown}
></div>

View File

@@ -1,7 +1,7 @@
<script lang="ts">
import { isMac, isSafari } from '$lib/utils';
import { onMount } from 'svelte';
import { _ } from '$lib/i18n';
import { i18n } from '$lib/i18n.svelte';
export let key: string | undefined = undefined;
export let shift: boolean = false;
@@ -25,12 +25,12 @@
<span></span>
{/if}
{#if ctrl}
<span>{mac && !safari ? '⌘' : $_('menu.ctrl') + '+'}</span>
<span>{mac && !safari ? '⌘' : i18n._('menu.ctrl') + '+'}</span>
{/if}
{#if key}
<span class={key === '+' ? 'font-medium text-sm/4' : ''}>{key}</span>
{/if}
{#if click}
<span>{$_('menu.click')}</span>
<span>{i18n._('menu.click')}</span>
{/if}
</div>

View File

@@ -5,6 +5,7 @@
export let side: 'top' | 'right' | 'bottom' | 'left' = 'top';
</script>
<Tooltip.Provider>
<Tooltip.Root>
<Tooltip.Trigger {...$$restProps} aria-label={label}>
<slot />
@@ -16,3 +17,4 @@
</div>
</Tooltip.Content>
</Tooltip.Root>
</Tooltip.Provider>

View File

@@ -10,18 +10,26 @@
getVelocityUnits,
secondsToHHMMSS,
} from '$lib/units';
import { i18n } from '$lib/i18n.svelte';
import { _ } from '$lib/i18n';
export let value: number;
export let type: 'distance' | 'elevation' | 'speed' | 'temperature' | 'time';
export let showUnits: boolean = true;
export let decimals: number | undefined = undefined;
let {
value,
type,
showUnits = true,
decimals = undefined,
class: className = '',
}: {
value: number;
type: 'distance' | 'elevation' | 'speed' | 'temperature' | 'time';
showUnits?: boolean;
decimals?: number;
class?: string;
} = $props();
const { distanceUnits, velocityUnits, temperatureUnits } = settings;
</script>
<span class={$$props.class}>
<span class={className}>
{#if type === 'distance'}
{getConvertedDistance(value, $distanceUnits).toFixed(decimals ?? 2)}
{showUnits ? getDistanceUnits($distanceUnits) : ''}
@@ -38,9 +46,9 @@
{/if}
{:else if type === 'temperature'}
{#if $temperatureUnits === 'celsius'}
{value} {showUnits ? $_('units.celsius') : ''}
{value} {showUnits ? i18n._('units.celsius') : ''}
{:else}
{celsiusToFahrenheit(value)} {showUnits ? $_('units.fahrenheit') : ''}
{celsiusToFahrenheit(value)} {showUnits ? i18n._('units.fahrenheit') : ''}
{/if}
{:else if type === 'time'}
{secondsToHHMMSS(value)}

View File

@@ -1,15 +1,23 @@
<script lang="ts">
import { setContext } from 'svelte';
import { writable } from 'svelte/store';
import { setContext, type Snippet } from 'svelte';
import { CollapsibleTreeState } from './utils.svelte';
export let defaultState: 'open' | 'closed' = 'open';
export let side: 'left' | 'right' = 'right';
export let nohover: boolean = false;
export let slotInsideTrigger: boolean = true;
const {
defaultState = 'open',
side = 'right',
nohover = false,
slotInsideTrigger = true,
children,
}: {
defaultState?: 'open' | 'closed';
side?: 'left' | 'right';
nohover?: boolean;
slotInsideTrigger?: boolean;
children: Snippet;
} = $props();
let open = writable<Record<string, boolean>>({});
let open = $state(new CollapsibleTreeState(defaultState));
setContext('collapsible-tree-default-state', defaultState);
setContext('collapsible-tree-state', open);
setContext('collapsible-tree-side', side);
setContext('collapsible-tree-nohover', nohover);
@@ -17,4 +25,4 @@
setContext('collapsible-tree-slot-inside-trigger', slotInsideTrigger);
</script>
<slot />
{@render children()}

View File

@@ -1,40 +1,35 @@
<script lang="ts">
import * as Collapsible from '$lib/components/ui/collapsible';
import { Button } from '$lib/components/ui/button';
import { ChevronDown, ChevronLeft, ChevronRight } from 'lucide-svelte';
import { getContext, onMount, setContext } from 'svelte';
import { get, type Writable } from 'svelte/store';
import { ChevronDown, ChevronLeft, ChevronRight } from '@lucide/svelte';
import { getContext, setContext, type Snippet } from 'svelte';
import type { ClassValue } from 'svelte/elements';
import type { CollapsibleTreeState } from './utils.svelte';
export let id: string | number;
const props: {
id: string | number;
class?: ClassValue;
trigger: Snippet;
content: Snippet;
} = $props();
let defaultState = getContext<'open' | 'closed'>('collapsible-tree-default-state');
let open = getContext<Writable<Record<string, boolean>>>('collapsible-tree-state');
let state = getContext<CollapsibleTreeState>('collapsible-tree-state');
let side = getContext<'left' | 'right'>('collapsible-tree-side');
let nohover = getContext<boolean>('collapsible-tree-nohover');
let slotInsideTrigger = getContext<boolean>('collapsible-tree-slot-inside-trigger');
let parentId = getContext<string>('collapsible-tree-parent-id');
let fullId = `${parentId}.${id}`;
let fullId = `${parentId}.${props.id}`;
setContext('collapsible-tree-parent-id', fullId);
onMount(() => {
if (!get(open).hasOwnProperty(fullId)) {
open.update((value) => {
value[fullId] = defaultState === 'open';
return value;
});
}
});
let open = state.get(fullId);
export function openNode() {
open.update((value) => {
value[fullId] = true;
return value;
});
open.current = true;
}
</script>
<Collapsible.Root bind:open={$open[fullId]} class={$$props.class ?? ''}>
<Collapsible.Root bind:open={open.current} class={props.class}>
{#if slotInsideTrigger}
<Collapsible.Trigger class="w-full">
<Button
@@ -46,15 +41,15 @@
: ''} pointer-events-none"
>
{#if side === 'left'}
{#if $open[fullId]}
{#if open.current}
<ChevronDown size="16" class="shrink-0" />
{:else}
<ChevronRight size="16" class="shrink-0" />
{/if}
{/if}
<slot name="trigger" />
{@render props.trigger()}
{#if side === 'right'}
{#if $open[fullId]}
{#if open.current}
<ChevronDown size="16" class="shrink-0" />
{:else}
<ChevronLeft size="16" class="shrink-0" />
@@ -71,17 +66,17 @@
>
{#if side === 'left'}
<Collapsible.Trigger>
{#if $open[fullId]}
{#if open.current}
<ChevronDown size="16" class="shrink-0" />
{:else}
<ChevronRight size="16" class="shrink-0" />
{/if}
</Collapsible.Trigger>
{/if}
<slot name="trigger" />
{@render props.trigger()}
{#if side === 'right'}
<Collapsible.Trigger>
{#if $open[fullId]}
{#if open.current}
<ChevronDown size="16" class="shrink-0" />
{:else}
<ChevronLeft size="16" class="shrink-0" />
@@ -92,6 +87,6 @@
{/if}
<Collapsible.Content class="ml-2">
<slot name="content" />
{@render props.content()}
</Collapsible.Content>
</Collapsible.Root>

View File

@@ -0,0 +1,31 @@
export class CollapsibleNodeState {
private _open: boolean;
constructor(defaultState: 'open' | 'closed') {
this._open = $state(defaultState === 'open');
}
get current(): boolean {
return this._open;
}
set current(value: boolean) {
this._open = value;
}
}
export class CollapsibleTreeState {
private _open: Record<string, CollapsibleNodeState> = {};
private _defaultState: 'open' | 'closed';
constructor(defaultState: 'open' | 'closed') {
this._defaultState = defaultState;
}
get(id: string): CollapsibleNodeState {
if (this._open[id] === undefined) {
this._open[id] = new CollapsibleNodeState(this._defaultState);
}
return this._open[id];
}
}

View File

@@ -1,27 +0,0 @@
<script lang="ts">
import CustomControl from './CustomControl';
import { map } from '$lib/stores';
export let position: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' = 'top-right';
let container: HTMLDivElement;
let control: CustomControl | undefined = undefined;
$: if ($map && container) {
if (position.includes('right')) container.classList.add('float-right');
else container.classList.add('float-left');
container.classList.remove('hidden');
if (control === undefined) {
control = new CustomControl(container);
}
$map.addControl(control, position);
}
</script>
<div
bind:this={container}
class="{$$props.class ||
''} clear-both translate-0 m-[10px] mb-0 last:mb-[10px] pointer-events-auto bg-background rounded shadow-md hidden"
>
<slot />
</div>

View File

@@ -1,12 +1,16 @@
<script lang="ts">
export let module;
import type { Component } from 'svelte';
let { module: Module }: { module: Component } = $props();
</script>
<div class="markdown flex flex-col gap-3">
<svelte:component this={module} />
<Module />
</div>
<style lang="postcss">
@reference "../../../app.css";
:global(.markdown) {
@apply text-muted-foreground;
}

View File

@@ -1,6 +1,11 @@
<script lang="ts">
export let src: 'getting-started/interface' | 'tools/routing' | 'tools/split';
export let alt: string;
let {
src,
alt,
}: {
src: 'getting-started/interface' | 'tools/routing' | 'tools/split';
alt: string;
} = $props();
</script>
<div class="flex flex-col items-center py-6 w-full">

View File

@@ -1,5 +1,7 @@
<script lang="ts">
export let type: 'note' | 'warning' = 'note';
import type { Snippet } from 'svelte';
let { type = 'note', children }: { type?: 'note' | 'warning'; children: Snippet } = $props();
</script>
<div
@@ -7,10 +9,12 @@
? 'border-link'
: 'border-destructive'} p-2 text-sm rounded-md"
>
<slot />
{@render children()}
</div>
<style lang="postcss">
@reference "../../../app.css";
div :global(a) {
@apply text-link;
@apply hover:underline;

View File

@@ -2,7 +2,6 @@ import {
File,
FilePen,
View,
type Icon,
Settings,
Pencil,
MapPin,
@@ -10,11 +9,12 @@ import {
CalendarClock,
Group,
Ungroup,
Filter,
Funnel,
SquareDashedMousePointer,
MountainSnow,
} from 'lucide-svelte';
import type { ComponentType } from 'svelte';
type IconProps,
} from '@lucide/svelte';
import type { Component } from 'svelte';
export const guides: Record<string, string[]> = {
'getting-started': [],
@@ -37,7 +37,7 @@ export const guides: Record<string, string[]> = {
faq: [],
};
export const guideIcons: Record<string, string | ComponentType<Icon>> = {
export const guideIcons: Record<string, string | Component<IconProps>> = {
'getting-started': '🚀',
menu: '📂 ⚙️',
file: File,
@@ -53,7 +53,7 @@ export const guideIcons: Record<string, string | ComponentType<Icon>> = {
merge: Group,
extract: Ungroup,
elevation: MountainSnow,
minify: Filter,
minify: Funnel,
clean: SquareDashedMousePointer,
'map-controls': '🗺',
gpx: '💾',

View File

@@ -1,17 +1,17 @@
<script lang="ts">
import GPXLayers from '$lib/components/gpx-layer/GPXLayers.svelte';
import GPXLayers from '$lib/components/map/gpx-layer/GPXLayers.svelte';
import ElevationProfile from '$lib/components/ElevationProfile.svelte';
import FileList from '$lib/components/file-list/FileList.svelte';
import GPXStatistics from '$lib/components/GPXStatistics.svelte';
import Map from '$lib/components/Map.svelte';
import LayerControl from '$lib/components/layer-control/LayerControl.svelte';
import Map from '$lib/components/map/Map.svelte';
import { map } from '$lib/components/map/map.svelte';
import LayerControl from '$lib/components/map/layer-control/LayerControl.svelte';
import OpenIn from '$lib/components/embedding/OpenIn.svelte';
import {
gpxStatistics,
slicedGPXStatistics,
embedding,
loadFile,
map,
updateGPXData,
} from '$lib/stores';
import { onDestroy, onMount } from 'svelte';

View File

@@ -14,8 +14,8 @@
Coins,
Milestone,
Video,
} from 'lucide-svelte';
import { _ } from '$lib/i18n';
} from '@lucide/svelte';
import { i18n } from '$lib/i18n.svelte';
import {
allowedEmbeddingBasemaps,
getCleanedEmbeddingOptions,
@@ -94,19 +94,22 @@
<Card.Root id="embedding-playground">
<Card.Header>
<Card.Title>{$_('embedding.title')}</Card.Title>
<Card.Title>{i18n._('embedding.title')}</Card.Title>
</Card.Header>
<Card.Content>
<fieldset class="flex flex-col gap-3">
<Label for="token">{$_('embedding.mapbox_token')}</Label>
<Label for="token">{i18n._('embedding.mapbox_token')}</Label>
<Input id="token" type="text" class="h-8" bind:value={options.token} />
<Label for="file_urls">{$_('embedding.file_urls')}</Label>
<Label for="file_urls">{i18n._('embedding.file_urls')}</Label>
<Input id="file_urls" type="text" class="h-8" bind:value={files} />
<Label for="drive_ids">{$_('embedding.drive_ids')}</Label>
<Label for="drive_ids">{i18n._('embedding.drive_ids')}</Label>
<Input id="drive_ids" type="text" class="h-8" bind:value={driveIds} />
<Label for="basemap">{$_('embedding.basemap')}</Label>
<Label for="basemap">{i18n._('embedding.basemap')}</Label>
<Select.Root
selected={{ value: options.basemap, label: $_(`layers.label.${options.basemap}`) }}
selected={{
value: options.basemap,
label: i18n._(`layers.label.${options.basemap}`),
}}
onSelectedChange={(selected) => {
if (selected?.value) {
options.basemap = selected?.value;
@@ -118,18 +121,20 @@
</Select.Trigger>
<Select.Content class="max-h-60 overflow-y-scroll">
{#each allowedEmbeddingBasemaps as basemap}
<Select.Item value={basemap}>{$_(`layers.label.${basemap}`)}</Select.Item>
<Select.Item value={basemap}
>{i18n._(`layers.label.${basemap}`)}</Select.Item
>
{/each}
</Select.Content>
</Select.Root>
<div class="flex flex-row items-center gap-2">
<Label for="profile">{$_('menu.elevation_profile')}</Label>
<Label for="profile">{i18n._('menu.elevation_profile')}</Label>
<Checkbox id="profile" bind:checked={options.elevation.show} />
</div>
{#if options.elevation.show}
<div class="grid grid-cols-2 gap-x-6 gap-y-3 rounded-md border p-3 mt-1">
<Label class="flex flex-row items-center gap-2">
{$_('embedding.height')}
{i18n._('embedding.height')}
<Input
type="number"
bind:value={options.elevation.height}
@@ -138,10 +143,10 @@
</Label>
<div class="flex flex-row items-center gap-2">
<span class="shrink-0">
{$_('embedding.fill_by')}
{i18n._('embedding.fill_by')}
</span>
<Select.Root
selected={{ value: 'none', label: $_('embedding.none') }}
selected={{ value: 'none', label: i18n._('embedding.none') }}
onSelectedChange={(selected) => {
let value = selected?.value;
if (value === 'none') {
@@ -159,52 +164,55 @@
<Select.Value />
</Select.Trigger>
<Select.Content>
<Select.Item value="slope">{$_('quantities.slope')}</Select.Item>
<Select.Item value="surface">{$_('quantities.surface')}</Select.Item
<Select.Item value="slope">{i18n._('quantities.slope')}</Select.Item
>
<Select.Item value="highway">{$_('quantities.highway')}</Select.Item
<Select.Item value="surface"
>{i18n._('quantities.surface')}</Select.Item
>
<Select.Item value="none">{$_('embedding.none')}</Select.Item>
<Select.Item value="highway"
>{i18n._('quantities.highway')}</Select.Item
>
<Select.Item value="none">{i18n._('embedding.none')}</Select.Item>
</Select.Content>
</Select.Root>
</div>
<div class="flex flex-row items-center gap-2">
<Checkbox id="controls" bind:checked={options.elevation.controls} />
<Label for="controls">{$_('embedding.show_controls')}</Label>
<Label for="controls">{i18n._('embedding.show_controls')}</Label>
</div>
<div class="flex flex-row items-center gap-2">
<Checkbox id="show-speed" bind:checked={options.elevation.speed} />
<Label for="show-speed" class="flex flex-row items-center gap-1">
<Zap size="16" />
{$_('quantities.speed')}
{i18n._('quantities.speed')}
</Label>
</div>
<div class="flex flex-row items-center gap-2">
<Checkbox id="show-hr" bind:checked={options.elevation.hr} />
<Label for="show-hr" class="flex flex-row items-center gap-1">
<HeartPulse size="16" />
{$_('quantities.heartrate')}
{i18n._('quantities.heartrate')}
</Label>
</div>
<div class="flex flex-row items-center gap-2">
<Checkbox id="show-cad" bind:checked={options.elevation.cad} />
<Label for="show-cad" class="flex flex-row items-center gap-1">
<Orbit size="16" />
{$_('quantities.cadence')}
{i18n._('quantities.cadence')}
</Label>
</div>
<div class="flex flex-row items-center gap-2">
<Checkbox id="show-temp" bind:checked={options.elevation.temp} />
<Label for="show-temp" class="flex flex-row items-center gap-1">
<Thermometer size="16" />
{$_('quantities.temperature')}
{i18n._('quantities.temperature')}
</Label>
</div>
<div class="flex flex-row items-center gap-2">
<Checkbox id="show-power" bind:checked={options.elevation.power} />
<Label for="show-power" class="flex flex-row items-center gap-1">
<SquareActivity size="16" />
{$_('quantities.power')}
{i18n._('quantities.power')}
</Label>
</div>
</div>
@@ -213,75 +221,75 @@
<Checkbox id="distance-markers" bind:checked={options.distanceMarkers} />
<Label for="distance-markers" class="flex flex-row items-center gap-1">
<Coins size="16" />
{$_('menu.distance_markers')}
{i18n._('menu.distance_markers')}
</Label>
</div>
<div class="flex flex-row items-center gap-2">
<Checkbox id="direction-markers" bind:checked={options.directionMarkers} />
<Label for="direction-markers" class="flex flex-row items-center gap-1">
<Milestone size="16" />
{$_('menu.direction_markers')}
{i18n._('menu.direction_markers')}
</Label>
</div>
<div class="flex flex-row flex-wrap justify-between gap-3">
<Label class="flex flex-col items-start gap-2">
{$_('menu.distance_units')}
{i18n._('menu.distance_units')}
<RadioGroup.Root bind:value={options.distanceUnits}>
<div class="flex items-center space-x-2">
<RadioGroup.Item value="metric" id="metric" />
<Label for="metric">{$_('menu.metric')}</Label>
<Label for="metric">{i18n._('menu.metric')}</Label>
</div>
<div class="flex items-center space-x-2">
<RadioGroup.Item value="imperial" id="imperial" />
<Label for="imperial">{$_('menu.imperial')}</Label>
<Label for="imperial">{i18n._('menu.imperial')}</Label>
</div>
<div class="flex items-center space-x-2">
<RadioGroup.Item value="nautical" id="nautical" />
<Label for="nautical">{$_('menu.nautical')}</Label>
<Label for="nautical">{i18n._('menu.nautical')}</Label>
</div>
</RadioGroup.Root>
</Label>
<Label class="flex flex-col items-start gap-2">
{$_('menu.velocity_units')}
{i18n._('menu.velocity_units')}
<RadioGroup.Root bind:value={options.velocityUnits}>
<div class="flex items-center space-x-2">
<RadioGroup.Item value="speed" id="speed" />
<Label for="speed">{$_('quantities.speed')}</Label>
<Label for="speed">{i18n._('quantities.speed')}</Label>
</div>
<div class="flex items-center space-x-2">
<RadioGroup.Item value="pace" id="pace" />
<Label for="pace">{$_('quantities.pace')}</Label>
<Label for="pace">{i18n._('quantities.pace')}</Label>
</div>
</RadioGroup.Root>
</Label>
<Label class="flex flex-col items-start gap-2">
{$_('menu.temperature_units')}
{i18n._('menu.temperature_units')}
<RadioGroup.Root bind:value={options.temperatureUnits}>
<div class="flex items-center space-x-2">
<RadioGroup.Item value="celsius" id="celsius" />
<Label for="celsius">{$_('menu.celsius')}</Label>
<Label for="celsius">{i18n._('menu.celsius')}</Label>
</div>
<div class="flex items-center space-x-2">
<RadioGroup.Item value="fahrenheit" id="fahrenheit" />
<Label for="fahrenheit">{$_('menu.fahrenheit')}</Label>
<Label for="fahrenheit">{i18n._('menu.fahrenheit')}</Label>
</div>
</RadioGroup.Root>
</Label>
</div>
<Label class="flex flex-col items-start gap-2">
{$_('menu.mode')}
{i18n._('menu.mode')}
<RadioGroup.Root bind:value={options.theme} class="flex flex-row">
<div class="flex items-center space-x-2">
<RadioGroup.Item value="system" id="system" />
<Label for="system">{$_('menu.system')}</Label>
<Label for="system">{i18n._('menu.system')}</Label>
</div>
<div class="flex items-center space-x-2">
<RadioGroup.Item value="light" id="light" />
<Label for="light">{$_('menu.light')}</Label>
<Label for="light">{i18n._('menu.light')}</Label>
</div>
<div class="flex items-center space-x-2">
<RadioGroup.Item value="dark" id="dark" />
<Label for="dark">{$_('menu.dark')}</Label>
<Label for="dark">{i18n._('menu.dark')}</Label>
</div>
</RadioGroup.Root>
</Label>
@@ -290,43 +298,43 @@
<Checkbox id="manual-camera" bind:checked={manualCamera} />
<Label for="manual-camera" class="flex flex-row items-center gap-1">
<Video size="16" />
{$_('embedding.manual_camera')}
{i18n._('embedding.manual_camera')}
</Label>
</div>
<p class="text-sm text-muted-foreground">
{$_('embedding.manual_camera_description')}
{i18n._('embedding.manual_camera_description')}
</p>
<div class="flex flex-row flex-wrap items-center gap-6">
<Label class="flex flex-col gap-1">
<span>{$_('embedding.latitude')}</span>
<span>{i18n._('embedding.latitude')}</span>
<span>{lat}</span>
</Label>
<Label class="flex flex-col gap-1">
<span>{$_('embedding.longitude')}</span>
<span>{i18n._('embedding.longitude')}</span>
<span>{lon}</span>
</Label>
<Label class="flex flex-col gap-1">
<span>{$_('embedding.zoom')}</span>
<span>{i18n._('embedding.zoom')}</span>
<span>{zoom}</span>
</Label>
<Label class="flex flex-col gap-1">
<span>{$_('embedding.bearing')}</span>
<span>{i18n._('embedding.bearing')}</span>
<span>{bearing}</span>
</Label>
<Label class="flex flex-col gap-1">
<span>{$_('embedding.pitch')}</span>
<span>{i18n._('embedding.pitch')}</span>
<span>{pitch}</span>
</Label>
</div>
</div>
<Label>
{$_('embedding.preview')}
{i18n._('embedding.preview')}
</Label>
<div class="relative h-[600px]">
<Embedding bind:options={iframeOptions} bind:hash useHash={false} />
</div>
<Label>
{$_('embedding.code')}
{i18n._('embedding.code')}
</Label>
<pre
class="bg-primary text-primary-foreground p-3 rounded-md whitespace-normal break-all">

View File

@@ -2,22 +2,27 @@
import { Button } from '$lib/components/ui/button';
import Logo from '$lib/components/Logo.svelte';
import { getURLForLanguage } from '$lib/utils';
import { _, locale } from '$lib/i18n';
import { i18n } from '$lib/i18n.svelte';
export let files: string[];
export let ids: string[];
let {
files,
ids,
}: {
files: string[];
ids: string[];
} = $props();
</script>
<Button
variant="ghost"
class="absolute top-0 flex-wrap h-fit bg-background font-semibold rounded-md py-1 px-2 gap-1.5 xs:text-base mt-2.5 ml-2.5 mr-12"
href="{getURLForLanguage($locale, '/app')}?{files.length > 0
href="{getURLForLanguage(i18n.lang, '/app')}?{files.length > 0
? `files=${encodeURIComponent(JSON.stringify(files))}`
: ''}{files.length > 0 && ids.length > 0 ? '&' : ''}{ids.length > 0
? `ids=${encodeURIComponent(JSON.stringify(ids))}`
: ''}"
target="_blank"
>
{$_('menu.open_in')}
{i18n._('menu.open_in')}
<Logo class="h-[18px] xs:h-5 translate-y-[1px]" />
</Button>

View File

@@ -5,13 +5,13 @@
import { Separator } from '$lib/components/ui/separator';
import { Dialog } from 'bits-ui';
import {
currentTool,
exportAllFiles,
exportSelectedFiles,
ExportState,
exportState,
gpxStatistics,
} from '$lib/stores';
} from '$lib/components/export/utils.svelte';
import { tool } from '$lib/components/toolbar/utils.svelte';
import { gpxStatistics } from '$lib/stores';
import { fileObservers } from '$lib/db';
import {
Download,
@@ -21,23 +21,25 @@
Orbit,
Thermometer,
SquareActivity,
} from 'lucide-svelte';
import { _ } from '$lib/i18n';
import { selection } from './file-list/Selection';
} from '@lucide/svelte';
import { i18n } from '$lib/i18n.svelte';
import { selection } from '$lib/components/file-list/Selection';
import { get } from 'svelte/store';
import { GPXStatistics } from 'gpx';
import { ListRootItem } from './file-list/FileList';
import { ListRootItem } from '$lib/components/file-list/FileList';
let open = false;
let exportOptions: Record<string, boolean> = {
let open = $derived(exportState.current !== ExportState.NONE);
let exportOptions: Record<string, boolean> = $state({
time: true,
hr: true,
cad: true,
atemp: true,
power: true,
extensions: true,
};
let hide: Record<string, boolean> = {
extensions: false,
});
let hide: Record<string, boolean> = $derived.by(() => {
if (exportState.current === ExportState.NONE) {
return {
time: false,
hr: false,
cad: false,
@@ -45,13 +47,9 @@
power: false,
extensions: false,
};
$: if ($exportState !== ExportState.NONE) {
open = true;
$currentTool = null;
} else {
let statistics = $gpxStatistics;
if ($exportState === ExportState.ALL) {
if (exportState.current === ExportState.ALL) {
statistics = Array.from($fileObservers.values())
.map((file) => get(file)?.statistics)
.reduce((acc, cur) => {
@@ -61,23 +59,30 @@
return acc;
}, new GPXStatistics());
}
hide.time = statistics.global.time.total === 0;
hide.hr = statistics.global.hr.count === 0;
hide.cad = statistics.global.cad.count === 0;
hide.atemp = statistics.global.atemp.count === 0;
hide.power = statistics.global.power.count === 0;
hide.extensions = Object.keys(statistics.global.extensions).length === 0;
return {
time: statistics.global.time.total === 0,
hr: statistics.global.hr.count === 0,
cad: statistics.global.cad.count === 0,
atemp: statistics.global.atemp.count === 0,
power: statistics.global.power.count === 0,
extensions: Object.keys(statistics.global.extensions).length === 0,
};
}
});
let exclude = $derived(Object.keys(exportOptions).filter((key) => !exportOptions[key]));
$: exclude = Object.keys(exportOptions).filter((key) => !exportOptions[key]);
$effect(() => {
if (open) {
tool.current = null;
}
});
</script>
<Dialog.Root
bind:open
onOpenChange={(isOpen) => {
if (!isOpen) {
$exportState = ExportState.NONE;
exportState.current = ExportState.NONE;
}
}}
>
@@ -91,32 +96,32 @@
>
<span>⚠️</span>
<span class="max-w-[80%] text-sm">
{$_('menu.support_message')}
{i18n._('menu.support_message')}
</span>
</div>
<div class="w-full flex flex-row flex-wrap gap-2">
<Button class="bg-support grow" href="https://ko-fi.com/gpxstudio" target="_blank">
{$_('menu.support_button')}
{i18n._('menu.support_button')}
<span class="ml-2">🙏</span>
</Button>
<Button
variant="outline"
class="grow"
on:click={() => {
if ($exportState === ExportState.SELECTION) {
onclick={() => {
if (exportState.current === ExportState.SELECTION) {
exportSelectedFiles(exclude);
} else if ($exportState === ExportState.ALL) {
} else if (exportState.current === ExportState.ALL) {
exportAllFiles(exclude);
}
open = false;
$exportState = ExportState.NONE;
exportState.current = ExportState.NONE;
}}
>
<Download size="16" class="mr-1" />
{#if $fileObservers.size === 1 || ($exportState === ExportState.SELECTION && $selection.size === 1)}
{$_('menu.download_file')}
{#if $fileObservers.size === 1 || (exportState.current === ExportState.SELECTION && $selection.size === 1)}
{i18n._('menu.download_file')}
{:else}
{$_('menu.download_files')}
{i18n._('menu.download_files')}
{/if}
</Button>
</div>
@@ -132,7 +137,7 @@
<Separator />
</div>
<Label class="shrink-0">
{$_('menu.export_options')}
{i18n._('menu.export_options')}
</Label>
<div class="grow">
<Separator />
@@ -143,7 +148,7 @@
<Checkbox id="export-time" bind:checked={exportOptions.time} />
<Label for="export-time" class="flex flex-row items-center gap-1">
<Zap size="16" />
{$_('quantities.time')}
{i18n._('quantities.time')}
</Label>
</div>
<div
@@ -152,35 +157,35 @@
<Checkbox id="export-extensions" bind:checked={exportOptions.extensions} />
<Label for="export-extensions" class="flex flex-row items-center gap-1">
<Earth size="16" />
{$_('quantities.osm_extensions')}
{i18n._('quantities.osm_extensions')}
</Label>
</div>
<div class="flex flex-row items-center gap-1.5 {hide.hr ? 'hidden' : ''}">
<Checkbox id="export-heartrate" bind:checked={exportOptions.hr} />
<Label for="export-heartrate" class="flex flex-row items-center gap-1">
<HeartPulse size="16" />
{$_('quantities.heartrate')}
{i18n._('quantities.heartrate')}
</Label>
</div>
<div class="flex flex-row items-center gap-1.5 {hide.cad ? 'hidden' : ''}">
<Checkbox id="export-cadence" bind:checked={exportOptions.cad} />
<Label for="export-cadence" class="flex flex-row items-center gap-1">
<Orbit size="16" />
{$_('quantities.cadence')}
{i18n._('quantities.cadence')}
</Label>
</div>
<div class="flex flex-row items-center gap-1.5 {hide.atemp ? 'hidden' : ''}">
<Checkbox id="export-temperature" bind:checked={exportOptions.atemp} />
<Label for="export-temperature" class="flex flex-row items-center gap-1">
<Thermometer size="16" />
{$_('quantities.temperature')}
{i18n._('quantities.temperature')}
</Label>
</div>
<div class="flex flex-row items-center gap-1.5 {hide.power ? 'hidden' : ''}">
<Checkbox id="export-power" bind:checked={exportOptions.power} />
<Label for="export-power" class="flex flex-row items-center gap-1">
<SquareActivity size="16" />
{$_('quantities.power')}
{i18n._('quantities.power')}
</Label>
</div>
</div>

View File

@@ -0,0 +1,67 @@
import { getFile, settings } from '$lib/db';
import { applyToOrderedSelectedItemsFromFile } from '$lib/components/file-list/Selection';
import { get } from 'svelte/store';
import { buildGPX, type GPXFile } from 'gpx';
import FileSaver from 'file-saver';
import JSZip from 'jszip';
const { fileOrder } = settings;
export enum ExportState {
NONE,
SELECTION,
ALL,
}
export const exportState = $state({
current: ExportState.NONE,
});
async function exportFiles(fileIds: string[], exclude: string[]) {
if (fileIds.length > 1) {
await exportFilesAsZip(fileIds, exclude);
} else {
const firstFileId = fileIds.at(0);
if (firstFileId != null) {
const file = getFile(firstFileId);
if (file) {
exportFile(file, exclude);
}
}
}
}
export async function exportSelectedFiles(exclude: string[]) {
const fileIds: string[] = [];
applyToOrderedSelectedItemsFromFile(async (fileId, level, items) => {
fileIds.push(fileId);
});
await exportFiles(fileIds, exclude);
}
export async function exportAllFiles(exclude: string[]) {
await exportFiles(get(fileOrder), exclude);
}
function exportFile(file: GPXFile, exclude: string[]) {
const blob = new Blob([buildGPX(file, exclude)], { type: 'application/gpx+xml' });
FileSaver.saveAs(blob, `${file.metadata.name}.gpx`);
}
async function exportFilesAsZip(fileIds: string[], exclude: string[]) {
const zip = new JSZip();
for (const fileId of fileIds) {
const file = getFile(fileId);
if (file) {
const gpx = buildGPX(file, exclude);
let filename = file.metadata.name;
for (let i = 1; zip.files[filename + '.gpx']; i++) {
filename = file.metadata.name + `-${i}`;
}
zip.file(filename + '.gpx', gpx);
}
}
if (Object.keys(zip.files).length > 0) {
const blob = await zip.generateAsync({ type: 'blob' });
FileSaver.saveAs(blob, 'gpx-files.zip');
}
}

View File

@@ -6,13 +6,22 @@
import { setContext } from 'svelte';
import { ListFileItem, ListLevel, ListRootItem, allowedPastes } from './FileList';
import { copied, pasteSelection, selectAll, selection } from './Selection';
import { ClipboardPaste, FileStack, Plus } from 'lucide-svelte';
import { ClipboardPaste, FileStack, Plus } from '@lucide/svelte';
import Shortcut from '$lib/components/Shortcut.svelte';
import { _ } from '$lib/i18n';
import { i18n } from '$lib/i18n.svelte';
import { createFile } from '$lib/stores';
export let orientation: 'vertical' | 'horizontal';
export let recursive = false;
let {
orientation,
recursive = false,
class: className = '',
style = '',
}: {
orientation: 'vertical' | 'horizontal';
recursive?: boolean;
class?: string;
style?: string;
} = $props();
setContext('orientation', orientation);
setContext('recursive', recursive);
@@ -52,23 +61,23 @@
<div
class="flex {orientation === 'vertical'
? 'flex-col py-1 pl-1 min-h-screen'
: 'flex-row'} {$$props.class ?? ''}"
{...$$restProps}
: 'flex-row'} {className ?? ''}"
{style}
>
<FileListNode bind:node={$fileObservers} item={new ListRootItem()} />
{#if orientation === 'vertical'}
<ContextMenu.Root>
<ContextMenu.Trigger class="grow" />
<ContextMenu.Content>
<ContextMenu.Item on:click={createFile}>
<ContextMenu.Item onclick={createFile}>
<Plus size="16" class="mr-1" />
{$_('menu.new_file')}
{i18n._('menu.new_file')}
<Shortcut key="+" ctrl={true} />
</ContextMenu.Item>
<ContextMenu.Separator />
<ContextMenu.Item on:click={selectAll} disabled={$fileObservers.size === 0}>
<ContextMenu.Item onclick={selectAll} disabled={$fileObservers.size === 0}>
<FileStack size="16" class="mr-1" />
{$_('menu.select_all')}
{i18n._('menu.select_all')}
<Shortcut key="A" ctrl={true} />
</ContextMenu.Item>
<ContextMenu.Separator />
@@ -76,10 +85,10 @@
disabled={$copied === undefined ||
$copied.length === 0 ||
!allowedPastes[$copied[0].level].includes(ListLevel.ROOT)}
on:click={pasteSelection}
onclick={pasteSelection}
>
<ClipboardPaste size="16" class="mr-1" />
{$_('menu.paste')}
{i18n._('menu.paste')}
<Shortcut key="V" ctrl={true} />
</ContextMenu.Item>
</ContextMenu.Content>

View File

@@ -21,7 +21,7 @@
type ListItem,
type ListTrackItem,
} from './FileList';
import { _ } from '$lib/i18n';
import { i18n } from '$lib/i18n.svelte';
import { selection } from './Selection';
export let node:
@@ -39,14 +39,14 @@
node instanceof GPXFile && item instanceof ListFileItem
? node.metadata.name
: node instanceof Track
? (node.name ?? `${$_('gpx.track')} ${(item as ListTrackItem).trackIndex + 1}`)
? (node.name ?? `${i18n._('gpx.track')} ${(item as ListTrackItem).trackIndex + 1}`)
: node instanceof TrackSegment
? `${$_('gpx.segment')} ${(item as ListTrackSegmentItem).segmentIndex + 1}`
? `${i18n._('gpx.segment')} ${(item as ListTrackSegmentItem).segmentIndex + 1}`
: node instanceof Waypoint
? (node.name ??
`${$_('gpx.waypoint')} ${(item as ListWaypointItem).waypointIndex + 1}`)
`${i18n._('gpx.waypoint')} ${(item as ListWaypointItem).waypointIndex + 1}`)
: node instanceof GPXFile && item instanceof ListWaypointsItem
? $_('gpx.waypoints')
? i18n._('gpx.waypoints')
: '';
const { treeFileView } = settings;
@@ -72,12 +72,16 @@
<FileListNodeLabel {node} {item} {label} />
{:else if recursive}
<CollapsibleTreeNode id={item.getId()} bind:this={collapsible}>
<FileListNodeLabel {node} {item} {label} slot="trigger" />
<div slot="content" class="ml-2">
{#snippet trigger()}
<FileListNodeLabel {node} {item} {label} />
{/snippet}
{#snippet content()}
<div class="ml-2">
{#key node}
<FileListNodeContent {node} {item} />
{/key}
</div>
{/snippet}
</CollapsibleTreeNode>
{:else}
<FileListNodeLabel {node} {item} {label} />

View File

@@ -23,7 +23,6 @@
} from './FileList';
import { selection } from './Selection';
import { isMac } from '$lib/utils';
import { _ } from '$lib/i18n';
export let node:
| Map<string, Readable<GPXFileWithStatistics | undefined>>
@@ -345,6 +344,8 @@
{/if}
<style lang="postcss">
@reference "../../../app.css";
.sortable > div {
@apply rounded-md;
@apply h-fit;

View File

@@ -19,7 +19,7 @@
Scissors,
FileStack,
FileX,
} from 'lucide-svelte';
} from '@lucide/svelte';
import {
ListFileItem,
ListLevel,
@@ -40,35 +40,34 @@
} from './Selection';
import { getContext } from 'svelte';
import { get } from 'svelte/store';
import {
allHidden,
editMetadata,
editStyle,
embedding,
centerMapOnSelection,
gpxLayers,
map,
} from '$lib/stores';
import { allHidden, embedding, gpxLayers } from '$lib/stores';
import { map, centerMapOnSelection } from '$lib/components/map/map.svelte';
import { GPXTreeElement, Track, type AnyGPXTreeElement, Waypoint, GPXFile } from 'gpx';
import { _ } from '$lib/i18n';
import MetadataDialog from './MetadataDialog.svelte';
import StyleDialog from './StyleDialog.svelte';
import { waypointPopup } from '$lib/components/gpx-layer/GPXLayerPopup';
import { i18n } from '$lib/i18n.svelte';
import MetadataDialog from '$lib/components/file-list/metadata/MetadataDialog.svelte';
import { editMetadata } from '$lib/components/file-list/metadata/utils.svelte';
import StyleDialog from './style/StyleDialog.svelte';
import { editStyle } from '$lib/components/file-list/style/utils.svelte';
import { waypointPopup } from '$lib/components/map/gpx-layer/GPXLayerPopup';
import { getSymbolKey, symbols } from '$lib/assets/symbols';
export let node: GPXTreeElement<AnyGPXTreeElement> | Waypoint[] | Waypoint;
export let item: ListItem;
export let label: string | undefined;
let {
node,
item,
label,
}: {
node: GPXTreeElement<AnyGPXTreeElement> | Waypoint[] | Waypoint;
item: ListItem;
label: string | undefined;
} = $props();
let orientation = getContext<'vertical' | 'horizontal'>('orientation');
$: singleSelection = $selection.size === 1;
let nodeColors: string[] = [];
$: if (node && $map) {
nodeColors = [];
let singleSelection = $derived($selection.size === 1);
let nodeColors: string[] = $derived.by(() => {
let colors: string[] = [];
if (node && map.current) {
if (node instanceof GPXFile) {
let defaultColor = undefined;
@@ -79,41 +78,54 @@
let style = node.getStyle(defaultColor);
style.color.forEach((c) => {
if (!nodeColors.includes(c)) {
nodeColors.push(c);
if (!colors.includes(c)) {
colors.push(c);
}
});
} else if (node instanceof Track) {
let style = node.getStyle();
if (style) {
if (style['gpx_style:color'] && !nodeColors.includes(style['gpx_style:color'])) {
if (
style['gpx_style:color'] &&
!nodeColors.includes(style['gpx_style:color'])
) {
nodeColors.push(style['gpx_style:color']);
}
}
if (nodeColors.length === 0) {
if (colors.length === 0) {
let layer = gpxLayers.get(item.getFileId());
if (layer) {
nodeColors.push(layer.layerColor);
colors.push(layer.layerColor);
}
}
}
}
return colors;
});
$: symbolKey = node instanceof Waypoint ? getSymbolKey(node.sym) : undefined;
let symbolKey = $derived(node instanceof Waypoint ? getSymbolKey(node.sym) : undefined);
let openEditMetadata: boolean = false;
let openEditStyle: boolean = false;
let openEditMetadata: boolean = $state(false);
let openEditStyle: boolean = $state(false);
$: openEditMetadata = $editMetadata && singleSelection && $selection.has(item);
$: openEditStyle =
$editStyle &&
$effect(() => {
openEditMetadata = editMetadata.current && singleSelection && $selection.has(item);
});
$effect(() => {
openEditStyle =
editStyle.current &&
$selection.has(item) &&
$selection.getSelected().findIndex((i) => i.getFullId() === item.getFullId()) === 0;
$: hidden = item.level === ListLevel.WAYPOINTS ? node._data.hiddenWpt : node._data.hidden;
});
let hidden = $derived(
item.level === ListLevel.WAYPOINTS ? node._data.hiddenWpt : node._data.hidden
);
</script>
<!-- svelte-ignore a11y-click-events-have-key-events -->
<!-- svelte-ignore a11y-no-static-element-interactions -->
<!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<ContextMenu.Root
onOpenChange={(open) => {
if (open) {
@@ -156,7 +168,7 @@
: ''} {$cut && $copied?.some((i) => i.getFullId() === item.getFullId())
? 'text-muted-foreground'
: ''}"
on:contextmenu={(e) => {
oncontextmenu={(e) => {
if ($embedding) {
e.preventDefault();
e.stopPropagation();
@@ -170,7 +182,7 @@
$selection = $selection;
}
}}
on:mouseenter={() => {
onmouseenter={() => {
if (item instanceof ListWaypointItem) {
let layer = gpxLayers.get(item.getFileId());
let file = getFile(item.getFileId());
@@ -185,7 +197,7 @@
}
}
}}
on:mouseleave={() => {
onmouseleave={() => {
if (item instanceof ListWaypointItem) {
let layer = gpxLayers.get(item.getFileId());
if (layer) {
@@ -198,11 +210,8 @@
<Waypoints size="16" class="mr-1 shrink-0" />
{:else if item.level === ListLevel.WAYPOINT}
{#if symbolKey && symbols[symbolKey].icon}
<svelte:component
this={symbols[symbolKey].icon}
size="16"
class="mr-1 shrink-0"
/>
{@const SymbolIcon = symbols[symbolKey].icon}
<SymbolIcon size="16" class="mr-1 shrink-0" />
{:else}
<MapPin size="16" class="mr-1 shrink-0" />
{/if}
@@ -230,18 +239,21 @@
</ContextMenu.Trigger>
<ContextMenu.Content>
{#if item instanceof ListFileItem || item instanceof ListTrackItem}
<ContextMenu.Item disabled={!singleSelection} on:click={() => ($editMetadata = true)}>
<ContextMenu.Item
disabled={!singleSelection}
onclick={() => (editMetadata.current = true)}
>
<Info size="16" class="mr-1" />
{$_('menu.metadata.button')}
{i18n._('menu.metadata.button')}
<Shortcut key="I" ctrl={true} />
</ContextMenu.Item>
<ContextMenu.Item on:click={() => ($editStyle = true)}>
<ContextMenu.Item onclick={() => (editStyle.current = true)}>
<PaintBucket size="16" class="mr-1" />
{$_('menu.style.button')}
{i18n._('menu.style.button')}
</ContextMenu.Item>
{/if}
<ContextMenu.Item
on:click={() => {
onclick={() => {
if ($allHidden) {
dbUtils.setHiddenToSelection(false);
} else {
@@ -251,10 +263,10 @@
>
{#if $allHidden}
<Eye size="16" class="mr-1" />
{$_('menu.unhide')}
{i18n._('menu.unhide')}
{:else}
<EyeOff size="16" class="mr-1" />
{$_('menu.hide')}
{i18n._('menu.hide')}
{/if}
<Shortcut key="H" ctrl={true} />
</ContextMenu.Item>
@@ -263,71 +275,71 @@
{#if item instanceof ListFileItem}
<ContextMenu.Item
disabled={!singleSelection}
on:click={() => dbUtils.addNewTrack(item.getFileId())}
onclick={() => dbUtils.addNewTrack(item.getFileId())}
>
<Plus size="16" class="mr-1" />
{$_('menu.new_track')}
{i18n._('menu.new_track')}
</ContextMenu.Item>
<ContextMenu.Separator />
{:else if item instanceof ListTrackItem}
<ContextMenu.Item
disabled={!singleSelection}
on:click={() => dbUtils.addNewSegment(item.getFileId(), item.getTrackIndex())}
onclick={() => dbUtils.addNewSegment(item.getFileId(), item.getTrackIndex())}
>
<Plus size="16" class="mr-1" />
{$_('menu.new_segment')}
{i18n._('menu.new_segment')}
</ContextMenu.Item>
<ContextMenu.Separator />
{/if}
{/if}
{#if item.level !== ListLevel.WAYPOINTS}
<ContextMenu.Item on:click={selectAll}>
<ContextMenu.Item onclick={selectAll}>
<FileStack size="16" class="mr-1" />
{$_('menu.select_all')}
{i18n._('menu.select_all')}
<Shortcut key="A" ctrl={true} />
</ContextMenu.Item>
{/if}
<ContextMenu.Item on:click={centerMapOnSelection}>
<ContextMenu.Item onclick={centerMapOnSelection}>
<Maximize size="16" class="mr-1" />
{$_('menu.center')}
{i18n._('menu.center')}
<Shortcut key="⏎" ctrl={true} />
</ContextMenu.Item>
<ContextMenu.Separator />
<ContextMenu.Item on:click={dbUtils.duplicateSelection}>
<ContextMenu.Item onclick={dbUtils.duplicateSelection}>
<Copy size="16" class="mr-1" />
{$_('menu.duplicate')}
{i18n._('menu.duplicate')}
<Shortcut key="D" ctrl={true} /></ContextMenu.Item
>
{#if orientation === 'vertical'}
<ContextMenu.Item on:click={copySelection}>
<ContextMenu.Item onclick={copySelection}>
<ClipboardCopy size="16" class="mr-1" />
{$_('menu.copy')}
{i18n._('menu.copy')}
<Shortcut key="C" ctrl={true} />
</ContextMenu.Item>
<ContextMenu.Item on:click={cutSelection}>
<ContextMenu.Item onclick={cutSelection}>
<Scissors size="16" class="mr-1" />
{$_('menu.cut')}
{i18n._('menu.cut')}
<Shortcut key="X" ctrl={true} />
</ContextMenu.Item>
<ContextMenu.Item
disabled={$copied === undefined ||
$copied.length === 0 ||
!allowedPastes[$copied[0].level].includes(item.level)}
on:click={pasteSelection}
onclick={pasteSelection}
>
<ClipboardPaste size="16" class="mr-1" />
{$_('menu.paste')}
{i18n._('menu.paste')}
<Shortcut key="V" ctrl={true} />
</ContextMenu.Item>
{/if}
<ContextMenu.Separator />
<ContextMenu.Item on:click={dbUtils.deleteSelection}>
<ContextMenu.Item onclick={dbUtils.deleteSelection}>
{#if item instanceof ListFileItem}
<FileX size="16" class="mr-1" />
{$_('menu.close')}
{i18n._('menu.close')}
{:else}
<Trash2 size="16" class="mr-1" />
{$_('menu.delete')}
{i18n._('menu.delete')}
{/if}
<Shortcut key="⌫" ctrl={true} />
</ContextMenu.Item>

View File

@@ -7,7 +7,11 @@
import type { Readable } from 'svelte/store';
import { ListFileItem } from './FileList';
export let file: Readable<GPXFileWithStatistics | undefined>;
let {
file,
}: {
file: Readable<GPXFileWithStatistics | undefined>;
} = $props();
let recursive = getContext<boolean>('recursive');
</script>

View File

@@ -11,7 +11,8 @@ import {
ListWaypointsItem,
moveItems,
} from './FileList';
import { fileObservers, getFile, getFileIds, settings } from '$lib/db';
import { fileObservers, getFile, getFileIds } from '$lib/db';
// import { settings } from '$lib/logic/settings.svelte';
export class SelectionTreeType {
item: ListItem;
@@ -232,29 +233,28 @@ export function applyToOrderedItemsFromFile(
callback: (fileId: string, level: ListLevel | undefined, items: ListItem[]) => void,
reverse: boolean = true
) {
get(settings.fileOrder).forEach((fileId) => {
let level: ListLevel | undefined = undefined;
let items: ListItem[] = [];
selectedItems.forEach((item) => {
if (item.getFileId() === fileId) {
level = item.level;
if (
item instanceof ListFileItem ||
item instanceof ListTrackItem ||
item instanceof ListTrackSegmentItem ||
item instanceof ListWaypointsItem ||
item instanceof ListWaypointItem
) {
items.push(item);
}
}
});
if (items.length > 0) {
sortItems(items, reverse);
callback(fileId, level, items);
}
});
// settings.fileOrder.value.forEach((fileId) => {
// let level: ListLevel | undefined = undefined;
// let items: ListItem[] = [];
// selectedItems.forEach((item) => {
// if (item.getFileId() === fileId) {
// level = item.level;
// if (
// item instanceof ListFileItem ||
// item instanceof ListTrackItem ||
// item instanceof ListTrackSegmentItem ||
// item instanceof ListWaypointsItem ||
// item instanceof ListWaypointItem
// ) {
// items.push(item);
// }
// }
// });
// if (items.length > 0) {
// sortItems(items, reverse);
// callback(fileId, level, items);
// }
// });
}
export function applyToOrderedSelectedItemsFromFile(

View File

@@ -1,173 +0,0 @@
<script lang="ts">
import { Button } from '$lib/components/ui/button';
import { Input } from '$lib/components/ui/input';
import { Label } from '$lib/components/ui/label/index.js';
import { Slider } from '$lib/components/ui/slider';
import * as Popover from '$lib/components/ui/popover';
import { dbUtils, getFile, settings } from '$lib/db';
import { Save } from 'lucide-svelte';
import { ListFileItem, ListTrackItem, type ListItem } from './FileList';
import { selection } from './Selection';
import { editStyle, gpxLayers } from '$lib/stores';
import { _ } from '$lib/i18n';
export let item: ListItem;
export let open = false;
const { defaultOpacity, defaultWidth } = settings;
let colors: string[] = [];
let color: string | undefined = undefined;
let opacity: number[] = [];
let width: number[] = [];
let colorChanged = false;
let opacityChanged = false;
let widthChanged = false;
function setStyleInputs() {
colors = [];
opacity = [];
width = [];
$selection.forEach((item) => {
if (item instanceof ListFileItem) {
let file = getFile(item.getFileId());
let layer = gpxLayers.get(item.getFileId());
if (file && layer) {
let style = file.getStyle();
style.color.push(layer.layerColor);
style.color.forEach((c) => {
if (!colors.includes(c)) {
colors.push(c);
}
});
style.opacity.forEach((o) => {
if (!opacity.includes(o)) {
opacity.push(o);
}
});
style.width.forEach((w) => {
if (!width.includes(w)) {
width.push(w);
}
});
}
} else if (item instanceof ListTrackItem) {
let file = getFile(item.getFileId());
let layer = gpxLayers.get(item.getFileId());
if (file && layer) {
let track = file.trk[item.getTrackIndex()];
let style = track.getStyle();
if (style) {
if (
style['gpx_style:color'] &&
!colors.includes(style['gpx_style:color'])
) {
colors.push(style['gpx_style:color']);
}
if (
style['gpx_style:opacity'] &&
!opacity.includes(style['gpx_style:opacity'])
) {
opacity.push(style['gpx_style:opacity']);
}
if (style['gpx_style:width'] && !width.includes(style['gpx_style:width'])) {
width.push(style['gpx_style:width']);
}
}
if (!colors.includes(layer.layerColor)) {
colors.push(layer.layerColor);
}
}
}
});
color = colors[0];
opacity = [opacity[0] ?? $defaultOpacity];
width = [width[0] ?? $defaultWidth];
colorChanged = false;
opacityChanged = false;
widthChanged = false;
}
$: if ($selection && open) {
setStyleInputs();
}
$: if (!open) {
$editStyle = false;
}
</script>
<Popover.Root bind:open>
<Popover.Trigger />
<Popover.Content side="top" sideOffset={22} alignOffset={30} class="flex flex-col gap-3">
<Label class="flex flex-row gap-2 items-center justify-between">
{$_('menu.style.color')}
<Input
bind:value={color}
type="color"
class="p-0 h-6 w-40"
on:change={() => (colorChanged = true)}
/>
</Label>
<Label class="flex flex-row gap-2 items-center justify-between">
{$_('menu.style.opacity')}
<div class="w-40 p-2">
<Slider
bind:value={opacity}
min={0.3}
max={1}
step={0.1}
onValueChange={() => (opacityChanged = true)}
/>
</div>
</Label>
<Label class="flex flex-row gap-2 items-center justify-between">
{$_('menu.style.width')}
<div class="w-40 p-2">
<Slider
bind:value={width}
id="width"
min={1}
max={10}
step={1}
onValueChange={() => (widthChanged = true)}
/>
</div>
</Label>
<Button
variant="outline"
disabled={!colorChanged && !opacityChanged && !widthChanged}
on:click={() => {
let style = {};
if (colorChanged) {
style['gpx_style:color'] = color;
}
if (opacityChanged) {
style['gpx_style:opacity'] = opacity[0];
}
if (widthChanged) {
style['gpx_style:width'] = width[0];
}
dbUtils.setStyleToSelection(style);
if (item instanceof ListFileItem && $selection.size === gpxLayers.size) {
if (style['gpx_style:opacity']) {
$defaultOpacity = style['gpx_style:opacity'];
}
if (style['gpx_style:width']) {
$defaultWidth = style['gpx_style:width'];
}
}
open = false;
}}
>
<Save size="16" class="mr-1" />
{$_('menu.metadata.save')}
</Button>
</Popover.Content>
</Popover.Root>

View File

@@ -5,44 +5,54 @@
import { Label } from '$lib/components/ui/label/index.js';
import * as Popover from '$lib/components/ui/popover';
import { dbUtils } from '$lib/db';
import { Save } from 'lucide-svelte';
import { ListFileItem, ListTrackItem, type ListItem } from './FileList';
import { Save } from '@lucide/svelte';
import { ListFileItem, ListTrackItem, type ListItem } from '../FileList';
import { GPXTreeElement, Track, type AnyGPXTreeElement, Waypoint, GPXFile } from 'gpx';
import { _ } from '$lib/i18n';
import { editMetadata } from '$lib/stores';
import { i18n } from '$lib/i18n.svelte';
import { editMetadata } from '$lib/components/file-list/metadata/utils.svelte';
export let node: GPXTreeElement<AnyGPXTreeElement> | Waypoint[] | Waypoint;
export let item: ListItem;
export let open = false;
let {
node,
item,
open = $bindable(),
}: {
node: GPXTreeElement<AnyGPXTreeElement> | Waypoint[] | Waypoint;
item: ListItem;
open: boolean;
} = $props();
let name: string =
let name: string = $derived(
node instanceof GPXFile
? (node.metadata.name ?? '')
: node instanceof Track
? (node.name ?? '')
: '';
let description: string =
: ''
);
let description: string = $derived(
node instanceof GPXFile
? (node.metadata.desc ?? '')
: node instanceof Track
? (node.desc ?? '')
: '';
: ''
);
$: if (!open) {
$editMetadata = false;
$effect(() => {
if (!open) {
editMetadata.current = false;
}
});
</script>
<Popover.Root bind:open>
<Popover.Trigger />
<Popover.Content side="top" sideOffset={22} alignOffset={30} class="flex flex-col gap-3">
<Label for="name">{$_('menu.metadata.name')}</Label>
<Label for="name">{i18n._('menu.metadata.name')}</Label>
<Input bind:value={name} id="name" class="font-semibold h-8" />
<Label for="description">{$_('menu.metadata.description')}</Label>
<Label for="description">{i18n._('menu.metadata.description')}</Label>
<Textarea bind:value={description} id="description" />
<Button
variant="outline"
on:click={() => {
onclick={() => {
dbUtils.applyToFile(item.getFileId(), (file) => {
if (item instanceof ListFileItem && node instanceof GPXFile) {
file.metadata.name = name;
@@ -59,7 +69,7 @@
}}
>
<Save size="16" class="mr-1" />
{$_('menu.metadata.save')}
{i18n._('menu.metadata.save')}
</Button>
</Popover.Content>
</Popover.Root>

View File

@@ -0,0 +1,3 @@
export const editMetadata = $state({
current: false,
});

View File

@@ -0,0 +1,164 @@
<script lang="ts">
import { Button } from '$lib/components/ui/button';
import { Input } from '$lib/components/ui/input';
import { Label } from '$lib/components/ui/label/index.js';
import { Slider } from '$lib/components/ui/slider';
import * as Popover from '$lib/components/ui/popover';
import { dbUtils, getFile, settings } from '$lib/db';
import { Save } from '@lucide/svelte';
import { ListFileItem, ListTrackItem, type ListItem } from '$lib/components/file-list/FileList';
import { editStyle } from '$lib/components/file-list/style/utils.svelte';
import { selection } from '../Selection';
import { gpxLayers } from '$lib/stores';
import { i18n } from '$lib/i18n.svelte';
import type { LineStyleExtension } from 'gpx';
let {
item,
open = $bindable(),
}: {
item: ListItem;
open: boolean;
} = $props();
const { defaultOpacity, defaultWidth } = settings;
let color: string = $state('');
let opacity: number = $state(0);
let width: number = $state(0);
let colorChanged = $state(false);
let opacityChanged = $state(false);
let widthChanged = $state(false);
function setStyleInputs() {
opacity = $defaultOpacity;
width = $defaultWidth;
$selection.forEach((item) => {
if (item instanceof ListFileItem) {
let file = getFile(item.getFileId());
let layer = gpxLayers.get(item.getFileId());
if (file && layer) {
let style = file.getStyle();
color = layer.layerColor;
if (style.opacity.length > 0) {
opacity = style.opacity[0];
}
if (style.width.length > 0) {
width = style.width[0];
}
}
} else if (item instanceof ListTrackItem) {
let file = getFile(item.getFileId());
let layer = gpxLayers.get(item.getFileId());
if (file && layer) {
color = layer.layerColor;
let track = file.trk[item.getTrackIndex()];
let style = track.getStyle();
if (style) {
if (style['gpx_style:color']) {
color = style['gpx_style:color'];
}
if (style['gpx_style:opacity']) {
opacity = style['gpx_style:opacity'];
}
if (style['gpx_style:width']) {
width = style['gpx_style:width'];
}
}
}
}
});
colorChanged = false;
opacityChanged = false;
widthChanged = false;
}
$effect(() => {
if ($selection && open) {
setStyleInputs();
}
});
$effect(() => {
if (!open) {
editStyle.current = false;
}
});
function applyStyle() {
let style: LineStyleExtension = {};
if (colorChanged) {
style['gpx_style:color'] = color;
}
if (opacityChanged) {
style['gpx_style:opacity'] = opacity;
}
if (widthChanged) {
style['gpx_style:width'] = width;
}
dbUtils.setStyleToSelection(style);
if (item instanceof ListFileItem && $selection.size === gpxLayers.size) {
if (style['gpx_style:opacity']) {
$defaultOpacity = style['gpx_style:opacity'];
}
if (style['gpx_style:width']) {
$defaultWidth = style['gpx_style:width'];
}
}
open = false;
}
</script>
<Popover.Root bind:open>
<Popover.Trigger />
<Popover.Content side="top" sideOffset={22} alignOffset={30} class="flex flex-col gap-3">
<Label class="flex flex-row gap-2 items-center justify-between">
{i18n._('menu.style.color')}
<Input
bind:value={color}
type="color"
class="p-0 h-6 w-40"
onchange={() => (colorChanged = true)}
/>
</Label>
<Label class="flex flex-row gap-2 items-center justify-between">
{i18n._('menu.style.opacity')}
<div class="w-40 p-2">
<Slider
bind:value={opacity}
min={0.3}
max={1}
step={0.1}
onValueChange={() => (opacityChanged = true)}
type="single"
/>
</div>
</Label>
<Label class="flex flex-row gap-2 items-center justify-between">
{i18n._('menu.style.width')}
<div class="w-40 p-2">
<Slider
bind:value={width}
id="width"
min={1}
max={10}
step={1}
onValueChange={() => (widthChanged = true)}
type="single"
/>
</div>
</Label>
<Button
variant="outline"
disabled={!colorChanged && !opacityChanged && !widthChanged}
onclick={applyStyle}
>
<Save size="16" class="mr-1" />
{i18n._('menu.metadata.save')}
</Button>
</Popover.Content>
</Popover.Root>

View File

@@ -0,0 +1,3 @@
export const editStyle = $state({
current: false,
});

View File

@@ -1,23 +0,0 @@
<script lang="ts">
import { Button } from '$lib/components/ui/button';
import { ClipboardCopy } from 'lucide-svelte';
import { _ } from '$lib/i18n';
import type { Coordinates } from 'gpx';
export let coordinates: Coordinates;
export let onCopy: () => void = () => {};
</script>
<Button
class="w-full px-2 py-1 h-8 justify-start {$$props.class}"
variant="outline"
on:click={() => {
navigator.clipboard.writeText(
`${coordinates.lat.toFixed(6)}, ${coordinates.lon.toFixed(6)}`
);
onCopy();
}}
>
<ClipboardCopy size="16" class="mr-1" />
{$_('menu.copy_coordinates')}
</Button>

View File

@@ -1,222 +0,0 @@
<script lang="ts">
import CustomControl from '$lib/components/custom-control/CustomControl.svelte';
import LayerTree from './LayerTree.svelte';
import { Separator } from '$lib/components/ui/separator';
import { ScrollArea } from '$lib/components/ui/scroll-area/index.js';
import { Layers } from 'lucide-svelte';
import { basemaps, defaultBasemap, overlays } from '$lib/assets/layers';
import { settings } from '$lib/db';
import { map } from '$lib/stores';
import { get, writable } from 'svelte/store';
import { customBasemapUpdate, getLayers } from './utils';
import { OverpassLayer } from './OverpassLayer';
let container: HTMLDivElement;
let overpassLayer: OverpassLayer;
const {
currentBasemap,
previousBasemap,
currentOverlays,
currentOverpassQueries,
selectedBasemapTree,
selectedOverlayTree,
selectedOverpassTree,
customLayers,
opacities,
} = settings;
function setStyle() {
if ($map) {
let basemap = basemaps.hasOwnProperty($currentBasemap)
? basemaps[$currentBasemap]
: ($customLayers[$currentBasemap]?.value ?? basemaps[defaultBasemap]);
$map.removeImport('basemap');
if (typeof basemap === 'string') {
$map.addImport({ id: 'basemap', url: basemap }, 'overlays');
} else {
$map.addImport(
{
id: 'basemap',
data: basemap,
},
'overlays'
);
}
}
}
$: if ($map && ($currentBasemap || $customBasemapUpdate)) {
setStyle();
}
function addOverlay(id: string) {
try {
let overlay = $customLayers.hasOwnProperty(id) ? $customLayers[id].value : overlays[id];
if (typeof overlay === 'string') {
$map.addImport({ id, url: overlay });
} else {
if ($opacities.hasOwnProperty(id)) {
overlay = {
...overlay,
layers: overlay.layers.map((layer) => {
if (layer.type === 'raster') {
if (!layer.paint) {
layer.paint = {};
}
layer.paint['raster-opacity'] = $opacities[id];
}
return layer;
}),
};
}
$map.addImport({
id,
data: overlay,
});
}
} catch (e) {
// No reliable way to check if the map is ready to add sources and layers
}
}
function updateOverlays() {
if ($map && $currentOverlays && $opacities) {
let overlayLayers = getLayers($currentOverlays);
try {
let activeOverlays = $map.getStyle().imports.reduce((acc, i) => {
if (!['basemap', 'overlays', 'glyphs-and-sprite'].includes(i.id)) {
acc[i.id] = i;
}
return acc;
}, {});
let toRemove = Object.keys(activeOverlays).filter((id) => !overlayLayers[id]);
toRemove.forEach((id) => {
$map.removeImport(id);
});
let toAdd = Object.entries(overlayLayers)
.filter(([id, selected]) => selected && !activeOverlays.hasOwnProperty(id))
.map(([id]) => id);
toAdd.forEach((id) => {
addOverlay(id);
});
} catch (e) {
// No reliable way to check if the map is ready to add sources and layers
}
}
}
$: if ($map && $currentOverlays && $opacities) {
updateOverlays();
}
$: if ($map) {
if (overpassLayer) {
overpassLayer.remove();
}
overpassLayer = new OverpassLayer($map);
overpassLayer.add();
$map.on('style.import.load', updateOverlays);
}
let selectedBasemap = writable(get(currentBasemap));
selectedBasemap.subscribe((value) => {
// Updates coming from radio buttons
if (value !== get(currentBasemap)) {
previousBasemap.set(get(currentBasemap));
currentBasemap.set(value);
}
});
currentBasemap.subscribe((value) => {
// Updates coming from the database, or from the user swapping basemaps
if (value !== get(selectedBasemap)) {
selectedBasemap.set(value);
}
});
let open = false;
function openLayerControl() {
open = true;
}
function closeLayerControl() {
open = false;
}
let cancelEvents = false;
</script>
<CustomControl class="group min-w-[29px] min-h-[29px] overflow-hidden">
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div
bind:this={container}
class="h-full w-full"
on:mouseenter={openLayerControl}
on:mouseleave={closeLayerControl}
on:pointerenter={() => {
if (!open) {
cancelEvents = true;
openLayerControl();
setTimeout(() => {
cancelEvents = false;
}, 500);
}
}}
>
<div
class="flex flex-row justify-center items-center delay-100 transition-[opacity] duration-0 {open
? 'opacity-0 w-0 h-0 delay-0'
: 'w-[29px] h-[29px]'}"
>
<Layers size="20" />
</div>
<div
class="transition-[grid-template-rows grid-template-cols] grid grid-rows-[0fr] grid-cols-[0fr] duration-150 h-full {open
? 'grid-rows-[1fr] grid-cols-[1fr]'
: ''} {cancelEvents ? 'pointer-events-none' : ''}"
>
<ScrollArea>
<div class="h-fit">
<div class="p-2">
<LayerTree
layerTree={$selectedBasemapTree}
name="basemaps"
bind:selected={$selectedBasemap}
/>
</div>
<Separator class="w-full" />
<div class="p-2">
{#if $currentOverlays}
<LayerTree
layerTree={$selectedOverlayTree}
name="overlays"
multiple={true}
bind:checked={$currentOverlays}
/>
{/if}
</div>
<Separator class="w-full" />
<div class="p-2">
{#if $currentOverpassQueries}
<LayerTree
layerTree={$selectedOverpassTree}
name="overpass"
multiple={true}
bind:checked={$currentOverpassQueries}
/>
{/if}
</div>
</div>
</ScrollArea>
</div>
</div>
</CustomControl>
<svelte:window
on:click={(e) => {
if (open && !cancelEvents && !container.contains(e.target)) {
closeLayerControl();
}
}}
/>

View File

@@ -1,20 +0,0 @@
<script lang="ts">
import LayerTreeNode from './LayerTreeNode.svelte';
import { type LayerTreeType } from '$lib/assets/layers';
import CollapsibleTree from '$lib/components/collapsible-tree/CollapsibleTree.svelte';
export let layerTree: LayerTreeType;
export let name: string;
export let selected: string | undefined = undefined;
export let multiple: boolean = false;
export let checked: LayerTreeType = {};
</script>
<form>
<fieldset class="min-w-64 mb-1">
<CollapsibleTree nohover={true}>
<LayerTreeNode {name} node={layerTree} bind:selected {multiple} bind:checked />
</CollapsibleTree>
</fieldset>
</form>

View File

@@ -0,0 +1,20 @@
<script lang="ts">
import { map } from '$lib/components/map/map.svelte';
import { trackpointPopup } from '$lib/components/map/gpx-layer/GPXLayerPopup';
import { TrackPoint } from 'gpx';
$effect(() => {
if (map.current) {
map.current.on('contextmenu', (e) => {
trackpointPopup?.setItem({
item: new TrackPoint({
attributes: {
lat: e.lngLat.lat,
lon: e.lngLat.lng,
},
}),
});
});
}
});
</script>

View File

@@ -0,0 +1,254 @@
<script lang="ts">
import { onDestroy, onMount } from 'svelte';
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';
import '@mapbox/mapbox-gl-geocoder/dist/mapbox-gl-geocoder.css';
import { Button } from '$lib/components/ui/button';
import { settings } from '$lib/logic/settings.svelte';
import { i18n } from '$lib/i18n.svelte';
import { PUBLIC_MAPBOX_TOKEN } from '$env/static/public';
import { page } from '$app/state';
import { map } from '$lib/components/map/utils.svelte';
let {
accessToken = PUBLIC_MAPBOX_TOKEN,
geolocate = true,
geocoder = true,
hash = true,
class: className = '',
}: {
accessToken?: string;
geolocate?: boolean;
geocoder?: boolean;
hash?: boolean;
class?: string;
} = $props();
mapboxgl.accessToken = accessToken;
let webgl2Supported = $state(true);
let embeddedApp = $state(false);
const { distanceUnits, elevationProfile, treeFileView, bottomPanelSize, rightPanelSize } =
settings;
onMount(() => {
let gl = document.createElement('canvas').getContext('webgl2');
if (!gl) {
webgl2Supported = false;
return;
}
if (window.top !== window.self && !page.route.id?.includes('embed')) {
embeddedApp = true;
return;
}
let language = page.params.language;
if (language === 'zh') {
language = 'zh-Hans';
} else if (language?.includes('-')) {
language = language.split('-')[0];
} else if (language === '' || language === undefined) {
language = 'en';
}
map.init(PUBLIC_MAPBOX_TOKEN, language, distanceUnits.value, hash, geocoder, geolocate);
});
onDestroy(() => {
map.destroy();
});
$effect(() => {
if (
!treeFileView.value ||
!elevationProfile.value ||
bottomPanelSize.value ||
rightPanelSize.value
) {
map.resize();
}
});
</script>
<div class={className}>
<div id="map" class="h-full {webgl2Supported && !embeddedApp ? '' : 'hidden'}"></div>
<div
class="flex flex-col items-center justify-center gap-3 h-full {webgl2Supported &&
!embeddedApp
? 'hidden'
: ''} {embeddedApp ? 'z-30' : ''}"
>
{#if !webgl2Supported}
<p>{i18n._('webgl2_required')}</p>
<Button href="https://get.webgl.org/webgl2/" target="_blank">
{i18n._('enable_webgl2')}
</Button>
{:else if embeddedApp}
<p>The app cannot be embedded in an iframe.</p>
<Button href="https://gpx.studio/help/integration" target="_blank">
Learn how to create a map for your website
</Button>
{/if}
</div>
</div>
<style lang="postcss">
@reference "../../../app.css";
div :global(.mapboxgl-map) {
@apply font-sans;
}
div :global(.mapboxgl-ctrl-top-right > .mapboxgl-ctrl) {
@apply shadow-md;
@apply bg-background;
@apply text-foreground;
}
div :global(.mapboxgl-ctrl-icon) {
@apply dark:brightness-[4.7];
}
div :global(.mapboxgl-ctrl-geocoder) {
@apply flex;
@apply flex-row;
@apply w-fit;
@apply min-w-fit;
@apply items-center;
@apply shadow-md;
}
div :global(.suggestions) {
@apply shadow-md;
@apply bg-background;
@apply text-foreground;
}
div :global(.mapboxgl-ctrl-geocoder .suggestions > li > a) {
@apply text-foreground;
@apply hover:text-accent-foreground;
@apply hover:bg-accent;
}
div :global(.mapboxgl-ctrl-geocoder .suggestions > .active > a) {
@apply bg-background;
}
div :global(.mapboxgl-ctrl-geocoder--button) {
@apply bg-transparent;
@apply hover:bg-transparent;
}
div :global(.mapboxgl-ctrl-geocoder--icon) {
@apply fill-foreground;
@apply hover:fill-accent-foreground;
}
div :global(.mapboxgl-ctrl-geocoder--icon-search) {
@apply relative;
@apply top-0;
@apply left-0;
@apply my-2;
@apply w-[29px];
}
div :global(.mapboxgl-ctrl-geocoder--input) {
@apply relative;
@apply w-64;
@apply py-0;
@apply pl-2;
@apply focus:outline-none;
@apply transition-[width];
@apply duration-200;
@apply text-foreground;
}
div :global(.mapboxgl-ctrl-geocoder--collapsed .mapboxgl-ctrl-geocoder--input) {
@apply w-0;
@apply p-0;
}
div :global(.mapboxgl-ctrl-top-right) {
@apply z-40;
@apply flex;
@apply flex-col;
@apply items-end;
@apply h-full;
@apply overflow-hidden;
}
.horizontal :global(.mapboxgl-ctrl-bottom-left) {
@apply bottom-[42px];
}
.horizontal :global(.mapboxgl-ctrl-bottom-right) {
@apply bottom-[42px];
}
div :global(.mapboxgl-ctrl-attrib) {
@apply dark:bg-transparent;
}
div :global(.mapboxgl-compact-show.mapboxgl-ctrl-attrib) {
@apply dark:bg-background;
}
div :global(.mapboxgl-ctrl-attrib-button) {
@apply dark:bg-foreground;
}
div :global(.mapboxgl-compact-show .mapboxgl-ctrl-attrib-button) {
@apply dark:bg-foreground;
}
div :global(.mapboxgl-ctrl-attrib a) {
@apply text-foreground;
}
div :global(.mapboxgl-popup) {
@apply w-fit;
@apply z-50;
}
div :global(.mapboxgl-popup-content) {
@apply p-0;
@apply bg-transparent;
@apply shadow-none;
}
div :global(.mapboxgl-popup-anchor-top .mapboxgl-popup-tip) {
@apply border-b-background;
}
div :global(.mapboxgl-popup-anchor-top-left .mapboxgl-popup-tip) {
@apply border-b-background;
}
div :global(.mapboxgl-popup-anchor-top-right .mapboxgl-popup-tip) {
@apply border-b-background;
}
div :global(.mapboxgl-popup-anchor-bottom .mapboxgl-popup-tip) {
@apply border-t-background;
@apply drop-shadow-md;
}
div :global(.mapboxgl-popup-anchor-bottom-left .mapboxgl-popup-tip) {
@apply border-t-background;
@apply drop-shadow-md;
}
div :global(.mapboxgl-popup-anchor-bottom-right .mapboxgl-popup-tip) {
@apply border-t-background;
@apply drop-shadow-md;
}
div :global(.mapboxgl-popup-anchor-left .mapboxgl-popup-tip) {
@apply border-r-background;
}
div :global(.mapboxgl-popup-anchor-right .mapboxgl-popup-tip) {
@apply border-l-background;
}
</style>

View File

@@ -0,0 +1,22 @@
<script lang="ts">
import { TrackPoint, Waypoint } from 'gpx';
import WaypointPopup from '$lib/components/map/gpx-layer/WaypointPopup.svelte';
import TrackpointPopup from '$lib/components/map/gpx-layer/TrackpointPopup.svelte';
import OverpassPopup from '$lib/components/map/layer-control/OverpassPopup.svelte';
import type { PopupItem } from '$lib/components/map/map.svelte';
let { item, container = null }: { item: PopupItem | null; container: HTMLDivElement | null } =
$props();
</script>
<div bind:this={container}>
{#if item}
{#if item.item instanceof Waypoint}
<WaypointPopup waypoint={item} />
{:else if item.item instanceof TrackPoint}
<TrackpointPopup trackpoint={item} />
{:else}
<OverpassPopup poi={item} />
{/if}
{/if}
</div>

View File

@@ -0,0 +1,38 @@
<script lang="ts">
import CustomControl from './CustomControl';
import { map } from '$lib/components/map/utils.svelte';
import { onMount, type Snippet } from 'svelte';
let {
position = 'top-right',
class: className = '',
children,
}: {
position?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';
class: string;
children: Snippet;
} = $props();
let container: HTMLDivElement;
let control: CustomControl | null = null;
onMount(() => {
map.onLoad((map: mapboxgl.Map) => {
if (position.includes('right')) container.classList.add('float-right');
else container.classList.add('float-left');
container.classList.remove('hidden');
if (control === null) {
control = new CustomControl(container);
}
map.addControl(control, position);
});
});
</script>
<div
bind:this={container}
class="{className ||
''} clear-both translate-0 m-[10px] mb-0 last:mb-[10px] pointer-events-auto bg-background rounded shadow-md hidden"
>
{@render children()}
</div>

View File

@@ -0,0 +1,30 @@
<script lang="ts">
import { Button } from '$lib/components/ui/button';
import { ClipboardCopy } from '@lucide/svelte';
import { i18n } from '$lib/i18n.svelte';
import type { Coordinates } from 'gpx';
let {
coordinates,
onCopy = () => {},
class: className = '',
}: {
coordinates: Coordinates;
onCopy: () => void;
class?: string;
} = $props();
</script>
<Button
class="w-full px-2 py-1 h-8 justify-start {className}"
variant="outline"
onclick={() => {
navigator.clipboard.writeText(
`${coordinates.lat.toFixed(6)}, ${coordinates.lon.toFixed(6)}`
);
onCopy();
}}
>
<ClipboardCopy size="16" class="mr-1" />
{i18n._('menu.copy_coordinates')}
</Button>

View File

@@ -1,8 +1,9 @@
import { settings } from '$lib/db';
import { gpxStatistics } from '$lib/stores';
import type { GeoJSONSource } from 'mapbox-gl';
import { get } from 'svelte/store';
const { distanceMarkers, distanceUnits } = settings;
// const { distanceMarkers, distanceUnits } = settings;
const stops = [
[100, 0],
@@ -30,7 +31,8 @@ export class DistanceMarkers {
update() {
try {
if (get(distanceMarkers)) {
let distanceSource = this.map.getSource('distance-markers');
let distanceSource: GeoJSONSource | undefined =
this.map.getSource('distance-markers');
if (distanceSource) {
distanceSource.setData(this.getDistanceMarkersGeoJSON());
} else {

View File

@@ -1,4 +1,4 @@
import { currentTool, map, Tool } from '$lib/stores';
import { currentTool, map, splitAs, Tool } from '$lib/stores';
import { settings, type GPXFileWithStatistics, dbUtils } from '$lib/db';
import { get, type Readable } from 'svelte/store';
import mapboxgl from 'mapbox-gl';
@@ -82,7 +82,7 @@ function getMarkerForSymbol(symbol: string | undefined, layerColor: string) {
</svg>`;
}
const { directionMarkers, treeFileView, defaultOpacity, defaultWidth } = settings;
// const { directionMarkers, treeFileView, defaultOpacity, defaultWidth } = settings;
export class GPXLayer {
map: mapboxgl.Map;
@@ -469,7 +469,7 @@ export class GPXLayer {
new ListTrackSegmentItem(this.fileId, trackIndex, segmentIndex)
)
) {
dbUtils.split(this.fileId, trackIndex, segmentIndex, {
dbUtils.split(splitAs.current, this.fileId, trackIndex, segmentIndex, {
lat: e.lngLat.lat,
lon: e.lngLat.lng,
});

View File

@@ -1,5 +1,5 @@
import { dbUtils } from '$lib/db';
import { MapPopup } from '$lib/components/MapPopup';
import { MapPopup } from '$lib/components/map/map.svelte';
export let waypointPopup: MapPopup | null = null;
export let trackpointPopup: MapPopup | null = null;

View File

@@ -1,13 +1,13 @@
<script lang="ts">
import type { TrackPoint } from 'gpx';
import type { PopupItem } from '$lib/components/MapPopup';
import CopyCoordinates from '$lib/components/gpx-layer/CopyCoordinates.svelte';
import type { PopupItem } from '$lib/components/map/map.svelte';
import CopyCoordinates from '$lib/components/map/gpx-layer/CopyCoordinates.svelte';
import * as Card from '$lib/components/ui/card';
import WithUnits from '$lib/components/WithUnits.svelte';
import { Compass, Mountain, Timer } from 'lucide-svelte';
import { _, df } from '$lib/i18n';
import { Compass, Mountain, Timer } from '@lucide/svelte';
import { i18n } from '$lib/i18n.svelte';
export let trackpoint: PopupItem<TrackPoint>;
let { trackpoint }: { trackpoint: PopupItem<TrackPoint> } = $props();
</script>
<Card.Root class="border-none shadow-md text-base p-2">
@@ -30,7 +30,7 @@
{#if trackpoint.item.time}
<div class="flex flex-row items-center gap-1">
<Timer size="14" />
{$df.format(trackpoint.item.time)}
{i18n.df.format(trackpoint.item.time)}
</div>
{/if}
<CopyCoordinates

View File

@@ -2,16 +2,16 @@
import * as Card from '$lib/components/ui/card';
import { Button } from '$lib/components/ui/button';
import Shortcut from '$lib/components/Shortcut.svelte';
import CopyCoordinates from '$lib/components/gpx-layer/CopyCoordinates.svelte';
import CopyCoordinates from '$lib/components/map/gpx-layer/CopyCoordinates.svelte';
import { deleteWaypoint } from './GPXLayerPopup';
import WithUnits from '$lib/components/WithUnits.svelte';
import { Dot, ExternalLink, Trash2 } from 'lucide-svelte';
import { Tool, currentTool } from '$lib/stores';
import { Dot, ExternalLink, Trash2 } from '@lucide/svelte';
import { tool, Tool } from '$lib/components/toolbar/utils.svelte';
import { getSymbolKey, symbols } from '$lib/assets/symbols';
import { _ } from '$lib/i18n';
import { i18n } from '$lib/i18n.svelte';
import sanitizeHtml from 'sanitize-html';
import type { Waypoint } from 'gpx';
import type { PopupItem } from '$lib/components/MapPopup';
import type { PopupItem } from '$lib/components/map/map.svelte';
import { ScrollArea } from '$lib/components/ui/scroll-area/index.js';
export let waypoint: PopupItem<Waypoint>;
@@ -41,7 +41,7 @@
<ExternalLink size="12" class="inline-block mb-1.5" />
</a>
{:else}
{waypoint.item.name ?? $_('gpx.waypoint')}
{waypoint.item.name ?? i18n._('gpx.waypoint')}
{/if}
</Card.Title>
</Card.Header>
@@ -58,7 +58,7 @@
{:else}
<span class="w-4 inline-block"></span>
{/if}
{$_(`gpx.symbol.${symbolKey}`)}
{i18n._(`gpx.symbol.${symbolKey}`)}
</span>
<Dot size="16" />
{/if}
@@ -70,7 +70,7 @@
<WithUnits value={waypoint.item.ele} type="elevation" />
{/if}
</div>
<ScrollArea class="flex flex-col" viewportClasses="max-h-[30dvh]">
<ScrollArea class="flex flex-col max-h-[30dvh]">
{#if waypoint.item.desc}
<span class="whitespace-pre-wrap">{@html sanitize(waypoint.item.desc)}</span>
{/if}
@@ -80,14 +80,14 @@
</ScrollArea>
<div class="mt-2 flex flex-col gap-1">
<CopyCoordinates coordinates={waypoint.item.attributes} />
{#if $currentTool === Tool.WAYPOINT}
{#if tool.current === Tool.WAYPOINT}
<Button
class="w-full px-2 py-1 h-8 justify-start"
variant="outline"
on:click={() => deleteWaypoint(waypoint.fileId, waypoint.item._data.index)}
onclick={() => deleteWaypoint(waypoint.fileId, waypoint.item._data.index)}
>
<Trash2 size="16" class="mr-1" />
{$_('menu.delete')}
{i18n._('menu.delete')}
<Shortcut shift={true} click={true} />
</Button>
{/if}
@@ -96,6 +96,8 @@
</Card.Root>
<style lang="postcss">
@reference "../../../../app.css";
div :global(a) {
@apply text-link;
@apply hover:underline;

View File

@@ -16,14 +16,14 @@
Move,
Map,
Layers2,
} from 'lucide-svelte';
import { _ } from '$lib/i18n';
} from '@lucide/svelte';
import { i18n } from '$lib/i18n.svelte';
import { settings } from '$lib/db';
import { defaultBasemap, type CustomLayer } from '$lib/assets/layers';
import { map } from '$lib/stores';
import { onDestroy, onMount } from 'svelte';
import Sortable from 'sortablejs/Sortable';
import { customBasemapUpdate } from './utils';
import { customBasemapUpdate } from './utils.svelte';
const {
customLayers,
@@ -298,7 +298,7 @@
{#if $customBasemapOrder.length > 0}
<div class="flex flex-row items-center gap-1 font-semibold mb-2">
<Map size="16" />
{$_('layers.label.basemaps')}
{i18n._('layers.label.basemaps')}
<div class="grow">
<Separator />
</div>
@@ -324,7 +324,7 @@
{#if $customOverlayOrder.length > 0}
<div class="flex flex-row items-center gap-1 font-semibold mb-2">
<Layers2 size="16" />
{$_('layers.label.overlays')}
{i18n._('layers.label.overlays')}
<div class="grow">
<Separator />
</div>
@@ -352,24 +352,24 @@
<Card.Header class="p-3">
<Card.Title class="text-base">
{#if selectedLayerId}
{$_('layers.custom_layers.edit')}
{i18n._('layers.custom_layers.edit')}
{:else}
{$_('layers.custom_layers.new')}
{i18n._('layers.custom_layers.new')}
{/if}
</Card.Title>
</Card.Header>
<Card.Content class="p-3 pt-0">
<fieldset class="flex flex-col gap-2">
<Label for="name">{$_('menu.metadata.name')}</Label>
<Label for="name">{i18n._('menu.metadata.name')}</Label>
<Input bind:value={name} id="name" class="h-8" />
<Label for="url">{$_('layers.custom_layers.urls')}</Label>
<Label for="url">{i18n._('layers.custom_layers.urls')}</Label>
{#each tileUrls as url, i}
<div class="flex flex-row gap-2">
<Input
bind:value={tileUrls[i]}
id="url"
class="h-8"
placeholder={$_('layers.custom_layers.url_placeholder')}
placeholder={i18n._('layers.custom_layers.url_placeholder')}
/>
{#if tileUrls.length > 1}
<Button
@@ -393,7 +393,7 @@
</div>
{/each}
{#if resourceType === 'raster'}
<Label for="maxZoom">{$_('layers.custom_layers.max_zoom')}</Label>
<Label for="maxZoom">{i18n._('layers.custom_layers.max_zoom')}</Label>
<Input
type="number"
bind:value={maxZoom}
@@ -403,22 +403,22 @@
class="h-8"
/>
{/if}
<Label>{$_('layers.custom_layers.layer_type')}</Label>
<Label>{i18n._('layers.custom_layers.layer_type')}</Label>
<RadioGroup.Root bind:value={layerType} class="flex flex-row">
<div class="flex items-center space-x-2">
<RadioGroup.Item value="basemap" id="basemap" />
<Label for="basemap">{$_('layers.custom_layers.basemap')}</Label>
<Label for="basemap">{i18n._('layers.custom_layers.basemap')}</Label>
</div>
<div class="flex items-center space-x-2">
<RadioGroup.Item value="overlay" id="overlay" />
<Label for="overlay">{$_('layers.custom_layers.overlay')}</Label>
<Label for="overlay">{i18n._('layers.custom_layers.overlay')}</Label>
</div>
</RadioGroup.Root>
{#if selectedLayerId}
<div class="mt-2 flex flex-row gap-2">
<Button variant="outline" on:click={createLayer} class="grow">
<Save size="16" class="mr-1" />
{$_('layers.custom_layers.update')}
{i18n._('layers.custom_layers.update')}
</Button>
<Button variant="outline" on:click={() => (selectedLayerId = undefined)}>
<CircleX size="16" />
@@ -427,7 +427,7 @@
{:else}
<Button variant="outline" class="mt-2" on:click={createLayer}>
<CirclePlus size="16" class="mr-1" />
{$_('layers.custom_layers.create')}
{i18n._('layers.custom_layers.create')}
</Button>
{/if}
</fieldset>

View File

@@ -0,0 +1,231 @@
<script lang="ts">
import CustomControl from '$lib/components/map/custom-control/CustomControl.svelte';
import LayerTree from './LayerTree.svelte';
// import { OverpassLayer } from './OverpassLayer';
import { Separator } from '$lib/components/ui/separator';
import { ScrollArea } from '$lib/components/ui/scroll-area/index.js';
import { Layers } from '@lucide/svelte';
import { basemaps, defaultBasemap, overlays } from '$lib/assets/layers';
import { settings } from '$lib/logic/settings.svelte';
import { map } from '$lib/components/map/utils.svelte';
import { customBasemapUpdate, getLayers } from './utils.svelte';
import type { ImportSpecification, StyleSpecification } from 'mapbox-gl';
let container: HTMLDivElement;
// let overpassLayer: OverpassLayer;
const {
currentBasemap,
previousBasemap,
currentOverlays,
currentOverpassQueries,
selectedBasemapTree,
selectedOverlayTree,
selectedOverpassTree,
customLayers,
opacities,
} = settings;
function setStyle() {
if (!map.value) {
return;
}
let basemap = basemaps.hasOwnProperty(currentBasemap.value)
? basemaps[currentBasemap.value]
: (customLayers.value[currentBasemap.value]?.value ?? basemaps[defaultBasemap]);
map.value.removeImport('basemap');
if (typeof basemap === 'string') {
map.value.addImport({ id: 'basemap', url: basemap }, 'overlays');
} else {
map.value.addImport(
{
id: 'basemap',
url: '',
data: basemap as StyleSpecification,
},
'overlays'
);
}
}
$effect(() => {
if (map.value && (currentBasemap.value || customBasemapUpdate.value)) {
setStyle();
}
});
function addOverlay(id: string) {
if (!map.value) {
return;
}
try {
let overlay = customLayers.value.hasOwnProperty(id)
? customLayers.value[id].value
: overlays[id];
if (typeof overlay === 'string') {
map.value.addImport({ id, url: overlay });
} else {
if (opacities.value.hasOwnProperty(id)) {
overlay = {
...overlay,
layers: (overlay as StyleSpecification).layers.map((layer) => {
if (layer.type === 'raster') {
if (!layer.paint) {
layer.paint = {};
}
layer.paint['raster-opacity'] = opacities.value[id];
}
return layer;
}),
};
}
map.value.addImport({
id,
url: '',
data: overlay as StyleSpecification,
});
}
} catch (e) {
// No reliable way to check if the map is ready to add sources and layers
}
}
function updateOverlays() {
if (map.value && currentOverlays.value && opacities.value) {
let overlayLayers = getLayers(currentOverlays.value);
try {
let activeOverlays =
map.value
.getStyle()
?.imports?.reduce(
(
acc: Record<string, ImportSpecification>,
imprt: ImportSpecification
) => {
if (
!['basemap', 'overlays', 'glyphs-and-sprite'].includes(imprt.id)
) {
acc[imprt.id] = imprt;
}
return acc;
},
{}
) || {};
let toRemove = Object.keys(activeOverlays).filter((id) => !overlayLayers[id]);
toRemove.forEach((id) => {
map.value?.removeImport(id);
});
let toAdd = Object.entries(overlayLayers)
.filter(([id, selected]) => selected && !activeOverlays.hasOwnProperty(id))
.map(([id]) => id);
toAdd.forEach((id) => {
addOverlay(id);
});
} catch (e) {
// No reliable way to check if the map is ready to add sources and layers
}
}
}
$effect(() => {
if (map.value && currentOverlays.value && opacities.value) {
updateOverlays();
}
});
// map.onLoad((map: mapboxgl.Map) => {
// if (overpassLayer) {
// overpassLayer.remove();
// }
// overpassLayer = new OverpassLayer(map);
// overpassLayer.add();
// map.on('style.import.load', updateOverlays);
// });
let open = $state(false);
function openLayerControl() {
open = true;
}
function closeLayerControl() {
open = false;
}
let cancelEvents = $state(false);
</script>
<CustomControl class="group min-w-[29px] min-h-[29px] overflow-hidden">
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
bind:this={container}
class="size-full"
onmouseenter={openLayerControl}
onmouseleave={closeLayerControl}
onpointerenter={() => {
if (!open) {
cancelEvents = true;
openLayerControl();
setTimeout(() => {
cancelEvents = false;
}, 500);
}
}}
>
<div
class="flex flex-row justify-center items-center delay-100 transition-[opacity] duration-0 {open
? 'opacity-0 size-0 delay-0'
: 'w-[29px] h-[29px]'}"
>
<Layers size="20" />
</div>
<div
class="transition-[grid-template-rows grid-template-cols] grid grid-rows-[0fr] grid-cols-[0fr] duration-150 h-full {open
? 'grid-rows-[1fr] grid-cols-[1fr]'
: ''} {cancelEvents ? 'pointer-events-none' : ''}"
>
<ScrollArea>
<div class="h-fit">
<div class="p-2">
<LayerTree
layerTree={selectedBasemapTree.value}
name="basemaps"
selected={currentBasemap.value}
onselect={(value) => {
previousBasemap.value = currentBasemap.value;
currentBasemap.value = value;
}}
/>
</div>
<Separator class="w-full" />
<div class="p-2">
{#if currentOverlays.value}
<LayerTree
layerTree={selectedOverlayTree.value}
name="overlays"
multiple={true}
bind:checked={currentOverlays.value}
/>
{/if}
</div>
<Separator class="w-full" />
<div class="p-2">
{#if currentOverpassQueries.value}
<LayerTree
layerTree={selectedOverpassTree.value}
name="overpass"
multiple={true}
bind:checked={currentOverpassQueries.value}
/>
{/if}
</div>
</div>
</ScrollArea>
</div>
</div>
</CustomControl>
<svelte:window
on:click={(e) => {
if (open && !cancelEvents && !container.contains(e.target)) {
closeLayerControl();
}
}}
/>

View File

@@ -1,6 +1,5 @@
<script lang="ts">
import LayerTree from './LayerTree.svelte';
import { Separator } from '$lib/components/ui/separator';
import { ScrollArea } from '$lib/components/ui/scroll-area/index.js';
import * as Sheet from '$lib/components/ui/sheet';
@@ -8,7 +7,6 @@
import { Label } from '$lib/components/ui/label';
import * as Select from '$lib/components/ui/select';
import { Slider } from '$lib/components/ui/slider';
import {
basemapTree,
defaultBasemap,
@@ -16,12 +14,10 @@
overlayTree,
overpassTree,
} from '$lib/assets/layers';
import { getLayers, isSelected, toggle } from '$lib/components/layer-control/utils';
import { getLayers, isSelected, toggle } from '$lib/components/map/layer-control/utils.svelte';
import { settings } from '$lib/db';
import { _ } from '$lib/i18n';
import { writable } from 'svelte/store';
import { map } from '$lib/stores';
import { i18n } from '$lib/i18n.svelte';
import { map } from '$lib/components/map/map.svelte';
import CustomLayers from './CustomLayers.svelte';
const {
@@ -34,22 +30,21 @@
opacities,
} = settings;
export let open: boolean;
let accordionValue: string | string[] | undefined = undefined;
let { open = $bindable() }: { open: boolean } = $props();
let selectedOverlay = writable(undefined);
let overlayOpacity = writable([1]);
let accordionValue: string | undefined = $state(undefined);
let selectedOverlay = $state(undefined);
let overlayOpacity = $state(1);
function setOpacityFromSelection() {
if ($selectedOverlay) {
let overlayId = $selectedOverlay.value;
if ($opacities.hasOwnProperty(overlayId)) {
$overlayOpacity = [$opacities[overlayId]];
if (selectedOverlay) {
if ($opacities.hasOwnProperty(selectedOverlay)) {
overlayOpacity = $opacities[selectedOverlay];
} else {
$overlayOpacity = [1];
overlayOpacity = 1;
}
} else {
$overlayOpacity = [1];
overlayOpacity = 1;
}
}
@@ -76,24 +71,20 @@
});
}
}
$: if ($selectedOverlay) {
setOpacityFromSelection();
}
</script>
<Sheet.Root bind:open>
<Sheet.Trigger class="hidden" />
<Sheet.Content>
<Sheet.Header class="h-full">
<Sheet.Title>{$_('layers.settings')}</Sheet.Title>
<Sheet.Title>{i18n._('layers.settings')}</Sheet.Title>
<ScrollArea class="w-[105%] min-h-full pr-4">
<Sheet.Description>
{$_('layers.settings_help')}
{i18n._('layers.settings_help')}
</Sheet.Description>
<Accordion.Root class="flex flex-col" bind:value={accordionValue}>
<Accordion.Root class="flex flex-col" bind:value={accordionValue} type="single">
<Accordion.Item value="layer-selection" class="flex flex-col">
<Accordion.Trigger>{$_('layers.selection')}</Accordion.Trigger>
<Accordion.Trigger>{i18n._('layers.selection')}</Accordion.Trigger>
<Accordion.Content class="grow flex flex-col border rounded">
<div class="py-2 pl-1 pr-2">
<LayerTree
@@ -124,21 +115,31 @@
</Accordion.Content>
</Accordion.Item>
<Accordion.Item value="overlay-opacity">
<Accordion.Trigger>{$_('layers.opacity')}</Accordion.Trigger>
<Accordion.Trigger>{i18n._('layers.opacity')}</Accordion.Trigger>
<Accordion.Content class="flex flex-col gap-3 overflow-visible">
<div class="flex flex-row gap-6 items-center">
<Label>
{$_('layers.custom_layers.overlay')}
{i18n._('layers.custom_layers.overlay')}
</Label>
<Select.Root bind:selected={$selectedOverlay}>
<Select.Root
bind:value={selectedOverlay}
type="single"
onValueChange={setOpacityFromSelection}
>
<Select.Trigger class="h-8 mr-1">
<Select.Value />
{#if selectedOverlay}
{#if isSelected($selectedOverlayTree, selectedOverlay)}
{i18n._(`layers.label.${selectedOverlay}`)}
{:else if $customLayers.hasOwnProperty(selectedOverlay)}
{$customLayers[selectedOverlay].name}
{/if}
{/if}
</Select.Trigger>
<Select.Content class="h-fit max-h-[40dvh] overflow-y-auto">
{#each Object.keys(overlays) as id}
{#if isSelected($selectedOverlayTree, id)}
<Select.Item value={id}
>{$_(`layers.label.${id}`)}</Select.Item
>{i18n._(`layers.label.${id}`)}</Select.Item
>
{/if}
{/each}
@@ -151,30 +152,28 @@
</Select.Root>
</div>
<Label class="flex flex-row gap-6 items-center">
{$_('menu.style.opacity')}
{i18n._('menu.style.opacity')}
<div class="p-2 pr-3 grow">
<Slider
bind:value={$overlayOpacity}
bind:value={overlayOpacity}
type="single"
min={0.1}
max={1}
step={0.1}
disabled={$selectedOverlay === undefined}
disabled={selectedOverlay === undefined}
onValueChange={(value) => {
if ($selectedOverlay) {
if (selectedOverlay) {
if (
$map &&
isSelected(
$currentOverlays,
$selectedOverlay.value
)
map.current &&
isSelected($currentOverlays, selectedOverlay)
) {
try {
$map.removeImport($selectedOverlay.value);
map.current.removeImport(selectedOverlay);
} catch (e) {
// No reliable way to check if the map is ready to remove sources and layers
}
}
$opacities[$selectedOverlay.value] = value[0];
$opacities[selectedOverlay] = value;
}
}}
/>
@@ -183,7 +182,8 @@
</Accordion.Content>
</Accordion.Item>
<Accordion.Item value="custom-layers">
<Accordion.Trigger>{$_('layers.custom_layers.title')}</Accordion.Trigger>
<Accordion.Trigger>{i18n._('layers.custom_layers.title')}</Accordion.Trigger
>
<Accordion.Content>
<ScrollArea>
<CustomLayers />

View File

@@ -0,0 +1,29 @@
<script lang="ts">
import LayerTreeNode from './LayerTreeNode.svelte';
import { type LayerTreeType } from '$lib/assets/layers';
import CollapsibleTree from '$lib/components/collapsible-tree/CollapsibleTree.svelte';
let {
layerTree,
name,
selected = '',
onselect = () => {},
multiple = false,
checked = $bindable({}),
}: {
layerTree: LayerTreeType;
name: string;
selected?: string;
onselect?: (value: string) => void;
multiple?: boolean;
checked?: LayerTreeType;
} = $props();
</script>
<form>
<fieldset class="min-w-64 mb-1">
<CollapsibleTree nohover={true}>
<LayerTreeNode {name} node={layerTree} {selected} {onselect} {multiple} bind:checked />
</CollapsibleTree>
</fieldset>
</form>

View File

@@ -1,25 +1,32 @@
<script lang="ts">
import Self from '$lib/components/map/layer-control/LayerTreeNode.svelte';
import { Label } from '$lib/components/ui/label';
import { Checkbox } from '$lib/components/ui/checkbox';
import CollapsibleTreeNode from '../collapsible-tree/CollapsibleTreeNode.svelte';
import CollapsibleTreeNode from '$lib/components/collapsible-tree/CollapsibleTreeNode.svelte';
import { type LayerTreeType } from '$lib/assets/layers';
import { anySelectedLayer } from './utils';
import { anySelectedLayer } from './utils.svelte';
import { i18n } from '$lib/i18n.svelte';
import { settings } from '$lib/logic/settings.svelte';
import { _ } from '$lib/i18n';
import { settings } from '$lib/db';
import { beforeUpdate } from 'svelte';
export let name: string;
export let node: LayerTreeType;
export let selected: string | undefined = undefined;
export let multiple: boolean = false;
export let checked: LayerTreeType;
let {
name,
node,
selected = '',
onselect = () => {},
multiple = false,
checked = $bindable({}),
}: {
name: string;
node: LayerTreeType;
selected?: string;
onselect?: (value: string) => void;
multiple: boolean;
checked: LayerTreeType;
} = $props();
const { customLayers } = settings;
beforeUpdate(() => {
$effect.pre(() => {
if (checked !== undefined) {
Object.keys(node).forEach((id) => {
if (!checked.hasOwnProperty(id)) {
@@ -46,7 +53,7 @@
value={id}
bind:checked={checked[id]}
class="scale-90"
aria-label={$_(`layers.label.${id}`)}
aria-label={i18n._(`layers.label.${id}`)}
/>
{:else}
<input
@@ -54,36 +61,48 @@
type="radio"
{name}
value={id}
bind:group={selected}
checked={selected === id}
oninput={(e) => {
if ((e.target as HTMLInputElement)?.checked) {
onselect(id);
}
}}
/>
{/if}
<Label for="{name}-{id}" class="flex flex-row items-center gap-1">
{#if $customLayers.hasOwnProperty(id)}
{$customLayers[id].name}
{#if customLayers.value.hasOwnProperty(id)}
{customLayers.value[id].name}
{:else}
{$_(`layers.label.${id}`)}
{i18n._(`layers.label.${id}`)}
{/if}
</Label>
</div>
{/if}
{:else if anySelectedLayer(node[id])}
<CollapsibleTreeNode {id}>
<span slot="trigger">{$_(`layers.label.${id}`)}</span>
<div slot="content">
<svelte:self
{#snippet trigger()}
<span>{i18n._(`layers.label.${id}`)}</span>
{/snippet}
{#snippet content()}
<div class="ml-2">
<Self
node={node[id]}
{name}
bind:selected
{selected}
{onselect}
{multiple}
bind:checked={checked[id]}
/>
</div>
{/snippet}
</CollapsibleTreeNode>
{/if}
{/each}
</div>
<style lang="postcss">
@reference "../../../../app.css";
div :global(input[type='radio']) {
@apply appearance-none;
@apply w-4 h-4;

View File

@@ -1,12 +1,12 @@
import { SphericalMercator } from '@mapbox/sphericalmercator';
import { getLayers } from './utils';
import { getLayers } from './utils.svelte';
import { get, writable } from 'svelte/store';
import { liveQuery } from 'dexie';
import { db, settings } from '$lib/db';
import { overpassQueryData } from '$lib/assets/layers';
import { MapPopup } from '$lib/components/MapPopup';
import { MapPopup } from '$lib/components/map/map.svelte';
const { currentOverpassQueries } = settings;
// const { currentOverpassQueries } = settings;
const mercator = new SphericalMercator({
size: 256,

View File

@@ -2,8 +2,8 @@
import * as Card from '$lib/components/ui/card';
import { Button } from '$lib/components/ui/button';
import { selection } from '$lib/components/file-list/Selection';
import { PencilLine, MapPin } from 'lucide-svelte';
import { _ } from '$lib/i18n';
import { PencilLine, MapPin } from '@lucide/svelte';
import { i18n } from '$lib/i18n.svelte';
import { dbUtils } from '$lib/db';
import type { PopupItem } from '$lib/components/MapPopup';
import { ScrollArea } from '$lib/components/ui/scroll-area/index.js';
@@ -18,7 +18,7 @@
if (tags.name !== undefined && tags.name !== '') {
name = tags.name;
} else {
name = $_(`layers.label.${poi.item.query}`);
name = i18n._(`layers.label.${poi.item.query}`);
}
}
@@ -101,7 +101,7 @@
on:click={addToFile}
>
<MapPin size="16" class="mr-1" />
{$_('toolbar.waypoint.add')}
{i18n._('toolbar.waypoint.add')}
</Button>
</Card.Content>
</Card.Root>

View File

@@ -55,4 +55,6 @@ export function toggle(node: LayerTreeType, id: string) {
return node;
}
export const customBasemapUpdate = writable(0);
export const customBasemapUpdate = $state({
value: 0,
});

View File

@@ -2,7 +2,6 @@ import mapboxgl, { type LayerSpecification, type VectorSourceSpecification } fro
import { Viewer, type ViewerBearingEvent } from 'mapillary-js/dist/mapillary.module';
import 'mapillary-js/dist/mapillary.css';
import { resetCursor, setPointerCursor } from '$lib/utils';
import type { Writable } from 'svelte/store';
const mapillarySource: VectorSourceSpecification = {
type: 'vector',
@@ -47,13 +46,13 @@ export class MapillaryLayer {
viewer: Viewer;
active = false;
popupOpen: Writable<boolean>;
popupOpen: { value: boolean };
addBinded = this.add.bind(this);
onMouseEnterBinded = this.onMouseEnter.bind(this);
onMouseLeaveBinded = this.onMouseLeave.bind(this);
constructor(map: mapboxgl.Map, container: HTMLElement, popupOpen: Writable<boolean>) {
constructor(map: mapboxgl.Map, container: HTMLElement, popupOpen: { value: boolean }) {
this.map = map;
this.viewer = new Viewer({
@@ -77,7 +76,7 @@ export class MapillaryLayer {
this.viewer.on('position', async () => {
if (this.active) {
popupOpen.set(true);
popupOpen.value = true;
let latLng = await this.viewer.getPosition();
this.marker.setLngLat(latLng).addTo(this.map);
if (!this.map.getBounds()?.contains(latLng)) {
@@ -126,13 +125,13 @@ export class MapillaryLayer {
}
this.marker.remove();
this.popupOpen.set(false);
this.popupOpen.value = false;
}
closePopup() {
this.active = false;
this.marker.remove();
this.popupOpen.set(false);
this.popupOpen.value = false;
}
onMouseEnter(e: mapboxgl.MapMouseEvent) {

View File

@@ -0,0 +1,79 @@
<script lang="ts">
import { streetViewEnabled } from '$lib/components/map/street-view-control/utils.svelte';
import { map } from '$lib/components/map/utils.svelte';
import CustomControl from '$lib/components/map/custom-control/CustomControl.svelte';
import Tooltip from '$lib/components/Tooltip.svelte';
import { Toggle } from '$lib/components/ui/toggle';
import { PersonStanding, X } from '@lucide/svelte';
import { MapillaryLayer } from './Mapillary';
import { GoogleRedirect } from './Google';
import { settings } from '$lib/logic/settings.svelte';
import { i18n } from '$lib/i18n.svelte';
import { onMount } from 'svelte';
const { streetViewSource } = settings;
let googleRedirect: GoogleRedirect | null = $state(null);
let mapillaryLayer: MapillaryLayer | null = $state(null);
let mapillaryOpen = $state({
value: false,
});
let container: HTMLElement;
onMount(() => {
map.onLoad((map: mapboxgl.Map) => {
googleRedirect = new GoogleRedirect(map);
mapillaryLayer = new MapillaryLayer(map, container, mapillaryOpen);
});
});
$effect(() => {
if (streetViewSource.value === 'mapillary') {
googleRedirect?.remove();
if (streetViewEnabled.current) {
mapillaryLayer?.add();
} else {
mapillaryLayer?.remove();
}
} else {
mapillaryLayer?.remove();
if (streetViewEnabled.current) {
googleRedirect?.add();
} else {
googleRedirect?.remove();
}
}
});
</script>
<CustomControl class="w-[29px] h-[29px] shrink-0">
<Tooltip class="w-full h-full" side="left" label={i18n._('menu.toggle_street_view')}>
<Toggle
bind:pressed={streetViewEnabled.current}
class="w-full h-full rounded p-0"
aria-label={i18n._('menu.toggle_street_view')}
>
<PersonStanding size="22" />
</Toggle>
</Tooltip>
</CustomControl>
<div
bind:this={container}
class="{mapillaryOpen.value
? ''
: 'hidden'} !absolute bottom-[44px] right-2.5 z-10 w-[40%] h-[40%] bg-background rounded-md overflow-hidden border-background border-2"
>
<!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="absolute top-0 right-0 z-10 bg-background p-1 rounded-bl-md cursor-pointer"
onclick={() => {
if (mapillaryLayer) {
mapillaryLayer.closePopup();
}
}}
>
<X size="16" />
</div>
</div>

View File

@@ -0,0 +1,3 @@
export const streetViewEnabled = $state({
current: false,
});

View File

@@ -0,0 +1,384 @@
import { TrackPoint, Waypoint, type Coordinates } from 'gpx';
import mapboxgl from 'mapbox-gl';
import { tick, mount } from 'svelte';
// import MapPopupComponent from '$lib/components/map/MapPopup.svelte';
import { get } from 'svelte/store';
// import { fileObservers } from '$lib/db';
import MapboxGeocoder from '@mapbox/mapbox-gl-geocoder';
let fitBoundsOptions: mapboxgl.MapOptions['fitBoundsOptions'] = {
maxZoom: 15,
linear: true,
easing: () => 1,
};
export class MapboxGLMap {
private _map: mapboxgl.Map | null = $state(null);
private _onLoadCallbacks: ((map: mapboxgl.Map) => void)[] = [];
init(
accessToken: string,
language: string,
distanceUnits: 'metric' | 'imperial' | 'nautical',
hash: boolean,
geocoder: boolean,
geolocate: boolean
) {
const map = new mapboxgl.Map({
container: 'map',
style: {
version: 8,
sources: {},
layers: [],
imports: [
{
id: 'glyphs-and-sprite', // make Mapbox glyphs and sprite available to other styles
url: '',
data: {
version: 8,
sources: {},
layers: [],
glyphs: 'mapbox://fonts/mapbox/{fontstack}/{range}.pbf',
sprite: `https://api.mapbox.com/styles/v1/mapbox/outdoors-v12/sprite?access_token=${accessToken}`,
},
},
{
id: 'basemap',
url: '',
},
{
id: 'overlays',
url: '',
data: {
version: 8,
sources: {},
layers: [],
},
},
],
},
projection: 'globe',
zoom: 0,
hash: hash,
language,
attributionControl: false,
logoPosition: 'bottom-right',
boxZoom: false,
});
map.addControl(
new mapboxgl.AttributionControl({
compact: true,
})
);
map.addControl(
new mapboxgl.NavigationControl({
visualizePitch: true,
})
);
if (geocoder) {
let geocoder = new MapboxGeocoder({
mapboxgl: mapboxgl,
enableEventLogging: false,
collapsed: true,
flyTo: fitBoundsOptions,
language,
localGeocoder: () => [],
localGeocoderOnly: true,
externalGeocoder: (query: string) =>
fetch(
`https://nominatim.openstreetmap.org/search?format=json&q=${query}&limit=5&accept-language=${language}`
)
.then((response) => response.json())
.then((data) => {
return data.map((result: any) => {
return {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [result.lon, result.lat],
},
place_name: result.display_name,
};
});
}),
});
let onKeyDown = geocoder._onKeyDown;
geocoder._onKeyDown = (e: KeyboardEvent) => {
// Trigger search on Enter key only
if (e.key === 'Enter') {
onKeyDown.apply(geocoder, [{ target: geocoder._inputEl }]);
} else if (geocoder._typeahead.data.length > 0) {
geocoder._typeahead.clear();
}
};
map.addControl(geocoder);
}
if (geolocate) {
map.addControl(
new mapboxgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true,
},
fitBoundsOptions,
trackUserLocation: true,
showUserHeading: true,
})
);
}
const scaleControl = new mapboxgl.ScaleControl({
unit: distanceUnits,
});
map.addControl(scaleControl);
map.on('style.load', () => {
map.addSource('mapbox-dem', {
type: 'raster-dem',
url: 'mapbox://mapbox.mapbox-terrain-dem-v1',
tileSize: 512,
maxzoom: 14,
});
if (map.getPitch() > 0) {
map.setTerrain({
source: 'mapbox-dem',
exaggeration: 1,
});
}
map.setFog({
color: 'rgb(186, 210, 235)',
'high-color': 'rgb(36, 92, 223)',
'horizon-blend': 0.1,
'space-color': 'rgb(156, 240, 255)',
});
map.on('pitch', () => {
if (map.getPitch() > 0) {
map.setTerrain({
source: 'mapbox-dem',
exaggeration: 1,
});
} else {
map.setTerrain(null);
}
});
});
map.on('load', () => {
this._map = map; // only set the store after the map has loaded
window._map = map; // entry point for extensions
scaleControl.setUnit(distanceUnits);
this._onLoadCallbacks.forEach((callback) => callback(map));
this._onLoadCallbacks = [];
});
}
onLoad(callback: (map: mapboxgl.Map) => void) {
if (this._map) {
callback(this._map);
} else {
this._onLoadCallbacks.push(callback);
}
}
destroy() {
if (this._map) {
this._map.remove();
this._map = null;
}
}
get value(): mapboxgl.Map | null {
return this._map;
}
resize() {
if (this._map) {
this._map.resize();
}
}
toggle3D() {
if (this._map) {
if (this._map.getPitch() === 0) {
this._map.easeTo({ pitch: 70 });
} else {
this._map.easeTo({ pitch: 0 });
}
}
}
}
export const map = new MapboxGLMap();
const targetMapBounds: {
bounds: mapboxgl.LngLatBounds;
ids: string[];
total: number;
} = $state({
bounds: new mapboxgl.LngLatBounds([180, 90, -180, -90]),
ids: [],
total: 0,
});
// $effect(() => {
// if (
// map.current === null ||
// targetMapBounds.ids.length > 0 ||
// (targetMapBounds.bounds.getSouth() === 90 &&
// targetMapBounds.bounds.getWest() === 180 &&
// targetMapBounds.bounds.getNorth() === -90 &&
// targetMapBounds.bounds.getEast() === -180)
// ) {
// return;
// }
// let currentZoom = map.current.getZoom();
// let currentBounds = map.current.getBounds();
// if (
// targetMapBounds.total !== get(fileObservers).size &&
// currentBounds &&
// currentZoom > 2 // Extend current bounds only if the map is zoomed in
// ) {
// // There are other files on the map
// if (
// currentBounds.contains(targetMapBounds.bounds.getSouthEast()) &&
// currentBounds.contains(targetMapBounds.bounds.getNorthWest())
// ) {
// return;
// }
// targetMapBounds.bounds.extend(currentBounds.getSouthWest());
// targetMapBounds.bounds.extend(currentBounds.getNorthEast());
// }
// map.current.fitBounds(targetMapBounds.bounds, { padding: 80, linear: true, easing: () => 1 });
// });
export function initTargetMapBounds(ids: string[]) {
targetMapBounds.bounds = new mapboxgl.LngLatBounds([180, 90, -180, -90]);
targetMapBounds.ids = ids;
targetMapBounds.total = ids.length;
}
export function updateTargetMapBounds(
id: string,
bounds: { southWest: Coordinates; northEast: Coordinates }
) {
if (targetMapBounds.ids.indexOf(id) === -1) {
return;
}
if (
bounds.southWest.lat !== 90 ||
bounds.southWest.lon !== 180 ||
bounds.northEast.lat !== -90 ||
bounds.northEast.lon !== -180
) {
// Avoid update for empty (new) files
targetMapBounds.ids = targetMapBounds.ids.filter((x) => x !== id);
targetMapBounds.bounds.extend(bounds.southWest);
targetMapBounds.bounds.extend(bounds.northEast);
}
}
// export function centerMapOnSelection() {
// let selected = get(selection).getSelected();
// let bounds = new mapboxgl.LngLatBounds();
// if (selected.find((item) => item instanceof ListWaypointItem)) {
// applyToOrderedSelectedItemsFromFile((fileId, level, items) => {
// let file = getFile(fileId);
// if (file) {
// items.forEach((item) => {
// if (item instanceof ListWaypointItem) {
// let waypoint = file.wpt[item.getWaypointIndex()];
// if (waypoint) {
// bounds.extend([waypoint.getLongitude(), waypoint.getLatitude()]);
// }
// }
// });
// }
// });
// } else {
// let selectionBounds = get(gpxStatistics).global.bounds;
// bounds.setNorthEast(selectionBounds.northEast);
// bounds.setSouthWest(selectionBounds.southWest);
// }
// get(map)?.fitBounds(bounds, {
// padding: 80,
// easing: () => 1,
// maxZoom: 15,
// });
// }
export type PopupItem<T = Waypoint | TrackPoint | any> = {
item: T;
fileId?: string;
hide?: () => void;
};
// export class MapPopup {
// map: mapboxgl.Map;
// popup: mapboxgl.Popup;
// item: PopupItem | null = $state(null);
// maybeHideBinded = this.maybeHide.bind(this);
// constructor(map: mapboxgl.Map, options?: mapboxgl.PopupOptions) {
// this.map = map;
// this.popup = new mapboxgl.Popup(options);
// let component = mount(MapPopupComponent, {
// target: document.body,
// props: {
// item: this.item,
// },
// });
// tick().then(() => this.popup.setDOMContent(component.container));
// }
// setItem(item: PopupItem | null) {
// if (item) item.hide = () => this.hide();
// this.item = item;
// if (item === null) {
// this.hide();
// } else {
// tick().then(() => this.show());
// }
// }
// show() {
// if (this.item === null) {
// this.hide();
// return;
// }
// this.popup.setLngLat(this.getCoordinates()).addTo(this.map);
// this.map.on('mousemove', this.maybeHideBinded);
// }
// maybeHide(e: mapboxgl.MapMouseEvent) {
// if (this.item === null) {
// this.hide();
// return;
// }
// if (this.map.project(this.getCoordinates()).dist(this.map.project(e.lngLat)) > 60) {
// this.hide();
// }
// }
// hide() {
// this.popup.remove();
// this.map.off('mousemove', this.maybeHideBinded);
// }
// remove() {
// this.popup.remove();
// }
// getCoordinates() {
// if (this.item === null) {
// return new mapboxgl.LngLat(0, 0);
// }
// return this.item.item instanceof Waypoint || this.item.item instanceof TrackPoint
// ? this.item.item.getCoordinates()
// : new mapboxgl.LngLat(this.item.item.lon, this.item.item.lat);
// }
// }

View File

@@ -1,74 +0,0 @@
<script lang="ts">
import CustomControl from '$lib/components/custom-control/CustomControl.svelte';
import Tooltip from '$lib/components/Tooltip.svelte';
import { Toggle } from '$lib/components/ui/toggle';
import { PersonStanding, X } from 'lucide-svelte';
import { MapillaryLayer } from './Mapillary';
import { GoogleRedirect } from './Google';
import { map, streetViewEnabled } from '$lib/stores';
import { settings } from '$lib/db';
import { _ } from '$lib/i18n';
import { writable } from 'svelte/store';
const { streetViewSource } = settings;
let googleRedirect: GoogleRedirect;
let mapillaryLayer: MapillaryLayer;
let mapillaryOpen = writable(false);
let container: HTMLElement;
$: if ($map) {
googleRedirect = new GoogleRedirect($map);
mapillaryLayer = new MapillaryLayer($map, container, mapillaryOpen);
}
$: if (mapillaryLayer) {
if ($streetViewSource === 'mapillary') {
googleRedirect.remove();
if ($streetViewEnabled) {
mapillaryLayer.add();
} else {
mapillaryLayer.remove();
}
} else {
mapillaryLayer.remove();
if ($streetViewEnabled) {
googleRedirect.add();
} else {
googleRedirect.remove();
}
}
}
</script>
<CustomControl class="w-[29px] h-[29px] shrink-0">
<Tooltip class="w-full h-full" side="left" label={$_('menu.toggle_street_view')}>
<Toggle
bind:pressed={$streetViewEnabled}
class="w-full h-full rounded p-0"
aria-label={$_('menu.toggle_street_view')}
>
<PersonStanding size="22" />
</Toggle>
</Tooltip>
</CustomControl>
<div
bind:this={container}
class="{$mapillaryOpen
? ''
: 'hidden'} !absolute bottom-[44px] right-2.5 z-10 w-[40%] h-[40%] bg-background rounded-md overflow-hidden border-background border-2"
>
<!-- svelte-ignore a11y-click-events-have-key-events -->
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div
class="absolute top-0 right-0 z-10 bg-background p-1 rounded-bl-md cursor-pointer"
on:click={() => {
if (mapillaryLayer) {
mapillaryLayer.closePopup();
}
}}
>
<X size="16" />
</div>
</div>

View File

@@ -1,6 +1,7 @@
<script lang="ts">
import { Tool } from '$lib/stores';
import ToolbarItem from './ToolbarItem.svelte';
import ToolbarItem from '$lib/components/toolbar/ToolbarItem.svelte';
import ToolbarItemMenu from '$lib/components/toolbar/ToolbarItemMenu.svelte';
import { Tool } from '$lib/components/toolbar/utils.svelte';
import {
Group,
CalendarClock,
@@ -8,47 +9,49 @@
SquareDashedMousePointer,
Ungroup,
MapPin,
Filter,
Funnel,
Scissors,
MountainSnow,
} from 'lucide-svelte';
} from '@lucide/svelte';
import { i18n } from '$lib/i18n.svelte';
import { _ } from '$lib/i18n';
import ToolbarItemMenu from './ToolbarItemMenu.svelte';
let props: {
class?: string;
} = $props();
</script>
<div class="flex flex-row w-full items-center pr-12">
<div
class="h-fit flex flex-col p-1 gap-1.5 bg-background rounded-r-md pointer-events-auto shadow-md {$$props.class ??
class="h-fit flex flex-col p-1 gap-1.5 bg-background rounded-r-md pointer-events-auto shadow-md {props.class ??
''}"
>
<ToolbarItem tool={Tool.ROUTING} label={$_('toolbar.routing.tooltip')}>
<Pencil slot="icon" size="18" />
<ToolbarItem itemTool={Tool.ROUTING} label={i18n._('toolbar.routing.tooltip')}>
<Pencil size="18" />
</ToolbarItem>
<ToolbarItem tool={Tool.WAYPOINT} label={$_('toolbar.waypoint.tooltip')}>
<MapPin slot="icon" size="18" />
<ToolbarItem itemTool={Tool.WAYPOINT} label={i18n._('toolbar.waypoint.tooltip')}>
<MapPin size="18" />
</ToolbarItem>
<ToolbarItem tool={Tool.SCISSORS} label={$_('toolbar.scissors.tooltip')}>
<Scissors slot="icon" size="18" />
<ToolbarItem itemTool={Tool.SCISSORS} label={i18n._('toolbar.scissors.tooltip')}>
<Scissors size="18" />
</ToolbarItem>
<ToolbarItem tool={Tool.TIME} label={$_('toolbar.time.tooltip')}>
<CalendarClock slot="icon" size="18" />
<ToolbarItem itemTool={Tool.TIME} label={i18n._('toolbar.time.tooltip')}>
<CalendarClock size="18" />
</ToolbarItem>
<ToolbarItem tool={Tool.MERGE} label={$_('toolbar.merge.tooltip')}>
<Group slot="icon" size="18" />
<ToolbarItem itemTool={Tool.MERGE} label={i18n._('toolbar.merge.tooltip')}>
<Group size="18" />
</ToolbarItem>
<ToolbarItem tool={Tool.EXTRACT} label={$_('toolbar.extract.tooltip')}>
<Ungroup slot="icon" size="18" />
<ToolbarItem itemTool={Tool.EXTRACT} label={i18n._('toolbar.extract.tooltip')}>
<Ungroup size="18" />
</ToolbarItem>
<ToolbarItem tool={Tool.ELEVATION} label={$_('toolbar.elevation.button')}>
<MountainSnow slot="icon" size="18" />
<ToolbarItem itemTool={Tool.ELEVATION} label={i18n._('toolbar.elevation.button')}>
<MountainSnow size="18" />
</ToolbarItem>
<ToolbarItem tool={Tool.REDUCE} label={$_('toolbar.reduce.tooltip')}>
<Filter slot="icon" size="18" />
<ToolbarItem itemTool={Tool.REDUCE} label={i18n._('toolbar.reduce.tooltip')}>
<Funnel size="18" />
</ToolbarItem>
<ToolbarItem tool={Tool.CLEAN} label={$_('toolbar.clean.tooltip')}>
<SquareDashedMousePointer slot="icon" size="18" />
<ToolbarItem itemTool={Tool.CLEAN} label={i18n._('toolbar.clean.tooltip')}>
<SquareDashedMousePointer size="18" />
</ToolbarItem>
</div>
<ToolbarItemMenu class={$$props.class ?? ''} />
<ToolbarItemMenu class={props.class ?? ''} />
</div>

View File

@@ -1,29 +1,45 @@
<script lang="ts">
import { Button } from '$lib/components/ui/button';
import * as Tooltip from '$lib/components/ui/tooltip/index.js';
import { currentTool, type Tool } from '$lib/stores';
import { tool, Tool } from '$lib/components/toolbar/utils.svelte';
import type { Snippet } from 'svelte';
export let tool: Tool;
export let label: string;
let {
itemTool,
label,
children,
}: {
itemTool: Tool;
label: string;
children: Snippet;
} = $props();
function toggleTool() {
currentTool.update((current) => (current === tool ? null : tool));
if (tool.current === itemTool) {
tool.current = null;
} else {
tool.current = itemTool;
}
}
</script>
<Tooltip.Root openDelay={300}>
<Tooltip.Trigger asChild let:builder>
<Tooltip.Provider>
<Tooltip.Root delayDuration={300}>
<Tooltip.Trigger>
{#snippet child({ props })}
<Button
builders={[builder]}
{...props}
variant="ghost"
class="h-[26px] px-1 py-1.5 {$currentTool === tool ? 'bg-accent' : ''}"
on:click={toggleTool}
class="h-[26px] px-1 py-1.5 {tool.current === itemTool ? 'bg-accent' : ''}"
onclick={toggleTool}
aria-label={label}
>
<slot name="icon" />
{@render children()}
</Button>
{/snippet}
</Tooltip.Trigger>
<Tooltip.Content side="right">
<span>{label}</span>
</Tooltip.Content>
</Tooltip.Root>
</Tooltip.Provider>

View File

@@ -1,7 +1,6 @@
<script lang="ts">
import { Tool, currentTool } from '$lib/stores';
import { Tool, tool } from '$lib/components/toolbar/utils.svelte';
import { settings } from '$lib/db';
import { flyAndScale } from '$lib/utils';
import * as Card from '$lib/components/ui/card';
import Routing from '$lib/components/toolbar/tools/routing/Routing.svelte';
import Scissors from '$lib/components/toolbar/tools/scissors/Scissors.svelte';
@@ -31,31 +30,28 @@
});
</script>
{#if $currentTool !== null}
<div
in:flyAndScale={{ x: -2, y: 0, duration: 100 }}
class="translate-x-1 h-full {$$props.class ?? ''}"
>
{#if tool.current !== null}
<div class="translate-x-1 h-full animate-in animate-out {$$props.class ?? ''}">
<div class="rounded-md shadow-md pointer-events-auto">
<Card.Root class="rounded-md border-none">
<Card.Content class="p-2.5">
{#if $currentTool === Tool.ROUTING}
{#if tool.current === Tool.ROUTING}
<Routing {popup} {popupElement} bind:minimized={$minimizeRoutingMenu} />
{:else if $currentTool === Tool.SCISSORS}
{:else if tool.current === Tool.SCISSORS}
<Scissors />
{:else if $currentTool === Tool.WAYPOINT}
{:else if tool.current === Tool.WAYPOINT}
<Waypoint />
{:else if $currentTool === Tool.TIME}
{:else if tool.current === Tool.TIME}
<Time />
{:else if $currentTool === Tool.MERGE}
{:else if tool.current === Tool.MERGE}
<Merge />
{:else if $currentTool === Tool.ELEVATION}
{:else if tool.current === Tool.ELEVATION}
<Elevation />
{:else if $currentTool === Tool.EXTRACT}
{:else if tool.current === Tool.EXTRACT}
<Extract />
{:else if $currentTool === Tool.CLEAN}
{:else if tool.current === Tool.CLEAN}
<Clean />
{:else if $currentTool === Tool.REDUCE}
{:else if tool.current === Tool.REDUCE}
<Reduce />
{/if}
</Card.Content>
@@ -66,8 +62,8 @@
<svelte:window
on:keydown={(e) => {
if ($currentTool !== null && e.key === 'Escape') {
currentTool.set(null);
if (tool.current !== null && e.key === 'Escape') {
tool.current = null;
}
}}
/>

View File

@@ -11,13 +11,14 @@
import * as RadioGroup from '$lib/components/ui/radio-group';
import { Button } from '$lib/components/ui/button';
import Help from '$lib/components/Help.svelte';
import { _, locale } from '$lib/i18n';
import { i18n } from '$lib/i18n.svelte';
import { onDestroy, onMount } from 'svelte';
import { getURLForLanguage, resetCursor, setCrosshairCursor } from '$lib/utils';
import { Trash2 } from 'lucide-svelte';
import { map } from '$lib/stores';
import { Trash2 } from '@lucide/svelte';
import { map } from '$lib/components/map/map.svelte';
import { selection } from '$lib/components/file-list/Selection';
import { dbUtils } from '$lib/db';
import type { GeoJSONSource } from 'mapbox-gl';
let cleanType = CleanType.INSIDE;
let deleteTrackpoints = true;
@@ -25,13 +26,13 @@
let rectangleCoordinates: mapboxgl.LngLat[] = [];
function updateRectangle() {
if ($map) {
if (map.current) {
if (rectangleCoordinates.length != 2) {
if ($map.getLayer('rectangle')) {
$map.removeLayer('rectangle');
if (map.current.getLayer('rectangle')) {
map.current.removeLayer('rectangle');
}
} else {
let data = {
let data: GeoJSON.Feature = {
type: 'Feature',
geometry: {
type: 'Polygon',
@@ -45,18 +46,19 @@
],
],
},
properties: {},
};
let source = $map.getSource('rectangle');
let source: GeoJSONSource | undefined = map.current.getSource('rectangle');
if (source) {
source.setData(data);
} else {
$map.addSource('rectangle', {
map.current.addSource('rectangle', {
type: 'geojson',
data: data,
});
}
if (!$map.getLayer('rectangle')) {
$map.addLayer({
if (!map.current.getLayer('rectangle')) {
map.current.addLayer({
id: 'rectangle',
type: 'fill',
source: 'rectangle',
@@ -91,35 +93,34 @@
}
onMount(() => {
setCrosshairCursor();
if (map.current) {
setCrosshairCursor(map.current.getCanvas());
map.current.on('mousedown', onMouseDown);
map.current.on('mousemove', onMouseMove);
map.current.on('mouseup', onMouseUp);
map.current.on('touchstart', onMouseDown);
map.current.on('touchmove', onMouseMove);
map.current.on('touchend', onMouseUp);
map.current.dragPan.disable();
}
});
$: if ($map) {
$map.on('mousedown', onMouseDown);
$map.on('mousemove', onMouseMove);
$map.on('mouseup', onMouseUp);
$map.on('touchstart', onMouseDown);
$map.on('touchmove', onMouseMove);
$map.on('touchend', onMouseUp);
$map.dragPan.disable();
}
onDestroy(() => {
resetCursor();
if ($map) {
$map.off('mousedown', onMouseDown);
$map.off('mousemove', onMouseMove);
$map.off('mouseup', onMouseUp);
$map.off('touchstart', onMouseDown);
$map.off('touchmove', onMouseMove);
$map.off('touchend', onMouseUp);
$map.dragPan.enable();
if (map.current) {
resetCursor(map.current.getCanvas());
map.current.off('mousedown', onMouseDown);
map.current.off('mousemove', onMouseMove);
map.current.off('mouseup', onMouseUp);
map.current.off('touchstart', onMouseDown);
map.current.off('touchmove', onMouseMove);
map.current.off('touchend', onMouseUp);
map.current.dragPan.enable();
if ($map.getLayer('rectangle')) {
$map.removeLayer('rectangle');
if (map.current.getLayer('rectangle')) {
map.current.removeLayer('rectangle');
}
if ($map.getSource('rectangle')) {
$map.removeSource('rectangle');
if (map.current.getSource('rectangle')) {
map.current.removeSource('rectangle');
}
}
});
@@ -132,23 +133,23 @@
<div class="flex flex-row items-center gap-[6.4px] h-3">
<Checkbox id="delete-trkpt" bind:checked={deleteTrackpoints} class="scale-90" />
<Label for="delete-trkpt">
{$_('toolbar.clean.delete_trackpoints')}
{i18n._('toolbar.clean.delete_trackpoints')}
</Label>
</div>
<div class="flex flex-row items-center gap-[6.4px] h-3">
<Checkbox id="delete-wpt" bind:checked={deleteWaypoints} class="scale-90" />
<Label for="delete-wpt">
{$_('toolbar.clean.delete_waypoints')}
{i18n._('toolbar.clean.delete_waypoints')}
</Label>
</div>
<RadioGroup.Root bind:value={cleanType}>
<Label class="flex flex-row items-center gap-2">
<RadioGroup.Item value={CleanType.INSIDE} />
{$_('toolbar.clean.delete_inside')}
{i18n._('toolbar.clean.delete_inside')}
</Label>
<Label class="flex flex-row items-center gap-2">
<RadioGroup.Item value={CleanType.OUTSIDE} />
{$_('toolbar.clean.delete_outside')}
{i18n._('toolbar.clean.delete_outside')}
</Label>
</RadioGroup.Root>
</fieldset>
@@ -156,7 +157,7 @@
variant="outline"
class="w-full"
disabled={!validSelection || rectangleCoordinates.length != 2}
on:click={() => {
onclick={() => {
dbUtils.cleanSelection(
[
{
@@ -176,13 +177,13 @@
}}
>
<Trash2 size="16" class="mr-1" />
{$_('toolbar.clean.button')}
{i18n._('toolbar.clean.button')}
</Button>
<Help link={getURLForLanguage($locale, '/help/toolbar/clean')}>
<Help link={getURLForLanguage(i18n.lang, '/help/toolbar/clean')}>
{#if validSelection}
{$_('toolbar.clean.help')}
{i18n._('toolbar.clean.help')}
{:else}
{$_('toolbar.clean.help_no_selection')}
{i18n._('toolbar.clean.help_no_selection')}
{/if}
</Help>
</div>

View File

@@ -2,34 +2,38 @@
import { Button } from '$lib/components/ui/button';
import { selection } from '$lib/components/file-list/Selection';
import Help from '$lib/components/Help.svelte';
import { MountainSnow } from 'lucide-svelte';
import { MountainSnow } from '@lucide/svelte';
import { dbUtils } from '$lib/db';
import { map } from '$lib/stores';
import { _, locale } from '$lib/i18n';
import { map } from '$lib/components/map/map.svelte';
import { i18n } from '$lib/i18n.svelte';
import { getURLForLanguage } from '$lib/utils';
$: validSelection = $selection.size > 0;
let props: {
class?: string;
} = $props();
let validSelection = $derived($selection.size > 0);
</script>
<div class="flex flex-col gap-3 w-full max-w-80 {$$props.class ?? ''}">
<div class="flex flex-col gap-3 w-full max-w-80 {props.class ?? ''}">
<Button
variant="outline"
class="whitespace-normal h-fit"
disabled={!validSelection}
on:click={async () => {
if ($map) {
dbUtils.addElevationToSelection($map);
onclick={async () => {
if (map.current) {
dbUtils.addElevationToSelection(map.current);
}
}}
>
<MountainSnow size="16" class="mr-1 shrink-0" />
{$_('toolbar.elevation.button')}
{i18n._('toolbar.elevation.button')}
</Button>
<Help link={getURLForLanguage($locale, '/help/toolbar/elevation')}>
<Help link={getURLForLanguage(i18n.lang, '/help/toolbar/elevation')}>
{#if validSelection}
{$_('toolbar.elevation.help')}
{i18n._('toolbar.elevation.help')}
{:else}
{$_('toolbar.elevation.help_no_selection')}
{i18n._('toolbar.elevation.help_no_selection')}
{/if}
</Help>
</div>

View File

@@ -1,6 +1,6 @@
<script lang="ts">
import { Button } from '$lib/components/ui/button';
import { Ungroup } from 'lucide-svelte';
import { Ungroup } from '@lucide/svelte';
import { selection } from '$lib/components/file-list/Selection';
import {
ListFileItem,
@@ -11,7 +11,7 @@
} from '$lib/components/file-list/FileList';
import Help from '$lib/components/Help.svelte';
import { dbUtils, getFile } from '$lib/db';
import { _, locale } from '$lib/i18n';
import { i18n } from '$lib/i18n.svelte';
import { getURLForLanguage } from '$lib/utils';
$: validSelection =
@@ -39,15 +39,15 @@
</script>
<div class="flex flex-col gap-3 w-full max-w-80 {$$props.class ?? ''}">
<Button variant="outline" disabled={!validSelection} on:click={dbUtils.extractSelection}>
<Button variant="outline" disabled={!validSelection} onclick={dbUtils.extractSelection}>
<Ungroup size="16" class="mr-1" />
{$_('toolbar.extract.button')}
{i18n._('toolbar.extract.button')}
</Button>
<Help link={getURLForLanguage($locale, '/help/toolbar/extract')}>
<Help link={getURLForLanguage(i18n.lang, '/help/toolbar/extract')}>
{#if validSelection}
{$_('toolbar.extract.help')}
{i18n._('toolbar.extract.help')}
{:else}
{$_('toolbar.extract.help_invalid_selection')}
{i18n._('toolbar.extract.help_invalid_selection')}
{/if}
</Help>
</div>

View File

@@ -13,9 +13,9 @@
import { Label } from '$lib/components/ui/label/index.js';
import { Checkbox } from '$lib/components/ui/checkbox';
import * as RadioGroup from '$lib/components/ui/radio-group';
import { _, locale } from '$lib/i18n';
import { i18n } from '$lib/i18n.svelte';
import { dbUtils, getFile } from '$lib/db';
import { Group } from 'lucide-svelte';
import { Group } from '@lucide/svelte';
import { getURLForLanguage } from '$lib/utils';
import Shortcut from '$lib/components/Shortcut.svelte';
import { gpxStatistics } from '$lib/stores';
@@ -61,17 +61,17 @@
<RadioGroup.Root bind:value={mergeType}>
<Label class="flex flex-row items-center gap-1.5 leading-5">
<RadioGroup.Item value={MergeType.TRACES} />
{$_('toolbar.merge.merge_traces')}
{i18n._('toolbar.merge.merge_traces')}
</Label>
<Label class="flex flex-row items-center gap-1.5 leading-5">
<RadioGroup.Item value={MergeType.CONTENTS} />
{$_('toolbar.merge.merge_contents')}
{i18n._('toolbar.merge.merge_contents')}
</Label>
</RadioGroup.Root>
{#if mergeType === MergeType.TRACES && $gpxStatistics.global.time.total > 0}
<div class="flex flex-row items-center gap-1.5">
<Checkbox id="remove-gaps" bind:checked={removeGaps} />
<Label for="remove-gaps">{$_('toolbar.merge.remove_gaps')}</Label>
<Label for="remove-gaps">{i18n._('toolbar.merge.remove_gaps')}</Label>
</div>
{/if}
<Button
@@ -79,7 +79,7 @@
class="whitespace-normal h-fit"
disabled={(mergeType === MergeType.TRACES && !canMergeTraces) ||
(mergeType === MergeType.CONTENTS && !canMergeContents)}
on:click={() => {
onclick={() => {
dbUtils.mergeSelection(
mergeType === MergeType.TRACES,
mergeType === MergeType.TRACES && $gpxStatistics.global.time.total > 0 && removeGaps
@@ -87,31 +87,31 @@
}}
>
<Group size="16" class="mr-1 shrink-0" />
{$_('toolbar.merge.merge_selection')}
{i18n._('toolbar.merge.merge_selection')}
</Button>
<Help link={getURLForLanguage($locale, '/help/toolbar/merge')}>
<Help link={getURLForLanguage(i18n.lang, '/help/toolbar/merge')}>
{#if mergeType === MergeType.TRACES && canMergeTraces}
{$_('toolbar.merge.help_merge_traces')}
{i18n._('toolbar.merge.help_merge_traces')}
{:else if mergeType === MergeType.TRACES && !canMergeTraces}
{$_('toolbar.merge.help_cannot_merge_traces')}
{$_('toolbar.merge.selection_tip').split('{KEYBOARD_SHORTCUT}')[0]}
{i18n._('toolbar.merge.help_cannot_merge_traces')}
{i18n._('toolbar.merge.selection_tip').split('{KEYBOARD_SHORTCUT}')[0]}
<Shortcut
ctrl={true}
click={true}
class="inline-flex text-muted-foreground text-xs border rounded p-0.5 gap-0"
/>
{$_('toolbar.merge.selection_tip').split('{KEYBOARD_SHORTCUT}')[1]}
{i18n._('toolbar.merge.selection_tip').split('{KEYBOARD_SHORTCUT}')[1]}
{:else if mergeType === MergeType.CONTENTS && canMergeContents}
{$_('toolbar.merge.help_merge_contents')}
{i18n._('toolbar.merge.help_merge_contents')}
{:else if mergeType === MergeType.CONTENTS && !canMergeContents}
{$_('toolbar.merge.help_cannot_merge_contents')}
{$_('toolbar.merge.selection_tip').split('{KEYBOARD_SHORTCUT}')[0]}
{i18n._('toolbar.merge.help_cannot_merge_contents')}
{i18n._('toolbar.merge.selection_tip').split('{KEYBOARD_SHORTCUT}')[0]}
<Shortcut
ctrl={true}
click={true}
class="inline-flex text-muted-foreground text-xs border rounded p-0.5 gap-0"
/>
{$_('toolbar.merge.selection_tip').split('{KEYBOARD_SHORTCUT}')[1]}
{i18n._('toolbar.merge.selection_tip').split('{KEYBOARD_SHORTCUT}')[1]}
{/if}
</Help>
</div>

View File

@@ -9,26 +9,30 @@
ListTrackSegmentItem,
} from '$lib/components/file-list/FileList';
import Help from '$lib/components/Help.svelte';
import { Filter } from 'lucide-svelte';
import { _, locale } from '$lib/i18n';
import { Funnel } from '@lucide/svelte';
import { i18n } from '$lib/i18n.svelte';
import WithUnits from '$lib/components/WithUnits.svelte';
import { dbUtils, fileObservers } from '$lib/db';
import { map } from '$lib/stores';
import { map } from '$lib/components/map/map.svelte';
import { onDestroy } from 'svelte';
import { ramerDouglasPeucker, TrackPoint, type SimplifiedTrackPoint } from 'gpx';
import { derived } from 'svelte/store';
import { getURLForLanguage } from '$lib/utils';
import type { GeoJSONSource } from 'mapbox-gl';
let sliderValue = [50];
let maxPoints = 0;
let currentPoints = 0;
let props: { class?: string } = $props();
let sliderValue = $state([50]);
let maxPoints = $state(0);
let currentPoints = $state(0);
const minTolerance = 0.1;
const maxTolerance = 10000;
$: validSelection = $selection.hasAnyChildren(new ListRootItem(), true, ['waypoints']);
$: tolerance =
minTolerance * 2 ** (sliderValue[0] / (100 / Math.log2(maxTolerance / minTolerance)));
let validSelection = $derived(
$selection.hasAnyChildren(new ListRootItem(), true, ['waypoints'])
);
let tolerance = $derived(
minTolerance * 2 ** (sliderValue[0] / (100 / Math.log2(maxTolerance / minTolerance)))
);
let simplified = new Map<string, [ListItem, number, SimplifiedTrackPoint[]]>();
let unsubscribes = new Map<string, () => void>();
@@ -63,18 +67,18 @@
});
});
if ($map) {
let source = $map.getSource('simplified');
if (map.current) {
let source: GeoJSONSource | undefined = map.current.getSource('simplified');
if (source) {
source.setData(data);
} else {
$map.addSource('simplified', {
map.current.addSource('simplified', {
type: 'geojson',
data: data,
});
}
if (!$map.getLayer('simplified')) {
$map.addLayer({
if (!map.current.getLayer('simplified')) {
map.current.addLayer({
id: 'simplified',
type: 'line',
source: 'simplified',
@@ -84,12 +88,13 @@
},
});
} else {
$map.moveLayer('simplified');
map.current.moveLayer('simplified');
}
}
}
$: if ($fileObservers) {
$effect(() => {
if ($fileObservers) {
unsubscribes.forEach((unsubscribe, fileId) => {
if (!$fileObservers.has(fileId)) {
unsubscribe();
@@ -128,18 +133,21 @@
}
});
}
});
$: if (tolerance) {
$effect(() => {
if (tolerance) {
update();
}
});
onDestroy(() => {
if ($map) {
if ($map.getLayer('simplified')) {
$map.removeLayer('simplified');
if (map.current) {
if (map.current.getLayer('simplified')) {
map.current.removeLayer('simplified');
}
if ($map.getSource('simplified')) {
$map.removeSource('simplified');
if (map.current.getSource('simplified')) {
map.current.removeSource('simplified');
}
}
unsubscribes.forEach((unsubscribe) => unsubscribe());
@@ -160,28 +168,28 @@
}
</script>
<div class="flex flex-col gap-3 w-full max-w-80 {$$props.class ?? ''}">
<div class="flex flex-col gap-3 w-full max-w-80 {props.class ?? ''}">
<div class="p-2">
<Slider bind:value={sliderValue} min={0} max={100} step={1} />
<Slider bind:value={sliderValue} min={0} max={100} step={1} type="multiple" />
</div>
<Label class="flex flex-row justify-between">
<span>{$_('toolbar.reduce.tolerance')}</span>
<span>{i18n._('toolbar.reduce.tolerance')}</span>
<WithUnits value={tolerance / 1000} type="distance" decimals={4} class="font-normal" />
</Label>
<Label class="flex flex-row justify-between">
<span>{$_('toolbar.reduce.number_of_points')}</span>
<span>{i18n._('toolbar.reduce.number_of_points')}</span>
<span class="font-normal">{currentPoints}/{maxPoints}</span>
</Label>
<Button variant="outline" disabled={!validSelection} on:click={reduce}>
<Filter size="16" class="mr-1" />
{$_('toolbar.reduce.button')}
<Button variant="outline" disabled={!validSelection} onclick={reduce}>
<Funnel size="16" class="mr-1" />
{i18n._('toolbar.reduce.button')}
</Button>
<Help link={getURLForLanguage($locale, '/help/toolbar/minify')}>
<Help link={getURLForLanguage(i18n.lang, '/help/toolbar/minify')}>
{#if validSelection}
{$_('toolbar.reduce.help')}
{i18n._('toolbar.reduce.help')}
{:else}
{$_('toolbar.reduce.help_no_selection')}
{i18n._('toolbar.reduce.help_no_selection')}
{/if}
</Help>
</div>

View File

@@ -14,10 +14,9 @@
nauticalMilesToKilometers,
} from '$lib/units';
import { CalendarDate, type DateValue } from '@internationalized/date';
import { CalendarClock, CirclePlay, CircleStop, CircleX, Timer, Zap } from 'lucide-svelte';
import { CalendarClock, CirclePlay, CircleStop, CircleX, Timer, Zap } from '@lucide/svelte';
import { tick } from 'svelte';
import { _, locale } from '$lib/i18n';
import { get } from 'svelte/store';
import { i18n } from '$lib/i18n.svelte';
import { selection } from '$lib/components/file-list/Selection';
import {
ListFileItem,
@@ -183,9 +182,9 @@
<Label for="speed" class="flex flex-row">
<Zap size="16" class="mr-1" />
{#if $velocityUnits === 'speed'}
{$_('quantities.speed')}
{i18n._('quantities.speed')}
{:else}
{$_('quantities.pace')}
{i18n._('quantities.pace')}
{/if}
</Label>
<div class="flex flex-row gap-1 items-center">
@@ -197,15 +196,15 @@
min={0.01}
disabled={!canUpdate}
bind:value={speed}
on:change={updateDataFromSpeed}
onchange={updateDataFromSpeed}
/>
<span class="text-sm shrink-0">
{#if $distanceUnits === 'imperial'}
{$_('units.miles_per_hour')}
{i18n._('units.miles_per_hour')}
{:else if $distanceUnits === 'metric'}
{$_('units.kilometers_per_hour')}
{i18n._('units.kilometers_per_hour')}
{:else if $distanceUnits === 'nautical'}
{$_('units.knots')}
{i18n._('units.knots')}
{/if}
</span>
{:else}
@@ -217,11 +216,11 @@
/>
<span class="text-sm shrink-0">
{#if $distanceUnits === 'imperial'}
{$_('units.minutes_per_mile')}
{i18n._('units.minutes_per_mile')}
{:else if $distanceUnits === 'metric'}
{$_('units.minutes_per_kilometer')}
{i18n._('units.minutes_per_kilometer')}
{:else if $distanceUnits === 'nautical'}
{$_('units.minutes_per_nautical_mile')}
{i18n._('units.minutes_per_nautical_mile')}
{/if}
</span>
{/if}
@@ -230,7 +229,7 @@
<div class="flex flex-col gap-2 grow">
<Label for="duration" class="flex flex-row">
<Timer size="16" class="mr-1" />
{$_('toolbar.time.total_time')}
{i18n._('toolbar.time.total_time')}
</Label>
<TimePicker
bind:value={movingTime}
@@ -241,14 +240,14 @@
</div>
<Label class="flex flex-row">
<CirclePlay size="16" class="mr-1" />
{$_('toolbar.time.start')}
{i18n._('toolbar.time.start')}
</Label>
<div class="flex flex-row gap-2">
<DatePicker
bind:value={startDate}
disabled={!canUpdate}
locale={get(locale) ?? 'en'}
placeholder={$_('toolbar.time.pick_date')}
locale={i18n.lang}
placeholder={i18n._('toolbar.time.pick_date')}
class="w-fit grow"
onValueChange={async () => {
await tick();
@@ -266,14 +265,14 @@
</div>
<Label class="flex flex-row">
<CircleStop size="16" class="mr-1" />
{$_('toolbar.time.end')}
{i18n._('toolbar.time.end')}
</Label>
<div class="flex flex-row gap-2">
<DatePicker
bind:value={endDate}
disabled={!canUpdate}
locale={get(locale) ?? 'en'}
placeholder={$_('toolbar.time.pick_date')}
locale={i18n.lang}
placeholder={i18n._('toolbar.time.pick_date')}
class="w-fit grow"
onValueChange={async () => {
await tick();
@@ -293,7 +292,7 @@
<div class="mt-0.5 flex flex-row gap-1 items-center">
<Checkbox id="artificial-time" bind:checked={artificial} disabled={!canUpdate} />
<Label for="artificial-time">
{$_('toolbar.time.artificial')}
{i18n._('toolbar.time.artificial')}
</Label>
</div>
{/if}
@@ -303,7 +302,7 @@
variant="outline"
disabled={!canUpdate}
class="grow whitespace-normal h-fit"
on:click={() => {
onclick={() => {
let effectiveSpeed = getSpeed();
if (
startDate === undefined ||
@@ -378,22 +377,24 @@
}}
>
<CalendarClock size="16" class="mr-1 shrink-0" />
{$_('toolbar.time.update')}
{i18n._('toolbar.time.update')}
</Button>
<Button variant="outline" on:click={setGPXData}>
<Button variant="outline" onclick={setGPXData}>
<CircleX size="16" />
</Button>
</div>
<Help link={getURLForLanguage($locale, '/help/toolbar/time')}>
<Help link={getURLForLanguage(i18n.lang, '/help/toolbar/time')}>
{#if canUpdate}
{$_('toolbar.time.help')}
{i18n._('toolbar.time.help')}
{:else}
{$_('toolbar.time.help_invalid_selection')}
{i18n._('toolbar.time.help_invalid_selection')}
{/if}
</Help>
</div>
<style lang="postcss">
@reference "../../../../app.css";
div :global(input[type='time']) {
/*
Style copy-pasted from shadcn-svelte Input.

View File

@@ -12,7 +12,7 @@
import * as Select from '$lib/components/ui/select';
import { selection } from '$lib/components/file-list/Selection';
import { Waypoint } from 'gpx';
import { _, locale } from '$lib/i18n';
import { i18n } from '$lib/i18n.svelte';
import { ListWaypointItem } from '$lib/components/file-list/FileList';
import { dbUtils, fileObservers, getFile, settings, type GPXFileWithStatistics } from '$lib/db';
import { get } from 'svelte/store';
@@ -20,7 +20,7 @@
import { onDestroy, onMount } from 'svelte';
import { map } from '$lib/stores';
import { getURLForLanguage, resetCursor, setCrosshairCursor } from '$lib/utils';
import { MapPin, CircleX, Save } from 'lucide-svelte';
import { MapPin, CircleX, Save } from '@lucide/svelte';
import { getSymbolKey, symbols } from '$lib/assets/symbols';
let name: string;
@@ -28,11 +28,7 @@
let link: string;
let longitude: number;
let latitude: number;
let selectedSymbol = {
value: '',
label: '',
};
let symbolKey: string;
const { treeFileView } = settings;
@@ -70,18 +66,7 @@
}
link = $selectedWaypoint[0].link?.attributes?.href ?? '';
let symbol = $selectedWaypoint[0].sym ?? '';
let symbolKey = getSymbolKey(symbol);
if (symbolKey) {
selectedSymbol = {
value: symbol,
label: $_(`gpx.symbol.${symbolKey}`),
};
} else {
selectedSymbol = {
value: symbol,
label: '',
};
}
symbolKey = getSymbolKey(symbol) ?? symbol ?? '';
longitude = parseFloat($selectedWaypoint[0].getLongitude().toFixed(6));
latitude = parseFloat($selectedWaypoint[0].getLatitude().toFixed(6));
} else {
@@ -97,10 +82,7 @@
name = '';
description = '';
link = '';
selectedSymbol = {
value: '',
label: '',
};
symbolKey = '';
longitude = 0;
latitude = 0;
}
@@ -140,7 +122,7 @@
desc: description.length > 0 ? description : undefined,
cmt: description.length > 0 ? description : undefined,
link: link.length > 0 ? { attributes: { href: link } } : undefined,
sym: selectedSymbol.value.length > 0 ? selectedSymbol.value : undefined,
sym: symbols[symbolKey]?.value ?? '',
},
$selectedWaypoint
? new ListWaypointItem($selectedWaypoint[1], $selectedWaypoint[0]._data.index)
@@ -157,7 +139,7 @@
}
$: sortedSymbols = Object.entries(symbols).sort((a, b) => {
return $_(`gpx.symbol.${a[0]}`).localeCompare($_(`gpx.symbol.${b[0]}`), $locale ?? 'en');
return i18n._(`gpx.symbol.${a[0]}`).localeCompare(i18n._(`gpx.symbol.${b[0]}`), i18n.lang);
});
onMount(() => {
@@ -180,27 +162,31 @@
<div class="flex flex-col gap-3 w-full max-w-96 {$$props.class ?? ''}">
<fieldset class="flex flex-col gap-2">
<Label for="name">{$_('menu.metadata.name')}</Label>
<Label for="name">{i18n._('menu.metadata.name')}</Label>
<Input
bind:value={name}
id="name"
class="font-semibold h-8"
disabled={!canCreate && !$selectedWaypoint}
/>
<Label for="description">{$_('menu.metadata.description')}</Label>
<Label for="description">{i18n._('menu.metadata.description')}</Label>
<Textarea
bind:value={description}
id="description"
disabled={!canCreate && !$selectedWaypoint}
/>
<Label for="symbol">{$_('toolbar.waypoint.icon')}</Label>
<Select.Root bind:selected={selectedSymbol}>
<Label for="symbol">{i18n._('toolbar.waypoint.icon')}</Label>
<Select.Root bind:value={symbolKey} type="single">
<Select.Trigger
id="symbol"
class="w-full h-8"
disabled={!canCreate && !$selectedWaypoint}
>
<Select.Value />
{#if symbolKey in symbols}
{i18n._(`gpx.symbol.${symbolKey}`)}
{:else}
{symbolKey}
{/if}
</Select.Trigger>
<Select.Content class="max-h-60 overflow-y-scroll">
{#each sortedSymbols as [key, symbol]}
@@ -215,13 +201,13 @@
{:else}
<span class="w-4 inline-block"></span>
{/if}
{$_(`gpx.symbol.${key}`)}
{i18n._(`gpx.symbol.${key}`)}
</span>
</Select.Item>
{/each}
</Select.Content>
</Select.Root>
<Label for="link">{$_('toolbar.waypoint.link')}</Label>
<Label for="link">{i18n._('toolbar.waypoint.link')}</Label>
<Input
bind:value={link}
id="link"
@@ -230,7 +216,7 @@
/>
<div class="flex flex-row gap-2">
<div class="grow">
<Label for="latitude">{$_('toolbar.waypoint.latitude')}</Label>
<Label for="latitude">{i18n._('toolbar.waypoint.latitude')}</Label>
<Input
bind:value={latitude}
type="number"
@@ -243,7 +229,7 @@
/>
</div>
<div class="grow">
<Label for="longitude">{$_('toolbar.waypoint.longitude')}</Label>
<Label for="longitude">{i18n._('toolbar.waypoint.longitude')}</Label>
<Input
bind:value={longitude}
type="number"
@@ -262,19 +248,19 @@
variant="outline"
disabled={!canCreate && !$selectedWaypoint}
class="grow whitespace-normal h-fit"
on:click={createOrUpdateWaypoint}
onclick={createOrUpdateWaypoint}
>
{#if $selectedWaypoint}
<Save size="16" class="mr-1 shrink-0" />
{$_('menu.metadata.save')}
{i18n._('menu.metadata.save')}
{:else}
<MapPin size="16" class="mr-1 shrink-0" />
{$_('toolbar.waypoint.create')}
{i18n._('toolbar.waypoint.create')}
{/if}
</Button>
<Button
variant="outline"
on:click={() => {
onclick={() => {
selectedWaypoint.set(undefined);
resetWaypointData();
}}
@@ -282,11 +268,11 @@
<CircleX size="16" />
</Button>
</div>
<Help link={getURLForLanguage($locale, '/help/toolbar/poi')}>
<Help link={getURLForLanguage(i18n.lang, '/help/toolbar/poi')}>
{#if $selectedWaypoint || canCreate}
{$_('toolbar.waypoint.help')}
{i18n._('toolbar.waypoint.help')}
{:else}
{$_('toolbar.waypoint.help_no_selection')}
{i18n._('toolbar.waypoint.help_no_selection')}
{/if}
</Help>
</div>

View File

@@ -20,13 +20,13 @@
Repeat,
SquareArrowUpLeft,
SquareArrowOutDownRight,
} from 'lucide-svelte';
} from '@lucide/svelte';
import { map, newGPXFile, routingControls, selectFileWhenLoaded } from '$lib/stores';
import { dbUtils, getFile, getFileIds, settings } from '$lib/db';
import { brouterProfiles, routingProfileSelectItem } from './Routing';
import { brouterProfiles } from '$lib/components/toolbar/tools/routing/routing.svelte';
import { _, locale } from '$lib/i18n';
import { i18n } from '$lib/i18n.svelte';
import { RoutingControls } from './RoutingControls';
import mapboxgl from 'mapbox-gl';
import { fileObservers } from '$lib/db';
@@ -39,7 +39,7 @@
ListTrackSegmentItem,
type ListItem,
} from '$lib/components/file-list/FileList';
import { flyAndScale, getURLForLanguage, resetCursor, setCrosshairCursor } from '$lib/utils';
import { getURLForLanguage, resetCursor, setCrosshairCursor } from '$lib/utils';
import { onDestroy, onMount } from 'svelte';
import { TrackPoint } from 'gpx';
@@ -49,7 +49,7 @@
export let popupElement: HTMLElement | undefined = undefined;
let selectedItem: ListItem | null = null;
const { privateRoads, routing } = settings;
const { privateRoads, routing, routingProfile } = settings;
$: if ($map && popup && popupElement) {
// remove controls for deleted files
@@ -111,15 +111,12 @@
{#if minimizable && minimized}
<div class="-m-1.5 -mb-2">
<Button variant="ghost" class="px-1 h-[26px]" on:click={() => (minimized = false)}>
<Button variant="ghost" class="px-1 h-[26px]" onclick={() => (minimized = false)}>
<SquareArrowOutDownRight size="18" />
</Button>
</div>
{:else}
<div
class="flex flex-col gap-3 w-full max-w-80 {$$props.class ?? ''}"
in:flyAndScale={{ x: -2, y: 0, duration: 50 }}
>
<div class="flex flex-col gap-3 w-full max-w-80 animate-in animate-out {$$props.class ?? ''}">
<div class="flex flex-col gap-3">
<Label class="flex flex-row justify-between items-center gap-2">
<span class="flex flex-row items-center gap-1">
@@ -128,9 +125,9 @@
{:else}
<RouteOff size="16" />
{/if}
{$_('toolbar.routing.use_routing')}
{i18n._('toolbar.routing.use_routing')}
</span>
<Tooltip label={$_('toolbar.routing.use_routing_tooltip')}>
<Tooltip label={i18n._('toolbar.routing.use_routing_tooltip')}>
<Switch class="scale-90" bind:checked={$routing} />
<Shortcut slot="extra" key="F5" />
</Tooltip>
@@ -139,25 +136,27 @@
<div class="flex flex-col gap-3" in:slide>
<Label class="flex flex-row justify-between items-center gap-2">
<span class="shrink-0 flex flex-row items-center gap-1">
{#if $routingProfileSelectItem.value.includes('bike') || $routingProfileSelectItem.value.includes('motorcycle')}
{#if $routingProfile.includes('bike') || $routingProfile.includes('motorcycle')}
<Bike size="16" />
{:else if $routingProfileSelectItem.value.includes('foot')}
{:else if $routingProfile.includes('foot')}
<Footprints size="16" />
{:else if $routingProfileSelectItem.value.includes('water')}
{:else if $routingProfile.includes('water')}
<Waves size="16" />
{:else if $routingProfileSelectItem.value.includes('railway')}
{:else if $routingProfile.includes('railway')}
<TrainFront size="16" />
{/if}
{$_('toolbar.routing.activity')}
{i18n._('toolbar.routing.activity')}
</span>
<Select.Root bind:selected={$routingProfileSelectItem}>
<Select.Root type="single" bind:value={$routingProfile}>
<Select.Trigger class="h-8 grow">
<Select.Value />
{i18n._(`toolbar.routing.activities.${$routingProfile}`)}
</Select.Trigger>
<Select.Content>
{#each Object.keys(brouterProfiles) as profile}
<Select.Item value={profile}
>{$_(`toolbar.routing.activities.${profile}`)}</Select.Item
>{i18n._(
`toolbar.routing.activities.${profile}`
)}</Select.Item
>
{/each}
</Select.Content>
@@ -166,7 +165,7 @@
<Label class="flex flex-row justify-between items-center gap-2">
<span class="flex flex-row gap-1">
<TriangleAlert size="16" />
{$_('toolbar.routing.allow_private')}
{i18n._('toolbar.routing.allow_private')}
</span>
<Switch class="scale-90" bind:checked={$privateRoads} />
</Label>
@@ -175,20 +174,20 @@
</div>
<div class="flex flex-row flex-wrap justify-center gap-1">
<ButtonWithTooltip
label={$_('toolbar.routing.reverse.tooltip')}
label={i18n._('toolbar.routing.reverse.tooltip')}
variant="outline"
class="flex flex-row gap-1 text-xs px-2"
disabled={!validSelection}
on:click={dbUtils.reverseSelection}
onclick={dbUtils.reverseSelection}
>
<ArrowRightLeft size="12" />{$_('toolbar.routing.reverse.button')}
<ArrowRightLeft size="12" />{i18n._('toolbar.routing.reverse.button')}
</ButtonWithTooltip>
<ButtonWithTooltip
label={$_('toolbar.routing.route_back_to_start.tooltip')}
label={i18n._('toolbar.routing.route_back_to_start.tooltip')}
variant="outline"
class="flex flex-row gap-1 text-xs px-2"
disabled={!validSelection}
on:click={() => {
onclick={() => {
const selected = getOrderedSelection();
if (selected.length > 0) {
const firstFileId = selected[0].getFileId();
@@ -217,30 +216,30 @@
}
}}
>
<Home size="12" />{$_('toolbar.routing.route_back_to_start.button')}
<Home size="12" />{i18n._('toolbar.routing.route_back_to_start.button')}
</ButtonWithTooltip>
<ButtonWithTooltip
label={$_('toolbar.routing.round_trip.tooltip')}
label={i18n._('toolbar.routing.round_trip.tooltip')}
variant="outline"
class="flex flex-row gap-1 text-xs px-2"
disabled={!validSelection}
on:click={dbUtils.createRoundTripForSelection}
onclick={dbUtils.createRoundTripForSelection}
>
<Repeat size="12" />{$_('toolbar.routing.round_trip.button')}
<Repeat size="12" />{i18n._('toolbar.routing.round_trip.button')}
</ButtonWithTooltip>
</div>
<div class="w-full flex flex-row gap-2 items-end justify-between">
<Help link={getURLForLanguage($locale, '/help/toolbar/routing')}>
<Help link={getURLForLanguage(i18n.lang, '/help/toolbar/routing')}>
{#if !validSelection}
{$_('toolbar.routing.help_no_file')}
{i18n._('toolbar.routing.help_no_file')}
{:else}
{$_('toolbar.routing.help')}
{i18n._('toolbar.routing.help')}
{/if}
</Help>
<Button
variant="ghost"
class="px-1 h-6"
on:click={() => {
onclick={() => {
if (minimizable) {
minimized = true;
}

View File

@@ -3,9 +3,9 @@
import { Button } from '$lib/components/ui/button';
import Shortcut from '$lib/components/Shortcut.svelte';
import { canChangeStart } from './RoutingControls';
import { CirclePlay, Trash2 } from 'lucide-svelte';
import { CirclePlay, Trash2 } from '@lucide/svelte';
import { _ } from '$lib/i18n';
import { i18n } from '$lib/i18n.svelte';
export let element: HTMLElement;
</script>
@@ -17,19 +17,19 @@
<Button
class="w-full px-2 py-1 h-6 justify-start"
variant="ghost"
on:click={() => element.dispatchEvent(new CustomEvent('change-start'))}
onclick={() => element.dispatchEvent(new CustomEvent('change-start'))}
>
<CirclePlay size="16" class="mr-1" />
{$_('toolbar.routing.start_loop_here')}
{i18n._('toolbar.routing.start_loop_here')}
</Button>
{/if}
<Button
class="w-full px-2 py-1 h-6 justify-start"
variant="ghost"
on:click={() => element.dispatchEvent(new CustomEvent('delete'))}
onclick={() => element.dispatchEvent(new CustomEvent('delete'))}
>
<Trash2 size="16" class="mr-1" />
{$_('menu.delete')}
{i18n._('menu.delete')}
<Shortcut shift={true} click={true} />
</Button>
</Card.Content>

View File

@@ -1,9 +1,9 @@
import { distance, type Coordinates, TrackPoint, TrackSegment, Track, projectedPoint } from 'gpx';
import { get, writable, type Readable } from 'svelte/store';
import mapboxgl from 'mapbox-gl';
import { route } from './Routing';
import { route } from './routing.svelte';
import { toast } from 'svelte-sonner';
import { _ } from '$lib/i18n';
import { i18n } from '$lib/i18n.svelte';
import { dbUtils, settings, type GPXFileWithStatistics } from '$lib/db';
import { getOrderedSelection, selection } from '$lib/components/file-list/Selection';
import {
@@ -14,7 +14,7 @@ import {
import { currentTool, streetViewEnabled, Tool } from '$lib/stores';
import { getClosestLinePoint, resetCursor, setGrabbingCursor } from '$lib/utils';
const { streetViewSource } = settings;
// const { streetViewSource } = settings;
export const canChangeStart = writable(false);
function stopPropagation(e: any) {

View File

@@ -1,8 +1,6 @@
import type { Coordinates } from 'gpx';
import { TrackPoint, distance } from 'gpx';
import { derived, get, writable } from 'svelte/store';
import { settings } from '$lib/db';
import { _, locale, isLoadingLocale } from '$lib/i18n';
import { settings } from '$lib/logic/settings.svelte';
import { getElevation } from '$lib/utils';
const { routing, routingProfile, privateRoads } = settings;
@@ -17,38 +15,10 @@ export const brouterProfiles: { [key: string]: string } = {
water: 'river',
railway: 'rail',
};
export const routingProfileSelectItem = writable({
value: '',
label: '',
});
derived([routingProfile, locale, isLoadingLocale], ([profile, l, i]) => [profile, l, i]).subscribe(
([profile, l, i]) => {
if (
!i &&
profile !== '' &&
(profile !== get(routingProfileSelectItem).value ||
get(_)(`toolbar.routing.activities.${profile}`) !==
get(routingProfileSelectItem).label) &&
l !== null
) {
routingProfileSelectItem.update((item) => {
item.value = profile;
item.label = get(_)(`toolbar.routing.activities.${profile}`);
return item;
});
}
}
);
routingProfileSelectItem.subscribe((item) => {
if (item.value !== '' && item.value !== get(routingProfile)) {
routingProfile.set(item.value);
}
});
export function route(points: Coordinates[]): Promise<TrackPoint[]> {
if (get(routing)) {
return getRoute(points, brouterProfiles[get(routingProfile)], get(privateRoads));
if (routing.value) {
return getRoute(points, brouterProfiles[routingProfile.value], privateRoads.value);
} else {
return getIntermediatePoints(points);
}

View File

@@ -1,12 +1,5 @@
<script lang="ts" context="module">
export enum SplitType {
FILES = 'files',
TRACKS = 'tracks',
SEGMENTS = 'segments',
}
</script>
<script lang="ts">
import { splitAs, SplitType } from '$lib/components/toolbar/tools/scissors/utils.svelte';
import Help from '$lib/components/Help.svelte';
import { ListRootItem } from '$lib/components/file-list/FileList';
import { selection } from '$lib/components/file-list/Selection';
@@ -15,31 +8,39 @@
import { Slider } from '$lib/components/ui/slider';
import * as Select from '$lib/components/ui/select';
import { Separator } from '$lib/components/ui/separator';
import { gpxStatistics, map, slicedGPXStatistics, splitAs } from '$lib/stores';
import { gpxStatistics, slicedGPXStatistics } from '$lib/stores';
import { map } from '$lib/components/map/map.svelte';
import { get } from 'svelte/store';
import { _, locale } from '$lib/i18n';
import { i18n } from '$lib/i18n.svelte';
import { onDestroy, tick } from 'svelte';
import { Crop } from 'lucide-svelte';
import { Crop } from '@lucide/svelte';
import { dbUtils } from '$lib/db';
import { SplitControls } from './SplitControls';
import { SplitControls } from './SplitControls.svelte';
import { getURLForLanguage } from '$lib/utils';
let splitControls: SplitControls | undefined = undefined;
let canCrop = false;
let props: {
class?: string;
} = $props();
$: if ($map) {
let splitControls: SplitControls | undefined = undefined;
let canCrop = $state(false);
$effect(() => {
if (map.current) {
if (splitControls) {
splitControls.destroy();
}
splitControls = new SplitControls($map);
splitControls = new SplitControls(map.current);
}
});
$: validSelection =
let validSelection = $derived(
$selection.hasAnyChildren(new ListRootItem(), true, ['waypoints']) &&
$gpxStatistics.local.points.length > 0;
$gpxStatistics.local.points.length > 0
);
let maxSliderValue = 1;
let sliderValues = [0, 1];
let maxSliderValue = $state(1);
let sliderValues = $state([0, 1]);
function updateCanCrop() {
canCrop = sliderValues[0] != 0 || sliderValues[1] != maxSliderValue;
@@ -73,32 +74,29 @@
sliderValues = [0, maxSliderValue];
}
$: if ($gpxStatistics.local.points.length - 1 != maxSliderValue) {
$effect(() => {
if ($gpxStatistics.local.points.length - 1 != maxSliderValue) {
updateSliderLimits();
}
});
$: if (sliderValues) {
$effect(() => {
if (sliderValues) {
updateCanCrop();
updateSlicedGPXStatistics();
}
});
$: if (
$effect(() => {
if (
$slicedGPXStatistics !== undefined &&
($slicedGPXStatistics[1] !== sliderValues[0] || $slicedGPXStatistics[2] !== sliderValues[1])
($slicedGPXStatistics[1] !== sliderValues[0] ||
$slicedGPXStatistics[2] !== sliderValues[1])
) {
updateSliderValues();
updateCanCrop();
}
const splitTypes = [
{ value: SplitType.FILES, label: $_('gpx.files') },
{ value: SplitType.TRACKS, label: $_('gpx.tracks') },
{ value: SplitType.SEGMENTS, label: $_('gpx.segments') },
];
let splitType = splitTypes.find((type) => type.value === $splitAs) ?? splitTypes[0];
$: splitAs.set(splitType.value);
});
onDestroy(() => {
$slicedGPXStatistics = undefined;
@@ -109,43 +107,44 @@
});
</script>
<div class="flex flex-col gap-3 w-full max-w-80 {$$props.class ?? ''}">
<div class="flex flex-col gap-3 w-full max-w-80 {props.class ?? ''}">
<div class="p-2">
<Slider
bind:value={sliderValues}
max={maxSliderValue}
step={1}
type="multiple"
disabled={!validSelection}
/>
</div>
<Button
variant="outline"
disabled={!validSelection || !canCrop}
on:click={() => dbUtils.cropSelection(sliderValues[0], sliderValues[1])}
onclick={() => dbUtils.cropSelection(sliderValues[0], sliderValues[1])}
>
<Crop size="16" class="mr-1" />{$_('toolbar.scissors.crop')}
<Crop size="16" class="mr-1" />{i18n._('toolbar.scissors.crop')}
</Button>
<Separator />
<Label class="flex flex-row flex-wrap gap-3 items-center">
<span class="shrink-0">
{$_('toolbar.scissors.split_as')}
{i18n._('toolbar.scissors.split_as')}
</span>
<Select.Root bind:selected={splitType}>
<Select.Root bind:value={splitAs.current} type="single">
<Select.Trigger class="h-8 w-fit grow">
<Select.Value />
{i18n._('gpx.' + splitAs)}
</Select.Trigger>
<Select.Content>
{#each splitTypes as { value, label }}
<Select.Item {value}>{label}</Select.Item>
{#each Object.values(SplitType) as splitType}
<Select.Item value={splitType}>{i18n._('gpx.' + splitType)}</Select.Item>
{/each}
</Select.Content>
</Select.Root>
</Label>
<Help link={getURLForLanguage($locale, '/help/toolbar/scissors')}>
<Help link={getURLForLanguage(i18n.lang, '/help/toolbar/scissors')}>
{#if validSelection}
{$_('toolbar.scissors.help')}
{i18n._('toolbar.scissors.help')}
{:else}
{$_('toolbar.scissors.help_invalid_selection')}
{i18n._('toolbar.scissors.help_invalid_selection')}
{/if}
</Help>
</div>

View File

@@ -7,8 +7,9 @@ import {
selection,
} from '$lib/components/file-list/Selection';
import { ListTrackSegmentItem } from '$lib/components/file-list/FileList';
import { currentTool, gpxStatistics, Tool } from '$lib/stores';
import { _ } from '$lib/i18n';
import { gpxStatistics } from '$lib/stores';
import { tool, Tool } from '$lib/components/toolbar/utils.svelte';
import { splitAs } from '$lib/components/toolbar/tools/scissors/utils.svelte';
import { Scissors } from 'lucide-static';
export class SplitControls {
@@ -26,11 +27,13 @@ export class SplitControls {
this.unsubscribes.push(selection.subscribe(this.addIfNeeded.bind(this)));
this.unsubscribes.push(gpxStatistics.subscribe(this.addIfNeeded.bind(this)));
this.unsubscribes.push(currentTool.subscribe(this.addIfNeeded.bind(this)));
$effect(() => {
tool.current, this.addIfNeeded.bind(this);
});
}
addIfNeeded() {
let scissors = get(currentTool) === Tool.SCISSORS;
let scissors = tool.current === Tool.SCISSORS;
if (!scissors) {
if (this.active) {
this.remove();
@@ -166,6 +169,7 @@ export class SplitControls {
marker.getElement().addEventListener('click', (e) => {
e.stopPropagation();
dbUtils.split(
splitAs.current,
control.fileId,
control.trackIndex,
control.segmentIndex,

View File

@@ -0,0 +1,9 @@
export enum SplitType {
FILES = 'files',
TRACKS = 'tracks',
SEGMENTS = 'segments',
}
export let splitAs = $state({
current: SplitType.FILES,
});

Some files were not shown because too many files have changed in this diff Show More