Init
This commit is contained in:
1 parent
dd596f16b9
commit
3c052a8b43
25 files changed
+2252
-74
No files matched your search
@@ -39,3 +39,5 @@ yarn-error.log*
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
|
||||
certificates
|
||||
+11
-2
@@ -1,8 +1,17 @@
|
||||
import type { NextConfig } from "next";
|
||||
import { withSerwist } from "@serwist/turbopack";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
/* config options here */
|
||||
reactCompiler: true,
|
||||
cacheComponents: true,
|
||||
partialPrefetching: true,
|
||||
experimental: {
|
||||
useOffline: true,
|
||||
},
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
module.exports = {
|
||||
allowedDevOrigins: ['192.168.0.110'],
|
||||
};
|
||||
|
||||
export default withSerwist(nextConfig);
|
||||
Generated
+1437
-7
File diff suppressed because it is too large.
Load diff
+11
-1
@@ -3,23 +3,33 @@
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"dev": "next dev --experimental-https",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "eslint"
|
||||
},
|
||||
"dependencies": {
|
||||
"@serwist/next": "^9.5.12",
|
||||
"maplibre-gl": "^6.8.0",
|
||||
"next": "16.3.4",
|
||||
"react": "19.2.8",
|
||||
"react-dom": "19.2.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@serwist/turbopack": "^9.5.12",
|
||||
"@types/node": "^20",
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"babel-plugin-react-compiler": "1.0.0",
|
||||
"esbuild": "^0.28.2",
|
||||
"eslint": "^9",
|
||||
"eslint-config-next": "16.3.4",
|
||||
"serwist": "^9.5.12",
|
||||
"typescript": "^5"
|
||||
},
|
||||
"allowScripts": {
|
||||
"unrs-resolver@1.12.2": true,
|
||||
"@swc/core@1.15.46": true,
|
||||
"esbuild@0.28.2": true
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 51 KiB |
@@ -42,8 +42,53 @@ a {
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.charged-button {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0.5rem 1.25rem;
|
||||
min-width: 8rem;
|
||||
height: 2.75rem;
|
||||
border: 2px solid white;
|
||||
border-radius: 0.625rem;
|
||||
outline: none;
|
||||
isolation: isolate;
|
||||
cursor: pointer;
|
||||
background: #000;
|
||||
color: #FFF;
|
||||
box-shadow: 0 0 0 1px hsl(0 0% 0% / 0.15);
|
||||
transition: box-shadow 120ms ease, transform 120ms ease;
|
||||
}
|
||||
|
||||
.charged-button:hover {
|
||||
box-shadow: 0 0 0 1px hsl(0 0% 0% / 0.45);
|
||||
}
|
||||
|
||||
.charged-button:active {
|
||||
transform: scale(0.97);
|
||||
}
|
||||
|
||||
.charged-button__label {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.charged-button-fill {
|
||||
pointer-events: none;
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border-radius: inherit;
|
||||
opacity: 0.7;
|
||||
background: linear-gradient(120deg, #1ea, #2af, #e1f, #2af);
|
||||
background-size: 200% 200%;
|
||||
transition: opacity 120ms ease;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
html {
|
||||
color-scheme: dark;
|
||||
}
|
||||
}
|
||||
|
||||
+10
-6
@@ -1,4 +1,5 @@
|
||||
import type { Metadata } from "next";
|
||||
import { SerwistProvider } from "@serwist/turbopack/react";
|
||||
import type { Metadata, Viewport } from "next";
|
||||
import { Geist, Geist_Mono } from "next/font/google";
|
||||
import "./globals.css";
|
||||
|
||||
@@ -13,14 +14,17 @@ const geistMono = Geist_Mono({
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Create Next App",
|
||||
description: "Generated by create next app",
|
||||
title: "Excalibur Outdoor Tour",
|
||||
description: "Excalibur Outdoor Tour Web App",
|
||||
};
|
||||
|
||||
export default function RootLayout({ children }: LayoutProps<"/">) {
|
||||
return (
|
||||
<html lang="en" className={`${geistSans.variable} ${geistMono.variable}`}>
|
||||
<body>{children}</body>
|
||||
<html lang="en" dir="ltr" className={`${geistSans.variable} ${geistMono.variable}`}>
|
||||
<meta name="apple-mobile-web-app-title" content="Excalibur Outdoor Tour" />
|
||||
<body>
|
||||
<SerwistProvider swUrl="/serwist/sw.js">{children}</SerwistProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { MetadataRoute } from 'next'
|
||||
|
||||
export default function manifest(): MetadataRoute.Manifest {
|
||||
return {
|
||||
name: 'Next.js PWA',
|
||||
short_name: 'NextPWA',
|
||||
description: 'A Progressive Web App built with Next.js',
|
||||
start_url: '/',
|
||||
display: 'standalone',
|
||||
orientation: "portrait-primary",
|
||||
background_color: '#ffffff',
|
||||
theme_color: '#000000',
|
||||
icons: [
|
||||
{
|
||||
src: '/icon-192x192.png',
|
||||
sizes: '192x192',
|
||||
type: 'image/png',
|
||||
},
|
||||
{
|
||||
src: '/icon-512x512.png',
|
||||
sizes: '512x512',
|
||||
type: 'image/png',
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import Image from "next/image";
|
||||
import styles from "./page.module.css";
|
||||
|
||||
export default function Home() {
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
<main className={styles.main}>
|
||||
<Image
|
||||
className={styles.logo}
|
||||
src="/next.svg"
|
||||
alt="Next.js logo"
|
||||
width={100}
|
||||
height={20}
|
||||
priority
|
||||
/>
|
||||
<div className={styles.intro}>
|
||||
<h1>
|
||||
404
|
||||
</h1>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+17
-58
@@ -1,68 +1,27 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import Image from "next/image";
|
||||
import styles from "./page.module.css";
|
||||
import ChargedButton from "@/components/ChargedButton";
|
||||
import MapView from "@/components/MapView";
|
||||
|
||||
export default function Home() {
|
||||
const [doTest, setDoTest] = useState(false);
|
||||
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
<main className={styles.main}>
|
||||
<Image
|
||||
className={styles.logo}
|
||||
src="/next.svg"
|
||||
alt="Next.js logo"
|
||||
width={100}
|
||||
height={20}
|
||||
priority
|
||||
/>
|
||||
<div className={styles.intro}>
|
||||
<h1>
|
||||
To get started, edit the{" "}
|
||||
<code className={styles.code}>page.tsx</code> file.
|
||||
</h1>
|
||||
<p>
|
||||
Looking for a starting point or more instructions? Head over to{" "}
|
||||
<a
|
||||
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Templates
|
||||
</a>{" "}
|
||||
or the{" "}
|
||||
<a
|
||||
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Learning
|
||||
</a>{" "}
|
||||
center.
|
||||
</p>
|
||||
</div>
|
||||
<div className={styles.ctas}>
|
||||
<a
|
||||
className={styles.primary}
|
||||
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Image
|
||||
className={styles.logo}
|
||||
src="/vercel.svg"
|
||||
alt="Vercel logomark"
|
||||
width={16}
|
||||
height={14}
|
||||
/>
|
||||
Deploy Now
|
||||
</a>
|
||||
<a
|
||||
className={styles.secondary}
|
||||
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Documentation
|
||||
</a>
|
||||
</div>
|
||||
<ChargedButton
|
||||
onAction={() => {
|
||||
console.log("Click!");
|
||||
}}
|
||||
holdDuration={2000}
|
||||
>Hello</ChargedButton>
|
||||
<button onClick={() => {
|
||||
setDoTest(true);
|
||||
}}>test</button>
|
||||
{doTest && <MapView></MapView>}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { createSerwistRoute } from "@serwist/turbopack";
|
||||
// If you are using Next.js versions older than 15.0.0, add the
|
||||
// `nextConfig` option so that Serwist can configure the service
|
||||
// worker according to your options. Serwist 10 and newer will
|
||||
// only support Next.js 15.0.0 and above.
|
||||
// import nextConfig from "$cwd/next.config.mjs";
|
||||
|
||||
// This is optional!
|
||||
// A revision helps Serwist version a precached page. This
|
||||
// avoids outdated precached responses being used. Using
|
||||
// `git rev-parse HEAD` might not the most efficient way
|
||||
// of determining a revision, however. You may prefer to use
|
||||
// the hashes of every extra file you precache.
|
||||
const revision = spawnSync("git", ["rev-parse", "HEAD"], { encoding: "utf-8" }).stdout ?? crypto.randomUUID();
|
||||
|
||||
export const { dynamic, dynamicParams, revalidate, generateStaticParams, GET } = createSerwistRoute({
|
||||
additionalPrecacheEntries: [{ url: "/~offline", revision }],
|
||||
swSrc: "src/app/sw.ts",
|
||||
// nextConfig,
|
||||
// If set to `false`, Serwist will attempt to use `esbuild-wasm`.
|
||||
useNativeEsbuild: true,
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
/// <reference lib="esnext" />
|
||||
/// <reference lib="webworker" />
|
||||
import { defaultCache } from "@serwist/turbopack/worker";
|
||||
import type { PrecacheEntry, SerwistGlobalConfig } from "serwist";
|
||||
import { Serwist } from "serwist";
|
||||
|
||||
// This declares the value of `injectionPoint` to TypeScript.
|
||||
// `injectionPoint` is the string that will be replaced by the
|
||||
// actual precache manifest. By default, this string is set to
|
||||
// `"self.__SW_MANIFEST"`.
|
||||
declare global {
|
||||
interface WorkerGlobalScope extends SerwistGlobalConfig {
|
||||
__SW_MANIFEST: (PrecacheEntry | string)[] | undefined;
|
||||
}
|
||||
}
|
||||
|
||||
declare const self: ServiceWorkerGlobalScope;
|
||||
|
||||
const serwist = new Serwist({
|
||||
precacheEntries: self.__SW_MANIFEST,
|
||||
precacheOptions: {
|
||||
cleanupOutdatedCaches: true,
|
||||
concurrency: 20,
|
||||
directoryIndex: "index.html",
|
||||
fallbackToNetwork: true,
|
||||
},
|
||||
disableDevLogs: true,
|
||||
skipWaiting: true,
|
||||
clientsClaim: true,
|
||||
navigationPreload: true,
|
||||
runtimeCaching: defaultCache,
|
||||
fallbacks: {
|
||||
entries: [
|
||||
{
|
||||
url: "/",
|
||||
matcher({ request }) {
|
||||
return request.destination === "document";
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
serwist.addEventListeners();
|
||||
|
||||
/** From Gemini */
|
||||
/*
|
||||
import { defaultCache } from '@serwist/next/worker';
|
||||
import type { PrecacheEntry, SerwistGlobalConfig } from 'serwist';
|
||||
import { CacheFirst, Serwist } from 'serwist';
|
||||
|
||||
declare const self: ServiceWorkerGlobalScope &
|
||||
SerwistGlobalConfig & {
|
||||
__SW_MANIFEST: (string | PrecacheEntry)[];
|
||||
};
|
||||
|
||||
const serwist = new Serwist({
|
||||
precacheEntries: self.__SW_MANIFEST,
|
||||
skipWaiting: true,
|
||||
clientsClaim: true,
|
||||
navigationPreload: true,
|
||||
runtimeCaching: [
|
||||
...defaultCache,
|
||||
{
|
||||
// Intercept map tile requests from standard OSM / tile servers
|
||||
matcher: ({ url }) => url.hostname.includes('tile.openstreetmap.org') || url.pathname.includes('/tiles/'),
|
||||
handler: new CacheFirst({
|
||||
cacheName: 'excalibur-offline-map-tiles-v1',
|
||||
}),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
serwist.addEventListeners();
|
||||
*/
|
||||
@@ -0,0 +1,102 @@
|
||||
"use client";
|
||||
|
||||
import { CSSProperties, ReactNode, useRef, useState } from "react";
|
||||
|
||||
interface ChargedButtonProps {
|
||||
children?: ReactNode;
|
||||
style?: CSSProperties;
|
||||
/** Time in milliseconds needed to fully charge by continuous hold. */
|
||||
holdDuration?: number;
|
||||
/** Runs exactly once, when the button is fully charged at 100%. */
|
||||
onAction?: () => void;
|
||||
}
|
||||
|
||||
export default function ChargedButton({
|
||||
children,
|
||||
style,
|
||||
holdDuration = 1000,
|
||||
onAction,
|
||||
}: ChargedButtonProps) {
|
||||
const [progress, setProgress] = useState(0);
|
||||
const [isCharging, setIsCharging] = useState(false);
|
||||
const [isDischarging, setIsDischarging] = useState(false);
|
||||
const rafRef = useRef(0);
|
||||
const startTimeRef = useRef(0);
|
||||
const stateRef = useRef({ charging: false, discharging: false });
|
||||
const dischargingRef = useRef(false);
|
||||
|
||||
const cancelRaf = () => {
|
||||
if (rafRef.current) {
|
||||
cancelAnimationFrame(rafRef.current);
|
||||
rafRef.current = 0;
|
||||
}
|
||||
};
|
||||
|
||||
const onPointerDown = () => {
|
||||
if (dischargingRef.current) return;
|
||||
cancelRaf();
|
||||
startTimeRef.current = performance.now();
|
||||
setIsCharging(true);
|
||||
dischargingRef.current = false;
|
||||
setIsDischarging(false);
|
||||
rafRef.current = requestAnimationFrame(updateProgress);
|
||||
};
|
||||
|
||||
const onPointerUp = () => {
|
||||
if (dischargingRef.current) return;
|
||||
cancelRaf();
|
||||
setIsCharging(false);
|
||||
setProgress(0);
|
||||
};
|
||||
|
||||
const updateProgress = () => {
|
||||
const elapsed = performance.now() - startTimeRef.current;
|
||||
const discharging = dischargingRef.current ?? false;
|
||||
|
||||
if (!discharging) {
|
||||
const fraction = Math.min(1, elapsed / holdDuration);
|
||||
setProgress(fraction);
|
||||
if (fraction >= 1) {
|
||||
setProgress(1);
|
||||
setIsCharging(false);
|
||||
dischargingRef.current = true;
|
||||
setIsDischarging(true);
|
||||
startTimeRef.current = performance.now();
|
||||
onAction?.();
|
||||
}
|
||||
} else {
|
||||
const fraction = Math.min(1, elapsed / (holdDuration * 0.1));
|
||||
setProgress(1.0 - fraction);
|
||||
if (fraction >= 1) {
|
||||
setProgress(0);
|
||||
cancelRaf();
|
||||
dischargingRef.current = false;
|
||||
setIsDischarging(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
rafRef.current = requestAnimationFrame(updateProgress);
|
||||
};
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="charged-button"
|
||||
style={style}
|
||||
onPointerDown={onPointerDown}
|
||||
onTouchStart={onPointerDown}
|
||||
onPointerUp={onPointerUp}
|
||||
onTouchEnd={onPointerUp}
|
||||
onPointerCancel={onPointerUp}
|
||||
onTouchCancel={onPointerUp}
|
||||
>
|
||||
<span className="charged-button__label">{children}</span>
|
||||
<span
|
||||
className=" charged-button-fill"
|
||||
aria-hidden="true"
|
||||
style={{ width: `${progress * 100}%` }}
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
.mapWrapper {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
min-height: 400px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.mapContainer {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
min-height: 500px;
|
||||
}
|
||||
|
||||
.controlOverlay {
|
||||
position: absolute;
|
||||
top: 12px;
|
||||
left: 12px;
|
||||
z-index: 10;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
background: rgba(18, 18, 18, 0.85);
|
||||
backdrop-filter: blur(8px);
|
||||
padding: 10px 14px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||
color: #fff;
|
||||
font-family: var(--font-geist-sans), sans-serif;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
|
||||
.precacheButton {
|
||||
background: #2563eb;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 8px 12px;
|
||||
border-radius: 6px;
|
||||
font-weight: 600;
|
||||
font-size: 0.875rem;
|
||||
cursor: pointer;
|
||||
transition: background-color 0.2s ease;
|
||||
}
|
||||
|
||||
.precacheButton:hover:not(:disabled) {
|
||||
background: #1d4ed8;
|
||||
}
|
||||
|
||||
.precacheButton:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.progressContainer {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.progressBar {
|
||||
width: 100%;
|
||||
height: 6px;
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
border-radius: 3px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.progressFill {
|
||||
height: 100%;
|
||||
background: #10b981;
|
||||
transition: width 0.2s ease;
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
'use client';
|
||||
|
||||
import React, { useEffect, useRef, useState, useCallback } from 'react';
|
||||
import * as maplibregl from 'maplibre-gl';
|
||||
import 'maplibre-gl/dist/maplibre-gl.css';
|
||||
import styles from './MapView.module.css';
|
||||
|
||||
export interface PlaceMarker {
|
||||
id: string;
|
||||
lat: number;
|
||||
lng: number;
|
||||
title: string;
|
||||
description?: string;
|
||||
category?: string;
|
||||
}
|
||||
|
||||
export interface MapViewProps {
|
||||
initialCenter?: [number, number]; // [lng, lat]
|
||||
initialZoom?: number;
|
||||
markers?: PlaceMarker[];
|
||||
onMarkerClick?: (marker: PlaceMarker) => void;
|
||||
// Default vector tile source or tile pattern
|
||||
tileUrlTemplate?: string;
|
||||
}
|
||||
|
||||
// MapTile calculations for Bounding Box precaching (Slippy Map Tile Names)
|
||||
function lng2tile(lng: number, zoom: number): number {
|
||||
return Math.floor(((lng + 180) / 360) * Math.pow(2, zoom));
|
||||
}
|
||||
|
||||
function lat2tile(lat: number, zoom: number): number {
|
||||
return Math.floor(
|
||||
((1 - Math.log(Math.tan((lat * Math.PI) / 180) + 1 / Math.cos((lat * Math.PI) / 180)) / Math.PI) / 2) *
|
||||
Math.pow(2, zoom)
|
||||
);
|
||||
}
|
||||
|
||||
const TILE_CACHE_NAME = 'excalibur-offline-map-tiles-v1';
|
||||
const DEFAULT_TILE_URL = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png';
|
||||
|
||||
export default function MapView({
|
||||
initialCenter = [11.5761, 48.1371], // Munich default [lng, lat]
|
||||
initialZoom = 13,
|
||||
markers = [],
|
||||
onMarkerClick,
|
||||
tileUrlTemplate = DEFAULT_TILE_URL,
|
||||
}: MapViewProps) {
|
||||
const mapContainerRef = useRef<HTMLDivElement>(null);
|
||||
const mapRef = useRef<maplibregl.Map | null>(null);
|
||||
const activeMarkersRef = useRef<Map<string, maplibregl.Marker>>(new Map());
|
||||
|
||||
const [isCaching, setIsCaching] = useState(false);
|
||||
const [cacheProgress, setCacheProgress] = useState<{ loaded: number; total: number } | null>(null);
|
||||
|
||||
// 1. Initialize Map instance
|
||||
useEffect(() => {
|
||||
if (!mapContainerRef.current) return;
|
||||
|
||||
// Standard OpenStreetMap raster style (can be swapped for MapTiler / custom PBF vector style)
|
||||
const mapStyle: maplibregl.StyleSpecification = {
|
||||
version: 8,
|
||||
sources: {
|
||||
'osm-tiles': {
|
||||
type: 'raster',
|
||||
tiles: [tileUrlTemplate],
|
||||
tileSize: 256,
|
||||
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
|
||||
},
|
||||
},
|
||||
layers: [
|
||||
{
|
||||
id: 'osm-tiles-layer',
|
||||
type: 'raster',
|
||||
source: 'osm-tiles',
|
||||
minzoom: 0,
|
||||
maxzoom: 19,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const map = new maplibregl.Map({
|
||||
container: mapContainerRef.current,
|
||||
style: mapStyle,
|
||||
center: initialCenter,
|
||||
zoom: initialZoom,
|
||||
});
|
||||
|
||||
// Default Controls
|
||||
map.addControl(new maplibregl.NavigationControl({ visualizePitch: true }), 'top-right');
|
||||
|
||||
// Offline Geolocation Control (Uses Native Device GPS)
|
||||
const geolocate = new maplibregl.GeolocateControl({
|
||||
positionOptions: {
|
||||
enableHighAccuracy: true,
|
||||
},
|
||||
trackUserLocation: true,
|
||||
showUserLocation: true,
|
||||
showAccuracyCircle: true,
|
||||
});
|
||||
map.addControl(geolocate, 'top-right');
|
||||
|
||||
map.addControl(new maplibregl.ScaleControl({ unit: 'metric' }), 'bottom-left');
|
||||
|
||||
mapRef.current = map;
|
||||
|
||||
return () => {
|
||||
map.remove();
|
||||
mapRef.current = null;
|
||||
};
|
||||
}, [initialCenter, initialZoom, tileUrlTemplate]);
|
||||
|
||||
// 2. Manage Markers Sync
|
||||
useEffect(() => {
|
||||
const map = mapRef.current;
|
||||
if (!map) return;
|
||||
|
||||
const currentMarkers = activeMarkersRef.current;
|
||||
const incomingMarkerIds = new Set(markers.map((m) => m.id));
|
||||
|
||||
// Remove obsolete markers
|
||||
currentMarkers.forEach((markerInstance, id) => {
|
||||
if (!incomingMarkerIds.has(id)) {
|
||||
markerInstance.remove();
|
||||
currentMarkers.delete(id);
|
||||
}
|
||||
});
|
||||
|
||||
// Add / Update markers
|
||||
markers.forEach((markerData) => {
|
||||
if (!currentMarkers.has(markerData.id)) {
|
||||
const popup = new maplibregl.Popup({ offset: 25 }).setHTML(
|
||||
`<strong>${markerData.title}</strong>${
|
||||
markerData.description ? `<p style="margin:4px 0 0;font-size:12px;">${markerData.description}</p>` : ''
|
||||
}`
|
||||
);
|
||||
|
||||
const newMarker = new maplibregl.Marker({ color: '#e11d48' })
|
||||
.setLngLat([markerData.lng, markerData.lat])
|
||||
.setPopup(popup)
|
||||
.addTo(map);
|
||||
|
||||
newMarker.getElement().addEventListener('click', () => {
|
||||
onMarkerClick?.(markerData);
|
||||
});
|
||||
|
||||
currentMarkers.set(markerData.id, newMarker);
|
||||
}
|
||||
});
|
||||
}, [markers, onMarkerClick]);
|
||||
|
||||
// 3. Region Precaching Logic for Offline Woods Usage
|
||||
const precacheCurrentRegion = useCallback(async () => {
|
||||
const map = mapRef.current;
|
||||
if (!map) return;
|
||||
|
||||
setIsCaching(true);
|
||||
setCacheProgress({ loaded: 0, total: 0 });
|
||||
|
||||
const bounds = map.getBounds();
|
||||
const currentZoom = Math.floor(map.getZoom());
|
||||
|
||||
// Precache current zoom level + 3 additional detailed zoom levels for hiking trails
|
||||
const minZoom = Math.max(10, currentZoom);
|
||||
const maxZoom = Math.min(17, currentZoom + 3);
|
||||
|
||||
const tileUrls: string[] = [];
|
||||
|
||||
for (let z = minZoom; z <= maxZoom; z++) {
|
||||
const minX = lng2tile(bounds.getWest(), z);
|
||||
const maxX = lng2tile(bounds.getEast(), z);
|
||||
const minY = lat2tile(bounds.getNorth(), z);
|
||||
const maxY = lat2tile(bounds.getSouth(), z);
|
||||
|
||||
for (let x = Math.min(minX, maxX); x <= Math.max(minX, maxX); x++) {
|
||||
for (let y = Math.min(minY, maxY); y <= Math.max(minY, maxY); y++) {
|
||||
const url = tileUrlTemplate
|
||||
.replace('{z}', z.toString())
|
||||
.replace('{x}', x.toString())
|
||||
.replace('{y}', y.toString());
|
||||
tileUrls.push(url);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setCacheProgress({ loaded: 0, total: tileUrls.length });
|
||||
|
||||
try {
|
||||
const cache = await caches.open(TILE_CACHE_NAME);
|
||||
let loaded = 0;
|
||||
|
||||
// Fetch tiles in batches to avoid network throttling
|
||||
const BATCH_SIZE = 6;
|
||||
for (let i = 0; i < tileUrls.length; i += BATCH_SIZE) {
|
||||
const batch = tileUrls.slice(i, i + BATCH_SIZE);
|
||||
await Promise.all(
|
||||
batch.map(async (url) => {
|
||||
try {
|
||||
const response = await fetch(url, { mode: 'cors' });
|
||||
if (response.ok) {
|
||||
await cache.put(url, response);
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn(`Failed to precache tile: ${url}`, err);
|
||||
} finally {
|
||||
loaded++;
|
||||
setCacheProgress({ loaded, total: tileUrls.length });
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error opening tile cache:', err);
|
||||
} finally {
|
||||
setIsCaching(false);
|
||||
}
|
||||
}, [tileUrlTemplate]);
|
||||
|
||||
return (
|
||||
<div className={styles.mapWrapper}>
|
||||
<div className={styles.controlOverlay}>
|
||||
<button
|
||||
className={styles.precacheButton}
|
||||
onClick={precacheCurrentRegion}
|
||||
disabled={isCaching}
|
||||
>
|
||||
{isCaching ? 'Downloading Area...' : 'Precache Region for Offline'}
|
||||
</button>
|
||||
|
||||
{cacheProgress && cacheProgress.total > 0 && (
|
||||
<div className={styles.progressContainer}>
|
||||
<span>
|
||||
{cacheProgress.loaded} / {cacheProgress.total} tiles saved
|
||||
</span>
|
||||
<div className={styles.progressBar}>
|
||||
<div
|
||||
className={styles.progressFill}
|
||||
style={{
|
||||
width: `${Math.round((cacheProgress.loaded / cacheProgress.total) * 100)}%`,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div ref={mapContainerRef} className={styles.mapContainer} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,29 @@
|
||||
'use client';
|
||||
|
||||
import { useSyncExternalStore, useCallback } from 'react';
|
||||
|
||||
function subscribe(callback: () => void) {
|
||||
window.addEventListener('storage', callback);
|
||||
return () => window.removeEventListener('storage', callback);
|
||||
}
|
||||
|
||||
export function useLocalStorage(key: string, defaultValue: string) {
|
||||
const getSnapshot = () => {
|
||||
if (typeof window === 'undefined') return defaultValue;
|
||||
return localStorage.getItem(key) ?? defaultValue;
|
||||
};
|
||||
|
||||
const getServerSnapshot = () => defaultValue;
|
||||
|
||||
const value = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
|
||||
|
||||
const setValue = useCallback(
|
||||
(newValue: string) => {
|
||||
localStorage.setItem(key, newValue);
|
||||
window.dispatchEvent(new Event('storage'));
|
||||
},
|
||||
[key]
|
||||
);
|
||||
|
||||
return [value, setValue] as const;
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { checkGpsPermission, checkCameraPermission, PermissionStateResult } from '../utils/permissions';
|
||||
|
||||
export function usePermissions() {
|
||||
const [gpsStatus, setGpsStatus] = useState<PermissionStateResult>('prompt');
|
||||
const [cameraStatus, setCameraStatus] = useState<PermissionStateResult>('prompt');
|
||||
|
||||
const updatePermissions = useCallback(async () => {
|
||||
const [gps, camera] = await Promise.all([
|
||||
checkGpsPermission(),
|
||||
checkCameraPermission(),
|
||||
]);
|
||||
setGpsStatus(gps);
|
||||
setCameraStatus(camera);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
let isMounted = true;
|
||||
|
||||
const initPermissions = async () => {
|
||||
const [gps, camera] = await Promise.all([
|
||||
checkGpsPermission(),
|
||||
checkCameraPermission(),
|
||||
]);
|
||||
if (isMounted) {
|
||||
setGpsStatus(gps);
|
||||
setCameraStatus(camera);
|
||||
}
|
||||
};
|
||||
|
||||
initPermissions();
|
||||
|
||||
if (typeof window !== 'undefined' && 'permissions' in navigator) {
|
||||
const registerListener = async (
|
||||
permissionName: PermissionName,
|
||||
setter: (val: PermissionStateResult) => void
|
||||
) => {
|
||||
try {
|
||||
const status = await navigator.permissions.query({ name: permissionName });
|
||||
const handleChange = () => setter(status.state);
|
||||
status.addEventListener('change', handleChange);
|
||||
return () => status.removeEventListener('change', handleChange);
|
||||
} catch {
|
||||
return () => {};
|
||||
}
|
||||
};
|
||||
|
||||
const cleanupGps = registerListener('geolocation', (val) => isMounted && setGpsStatus(val));
|
||||
const cleanupCamera = registerListener('camera' as PermissionName, (val) => isMounted && setCameraStatus(val));
|
||||
|
||||
return () => {
|
||||
isMounted = false;
|
||||
cleanupGps.then((cleanup) => cleanup());
|
||||
cleanupCamera.then((cleanup) => cleanup());
|
||||
};
|
||||
}
|
||||
|
||||
return () => {
|
||||
isMounted = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
return { gpsStatus, cameraStatus, refresh: updatePermissions };
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
export type PermissionStateResult = 'granted' | 'prompt' | 'denied' | 'unsupported';
|
||||
|
||||
/**
|
||||
* Check GPS / Geolocation permission status
|
||||
*/
|
||||
export async function checkGpsPermission(): Promise<PermissionStateResult> {
|
||||
if (typeof window === 'undefined' || !('permissions' in navigator)) {
|
||||
return 'unsupported';
|
||||
}
|
||||
|
||||
try {
|
||||
const status = await navigator.permissions.query({ name: 'geolocation' });
|
||||
return status.state; // 'granted' | 'prompt' | 'denied'
|
||||
} catch {
|
||||
return 'unsupported';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check Camera permission status with fallback
|
||||
*/
|
||||
export async function checkCameraPermission(): Promise<PermissionStateResult> {
|
||||
if (typeof window === 'undefined') return 'unsupported';
|
||||
|
||||
// 1. Try modern Permissions API query
|
||||
if ('permissions' in navigator) {
|
||||
try {
|
||||
const status = await navigator.permissions.query({ name: 'camera' as PermissionName });
|
||||
return status.state;
|
||||
} catch {
|
||||
// Browser doesn't support 'camera' in permissions.query (e.g., Safari)
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Fallback: Inspect mediaDevice device labels
|
||||
if ('mediaDevices' in navigator && 'enumerateDevices' in navigator.mediaDevices) {
|
||||
try {
|
||||
const devices = await navigator.mediaDevices.enumerateDevices();
|
||||
const videoInputs = devices.filter((device) => device.kind === 'videoinput');
|
||||
|
||||
// If camera label is not empty, permission has already been granted
|
||||
if (videoInputs.some((device) => device.label !== '')) {
|
||||
return 'granted';
|
||||
}
|
||||
return 'prompt';
|
||||
} catch {
|
||||
return 'unsupported';
|
||||
}
|
||||
}
|
||||
|
||||
return 'unsupported';
|
||||
}
|
||||
Reference in new issue
Block a user