arthur installs as an app, and keeps what projects load
A manifest and icons make it installable. A service worker at /sw.js, so its scope is every page, keeps by kind of URL: content-addressed blobs and blocks for good, as projects load them; the versioned bundle and styles until the next build; and the last copy of the page, the API reads and other statics, for when there is no network. A project opened once opens again offline. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011FLuCjp9kNH6ovwJVXSbq9
This commit is contained in:
parent
bbe20b3abf
commit
f0af8d392a
9 changed files with 172 additions and 1 deletions
|
|
@ -21,11 +21,28 @@ and PUTs with ordinary CSRF protection — no endpoint in this app is exempt.
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
|
||||||
<title>arthur</title>
|
<title>arthur</title>
|
||||||
<link rel="stylesheet" href="{% static 'arthur/app.css' %}?v={{ css_version }}">
|
<link rel="stylesheet" href="{% static 'arthur/app.css' %}?v={{ css_version }}">
|
||||||
|
<link rel="manifest" href="{% static 'arthur/manifest.webmanifest' %}">
|
||||||
|
<meta name="theme-color" content="#e4e4e1">
|
||||||
|
<link rel="icon" type="image/png" href="{% static 'arthur/icons/icon-192.png' %}">
|
||||||
|
<link rel="apple-touch-icon" href="{% static 'arthur/icons/icon-180.png' %}">
|
||||||
|
<meta name="apple-mobile-web-app-capable" content="yes">
|
||||||
|
<meta name="apple-mobile-web-app-title" content="arthur">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
{% csrf_token %}
|
{% csrf_token %}
|
||||||
<div id="app"></div>
|
<div id="app"></div>
|
||||||
<script src="{% static 'mediapipe/vision_bundle.js' %}"></script>
|
<script src="{% static 'mediapipe/vision_bundle.js' %}"></script>
|
||||||
<script src="{% static 'arthur/js/main.js' %}?v={{ js_version }}"></script>
|
<script src="{% static 'arthur/js/main.js' %}?v={{ js_version }}"></script>
|
||||||
|
<script>
|
||||||
|
// An installable app that opens offline, and keeps what projects load —
|
||||||
|
// see `static/arthur/sw.js`.
|
||||||
|
if ('serviceWorker' in navigator) {
|
||||||
|
navigator.serviceWorker.register('/sw.js');
|
||||||
|
navigator.serviceWorker.ready.then(reg => reg.active.postMessage({
|
||||||
|
keep: [...document.querySelectorAll('link[rel=stylesheet], script[src]')]
|
||||||
|
.map(el => el.href || el.src)
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|
|
||||||
|
|
@ -760,6 +760,17 @@ class PageTests(TestCase):
|
||||||
# save path reads to write the X-CSRFToken header.
|
# save path reads to write the X-CSRFToken header.
|
||||||
self.assertIn("csrfmiddlewaretoken", body)
|
self.assertIn("csrfmiddlewaretoken", body)
|
||||||
|
|
||||||
|
def test_the_service_worker_is_served_from_the_root(self):
|
||||||
|
# At the root so its scope is every page — a project is /p/<id> — and
|
||||||
|
# never cached, or a browser would keep an old worker for good.
|
||||||
|
response = self.client.get("/sw.js")
|
||||||
|
self.assertEqual(200, response.status_code)
|
||||||
|
self.assertEqual("application/javascript", response["Content-Type"])
|
||||||
|
self.assertEqual("no-cache", response["Cache-Control"])
|
||||||
|
body = self.client.get("/").content.decode()
|
||||||
|
self.assertIn("manifest.webmanifest", body)
|
||||||
|
self.assertIn("serviceWorker.register('/sw.js')", body)
|
||||||
|
|
||||||
def test_the_detector_reports_a_version_derived_from_the_model(self):
|
def test_the_detector_reports_a_version_derived_from_the_model(self):
|
||||||
# The version is the package version plus the model asset's own hash,
|
# The version is the package version plus the model asset's own hash,
|
||||||
# because a version string in the client is one somebody has to remember to
|
# because a version string in the client is one somebody has to remember to
|
||||||
|
|
|
||||||
|
|
@ -37,7 +37,7 @@ from django.contrib.auth import login as auth_login, logout as auth_logout
|
||||||
from django.core.exceptions import ValidationError
|
from django.core.exceptions import ValidationError
|
||||||
from django.db import transaction
|
from django.db import transaction
|
||||||
from django.db.models import Q
|
from django.db.models import Q
|
||||||
from django.http import FileResponse, HttpResponse, JsonResponse
|
from django.http import FileResponse, Http404, HttpResponse, JsonResponse
|
||||||
from django.shortcuts import render
|
from django.shortcuts import render
|
||||||
from django.views.decorators.http import require_http_methods
|
from django.views.decorators.http import require_http_methods
|
||||||
|
|
||||||
|
|
@ -146,6 +146,22 @@ def page(request, project_id=None, slug=None):
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
|
def service_worker(request):
|
||||||
|
"""`static/arthur/sw.js`, at the root of the site.
|
||||||
|
|
||||||
|
A service worker controls only the paths under where it is served from, and
|
||||||
|
a project is `/p/<id>`, so `/static/arthur/sw.js` would control nothing that
|
||||||
|
matters. Never cached itself: a browser compares this file to decide whether
|
||||||
|
there is a new worker, so a stale copy would keep the old one for good."""
|
||||||
|
for root in settings.STATICFILES_DIRS:
|
||||||
|
path = Path(root) / "arthur" / "sw.js"
|
||||||
|
if path.exists():
|
||||||
|
response = HttpResponse(path.read_bytes(), content_type="application/javascript")
|
||||||
|
response["Cache-Control"] = "no-cache"
|
||||||
|
return response
|
||||||
|
raise Http404("no service worker")
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# the detector
|
# the detector
|
||||||
#
|
#
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,9 @@ urlpatterns = [
|
||||||
# same page; the client reads the id out of the path and opens it.
|
# same page; the client reads the id out of the path and opens it.
|
||||||
path("p/<uuid:project_id>", views.page),
|
path("p/<uuid:project_id>", views.page),
|
||||||
path("p/<uuid:project_id>/<slug:slug>", views.page),
|
path("p/<uuid:project_id>/<slug:slug>", views.page),
|
||||||
|
# The service worker, at the root so it can control every page; see
|
||||||
|
# `views.service_worker`.
|
||||||
|
path("sw.js", views.service_worker),
|
||||||
path("api/", include("clips.urls")),
|
path("api/", include("clips.urls")),
|
||||||
path("blob/<str:digest>", views.blob, name="blob"),
|
path("blob/<str:digest>", views.blob, name="blob"),
|
||||||
path("admin/", admin.site.urls),
|
path("admin/", admin.site.urls),
|
||||||
|
|
|
||||||
BIN
static/arthur/icons/icon-180.png
Normal file
BIN
static/arthur/icons/icon-180.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 540 B |
BIN
static/arthur/icons/icon-192.png
Normal file
BIN
static/arthur/icons/icon-192.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 587 B |
BIN
static/arthur/icons/icon-512.png
Normal file
BIN
static/arthur/icons/icon-512.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.3 KiB |
15
static/arthur/manifest.webmanifest
Normal file
15
static/arthur/manifest.webmanifest
Normal file
|
|
@ -0,0 +1,15 @@
|
||||||
|
{
|
||||||
|
"name": "arthur",
|
||||||
|
"short_name": "arthur",
|
||||||
|
"description": "Draw and animate, frame by frame.",
|
||||||
|
"start_url": "/",
|
||||||
|
"scope": "/",
|
||||||
|
"display": "standalone",
|
||||||
|
"orientation": "any",
|
||||||
|
"background_color": "#8e8e8e",
|
||||||
|
"theme_color": "#e4e4e1",
|
||||||
|
"icons": [
|
||||||
|
{"src": "/static/arthur/icons/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any maskable"},
|
||||||
|
{"src": "/static/arthur/icons/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any maskable"}
|
||||||
|
]
|
||||||
|
}
|
||||||
109
static/arthur/sw.js
Normal file
109
static/arthur/sw.js
Normal file
|
|
@ -0,0 +1,109 @@
|
||||||
|
// The service worker: what arthur keeps so it opens, and shows what it has
|
||||||
|
// already shown, without the network. Served from `/sw.js` by `clips.views`
|
||||||
|
// so its scope is the whole site; see `server/urls.py`.
|
||||||
|
//
|
||||||
|
// ONE RULE PER KIND OF URL, chosen by whether what is at it can change:
|
||||||
|
//
|
||||||
|
// - CONTENT-ADDRESSED — `/blob/<digest>`, `/api/blocks/<key>` — is named by its
|
||||||
|
// own hash, so a copy cannot be stale: cache first, keep for good. These are
|
||||||
|
// a project's frames, footage and drawings, cached as they load.
|
||||||
|
// - VERSIONED — the bundle and the stylesheet, `?v=<mtime>` — is a new URL
|
||||||
|
// for every build: cache first, and drop the versions it replaces.
|
||||||
|
// - EVERYTHING ELSE of ours — the page, `/api/` reads, unversioned statics —
|
||||||
|
// can change under the same URL: the network first, the last copy offline.
|
||||||
|
//
|
||||||
|
// A Range request is left to the browser: a `<video>` seeking a blob asks for
|
||||||
|
// slices, and the Cache API cannot store a 206.
|
||||||
|
|
||||||
|
const KEEP = 'arthur-keep-v1'; // content-addressed, never stale
|
||||||
|
const BUILD = 'arthur-build-v1'; // versioned bundle and styles
|
||||||
|
const LAST = 'arthur-last-v1'; // last good copy of everything else
|
||||||
|
|
||||||
|
// The page every address opens, kept at install, so the app opens offline
|
||||||
|
// even at an address it was never opened at.
|
||||||
|
self.addEventListener('install', event => {
|
||||||
|
event.waitUntil(caches.open(LAST).then(cache => cache.add('/')).catch(() => {}));
|
||||||
|
self.skipWaiting();
|
||||||
|
});
|
||||||
|
|
||||||
|
self.addEventListener('activate', event => {
|
||||||
|
const ours = new Set([KEEP, BUILD, LAST]);
|
||||||
|
event.waitUntil((async () => {
|
||||||
|
for (const name of await caches.keys()) {
|
||||||
|
if (!ours.has(name)) await caches.delete(name);
|
||||||
|
}
|
||||||
|
await self.clients.claim();
|
||||||
|
})());
|
||||||
|
});
|
||||||
|
|
||||||
|
const immutable = url =>
|
||||||
|
url.pathname.startsWith('/blob/') || url.pathname.startsWith('/api/blocks/');
|
||||||
|
|
||||||
|
const versioned = url =>
|
||||||
|
url.pathname.startsWith('/static/') && url.searchParams.has('v');
|
||||||
|
|
||||||
|
async function keep(cache, request) {
|
||||||
|
const hit = await cache.match(request);
|
||||||
|
if (hit) return hit;
|
||||||
|
const response = await fetch(request);
|
||||||
|
if (response.ok) await cache.put(request, response.clone());
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function build(request) {
|
||||||
|
const cache = await caches.open(BUILD);
|
||||||
|
const hit = await cache.match(request);
|
||||||
|
if (hit) return hit;
|
||||||
|
const response = await fetch(request);
|
||||||
|
if (response.ok) {
|
||||||
|
// A new build of this file replaces the old ones rather than piling up.
|
||||||
|
const path = new URL(request.url).pathname;
|
||||||
|
for (const old of await cache.keys()) {
|
||||||
|
if (new URL(old.url).pathname === path) await cache.delete(old);
|
||||||
|
}
|
||||||
|
await cache.put(request, response.clone());
|
||||||
|
}
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function last(request, fallback) {
|
||||||
|
const cache = await caches.open(LAST);
|
||||||
|
try {
|
||||||
|
const response = await fetch(request);
|
||||||
|
if (response.ok) await cache.put(request, response.clone());
|
||||||
|
return response;
|
||||||
|
} catch (offline) {
|
||||||
|
const hit = (await cache.match(request)) || (fallback && (await cache.match(fallback)));
|
||||||
|
if (hit) return hit;
|
||||||
|
throw offline;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The rule for one request, or nil for the browser's own handling.
|
||||||
|
function handle(request) {
|
||||||
|
const url = new URL(request.url);
|
||||||
|
if (request.method !== 'GET' || url.origin !== self.location.origin) return null;
|
||||||
|
if (request.headers.has('range')) return null;
|
||||||
|
if (url.pathname === '/sw.js') return null;
|
||||||
|
|
||||||
|
if (immutable(url)) return caches.open(KEEP).then(cache => keep(cache, request));
|
||||||
|
if (versioned(url)) return build(request);
|
||||||
|
// Every page is the same shell, which opens whichever project the path
|
||||||
|
// names: offline, any copy of it will do.
|
||||||
|
if (request.mode === 'navigate') return last(request, '/');
|
||||||
|
if (url.pathname.startsWith('/api/') || url.pathname.startsWith('/static/')) return last(request);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.addEventListener('fetch', event => {
|
||||||
|
const answer = handle(event.request);
|
||||||
|
if (answer) event.respondWith(answer);
|
||||||
|
});
|
||||||
|
|
||||||
|
// The first page a worker sees loaded its bundle and styles before the worker
|
||||||
|
// was there to keep them; it sends their URLs once the worker is ready.
|
||||||
|
self.addEventListener('message', event => {
|
||||||
|
const urls = (event.data && event.data.keep) || [];
|
||||||
|
event.waitUntil(Promise.all(urls.map(u => handle(new Request(u))).filter(Boolean))
|
||||||
|
.catch(() => {}));
|
||||||
|
});
|
||||||
Loading…
Add table
Add a link
Reference in a new issue