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
58 changes: 58 additions & 0 deletions app/static/page-loading.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// A skeleton over the page while the next one loads: shown only when the document itself navigates,
// a moment after the click or submit, so a fast page never flashes it. The next page replaces it.
(() => {
const main = document.getElementById('main-content');
if (!main) return;
const status = document.createElement('span');
status.className = 'sr';
status.setAttribute('role', 'status');
document.body.append(status);
let timer = 0, skeleton = null;
const html = '<div class="skel skel-title"></div><div class="skel skel-line"></div>'
+ '<div class="skel-row"><div class="skel skel-btn"></div><div class="skel skel-btn"></div><div class="skel skel-btn"></div></div>'
+ '<div class="skel skel-block"></div>'.repeat(5);
function show() {
skeleton = document.createElement('div');
skeleton.className = 'page-skeleton';
skeleton.setAttribute('aria-hidden', 'true');
skeleton.innerHTML = html;
main.prepend(skeleton);
main.setAttribute('aria-busy', 'true');
status.textContent = 'Loading';
}
function hide() {
clearTimeout(timer);
skeleton?.remove();
skeleton = null;
main.removeAttribute('aria-busy');
status.textContent = '';
}
// Whether going to `url` in this tab replaces this document: same origin, and not a jump within it.
function leaves(url, target) {
if (target && target !== '_self') return false;
let to;
try { to = new URL(url, location.href); } catch { return false; }
if (to.origin !== location.origin) return false;
return !(to.hash && to.pathname === location.pathname && to.search === location.search);
}
// Checked when the delay is up, so a handler anywhere that prevented the default has had its turn.
function later(event) {
hide();
timer = setTimeout(() => { if (!event.defaultPrevented) show(); }, 180);
}
addEventListener('click', event => {
if (event.button || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
const a = event.target.closest?.('a[href]');
if (a && !a.hasAttribute('download') && leaves(a.href, a.target)) later(event);
});
addEventListener('submit', event => {
// Attributes, not properties: a field named "action" or "target" shadows the form's own.
const form = event.target, by = event.submitter, attr = name => by?.getAttribute('form' + name) || form.getAttribute(name);
if ((attr('method') || '').toLowerCase() === 'dialog') return;
if (leaves(attr('action') || location.href, attr('target'))) later(event);
});
// A page that asks before leaving: whether the user stays or goes, this navigation shows no skeleton.
addEventListener('beforeunload', event => setTimeout(() => { if (event.defaultPrevented || event.returnValue) hide(); }));
addEventListener('keydown', event => { if (event.key === 'Escape') hide(); }); // Escape stops the load
addEventListener('pageshow', event => { if (event.persisted) hide(); }); // back to this page, from the cache
})();
12 changes: 12 additions & 0 deletions app/static/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -1874,3 +1874,15 @@ select.ui-select-native { display: none !important; }
/* the judge's button under its badge, what its last call took beside it */
.judge-actions { display: flex; align-items: center; gap: .75rem; flex-wrap: wrap; margin: .6rem 0 1rem; }
.judge-actions .header-form { margin: 0; }

/* a placeholder while content loads (.skel, reusable); the whole page's, while the next page loads (page-loading.js) */
.skel { background: var(--surface-2); border-radius: 6px; animation: skel-pulse 1.6s ease-in-out infinite; }
@keyframes skel-pulse { 50% { opacity: .45; } }
@media (prefers-reduced-motion: reduce) { .skel { animation: none; } }
main[aria-busy="true"] > :not(.page-skeleton) { display: none; }
.page-skeleton { display: grid; gap: .6rem; }
.skel-title { height: calc(var(--h1-size) * 1.22); width: min(20rem, 70%); }
.skel-line { height: .95rem; width: min(32rem, 90%); }
.skel-row { display: flex; flex-wrap: wrap; gap: .5rem; margin: .5rem 0 var(--head-gap); }
.skel-btn { height: var(--tool-h); width: 6.5rem; }
.skel-block { height: 3.75rem; }
1 change: 1 addition & 0 deletions app/templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,7 @@
<div class="scrim" id="scrim" hidden></div>
</div>
<script src="{{ url_for('static', filename='disclosures.js') }}"></script>
<script src="{{ url_for('static', filename='page-loading.js') }}"></script>
<script>
(() => {
const root = document.documentElement;
Expand Down
92 changes: 92 additions & 0 deletions app/ui_tests/test_page_loading.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
"""The page skeleton: every page loads it, and it shows only when the document itself navigates."""
import json
from pathlib import Path
import shutil
import subprocess
import unittest
from unittest.mock import patch

from .test_routes import web

SCRIPT = Path(__file__).resolve().parents[1] / "static" / "page-loading.js"

# A stand-in DOM on http://app.test/runs. Each case: an event ("click" with a link, or "submit" with a form) and
# whether a later handler prevents it; the output is whether the skeleton is on after the delay.
HARNESS = r'''
const cases = JSON.parse(require('fs').readFileSync(0, 'utf8')), handlers = {}, timers = [];
const element = () => ({attrs: {}, setAttribute(k, v) { this.attrs[k] = v; }, removeAttribute(k) { delete this.attrs[k]; },
getAttribute(k) { return this.attrs[k] ?? null; }, hasAttribute(k) { return k in this.attrs; }, remove() {}});
const main = element();
main.prepend = () => {};
global.location = new URL('http://app.test/runs');
global.setTimeout = f => timers.push(f);
global.clearTimeout = () => timers.splice(0);
global.addEventListener = (type, f) => { handlers[type] = f; };
global.document = {getElementById: () => main, body: {append() {}}, createElement: element};
require(process.argv[1]);
const busy = () => main.getAttribute('aria-busy') === 'true';
const out = cases.map(([type, given, prevented, after]) => {
handlers.pageshow({persisted: true});
const node = element();
Object.assign(node.attrs, given.attrs || {});
const event = {type, button: 0, ...given.keys, defaultPrevented: false, submitter: null};
if (type === 'click') { node.href = new URL(given.href, location).href; event.target = {closest: () => node}; }
else event.target = node;
handlers[type](event);
event.defaultPrevented = prevented;
timers.splice(0).forEach(f => f());
const shown = busy();
if (after) { handlers[after.type](after); timers.splice(0).forEach(f => f()); }
return after ? [shown, busy()] : shown;
});
process.stdout.write(JSON.stringify(out));
'''


def run(cases):
if not shutil.which("node"):
raise unittest.SkipTest("Node is required for the page skeleton")
out = subprocess.run(["node", "-e", HARNESS, str(SCRIPT)], input=json.dumps(cases),
capture_output=True, text=True, check=True)
return json.loads(out.stdout)


class Skeleton(unittest.TestCase):
def test_a_link_that_navigates_the_document_shows_it(self):
self.assertEqual(run([["click", {"href": "/workspaces"}, False, None],
["click", {"href": "http://app.test/runs?page=2#top"}, False, None]]), [True, True])

def test_what_the_browser_does_not_navigate_this_document_with_does_not(self):
cases = [{"href": "/workspaces", "keys": {"ctrlKey": True}}, {"href": "/workspaces", "keys": {"metaKey": True}},
{"href": "/workspaces", "keys": {"button": 1}}, {"href": "/workspaces", "attrs": {"download": ""}},
{"href": "#later"}, {"href": "https://elsewhere.example/"}, {"href": "mailto:a@example.com"}]
self.assertEqual(run([["click", given, False, None] for given in cases]), [False] * len(cases))
target = {"href": "/workspaces"}
self.assertEqual(run([["click", target, True, None]]), [False]) # a handler took it

def test_a_form_shows_it_unless_a_script_handles_it_or_it_opens_elsewhere(self):
self.assertEqual(run([["submit", {"attrs": {"action": "/settings/save"}}, False, None],
["submit", {"attrs": {}}, False, None],
["submit", {"attrs": {"action": "/settings/save"}}, True, None],
["submit", {"attrs": {"target": "_blank"}}, False, None],
["submit", {"attrs": {"method": "dialog"}}, False, None]]), [True, True, False, False, False])

def test_back_to_a_cached_page_a_cancelled_leave_or_escape_takes_it_away(self):
link = {"href": "/workspaces"}
self.assertEqual(run([["click", link, False, {"type": "pageshow", "persisted": True}],
["click", link, False, {"type": "keydown", "key": "Escape"}],
["click", link, False, {"type": "beforeunload", "defaultPrevented": True}],
["click", link, False, {"type": "beforeunload", "defaultPrevented": False, "returnValue": ""}]]),
[[True, False], [True, False], [True, False], [True, True]])

def test_every_page_loads_it(self):
with patch.dict(web.app.config, TESTING=True):
client = web.app.test_client()
for url in ("/runs", "/benchmarks", "/settings"):
with self.subTest(url):
page = client.get(url, follow_redirects=True); self.addCleanup(page.close)
self.assertIn('src="/static/page-loading.js"', page.get_data(as_text=True))


if __name__ == "__main__":
unittest.main()
Loading