Something went wrong. Try again.
source code of sayemon10.com sayemon10.com
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369<script lang="ts"> import { onMount, onDestroy, setContext, untrack } from 'svelte'; import * as MapLibreGL from 'maplibre-gl'; import 'maplibre-gl/dist/maplibre-gl.css'; import { browser } from '$app/env'; import { theme } from '#lib/theme.js'; import { cn } from '#lib/utils.js'; import { resolveMapTheme } from './theme';
// Check document class for theme (works with next-themes, etc.) function getDocumentTheme(): 'light' | 'dark' | null { if (typeof document === 'undefined') return null; if (document.documentElement.classList.contains('dark')) return 'dark'; if (document.documentElement.classList.contains('light')) return 'light'; return null; }
// Get system preference function getSystemTheme(): 'light' | 'dark' { if (typeof window === 'undefined') return 'light'; return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; }
let tailwindTheme: 'light' | 'dark' = $state('light');
type MapStyleOption = string | MapLibreGL.StyleSpecification;
/** Map viewport state */ export type MapViewport = { /** Center coordinates [longitude, latitude] */ center: [number, number]; /** Zoom level */ zoom: number; /** Bearing (rotation) in degrees */ bearing: number; /** Pitch (tilt) in degrees */ pitch: number; };
interface Props { children?: import('svelte').Snippet; class?: string; styles?: { light?: MapStyleOption; dark?: MapStyleOption; }; theme?: 'light' | 'dark'; /** Map projection type. Use `{ type: "globe" }` for 3D globe view. */ projection?: MapLibreGL.ProjectionSpecification; center?: [number, number]; zoom?: number; options?: Omit<MapLibreGL.MapOptions, 'container' | 'style'>; /** * Bindable reference to the underlying MapLibre map instance. * Useful for calling map methods imperatively from the parent. */ map?: MapLibreGL.Map | null; /** * Controlled viewport. When provided with onViewportChange, * the map becomes controlled and viewport is driven by this prop. */ viewport?: Partial<MapViewport>; /** * Callback fired continuously as the viewport changes (pan, zoom, rotate, pitch). * Can be used standalone to observe changes, or with `viewport` prop * to enable controlled mode where the map viewport is driven by your state. */ onviewportchange?: (viewport: MapViewport) => void; /** * Callback fired after each style load completes (initial load and subsequent style changes). * Runs after any viewport restoration, so it's safe to call map methods here. */ onstyleloaded?: () => void; }
const defaultStyles = { dark: 'https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json', light: 'https://basemaps.cartocdn.com/gl/positron-gl-style/style.json' };
let { children, class: className, styles, theme: explicitTheme, projection, center = [13.405, 52.52], zoom = 0, options = {}, map = $bindable(null), viewport, onviewportchange, onstyleloaded }: Props = $props();
let mapContainer: HTMLDivElement; let isMounted = $state(false); let isLoaded = $state(false); let isStyleLoaded = $state(false); let isInteracting = $state(false); let hasInitiallyLoaded = $state(false); let initialStyleApplied = $state(false); let appliedStyle: MapStyleOption | null = null; let initialCenterZoomApplied = false; let styleTimeoutId: ReturnType<typeof setTimeout> | null = null; let internalUpdate = false;
const isControlled = $derived(viewport !== undefined && onviewportchange !== undefined);
function getViewport(mapInstance: MapLibreGL.Map): MapViewport { const c = mapInstance.getCenter(); return { center: [c.lng, c.lat], zoom: mapInstance.getZoom(), bearing: mapInstance.getBearing(), pitch: mapInstance.getPitch() }; }
const mapStyles = $derived({ dark: styles?.dark ?? defaultStyles.dark, light: styles?.light ?? defaultStyles.light });
const resolvedTheme = $derived(resolveMapTheme({ explicitTheme, ambientTheme: tailwindTheme }));
const currentStyle = $derived(resolvedTheme === 'light' ? mapStyles.light : mapStyles.dark);
const isReady = $derived(isMounted && isLoaded && isStyleLoaded);
setContext('map', { getMap: () => map, isLoaded: () => hasInitiallyLoaded, isStyleReady: () => isReady });
function clearStyleTimeout() { if (styleTimeoutId) { clearTimeout(styleTimeoutId); styleTimeoutId = null; } }
onMount(() => { isMounted = true;
// Subscribe to theme store for instant updates const themeUnsubscribe = theme.subscribe((value) => { tailwindTheme = value; });
// Clean up theme subscription onDestroy(() => { themeUnsubscribe(); });
if (browser) { // Also watch for document class changes (e.g., external theme togglers) const updateTheme = () => { const docTheme = getDocumentTheme(); // Only use document theme if set, otherwise fall back to system preference tailwindTheme = docTheme ?? getSystemTheme(); };
updateTheme();
const observer = new MutationObserver(updateTheme); observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
// Also watch for system preference changes const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)'); const handleSystemChange = (e: MediaQueryListEvent) => { // Only use system preference if no document class is set if (!getDocumentTheme()) { tailwindTheme = e.matches ? 'dark' : 'light'; } }; mediaQuery.addEventListener('change', handleSystemChange);
onDestroy(() => { observer.disconnect(); mediaQuery.removeEventListener('change', handleSystemChange); }); }
const constructedStyle = currentStyle;
const mapInstance = new MapLibreGL.Map({ container: mapContainer, style: constructedStyle, fadeDuration: 0, renderWorldCopies: false, attributionControl: { compact: true }, center: viewport?.center ?? center, zoom: viewport?.zoom ?? zoom, bearing: viewport?.bearing ?? 0, pitch: viewport?.pitch ?? 0, ...options });
const markStyleReady = () => { clearStyleTimeout(); // Delay so style objects finish processing before layers attach. styleTimeoutId = setTimeout(() => { isStyleLoaded = true; if (!initialStyleApplied) { appliedStyle = constructedStyle; initialStyleApplied = true; } if (!hasInitiallyLoaded) { hasInitiallyLoaded = true; } if (projection) { mapInstance.setProjection(projection); } mapInstance.resize(); onstyleloaded?.(); }, 100); };
const loadHandler = () => { isLoaded = true; markStyleReady(); };
const errorHandler = (event: MapLibreGL.ErrorEvent) => { if (hasInitiallyLoaded) return; console.error('Map failed to load style', event.error); clearStyleTimeout(); isLoaded = true; isStyleLoaded = true; hasInitiallyLoaded = true; };
// Viewport change handler - skip if triggered by internal update const handleMove = () => { if (internalUpdate) return; onviewportchange?.(getViewport(mapInstance)); };
mapInstance.on('load', loadHandler); mapInstance.on('styledata', markStyleReady); mapInstance.on('error', errorHandler); mapInstance.on('move', handleMove);
requestAnimationFrame(() => { mapInstance.resize(); });
mapInstance.on('dragstart', () => (isInteracting = true)); mapInstance.on('dragend', () => (isInteracting = false)); mapInstance.on('zoomstart', () => (isInteracting = true)); mapInstance.on('zoomend', () => (isInteracting = false)); mapInstance.on('rotatestart', () => (isInteracting = true)); mapInstance.on('rotateend', () => (isInteracting = false)); mapInstance.on('pitchstart', () => (isInteracting = true)); mapInstance.on('pitchend', () => (isInteracting = false));
map = mapInstance; });
// Sync controlled viewport to map $effect(() => { if (!map || !isControlled || !viewport) return; if (map.isMoving()) return;
const current = getViewport(map); const next = { center: viewport.center ?? current.center, zoom: viewport.zoom ?? current.zoom, bearing: viewport.bearing ?? current.bearing, pitch: viewport.pitch ?? current.pitch };
if ( next.center[0] === current.center[0] && next.center[1] === current.center[1] && next.zoom === current.zoom && next.bearing === current.bearing && next.pitch === current.pitch ) { return; }
internalUpdate = true; map!.once('moveend', () => { internalUpdate = false; }); map.jumpTo(next); });
$effect(() => { const style = currentStyle;
if (!map || !initialStyleApplied || style === appliedStyle) { return; }
untrack(() => { const currCenter = map!.getCenter(); const currZoom = map!.getZoom(); const currBearing = map!.getBearing(); const currPitch = map!.getPitch();
appliedStyle = style; isStyleLoaded = false; map!.setStyle(style);
map!.once('style.load', () => { map!.jumpTo({ center: currCenter, zoom: currZoom, bearing: currBearing, pitch: currPitch }); map!.resize(); }); }); });
$effect(() => { if (!map || !isReady || isInteracting || initialCenterZoomApplied || isControlled) { return; }
// Only apply initial center/zoom once, then let user move freely // Skip if controlled mode is enabled initialCenterZoomApplied = true;
const [lng, lat] = center;
untrack(() => { map!.easeTo({ center: [lng, lat], zoom }); }); });
onDestroy(() => { map?.remove(); map = null; isLoaded = false; isStyleLoaded = false; });</script>
<div bind:this={mapContainer} class={cn('relative h-full min-h-0 w-full flex-1', className)}> {#if !isReady} <div class="absolute inset-0 flex items-center justify-center"> <div class="flex gap-1"> <span class="size-1.5 animate-pulse rounded-full bg-muted-foreground/60"></span>
<span class="size-1.5 animate-pulse rounded-full bg-muted-foreground/60 [animation-delay:150ms]" ></span> <span class="size-1.5 animate-pulse rounded-full bg-muted-foreground/60 [animation-delay:300ms]" ></span> </div> </div> {/if} {#if hasInitiallyLoaded} {@render children?.()} {/if}</div>