feat(phase 3j pwa): manifest + service worker + icons → installable PWA

- web/static/manifest.webmanifest: name/short_name/start_url=/dashboard/
  display=standalone/theme_color/background_color + three icons (192, 512,
  512-maskable with ~12% safe-zone padding)
- web/static/sw.js: minimal SW — install caches /static/* shell assets,
  fetch is network-first with cache fallback on GETs only, skips /mcp/
  and non-GETs entirely. CACHE_NAME versioned for clean activate-time
  prune.
- cmd/icongen: stdlib-only generator that produces the three PNG icons
  from a stylised "p" monogram. Run once at brand-change, commit output.
- web.init() registers .webmanifest → application/manifest+json with
  mime.AddExtensionType so Chrome accepts the manifest at all
- layout.tmpl + login.tmpl: manifest link, apple-touch-icon, theme-color,
  apple-mobile-web-app-* metas, inline SW-register on load (silent on
  failure — older browsers still work)
- design.md gets §"PWA install (Phase 3j)"; CLAUDE.md "Out of scope"
  drops the Phase-3j line and adds push/background-sync as the
  remaining Otto-PWA territory
- 4 new tests cover manifest MIME, sw.js delivery, all 3 icons, layout
  meta tags
This commit is contained in:
mAi
2026-05-15 19:32:48 +02:00
parent 91c807da1d
commit 1d5db0fe7b
12 changed files with 389 additions and 2 deletions

View File

@@ -51,7 +51,7 @@ When a phase-1 follow-up surfaces (auth, hiding mai.projects test rows, mBrian t
## Out of scope (still)
- Multi-user
- Native PWA install (manifest.json + service worker) — Phase 3j if m wants home-screen install
- Push notifications + background sync (Otto-PWA's domain)
- Public exposure
- Generic SaaS-product instincts
- CLI surface (m has explicitly opted out)

128
cmd/icongen/main.go Normal file
View File

@@ -0,0 +1,128 @@
// icongen produces the three PNG icons projax needs for the PWA manifest.
// Run once at branch-cut, commit the output PNGs into web/static/, and forget
// this tool until the brand changes. Stdlib-only — no external image libs.
//
// go run ./cmd/icongen
//
// Output files (overwritten):
// web/static/icon-192.png
// web/static/icon-512.png
// web/static/icon-maskable.png (with 10% safe-zone padding)
package main
import (
"fmt"
"image"
"image/color"
"image/png"
"os"
)
func main() {
cases := []struct {
name string
size int
padding int // safe-zone padding for the maskable variant
}{
{"web/static/icon-192.png", 192, 0},
{"web/static/icon-512.png", 512, 0},
{"web/static/icon-maskable.png", 512, 64}, // ~12% safe area
}
for _, c := range cases {
img := renderIcon(c.size, c.padding)
f, err := os.Create(c.name)
if err != nil {
fmt.Fprintln(os.Stderr, "create:", err)
os.Exit(1)
}
if err := png.Encode(f, img); err != nil {
fmt.Fprintln(os.Stderr, "encode:", err)
os.Exit(1)
}
_ = f.Close()
fmt.Println("wrote", c.name)
}
}
// renderIcon draws a stylised "p" monogram inside a rounded-square dark
// background. padding is the safe-zone inset (icon content shrinks to make
// room for the maskable cutout regions).
func renderIcon(size, padding int) image.Image {
img := image.NewRGBA(image.Rect(0, 0, size, size))
bg := color.RGBA{0x1a, 0x1a, 0x1a, 0xff}
fg := color.RGBA{0xe0, 0xe0, 0xe0, 0xff}
accent := color.RGBA{0x2f, 0x5d, 0x9e, 0xff}
// Background fill.
fillRect(img, image.Rect(0, 0, size, size), bg)
// Rounded-corner mask only on the non-maskable variants. For maskable
// PWA icons the system clips to its own mask shape, so the full square
// must be filled (the padding gives the system room to clip).
if padding == 0 {
drawRoundedSquare(img, size, bg)
}
// Inset by padding so the "p" sits inside the safe zone.
inset := padding
content := image.Rect(inset, inset, size-inset, size-inset)
// Letterform: a stylised "p". Composed of three rectangles + a circle
// approximation built from filled disks.
cw := content.Dx() // content width
ch := content.Dy()
stemW := cw / 8
bowlH := ch * 2 / 5
stemX := content.Min.X + cw*5/16
stemTopY := content.Min.Y + ch/6
stemBotY := content.Max.Y - ch/8
// Vertical stem.
fillRect(img, image.Rect(stemX, stemTopY, stemX+stemW, stemBotY), fg)
// Bowl top.
bowlLeft := stemX
bowlRight := content.Min.X + cw*12/16
bowlTop := stemTopY
bowlBot := bowlTop + bowlH
fillRect(img, image.Rect(bowlLeft, bowlTop, bowlRight, bowlTop+stemW), fg)
// Bowl bottom of the closed loop.
fillRect(img, image.Rect(bowlLeft, bowlBot-stemW, bowlRight, bowlBot), fg)
// Bowl right side.
fillRect(img, image.Rect(bowlRight-stemW, bowlTop, bowlRight, bowlBot), fg)
// Accent stripe at the bottom (projax's blue) for branding.
stripeTop := content.Max.Y - ch/16
fillRect(img, image.Rect(content.Min.X, stripeTop, content.Max.X, content.Max.Y), accent)
return img
}
func fillRect(img *image.RGBA, r image.Rectangle, c color.Color) {
r = r.Intersect(img.Bounds())
for y := r.Min.Y; y < r.Max.Y; y++ {
for x := r.Min.X; x < r.Max.X; x++ {
img.Set(x, y, c)
}
}
}
// drawRoundedSquare punches corners of the canvas to transparent so the icon
// reads as a tile rather than a hard-edged square. Only used on the
// non-maskable variants — the maskable system clips with its own mask shape.
func drawRoundedSquare(img *image.RGBA, size int, bg color.RGBA) {
radius := size / 10
transparent := color.RGBA{0, 0, 0, 0}
for y := 0; y < radius; y++ {
for x := 0; x < radius; x++ {
dx := radius - x
dy := radius - y
if dx*dx+dy*dy > radius*radius {
img.Set(x, y, transparent)
img.Set(size-1-x, y, transparent)
img.Set(x, size-1-y, transparent)
img.Set(size-1-x, size-1-y, transparent)
}
}
}
_ = bg
}

View File

@@ -442,11 +442,40 @@ Pure CSS + minimal template tweaks make every projax page legible and tappable o
**Out of scope:**
- Native PWA install (manifest.json + service worker) — Phase 3j candidate.
- Push notifications (Otto-PWA's domain).
- Dark mode toggle.
- Right-to-left layout.
## PWA install (Phase 3j)
projax is now installable as a real PWA — iOS Safari "Add to Home Screen" produces a standalone-launching icon and Android Chrome offers the same install flow. Scope is "install affordance," NOT full offline mode.
**Manifest** (`/static/manifest.webmanifest`, served with `application/manifest+json` via `mime.AddExtensionType` in `web.init`):
- `name` / `short_name`: "projax"
- `start_url`: `/dashboard` (the daily-driver surface m wants on tap)
- `scope`: `/`
- `display`: `standalone`
- `theme_color` / `background_color`: `#1a1a1a` (matches login-page palette)
- `icons`: 192×192, 512×512, and a 512×512 maskable variant with ~12% safe-zone padding
**Icons** (`/static/icon-{192,512,maskable}.png`): stdlib-only generation via `cmd/icongen``go run ./cmd/icongen` rewrites them from the source design. Stylised "p" monogram on a dark ground with an accent stripe. Re-run when the brand or palette changes; the PNGs are checked in.
**Service worker** (`/static/sw.js`):
- On `install`: pre-cache `/static/style.css` + manifest + icons.
- On `activate`: prune stale caches from earlier `CACHE_NAME` versions.
- On `fetch` (GET only): network-first with cache fallback on failure. Successful GETs are stashed for the next offline render.
- Explicitly skipped: any non-GET request, anything under `/mcp/`.
This is deliberately the smallest correct service worker. Mutations (CalDAV/Gitea writeback, MCP) require the network; m airplane-modes → he sees the last cached read view but can't change anything until reconnected.
**Layout meta**: `theme-color`, `apple-mobile-web-app-capable=yes` (iOS treats as standalone), `apple-mobile-web-app-status-bar-style=black-translucent`, `apple-mobile-web-app-title=projax`, plus the `<link rel="manifest">` + `<link rel="apple-touch-icon">` chain. Login template carries the same set so a first-time install from `/login` works the same as from `/dashboard`.
**Tests**: `TestManifestServedWithCorrectMIME`, `TestServiceWorkerServed`, `TestIconsServed`, `TestLayoutHasManifestAndAppleTouchIcon`.
**Out of scope for 3j**: push notifications, background sync, full offline write mode, splash-screen tuning.
## 9. Phase-1 deliverable checklist
- [ ] `projax.items` + `projax.item_links` migrations in `db/migrations/`

121
web/pwa_test.go Normal file
View File

@@ -0,0 +1,121 @@
package web_test
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// TestManifestServedWithCorrectMIME asserts /static/manifest.webmanifest
// returns 200 with the W3C-required Content-Type. Without it, Chrome treats
// the file as plain text and refuses to register the manifest.
func TestManifestServedWithCorrectMIME(t *testing.T) {
srv, pool := mustServer(t)
defer pool.Close()
h := srv.Routes()
req := httptest.NewRequest(http.MethodGet, "/static/manifest.webmanifest", nil)
w := httptest.NewRecorder()
h.ServeHTTP(w, req)
if w.Result().StatusCode != 200 {
t.Fatalf("GET manifest → %d", w.Result().StatusCode)
}
ct := w.Result().Header.Get("Content-Type")
if !strings.HasPrefix(ct, "application/manifest+json") {
t.Errorf("Content-Type = %q, want application/manifest+json", ct)
}
// Validate the manifest payload parses + has required fields.
var m map[string]any
body, _ := readAll(t, w.Result().Body)
if err := json.Unmarshal([]byte(body), &m); err != nil {
t.Fatalf("manifest is not valid JSON: %v\n%s", err, body)
}
for _, k := range []string{"name", "short_name", "start_url", "display", "icons", "theme_color"} {
if _, ok := m[k]; !ok {
t.Errorf("manifest missing required field %q", k)
}
}
}
func TestServiceWorkerServed(t *testing.T) {
srv, pool := mustServer(t)
defer pool.Close()
h := srv.Routes()
req := httptest.NewRequest(http.MethodGet, "/static/sw.js", nil)
w := httptest.NewRecorder()
h.ServeHTTP(w, req)
if w.Result().StatusCode != 200 {
t.Fatalf("GET sw.js → %d", w.Result().StatusCode)
}
ct := w.Result().Header.Get("Content-Type")
if !strings.Contains(ct, "javascript") {
t.Errorf("Content-Type = %q, want a javascript type", ct)
}
body, _ := readAll(t, w.Result().Body)
for _, want := range []string{"CACHE_NAME", "addEventListener", "fetch"} {
if !strings.Contains(body, want) {
t.Errorf("sw.js missing %q", want)
}
}
}
func TestIconsServed(t *testing.T) {
srv, pool := mustServer(t)
defer pool.Close()
h := srv.Routes()
for _, p := range []string{"/static/icon-192.png", "/static/icon-512.png", "/static/icon-maskable.png"} {
req := httptest.NewRequest(http.MethodGet, p, nil)
w := httptest.NewRecorder()
h.ServeHTTP(w, req)
if w.Result().StatusCode != 200 {
t.Errorf("GET %s → %d", p, w.Result().StatusCode)
}
if ct := w.Result().Header.Get("Content-Type"); ct != "image/png" {
t.Errorf("GET %s Content-Type = %q, want image/png", p, ct)
}
}
}
func TestLayoutHasManifestAndAppleTouchIcon(t *testing.T) {
srv, pool := mustServer(t)
defer pool.Close()
h := srv.Routes()
_, body := get(t, h, "/dashboard")
for _, want := range []string{
`rel="manifest"`,
`/static/manifest.webmanifest`,
`rel="apple-touch-icon"`,
`/static/icon-192.png`,
`name="theme-color"`,
`apple-mobile-web-app-capable`,
`serviceWorker`,
} {
if !strings.Contains(body, want) {
t.Errorf("layout missing %q", want)
}
}
}
// readAll is a tiny helper that returns the response body as a string.
func readAll(t *testing.T, body interface {
Read(p []byte) (n int, err error)
Close() error
}) (string, error) {
t.Helper()
defer body.Close()
var b strings.Builder
buf := make([]byte, 4096)
for {
n, err := body.Read(buf)
if n > 0 {
b.Write(buf[:n])
}
if err != nil {
if err.Error() == "EOF" {
return b.String(), nil
}
return b.String(), err
}
}
}

View File

@@ -8,6 +8,7 @@ import (
"html/template"
"io/fs"
"log/slog"
"mime"
"net/http"
"sort"
"strings"
@@ -16,6 +17,14 @@ import (
"github.com/m/projax/store"
)
// Register MIME types stdlib doesn't ship by default. The web-app manifest
// spec requires application/manifest+json for the `<link rel=manifest>` →
// without this Go's FileServer falls back to text/plain and Chrome refuses
// to treat the file as a manifest.
func init() {
_ = mime.AddExtensionType(".webmanifest", "application/manifest+json")
}
//go:embed templates/*.tmpl
var templatesFS embed.FS

BIN
web/static/icon-192.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 768 B

BIN
web/static/icon-512.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

View File

@@ -0,0 +1,16 @@
{
"name": "projax",
"short_name": "projax",
"description": "m's project + task data backbone",
"start_url": "/dashboard",
"scope": "/",
"display": "standalone",
"orientation": "portrait",
"background_color": "#1a1a1a",
"theme_color": "#1a1a1a",
"icons": [
{ "src": "/static/icon-192.png", "sizes": "192x192", "type": "image/png" },
{ "src": "/static/icon-512.png", "sizes": "512x512", "type": "image/png" },
{ "src": "/static/icon-maskable.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" }
]
}

59
web/static/sw.js Normal file
View File

@@ -0,0 +1,59 @@
// projax service worker — Phase 3j install affordance only.
//
// Strategy:
// * On install: pre-cache /static/style.css + manifest + icons so the
// standalone shell renders even when offline.
// * On fetch (GET only): network-first. On network failure, fall back to
// cache. POSTs, the /mcp/ surface, and everything else go straight to the
// network so writeback semantics are preserved.
// * On activate: prune stale caches from earlier versions.
//
// This is NOT full offline mode. It's enough to make the icon work as a
// real PWA + keep static assets warm. Mutations (CalDAV / Gitea writeback)
// still require connectivity.
const CACHE_NAME = 'projax-shell-v1';
const SHELL_ASSETS = [
'/static/style.css',
'/static/manifest.webmanifest',
'/static/icon-192.png',
'/static/icon-512.png',
'/static/icon-maskable.png',
];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => cache.addAll(SHELL_ASSETS))
);
self.skipWaiting();
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((keys) =>
Promise.all(keys.filter((k) => k !== CACHE_NAME).map((k) => caches.delete(k)))
)
);
self.clients.claim();
});
self.addEventListener('fetch', (event) => {
const req = event.request;
// Only GET — never cache POST/PATCH/DELETE/PUT (writeback + MCP RPC).
if (req.method !== 'GET') return;
// Skip MCP RPC entirely — it's stateful JSON-RPC.
if (new URL(req.url).pathname.startsWith('/mcp/')) return;
event.respondWith(
fetch(req)
.then((res) => {
// Stash successful GETs into the cache for offline fallback.
if (res.ok && req.url.startsWith(self.location.origin)) {
const copy = res.clone();
caches.open(CACHE_NAME).then((c) => c.put(req, copy));
}
return res;
})
.catch(() => caches.match(req))
);
});

View File

@@ -3,9 +3,27 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="theme-color" content="#1a1a1a">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="apple-mobile-web-app-title" content="projax">
<title>{{.Title}} — projax</title>
<link rel="manifest" href="/static/manifest.webmanifest">
<link rel="apple-touch-icon" href="/static/icon-192.png">
<link rel="icon" type="image/png" sizes="192x192" href="/static/icon-192.png">
<link rel="icon" type="image/png" sizes="512x512" href="/static/icon-512.png">
<link rel="stylesheet" href="/static/style.css">
<script src="https://unpkg.com/htmx.org@1.9.12" integrity="sha384-ujb1lZYygJmzgSwoxRggbCHcjc0rB2XoQrxeTUQyRjrOnlCoYta87iKBWq3EsdM2" crossorigin="anonymous"></script>
<script>
// Phase 3j — register the service worker post-load so the install
// affordance fires and shell assets warm into cache. Failures are silent
// (older browsers, http context, etc.) — projax must work without SW.
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/static/sw.js').catch(function(){});
});
}
</script>
</head>
<body>
<header>

View File

@@ -3,6 +3,13 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="theme-color" content="#1a1a1a">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="apple-mobile-web-app-title" content="projax">
<link rel="manifest" href="/static/manifest.webmanifest">
<link rel="apple-touch-icon" href="/static/icon-192.png">
<link rel="icon" type="image/png" sizes="192x192" href="/static/icon-192.png">
<title>Sign in — projax</title>
<style>
:root { color-scheme: dark; }