Implement PWA shell (task 50)

Add web manifest, placeholder icons, app-shell service worker, and
install prompt so famapp is installable on iOS and Android home screens.

- public/manifest.webmanifest — name, short_name, standalone display,
  start_url /, all four icon sizes (192/384/512 + maskable)
- public/icon-{180,192,384,512,512-maskable}.png — indigo placeholder
  squares generated by scripts/generate-icons.mjs (pnpm gen:icons)
- public/icon.svg — house-icon SVG source for future branded export
- public/sw.js — hand-rolled app-shell SW: precaches offline.html,
  cache-first for /_next/static/, network-first navigation with offline
  fallback, network-only for /api/*
- public/offline.html — branded offline fallback page
- src/components/pwa-register.tsx — client SW registration
- src/components/install-prompt.tsx — dismissible install banner:
  beforeinstallprompt on Android, "Add to Home Screen" hint on iOS
- Root layout: viewport themeColor, manifest/appleWebApp metadata,
  apple-touch-icon, mounts PwaRegister + InstallPrompt

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
ginnoir
2026-05-06 16:00:02 -05:00
co-authored by Claude Sonnet 4.6
parent d5a8bf9d95
commit 8aab25e0ac
15 changed files with 459 additions and 2 deletions
+2
View File
@@ -27,6 +27,8 @@ Living progress tracker. Update at the end of each task. Codex and Claude Code b
- **26 — Customizable layout + widget configuration**. Installed `react-grid-layout` v2. Dashboard pages check `?edit=1` to enter edit mode, rendering a client `DashboardEditor` instead of the static grid. Editor uses `react-grid-layout` with `gridConfig`/`dragConfig` v2 API; each widget shell shows a drag handle, configure button (⚙), and remove button (🗑). `WidgetPicker` is a two-step modal: step 1 lists all registry widgets grouped by category; step 2 is a `WidgetConfigurator` auto-generated from the widget's default config — handles `"all"|string[]` multi-selects, booleans, numbers, and enums. `resolveWidgetConfigOptions` server action fetches dynamic options (calendars, lists). Save validates each config against its registered Zod schema. Reset to defaults calls `computeDefaultLayout()`. `pnpm typecheck`, `pnpm build` pass.
- **31 — Public share viewer**. Made `actorId` nullable in `activity_log` (migration `0010_nullable_actor_id.sql`, `onDelete: "set null"`) for anonymous share-page mutations. Added `logShareActivity` to `_core/activity.ts` (no session, explicit `householdId`). Added `householdId` to `resolveShareToken` return. Added `renderSharedView` to `EntityTypeRegistration` type. Each module implements `loadForShare` (bare DB queries, no session) and `renderSharedView`: calendar shows upcoming 90-day events or single-event details, lists shows items with optional toggle, notes shows title + body. `toggleShareListItem` server action lives in `lists/server/share-actions.ts` — validates token write capability, verifies item→list→household chain, logs `share.toggle` with `actorId = null`. `/app/s/[token]/page.tsx` resolves token, dispatches to `loadForShare` + `renderSharedView`, returns friendly error for invalid/expired tokens, sets `noindex`. Middleware `/s/*` exemption confirmed present. `pnpm typecheck`, `pnpm lint`, `pnpm build`, and all 4 E2E specs pass.
- **50 — PWA shell**. `public/manifest.webmanifest` (name, short_name, icons, theme_color, display: standalone, start_url `/`). Placeholder PNG icons at 180, 192, 384, 512 (regular + maskable) generated by `scripts/generate-icons.mjs` (`pnpm gen:icons`); `public/icon.svg` committed as source. Hand-rolled service worker at `public/sw.js`: precaches `offline.html` on install, cache-first for `/_next/static/`, network-first for navigation with offline fallback, network-only for API routes. `src/components/pwa-register.tsx` registers the SW client-side. `src/components/install-prompt.tsx` shows a dismissible banner: `beforeinstallprompt` on Android/Chrome, a one-time "Add to Home Screen" hint on iOS (detected via UA + `navigator.maxTouchPoints`, suppressed in standalone mode). Root layout exports `viewport` (themeColor), updated `metadata` (manifest, appleWebApp, apple-touch-icon), and mounts both new components. `pnpm typecheck`, `pnpm lint`, `pnpm build` all clean.
## Next up
- Next task in `docs/tasks/`.
+2 -1
View File
@@ -20,7 +20,8 @@
"db:generate": "drizzle-kit generate",
"db:migrate": "drizzle-kit migrate",
"db:seed": "tsx --env-file=.env scripts/seed.ts",
"db:studio": "drizzle-kit studio"
"db:studio": "drizzle-kit studio",
"gen:icons": "node scripts/generate-icons.mjs"
},
"devDependencies": {
"@eslint/eslintrc": "^3.3.5",
Binary file not shown.

After

Width:  |  Height:  |  Size: 496 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 547 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

+12
View File
@@ -0,0 +1,12 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
<!-- Background -->
<rect width="512" height="512" rx="80" fill="#4F46E5"/>
<!-- House body -->
<polygon points="256,108 396,234 364,234 364,392 148,392 148,234 116,234" fill="white"/>
<!-- Door -->
<rect x="212" y="296" width="88" height="96" rx="6" fill="#4F46E5"/>
<!-- Left window -->
<rect x="164" y="254" width="66" height="54" rx="6" fill="#4F46E5" opacity="0.55"/>
<!-- Right window -->
<rect x="282" y="254" width="66" height="54" rx="6" fill="#4F46E5" opacity="0.55"/>
</svg>

After

Width:  |  Height:  |  Size: 594 B

+32
View File
@@ -0,0 +1,32 @@
{
"name": "famapp",
"short_name": "famapp",
"description": "Family coordination app",
"start_url": "/",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#4F46E5",
"icons": [
{
"src": "/icon-192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/icon-384.png",
"sizes": "384x384",
"type": "image/png"
},
{
"src": "/icon-512.png",
"sizes": "512x512",
"type": "image/png"
},
{
"src": "/icon-512-maskable.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
}
]
}
+71
View File
@@ -0,0 +1,71 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#4F46E5" />
<title>famapp — offline</title>
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root { --indigo: #4F46E5; --indigo-light: #E0E7FF; }
body {
font-family: system-ui, -apple-system, sans-serif;
min-height: 100dvh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 1.25rem;
padding: 2rem;
background: #f9fafb;
color: #111827;
text-align: center;
}
.icon {
width: 72px;
height: 72px;
border-radius: 16px;
background: var(--indigo);
display: flex;
align-items: center;
justify-content: center;
}
.icon svg { width: 40px; height: 40px; }
h1 { font-size: 1.25rem; font-weight: 600; }
p { font-size: 0.9375rem; color: #6b7280; max-width: 28ch; }
button {
margin-top: 0.5rem;
padding: 0.625rem 1.5rem;
background: var(--indigo);
color: white;
border: none;
border-radius: 0.5rem;
font-size: 0.9375rem;
font-weight: 500;
cursor: pointer;
}
button:active { opacity: 0.85; }
</style>
</head>
<body>
<div class="icon">
<!-- House silhouette -->
<svg viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
<polygon points="20,5 34,17 31,17 31,35 9,35 9,17 6,17" fill="white"/>
<rect x="15" y="22" width="10" height="13" rx="1" fill="#4F46E5"/>
</svg>
</div>
<h1>You're offline</h1>
<p>famapp needs a connection — check your network and try again.</p>
<button onclick="location.reload()">Retry</button>
</body>
</html>
+69
View File
@@ -0,0 +1,69 @@
// famapp service worker — app-shell pattern
// Caches a minimal offline fallback on install.
// Navigation requests: network-first with offline fallback.
// Next.js static chunks: cache-first.
// API routes: network-only (pass through).
const CACHE = "famapp-shell-v1";
const OFFLINE = "/offline.html";
// --- install: precache offline shell ---
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE).then((cache) => cache.add(OFFLINE))
);
self.skipWaiting();
});
// --- activate: evict old caches ---
self.addEventListener("activate", (event) => {
event.waitUntil(
caches
.keys()
.then((keys) =>
Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)))
)
);
self.clients.claim();
});
// --- fetch ---
self.addEventListener("fetch", (event) => {
const { request } = event;
if (request.method !== "GET") return;
const url = new URL(request.url);
// API routes — always go to network, never cache.
if (url.pathname.startsWith("/api/")) return;
// NextAuth — network-only.
if (url.pathname.startsWith("/api/auth/")) return;
// Next.js immutable static assets — cache-first.
if (url.pathname.startsWith("/_next/static/")) {
event.respondWith(
caches.match(request).then(
(cached) =>
cached ??
fetch(request).then((res) => {
const clone = res.clone();
caches.open(CACHE).then((c) => c.put(request, clone));
return res;
})
)
);
return;
}
// Navigation requests — network-first, serve offline shell if unreachable.
if (request.mode === "navigate") {
event.respondWith(
fetch(request).catch(() => caches.match(OFFLINE))
);
return;
}
});
+101
View File
@@ -0,0 +1,101 @@
/**
* Generates placeholder PNG icons for the famapp PWA.
*
* Usage: node scripts/generate-icons.mjs
*
* Produces:
* public/icon-192.png
* public/icon-384.png
* public/icon-512.png
* public/icon-512-maskable.png (same image; OS applies its own mask)
* public/icon-180.png (apple-touch-icon)
*
* All images are solid indigo (#4F46E5) squares — replace with a real
* branded export from icon.svg when assets are finalised.
*/
import { deflateSync } from "zlib";
import { writeFileSync } from "fs";
import { resolve, dirname } from "path";
import { fileURLToPath } from "url";
const __dir = dirname(fileURLToPath(import.meta.url));
const publicDir = resolve(__dir, "../public");
// Build CRC-32 lookup table once.
const CRC_TABLE = new Uint32Array(256);
for (let i = 0; i < 256; i++) {
let c = i;
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
CRC_TABLE[i] = c;
}
function crc32(buf) {
let crc = 0xffffffff;
for (let i = 0; i < buf.length; i++)
crc = CRC_TABLE[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);
return (crc ^ 0xffffffff) >>> 0;
}
function u32(n) {
const b = Buffer.alloc(4);
b.writeUInt32BE(n, 0);
return b;
}
function pngChunk(type, data) {
const typeBytes = Buffer.from(type, "ascii");
const crc = u32(crc32(Buffer.concat([typeBytes, data])));
return Buffer.concat([u32(data.length), typeBytes, data, crc]);
}
/**
* Returns a Buffer containing a valid PNG of size×size filled with (r, g, b).
*/
function solidPNG(size, r, g, b) {
const PNG_SIG = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
const ihdr = pngChunk(
"IHDR",
Buffer.concat([
u32(size),
u32(size),
Buffer.from([8, 2, 0, 0, 0]), // 8-bit RGB, no interlace
])
);
// One filter byte (0 = None) followed by size×3 RGB bytes per row.
const rowLen = 1 + size * 3;
const raw = Buffer.alloc(size * rowLen);
for (let y = 0; y < size; y++) {
const base = y * rowLen;
raw[base] = 0;
for (let x = 0; x < size; x++) {
raw[base + 1 + x * 3] = r;
raw[base + 2 + x * 3] = g;
raw[base + 3 + x * 3] = b;
}
}
const idat = pngChunk("IDAT", deflateSync(raw));
const iend = pngChunk("IEND", Buffer.alloc(0));
return Buffer.concat([PNG_SIG, ihdr, idat, iend]);
}
// Indigo-600 (#4F46E5)
const [R, G, B] = [0x4f, 0x46, 0xe5];
const icons = [
{ name: "icon-192.png", size: 192 },
{ name: "icon-384.png", size: 384 },
{ name: "icon-512.png", size: 512 },
{ name: "icon-512-maskable.png", size: 512 },
{ name: "icon-180.png", size: 180 },
];
for (const { name, size } of icons) {
const out = resolve(publicDir, name);
writeFileSync(out, solidPNG(size, R, G, B));
console.log(` ✓ public/${name} (${size}×${size})`);
}
+18 -1
View File
@@ -1,4 +1,4 @@
import type { Metadata } from "next";
import type { Metadata, Viewport } from "next";
import "./globals.css";
import { Geist } from "next/font/google";
import { cn } from "@/lib/utils";
@@ -13,12 +13,27 @@ import { getQuickAdds } from "@/modules/_core";
import { QuickAddProvider } from "@/components/quick-add-provider";
import { QuickAddSheet } from "@/components/quick-add-sheet";
import { CommandPalette } from "@/components/command-palette";
import { PwaRegister } from "@/components/pwa-register";
import { InstallPrompt } from "@/components/install-prompt";
const geist = Geist({ subsets: ["latin"], variable: "--font-sans" });
export const viewport: Viewport = {
themeColor: "#4F46E5",
};
export const metadata: Metadata = {
title: "famapp",
description: "Family coordination app",
manifest: "/manifest.webmanifest",
appleWebApp: {
capable: true,
statusBarStyle: "default",
title: "famapp",
},
icons: {
apple: "/icon-180.png",
},
};
// Runs before paint — reads localStorage / prefers-color-scheme and applies
@@ -82,6 +97,8 @@ export default async function RootLayout({
<main>{children}</main>
<QuickAddSheet />
<CommandPalette />
<InstallPrompt />
<PwaRegister />
</QuickAddProvider>
</body>
</html>
+124
View File
@@ -0,0 +1,124 @@
"use client";
import { useEffect, useState } from "react";
import { X, Share, Plus } from "lucide-react";
const DISMISSED_KEY = "pwa-install-dismissed";
type Prompt = "android" | "ios";
function isIos() {
return (
/iphone|ipad|ipod/i.test(navigator.userAgent) ||
// iPad on iOS 13+ reports as Mac
(navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1)
);
}
function isInStandaloneMode() {
return (
"standalone" in window.navigator &&
(window.navigator as { standalone?: boolean }).standalone === true
);
}
export function InstallPrompt() {
const [prompt, setPrompt] = useState<Prompt | null>(null);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const [deferredEvent, setDeferredEvent] = useState<any>(null);
useEffect(() => {
if (localStorage.getItem(DISMISSED_KEY)) return;
// Android / Chrome desktop — beforeinstallprompt fires
const handler = (e: Event) => {
e.preventDefault();
setDeferredEvent(e);
setPrompt("android");
};
window.addEventListener("beforeinstallprompt", handler);
// iOS — no beforeinstallprompt; defer setState out of the synchronous
// effect body to satisfy react-hooks/set-state-in-effect.
let iosTimer: ReturnType<typeof setTimeout> | undefined;
if (isIos() && !isInStandaloneMode()) {
iosTimer = setTimeout(() => setPrompt("ios"), 0);
}
return () => {
window.removeEventListener("beforeinstallprompt", handler);
clearTimeout(iosTimer);
};
}, []);
function dismiss() {
localStorage.setItem(DISMISSED_KEY, "1");
setPrompt(null);
}
async function install() {
if (!deferredEvent) return;
deferredEvent.prompt();
const { outcome } = await deferredEvent.userChoice;
if (outcome === "accepted" || outcome === "dismissed") {
dismiss();
}
}
if (!prompt) return null;
return (
<div
role="banner"
className="fixed bottom-0 left-0 right-0 z-50 flex items-start gap-3 border-t bg-background px-4 py-3 shadow-lg sm:bottom-4 sm:left-1/2 sm:right-auto sm:-translate-x-1/2 sm:rounded-xl sm:border sm:px-5 sm:py-4 sm:shadow-xl"
>
{/* App icon */}
<div className="mt-0.5 h-10 w-10 shrink-0 overflow-hidden rounded-xl bg-[#4F46E5]">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src="/icon-192.png" alt="" className="h-full w-full object-cover" />
</div>
<div className="flex-1 text-sm">
<p className="font-semibold leading-snug">Add famapp to your home screen</p>
{prompt === "android" && (
<>
<p className="mt-0.5 text-muted-foreground">
Install for a faster, app-like experience.
</p>
<button
onClick={install}
className="mt-2 rounded-md bg-[#4F46E5] px-3 py-1.5 text-xs font-semibold text-white"
>
Install
</button>
</>
)}
{prompt === "ios" && (
<p className="mt-0.5 text-muted-foreground">
Tap{" "}
<Share
className="inline-block h-4 w-4 align-text-bottom"
aria-label="Share"
/>{" "}
then{" "}
<strong className="font-medium">
<Plus className="inline-block h-3.5 w-3.5 align-text-bottom" />
&nbsp;Add to Home Screen
</strong>
.
</p>
)}
</div>
<button
onClick={dismiss}
aria-label="Dismiss"
className="mt-0.5 shrink-0 rounded p-1 text-muted-foreground hover:bg-muted"
>
<X className="h-4 w-4" />
</button>
</div>
);
}
+28
View File
@@ -0,0 +1,28 @@
"use client";
import { useEffect } from "react";
export function PwaRegister() {
useEffect(() => {
if (!("serviceWorker" in navigator)) return;
navigator.serviceWorker
.register("/sw.js", { scope: "/" })
.then((reg) => {
reg.addEventListener("updatefound", () => {
const next = reg.installing;
if (!next) return;
next.addEventListener("statechange", () => {
if (next.state === "installed" && navigator.serviceWorker.controller) {
// New version available — the next navigation will pick it up
// because skipWaiting() is called in the SW install handler.
console.info("[famapp] Service worker updated.");
}
});
});
})
.catch((err) => console.warn("[famapp] SW registration failed:", err));
}, []);
return null;
}