Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
sooner. scipy is loaded in the background after the app appears, and pandas and the
plotting libraries are imported while you read the Home page. A page that needs scipy
says so for a moment if you open it within the first seconds.
- **Install the web app like a program.** Chrome and Edge offer **Install EaglePlot**:
it then opens in its own window from a desktop icon, with no admin rights, and after one
online visit it also works offline. Later visits load from the computer instead of the
network.
- Importing `eagleplot.plotting` no longer imports seaborn, plotly or scipy (they load when
a plot type needs them), and importing `eagleplot.utils` no longer imports pandas. This
also makes the installed GUI start a little faster.
Expand Down
25 changes: 25 additions & 0 deletions packaging/web/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ Streamlit exception, uncaught page error, failed download or request to another
| --- | --- |
| `index.html` | Loading splash (below), the stlite mount call, and a download workaround (below) |
| `404.html` | A copy of `index.html`, for hosts that serve the nearest `404.html` (below) |
| `manifest.webmanifest`, `icons/` | Web app manifest and icons: the app can be installed (below) |
| `sw.js` | Service worker: caches the app and Pyodide, so it opens offline (below) |
| `site-config.js` | Written by the build: entrypoint, packages, wheels, Pyodide URL, Streamlit flags, storage mount, environment |
| `eagleplot-app.zip` | `eagleplot/` (code, assets, gallery, example data) and `.streamlit/config.toml`; entrypoint `eagleplot/Home.py` |
| `wheels/` | Pure-Python packages not in Pyodide: seaborn, plotly, narwhals, openpyxl, et-xmlfile, jcamp (`.jdx` uploads), and Streamlit's python-multipart and itsdangerous |
Expand All @@ -73,6 +75,29 @@ Opening `index.html` from disk fails: the app runs in a module Web Worker and lo
app zip, wheels and Pyodide with `fetch()`, and browsers block both for `file://` pages.
Serve the directory over HTTP (`python -m http.server`, GitHub Pages, any static host).

## Installable app and offline use

`manifest.webmanifest` (written by the build, icons in `icons/`) and the service worker
`sw.js` make the app installable: Chrome and Edge show **Install EaglePlot** in the
address bar or menu. It then opens in its own window from a desktop or Start-menu icon,
with no admin rights. After one online visit it also opens offline.

- **First visit:** `index.html` registers `sw.js` and waits (at most 3 s) until it
controls the page before starting Python, so this visit's downloads, the Python
worker's included, pass through it and are cached. The page and the stlite runtime load
before that; the page sends their URLs to the worker to cache.
- **Site files:** network first (a new deploy shows up at once), the cached copy offline.
The cache is per build (`build_site.py` stamps `sw.js` with a hash of the build), and
older builds' caches are removed when a new one activates.
- **Pyodide from the CDN:** cache first; its URLs contain the version and never change.
- `window.eaglePlotOffline` says what happened: `ready`, `next-visit` (the worker didn't
take over within 3 s), `failed`, or `unsupported` (no service workers, or not https).
- `scripts/web/smoke.js` checks both: Chromium's installability check, then a reload
with the network off.
- The icons are PNGs made from `eagleplot/assets/logo.png` (192 and 512 px, maskable
versions on the dark background, a 180 px Apple touch icon). Regenerate them if the
logo changes.

## Loading splash

`index.html` draws the splash before anything else loads: a classic inline script, inline
Expand Down
51 changes: 51 additions & 0 deletions packaging/web/build_site.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from __future__ import annotations

import argparse
import hashlib
import io
import json
import shutil
Expand Down Expand Up @@ -238,6 +239,7 @@ def main(argv: Optional[List[str]] = None) -> None:
"window.EAGLEPLOT_STLITE = " + json.dumps(config, indent=2) + ";\n", encoding="utf-8"
)
(out / ".nojekyll").write_text("")
write_pwa_files(out)

pyodide_dir = out / "pyodide"
size = site_size_mb(out, exclude=pyodide_dir)
Expand All @@ -249,5 +251,54 @@ def main(argv: Optional[List[str]] = None) -> None:
print(msg)


#: Web app manifest (roadmap D4.2): with sw.js, Chrome and Edge offer "Install EaglePlot".
MANIFEST = {
"name": "EaglePlot",
"short_name": "EaglePlot",
"description": "Scientific data visualization and analysis, running in your browser.",
"start_url": "./",
"scope": "./",
"display": "standalone",
"background_color": "#1b1b1b",
"theme_color": "#1b1b1b",
"icons": [
{"src": "icons/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any"},
{"src": "icons/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any"},
{
"src": "icons/maskable-192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "maskable",
},
{
"src": "icons/maskable-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable",
},
],
}


def build_id(out: Path) -> str:
"""A hash of the files that change between deploys (app, config, page, wheel names)."""
h = hashlib.sha256()
for name in ("index.html", "site-config.js", "eagleplot-app.zip"):
h.update((out / name).read_bytes())
for wheel in sorted((out / "wheels").glob("*.whl")):
h.update(wheel.name.encode())
return h.hexdigest()[:12]


def write_pwa_files(out: Path) -> None:
"""Manifest, icons and the service worker (stamped with this build's id)."""
(out / "manifest.webmanifest").write_text(json.dumps(MANIFEST, indent=2), encoding="utf-8")
shutil.copytree(HERE / "icons", out / "icons")
sw = (HERE / "sw.js").read_text(encoding="utf-8")
if "__EAGLEPLOT_BUILD__" not in sw:
sys.exit("packaging/web/sw.js has lost its __EAGLEPLOT_BUILD__ placeholder")
(out / "sw.js").write_text(sw.replace("__EAGLEPLOT_BUILD__", build_id(out)), encoding="utf-8")


if __name__ == "__main__":
main()
Binary file added packaging/web/icons/apple-touch-icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added packaging/web/icons/icon-192.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added packaging/web/icons/icon-512.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added packaging/web/icons/maskable-192.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added packaging/web/icons/maskable-512.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
33 changes: 33 additions & 0 deletions packaging/web/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<title>EaglePlot in the browser</title>
<link rel="icon" href="./eagleplot-icon.png" />
<!-- Installable app (roadmap D4.2): manifest + service worker (sw.js). -->
<link rel="manifest" href="./manifest.webmanifest" />
<meta name="theme-color" content="#1b1b1b" />
<link rel="apple-touch-icon" href="./icons/apple-touch-icon.png" />
<link rel="stylesheet" href="./stlite/stlite.css" />
<style>
:root { --bg: #1b1b1b; --fg: #f4f4f4; --muted: #b9b9b9; --rose: #e0a3a3; --track: #333; }
Expand Down Expand Up @@ -235,6 +239,35 @@

const t0 = performance.now();

// Service worker (sw.js): makes the app installable and lets it open offline. On a
// first visit, wait (at most 3 s) until it controls this page before starting Python,
// so the downloads of this visit, the Python worker's included, are cached too.
// Only over https or on localhost; a failure just means no offline copy.
window.eaglePlotOffline = "unsupported";
if ("serviceWorker" in navigator && window.isSecureContext) {
try {
await navigator.serviceWorker.register("./sw.js", { scope: "./" });
if (!navigator.serviceWorker.controller) {
await Promise.race([
new Promise((resolve) =>
navigator.serviceWorker.addEventListener("controllerchange", resolve, { once: true }),
),
new Promise((resolve) => setTimeout(resolve, 3000)),
]);
}
window.eaglePlotOffline = navigator.serviceWorker.controller ? "ready" : "next-visit";
// This page and what it loaded before the worker took over didn't pass through
// it: hand it their URLs to cache.
navigator.serviceWorker.controller?.postMessage({
type: "cache-urls",
urls: [location.href.split("#")[0], ...performance.getEntriesByType("resource").map((e) => e.name)],
});
} catch (err) {
window.eaglePlotOffline = "failed";
console.warn("EaglePlot: offline support unavailable", err);
}
}

// The controller is kept on window so browser tests (scripts/web/smoke.js) can wait
// for the app and inspect the in-browser file system.
window.eaglePlotApp = mount(
Expand Down
100 changes: 100 additions & 0 deletions packaging/web/sw.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// EaglePlot web app: service worker (roadmap D4.2).
//
// Makes the app installable ("Install EaglePlot" in Chrome and Edge) and lets it open
// offline after one online visit. index.html registers it and, on a first visit, waits
// until it controls the page before starting Python, so even the first visit's downloads
// (including the Python worker's) pass through here and are cached.
//
// - Files of this site: network first, so a new deploy shows up at once; the cached copy
// when offline. Cached per build (BUILD changes with every deploy); older builds' caches
// are removed when this version activates.
// - Pyodide from the CDN: cache first. Its URLs contain the version and never change.
//
// packaging/web/build_site.py replaces __EAGLEPLOT_BUILD__ with a hash of the build.
'use strict';

const BUILD = '__EAGLEPLOT_BUILD__';
const APP_CACHE = `eagleplot-app-${BUILD}`;
const CDN_CACHE = 'eagleplot-cdn';
const CDN_ORIGINS = ['https://cdn.jsdelivr.net'];

self.addEventListener('install', () => {
self.skipWaiting();
});

self.addEventListener('activate', (event) => {
event.waitUntil((async () => {
const names = await caches.keys();
await Promise.all(
names.filter((n) => n.startsWith('eagleplot-app-') && n !== APP_CACHE).map((n) => caches.delete(n)),
);
await self.clients.claim();
})());
});

// Responses are handed to the page at once and written to the cache in the background
// (event.waitUntil): awaiting the cache write first delayed every download until it had
// been copied in full, which made start-up ~3 s slower.
async function networkFirst(event) {
const request = event.request;
const cache = await caches.open(APP_CACHE);
try {
const response = await fetch(request);
if (response.ok) event.waitUntil(cache.put(request, response.clone()));
return response;
} catch (err) {
const cached = await cache.match(request, { ignoreSearch: true });
if (cached) return cached;
// Offline and never seen: a page of the app (…/app/settings) gets the app itself.
if (request.mode === 'navigate') {
const shell = await cache.match(new URL('./', self.registration.scope).href);
if (shell) return shell;
}
throw err;
}
}

async function cacheFirst(event) {
const request = event.request;
const cache = await caches.open(CDN_CACHE);
const cached = await cache.match(request);
if (cached) return cached;
const response = await fetch(request);
if (response.ok) event.waitUntil(cache.put(request, response.clone()));
return response;
}

// On a first visit the page itself and the stlite runtime load before this worker controls
// the page, so they never pass through the fetch handler. index.html then sends their
// URLs; cache them (mostly from the HTTP cache) so the app can open offline next time.
self.addEventListener('message', (event) => {
if (event.data?.type !== 'cache-urls') return;
event.waitUntil((async () => {
const cache = await caches.open(APP_CACHE);
const scope = self.registration.scope;
await Promise.all(
(event.data.urls || [])
.filter((u) => typeof u === 'string' && u.startsWith(scope))
.map(async (u) => {
try {
if (await cache.match(u)) return;
const response = await fetch(u);
if (response.ok) await cache.put(u, response);
} catch (err) {
/* offline or gone: skip it */
}
}),
);
})());
});

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) {
if (url.href.startsWith(self.registration.scope)) event.respondWith(networkFirst(event));
} else if (CDN_ORIGINS.includes(url.origin)) {
event.respondWith(cacheFirst(event));
}
});
31 changes: 31 additions & 0 deletions scripts/web/smoke.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
// loadFinished event) and is gone once the app is up.
// - An on-click download (Quick Plot, PNG 300 dpi, built by a callable) arrives and leaves
// the app running. Under stlite these go through a workaround in index.html.
// - The app is installable (Chromium's installability check passes) and, after this one
// online visit, opens offline (service worker, roadmap D4.2).
// - Data never leaves the browser: every request goes to the site's own origin, or to an
// origin allowed with --allow-origin (the Pyodide CDN, https://cdn.jsdelivr.net, is
// allowed by default).
Expand Down Expand Up @@ -176,6 +178,34 @@ async function checkSplash(page, firstStep, results) {
console.log(`${errors.length ? 'FAIL' : 'ok '} splash first step "${firstStep}", last step ${state.stage + 1} of 4, ${gone ? 'removed' : 'STILL SHOWN'}`);
}

// Installable, and opens offline after this visit: reload with the network off.
async function checkOffline(page, events, results) {
const r = { phase: 'offline', page: '-', label: 'Installable + offline reload', exceptions: [], errorAlerts: [],
consoleErrors: [], failedRequests: [], pageErrors: [] };
const cdp = await page.context().newCDPSession(page);
const { installabilityErrors } = await cdp.send('Page.getInstallabilityErrors');
const state = await page.evaluate(() => window.eaglePlotOffline);
if (installabilityErrors.length) r.pageErrors.push(`not installable: ${installabilityErrors.map((e) => e.errorId).join(', ')}`);
if (state !== 'ready') r.pageErrors.push(`service worker not controlling the page (${state})`);
const t0 = Date.now();
await page.context().setOffline(true);
try {
await page.reload();
await page.waitForFunction(() => (window.eaglePlotBootLog || []).some((e) => e.event === 'ready'), null, { timeout: 180000, polling: 200 });
const exc = await page.locator('[data-testid="stException"]').count();
if (exc) r.pageErrors.push(`${exc} exception(s) after the offline reload`);
} catch (e) {
r.pageErrors.push(`offline reload: ${e.message.split('\n')[0]}`);
} finally {
await page.context().setOffline(false);
}
r.ms = Date.now() - t0;
events.failedRequests.splice(0); // requests failing while offline are expected
results.push(r);
console.log(`${r.pageErrors.length ? 'FAIL' : 'ok '} offline installable ${installabilityErrors.length ? 'NO' : 'yes'}, ` +
`service worker ${state}, offline reload ${r.pageErrors.length ? 'failed' : `ready in ${(r.ms / 1000).toFixed(1)} s`}`);
}

async function loadExample(page, base, example, events, results) {
const dataPath = new URL('data-upload', base).pathname;
const ms = await openPage(page, dataPath);
Expand Down Expand Up @@ -272,6 +302,7 @@ function exampleLabel(file) {
await loadExample(page, base, opts.example, events, results);
await visitAll('with-data');
await checkDownload(page, base, events, results);
await checkOffline(page, events, results);

await browser.close();
const allowed = new Set([new URL(base).origin, ...opts.allowOrigins]);
Expand Down
Loading