diff --git a/web/app/layout.tsx b/web/app/layout.tsx index 907667e..5a0c29f 100644 --- a/web/app/layout.tsx +++ b/web/app/layout.tsx @@ -9,6 +9,10 @@ import { FirmenLogo } from "@/components/FirmenLogo"; import { NavLinks } from "@/components/NavLinks"; import { LogoutButton } from "@/components/LogoutButton"; import { MobileNav } from "@/components/MobileNav"; +import { PwaHead } from "@/components/pwa/PwaHead"; +import { ServiceWorkerRegistrierung } from "@/components/pwa/ServiceWorkerRegistrierung"; +import { OfflineBalken } from "@/components/pwa/OfflineBalken"; +import { themeFarbe } from "@/lib/pwa/manifest"; const inter = Inter({ subsets: ["latin"], variable: "--font-inter" }); @@ -16,6 +20,11 @@ export const metadata = { title: "Aushilfsfahrer", }; +export async function generateViewport() { + const ergebnis = await ladeEigeneFirma(); + return { themeColor: themeFarbe(ergebnis.status === "ok" ? ergebnis.firma : null) }; +} + export default async function RootLayout({ children, }: Readonly<{ children: React.ReactNode }>) { @@ -31,6 +40,9 @@ export default async function RootLayout({ return ( + + +

Profil nicht gefunden

@@ -47,6 +59,9 @@ export default async function RootLayout({ return ( + + + {result.status === "ok" && (
diff --git a/web/app/manifest.webmanifest/route.ts b/web/app/manifest.webmanifest/route.ts new file mode 100644 index 0000000..33d8be6 --- /dev/null +++ b/web/app/manifest.webmanifest/route.ts @@ -0,0 +1,13 @@ +import { ladeEigeneFirma } from "@/lib/firma/eigene-firma"; +import { baueManifest } from "@/lib/pwa/manifest"; + +export async function GET() { + const ergebnis = await ladeEigeneFirma(); + const manifest = baueManifest(ergebnis.status === "ok" ? ergebnis.firma : null); + return new Response(JSON.stringify(manifest), { + headers: { + "Content-Type": "application/manifest+json", + "Cache-Control": "private, no-cache", + }, + }); +} diff --git a/web/app/page.tsx b/web/app/page.tsx index a74cb27..8307ad3 100644 --- a/web/app/page.tsx +++ b/web/app/page.tsx @@ -1,5 +1,8 @@ import { redirect } from "next/navigation"; +import { loadProfile } from "@/lib/auth/profile"; -export default function Home() { +export default async function Home() { + const result = await loadProfile(); + if (result.status === "ok" && result.profile.role === "superadmin") redirect("/plattform"); redirect("/dashboard"); } diff --git a/web/components/pwa/OfflineBalken.tsx b/web/components/pwa/OfflineBalken.tsx new file mode 100644 index 0000000..2b026fd --- /dev/null +++ b/web/components/pwa/OfflineBalken.tsx @@ -0,0 +1,26 @@ +"use client"; + +import { useSyncExternalStore } from "react"; + +function abonnieren(callback: () => void) { + window.addEventListener("online", callback); + window.addEventListener("offline", callback); + return () => { + window.removeEventListener("online", callback); + window.removeEventListener("offline", callback); + }; +} + +export function OfflineBalken() { + const online = useSyncExternalStore( + abonnieren, + () => navigator.onLine, + () => true + ); + if (online) return null; + return ( +
+ Offline – keine Verbindung +
+ ); +} diff --git a/web/components/pwa/PwaHead.tsx b/web/components/pwa/PwaHead.tsx new file mode 100644 index 0000000..610baad --- /dev/null +++ b/web/components/pwa/PwaHead.tsx @@ -0,0 +1,15 @@ +import { iconUrl, type IconBranding } from "@/lib/pwa/icon-url"; +import { kurzname } from "@/lib/pwa/manifest"; + +export function PwaHead({ firma }: { firma: IconBranding | null }) { + return ( + <> + + + + + + + + ); +} diff --git a/web/components/pwa/ServiceWorkerRegistrierung.tsx b/web/components/pwa/ServiceWorkerRegistrierung.tsx new file mode 100644 index 0000000..b430f77 --- /dev/null +++ b/web/components/pwa/ServiceWorkerRegistrierung.tsx @@ -0,0 +1,11 @@ +"use client"; + +import { useEffect } from "react"; + +export function ServiceWorkerRegistrierung() { + useEffect(() => { + if (process.env.NODE_ENV !== "production" || !("serviceWorker" in navigator)) return; + navigator.serviceWorker.register("/sw.js").catch((e) => console.warn("Service Worker nicht registriert", e)); + }, []); + return null; +} diff --git a/web/lib/pwa/app-icon.ts b/web/lib/pwa/app-icon.ts index 66bc90a..15cb56b 100644 --- a/web/lib/pwa/app-icon.ts +++ b/web/lib/pwa/app-icon.ts @@ -1,16 +1,9 @@ -import { createHash } from "node:crypto"; import sharp from "sharp"; +import { iconUrl, iconVersion, type IconBranding, type IconGroesse } from "./icon-url"; import { validateLogo, type LogoEndung } from "@/lib/firma/logo"; -export type IconGroesse = "180" | "192" | "512" | "512-maskable"; - -export type IconBranding = { - id: string; - name: string; - logo_pfad: string | null; - app_icon_pfad: string | null; - farbe_primaer: string | null; -}; +export { iconUrl, iconVersion }; +export type { IconBranding, IconGroesse }; const GROESSEN: readonly IconGroesse[] = ["180", "192", "512", "512-maskable"]; const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; @@ -25,16 +18,6 @@ export function validateAppIcon(datei: { type: string; size: number }): ReturnTy return r.valid ? r : { valid: false, error: r.error.replace("Das Logo", "Das App-Icon") }; } -export function iconVersion(f: IconBranding | null): string { - if (!f) return "standard"; - const roh = [f.name, f.logo_pfad, f.app_icon_pfad, f.farbe_primaer].map((v) => v ?? "").join("|"); - return createHash("sha1").update(roh).digest("hex").slice(0, 10); -} - -export function iconUrl(f: IconBranding | null, groesse: IconGroesse): string { - return `/app-icon/${f ? f.id : "standard"}/${iconVersion(f)}/${groesse}.png`; -} - export function parseIconAnfrage( firma: string, datei: string diff --git a/web/lib/pwa/icon-url.ts b/web/lib/pwa/icon-url.ts new file mode 100644 index 0000000..71e10a0 --- /dev/null +++ b/web/lib/pwa/icon-url.ts @@ -0,0 +1,21 @@ +import { createHash } from "node:crypto"; + +export type IconGroesse = "180" | "192" | "512" | "512-maskable"; + +export type IconBranding = { + id: string; + name: string; + logo_pfad: string | null; + app_icon_pfad: string | null; + farbe_primaer: string | null; +}; + +export function iconVersion(f: IconBranding | null): string { + if (!f) return "standard"; + const roh = [f.name, f.logo_pfad, f.app_icon_pfad, f.farbe_primaer].map((v) => v ?? "").join("|"); + return createHash("sha1").update(roh).digest("hex").slice(0, 10); +} + +export function iconUrl(f: IconBranding | null, groesse: IconGroesse): string { + return `/app-icon/${f ? f.id : "standard"}/${iconVersion(f)}/${groesse}.png`; +} diff --git a/web/lib/pwa/manifest.test.ts b/web/lib/pwa/manifest.test.ts new file mode 100644 index 0000000..799edbf --- /dev/null +++ b/web/lib/pwa/manifest.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from "vitest"; +import { baueManifest, kurzname, themeFarbe } from "./manifest"; +import { iconUrl, type IconBranding } from "./icon-url"; + +const firma: IconBranding = { + id: "11111111-1111-1111-1111-111111111111", + name: "Mercedes-Benz Widmann GmbH", + logo_pfad: null, + app_icon_pfad: null, + farbe_primaer: "#123456", +}; + +describe("baueManifest", () => { + it("liefert ohne Firma das Standard-Branding", () => { + expect(baueManifest(null)).toEqual({ + name: "Aushilfsfahrer", + short_name: "Aushilfsfahrer", + theme_color: "#0071ed", + background_color: "#ffffff", + display: "standalone", + start_url: "/", + scope: "/", + lang: "de", + icons: [ + { src: iconUrl(null, "192"), sizes: "192x192", type: "image/png", purpose: "any" }, + { src: iconUrl(null, "512"), sizes: "512x512", type: "image/png", purpose: "any" }, + { src: iconUrl(null, "512-maskable"), sizes: "512x512", type: "image/png", purpose: "maskable" }, + ], + }); + }); + + it("nutzt Name, Farbe und Icons der Firma", () => { + const m = baueManifest(firma) as { name: string; short_name: string; theme_color: string; icons: { src: string }[] }; + expect(m.name).toBe("Mercedes-Benz Widmann GmbH"); + expect(m.short_name.length).toBeLessThanOrEqual(12); + expect(m.theme_color).toBe("#123456"); + for (const i of m.icons) expect(i.src).toContain(firma.id); + }); +}); + +describe("kurzname", () => { + it("kuerzt an der Wortgrenze, sonst hart", () => { + expect(kurzname("Widmann Fahrer GmbH")).toBe("Widmann"); + expect(kurzname("Mercedes-Benz Widmann GmbH")).toBe("Mercedes-Ben"); + expect(kurzname("Kurz AG")).toBe("Kurz AG"); + expect(kurzname("Abcdefghijkl Xy")).toBe("Abcdefghijkl"); + }); +}); + +describe("themeFarbe", () => { + it("faellt auf die Standardfarbe zurueck", () => { + expect(themeFarbe(null)).toBe("#0071ed"); + expect(themeFarbe({ farbe_primaer: null })).toBe("#0071ed"); + expect(themeFarbe({ farbe_primaer: "#123456" })).toBe("#123456"); + }); +}); diff --git a/web/lib/pwa/manifest.ts b/web/lib/pwa/manifest.ts new file mode 100644 index 0000000..f2a92ea --- /dev/null +++ b/web/lib/pwa/manifest.ts @@ -0,0 +1,37 @@ +import { STANDARD_FARBE_PRIMAER } from "@/lib/firma/farben"; +import { iconUrl, type IconBranding } from "./icon-url"; + +const STANDARD_NAME = "Aushilfsfahrer"; +const MAX_KURZNAME = 12; + +// Kurzname fuers Homescreen-Label: an der Wortgrenze kuerzen, sonst hart. +export function kurzname(name: string): string { + const n = name.trim(); + if (n.length <= MAX_KURZNAME) return n; + if (n[MAX_KURZNAME] === " ") return n.slice(0, MAX_KURZNAME); + const kopf = n.slice(0, MAX_KURZNAME); + const grenze = kopf.lastIndexOf(" "); + return grenze > 0 ? kopf.slice(0, grenze).trim() : kopf; +} + +export function themeFarbe(f: { farbe_primaer: string | null } | null): string { + return f?.farbe_primaer ?? STANDARD_FARBE_PRIMAER; +} + +export function baueManifest(f: IconBranding | null): Record { + return { + name: f ? f.name : STANDARD_NAME, + short_name: f ? kurzname(f.name) : STANDARD_NAME, + theme_color: themeFarbe(f), + background_color: "#ffffff", + display: "standalone", + start_url: "/", + scope: "/", + lang: "de", + icons: [ + { src: iconUrl(f, "192"), sizes: "192x192", type: "image/png", purpose: "any" }, + { src: iconUrl(f, "512"), sizes: "512x512", type: "image/png", purpose: "any" }, + { src: iconUrl(f, "512-maskable"), sizes: "512x512", type: "image/png", purpose: "maskable" }, + ], + }; +} diff --git a/web/lib/pwa/sw-regeln.test.ts b/web/lib/pwa/sw-regeln.test.ts new file mode 100644 index 0000000..de2e134 --- /dev/null +++ b/web/lib/pwa/sw-regeln.test.ts @@ -0,0 +1,22 @@ +import { createRequire } from "node:module"; +import { describe, expect, it } from "vitest"; + +(globalThis as unknown as { self: unknown }).self = { addEventListener() {} }; +const require = createRequire(import.meta.url); +const { istCachebar } = require("../../public/sw.js") as { istCachebar: (p: string) => boolean }; + +describe("istCachebar", () => { + it.each(["/_next/static/chunks/a.js", "/app-icon/f/v/192.png", "/brand/widmann-logo.svg", "/fonts/a.woff2"])( + "cached %s", + (p) => expect(istCachebar(p)).toBe(true) + ); + it.each([ + "/", + "/dashboard", + "/auftraege/x", + "/manifest.webmanifest", + "/firma/logo", + "/api/notifications/dispatch", + "/offline.html", + ])("cached nicht %s", (p) => expect(istCachebar(p)).toBe(false)); +}); diff --git a/web/middleware.ts b/web/middleware.ts index d1e85bb..eeea395 100644 --- a/web/middleware.ts +++ b/web/middleware.ts @@ -11,6 +11,8 @@ export async function middleware(request: NextRequest) { return await updateSession(request); } +// Ausgeschlossen: Manifest (ohne Session Standard-Branding), Service Worker und +// Offline-Seite -- muessen ohne Login-Redirect ladbar sein. export const config = { - matcher: ["/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp|wasm)$).*)"], + matcher: ["/((?!_next/static|_next/image|favicon.ico|manifest\\.webmanifest|sw\\.js|offline\\.html|.*\\.(?:svg|png|jpg|jpeg|gif|webp|wasm)$).*)"], }; diff --git a/web/public/offline.html b/web/public/offline.html new file mode 100644 index 0000000..7e9b8b0 --- /dev/null +++ b/web/public/offline.html @@ -0,0 +1,19 @@ + + + + + +Offline + + + +
+

Keine Verbindung. Bitte erneut versuchen, sobald du wieder Empfang hast.

+ +
+ + diff --git a/web/public/sw.js b/web/public/sw.js new file mode 100644 index 0000000..8557219 --- /dev/null +++ b/web/public/sw.js @@ -0,0 +1,51 @@ +const VERSION = "v1"; +const CACHE = `pwa-${VERSION}`; +const PRECACHE = ["/offline.html"]; + +function istCachebar(pathname) { + return ( + pathname.startsWith("/_next/static/") || + pathname.startsWith("/app-icon/") || + pathname.startsWith("/brand/") || + pathname.endsWith(".woff2") + ); +} + +self.addEventListener("install", (event) => { + event.waitUntil(caches.open(CACHE).then((c) => c.addAll(PRECACHE)).then(() => self.skipWaiting())); +}); + +self.addEventListener("activate", (event) => { + event.waitUntil( + caches + .keys() + .then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)))) + .then(() => self.clients.claim()) + ); +}); + +self.addEventListener("fetch", (event) => { + const request = event.request; + if (request.method !== "GET") return; + const url = new URL(request.url); + if (url.origin !== self.location.origin) return; + + if (request.mode === "navigate") { + event.respondWith(fetch(request).catch(() => caches.match("/offline.html"))); + return; + } + + if (!istCachebar(url.pathname)) return; + + event.respondWith( + caches.open(CACHE).then(async (cache) => { + const treffer = await cache.match(request); + if (treffer) return treffer; + const antwort = await fetch(request); + if (antwort.ok) cache.put(request, antwort.clone()); + return antwort; + }) + ); +}); + +if (typeof module !== "undefined") module.exports = { istCachebar };