oficina / fichas Public

Clone
git clone https://amadan.net/oficina/fichas

Plain git — no account needed to clone.

Download

Download this file

1/* shell.js — transition observation and phone shell navigation.
2 First-party, dependency-free, CSP-clean, and optional: delete it (and
3 its <script> tag) and every page still works, because the index and
4 the back control are ordinary server-rendered pages and links. It is
5 app-owned from the moment it is scaffolded.
6
7 What it reads, all written by the layouts, in either spelling:
8 [rst-shell-sidebar~="index"|"page"], [rst-shell-console~=…],
9 [rst-shell-topbar~=…] which view the server rendered (the "view"
10 block): .rst-shell-sidebar--index and so on
11 [rst-shell-back] > a the back control: the strip's own link, not
12 one in a menu also in the strip
13 [rst-shell-up] the back control in a one-row shell's bar
14 (each one's href is the "up" block)
15 [rst-shell-nav] a the index's rows
16
17 What it adds, four things:
18 1. Direction. In pagereveal it types the view transition "back" or
19 "forward", which shell.css turns into a slide.
20 2. Back reuses history. A plain click on the back control calls
21 history.back() when, and only when, the Navigation API proves the
22 entry behind this one is the up page, in another document; the
23 index then comes back from the back/forward cache as it was left.
24 3. Focus returns to the section you left. Leaving a content page
25 records its path in sessionStorage; revealing the index at phone
26 width focuses the nav link to that path, or else the one the URL's
27 #fragment names.
28 4. A name that does not fit. In a one-row shell's phone row (the
29 title or brand after [rst-shell-up], or in the rail of a sidebar
30 holding one) tokens.css cuts a name too wide for the row with an
31 ellipsis; this marks it hidden, so a name shows whole or not at
32 all, and measures it again on a resize.
33
34 Sidebar, console and the one-row topbar (whose index is /menu) use
35 defer blocking="render" for focus and direction after parsing. Other layouts use transition.js before
36 styles so incoming transitions skipped before pagereveal are observed. */
37(function () {
38 "use strict";
39
40 var ROOT = "[rst-shell-sidebar],[rst-shell-console],[rst-shell-topbar],.rst-shell-sidebar,.rst-shell-console,.rst-shell-topbar";
41 var INDEX = '[rst-shell-sidebar~="index"],[rst-shell-console~="index"],[rst-shell-topbar~="index"],.rst-shell-sidebar--index,.rst-shell-console--index,.rst-shell-topbar--index';
42 var PAGE = '[rst-shell-sidebar~="page"],[rst-shell-console~="page"],[rst-shell-topbar~="page"],.rst-shell-sidebar--page,.rst-shell-console--page,.rst-shell-topbar--page';
43 var BACK = "[rst-shell-back] > a[href],.rst-shell__back > a[href],[rst-shell-up][href],.rst-shell__up[href]";
44 var NAV = "[rst-shell-nav] a[href],.rst-shell__nav a[href]";
45 var NARROW = "(max-width: 799.98px)";
46 var RETURN = "rst-shell-return", WENT_BACK = "rst-shell-back";
47
48 // sessionStorage can throw: storage disabled, a quota, a sandboxed
49 // frame. Any throw reads as "no record", so the fragment rule below
50 // still works.
51 function store(fn) {
52 try { return fn(window.sessionStorage); } catch (e) { return null; }
53 }
54 // One-shot: read and remove, so a record is consumed at most once.
55 function take(key) {
56 return store(function (s) { var v = s.getItem(key); s.removeItem(key); return v; });
57 }
58 // A URL as this script compares URLs: resolved against the page, path
59 // and query, fragment ignored; null for another origin.
60 function place(href) {
61 var u = new URL(href, location.href);
62 return u.origin === location.origin ? u.pathname + u.search : null;
63 }
64 function view(sel) {
65 var r = document.querySelector(ROOT);
66 return !!r && r.matches(sel);
67 }
68
69 // 3. Focus return, read when an index is revealed and never while
70 // prerendering: a prerendered index runs its first scripts with a copy
71 // of storage taken before the reader left the page, and pagereveal at
72 // activation is the first moment the fresh record is there. The record
73 // wins over the fragment: after going back to /#nav-invoices and then
74 // visiting Orders, a history return restores the old fragment. The
75 // record is taken before the width test: an index revealed wide would
76 // otherwise leave it behind, and a later phone-width index reached some
77 // other way would focus a link the reader left long ago.
78 function returnFocus() {
79 if (document.prerendering || !view(INDEX)) return;
80 var rec = take(RETURN), links, hit = null, i, id;
81 if (!matchMedia(NARROW).matches) return;
82 links = document.querySelectorAll(NAV);
83 for (i = 0; rec && !hit && i < links.length; i++) {
84 if (place(links[i].href) === rec) hit = links[i];
85 }
86 if (!hit && location.hash) {
87 try { id = decodeURIComponent(location.hash.slice(1)); } catch (e) { id = location.hash.slice(1); }
88 hit = document.getElementById(id);
89 if (hit && !hit.matches(NAV)) hit = null;
90 }
91 if (hit) hit.focus();
92 }
93
94 // A skipped browser transition rejects even though navigation succeeds.
95 // Startup and pagereveal can expose the same object; observe it once.
96 var observed = new WeakSet();
97 function observeTransition(transition) {
98 if (!transition || observed.has(transition)) return;
99 observed.add(transition);
100 ["ready", "finished", "updateCallbackDone"].forEach(function (key) {
101 if (transition[key]) transition[key].catch(function (err) {
102 if (!(err instanceof DOMException) ||
103 ["AbortError", "InvalidStateError", "TimeoutError"].indexOf(err.name) < 0) throw err;
104 });
105 });
106 }
107
108 observeTransition(document.activeViewTransition);
109
110 // 1. Direction. The back record is scoped to its destination because
111 // a cancelled leave-page prompt can leave it behind. Consume it on
112 // every reveal so it cannot affect a later visit. Browser Back uses
113 // the Navigation API's entry order; URL patterns belong to the app.
114 function reveal(e) {
115 observeTransition(e.viewTransition);
116 var back = take(WENT_BACK) === location.pathname + location.search, a = window.navigation && navigation.activation;
117 if (!back && a && a.navigationType === "traverse" && a.from && a.entry) back = a.entry.index < a.from.index;
118 // Focus first, and the type only where there is a set to add it to:
119 // an engine with cross-document transitions but no types must not
120 // turn a cosmetic step into a throw that skips the focus return.
121 returnFocus();
122 if (e.viewTransition && e.viewTransition.types) e.viewTransition.types.add(back ? "back" : "forward");
123 }
124 if ("onpagereveal" in window) window.addEventListener("pagereveal", reveal);
125 else window.addEventListener("pageshow", returnFocus);
126
127 // The record is written when a content page is LEFT, which covers
128 // every way back: the back control, the browser's Back, a deep link.
129 // pageswap fires on the outgoing document for every navigation, the
130 // activation of a prerendered page included, before the new one is
131 // revealed; pagehide is the fallback where there is no pageswap.
132 // Never both: a pagehide landing after the index took the record
133 // would leave a stale one behind.
134 function leave(e) {
135 observeTransition(e.viewTransition);
136 if (view(PAGE)) store(function (s) { s.setItem(RETURN, location.pathname + location.search); });
137 }
138 window.addEventListener("onpageswap" in window ? "pageswap" : "pagehide", leave);
139
140 // 2. Back reuses history, only when it can prove what is behind: a
141 // plain primary click, the Navigation API, and the entry before this
142 // one a DIFFERENT document whose path and query are the back link's
143 // (index, page, #section on the same page: Back must not stop at the
144 // fragment). A redirect behind "up" fails the test and the link is
145 // followed. Anything unproven follows the link and history grows by
146 // one, which is the scriptless behaviour, not a failure. The referrer
147 // is not consulted: it names the document's referrer, not the entry
148 // behind this one.
149 document.addEventListener("click", function (e) {
150 var a = e.target.closest && e.target.closest(BACK), nav = window.navigation, cur, prev, want;
151 if (!a || e.defaultPrevented || e.button !== 0 || e.ctrlKey || e.metaKey || e.shiftKey || e.altKey) return;
152 want = place(a.href);
153 if (want !== null) store(function (s) { s.setItem(WENT_BACK, want); });
154 cur = nav && nav.currentEntry;
155 if (!cur || cur.index < 1) return;
156 prev = nav.entries()[cur.index - 1];
157 if (want !== null && prev && !prev.sameDocument && prev.url && place(prev.url) === want) {
158 e.preventDefault();
159 history.back();
160 }
161 });
162
163 // 4. Shown to be measured: cut, the name or the link in it is wider
164 // inside than out. Synchronous, so the shown state never paints.
165 // The console's is in the bar after the up link; the sidebar's is in
166 // the rail of a root holding one, as tokens.css matches it.
167 var T = ":is([rst-shell-title],[rst-shell-brand],.rst-shell__title,.rst-shell__brand)";
168 var NAME = ":is([rst-shell-up],.rst-shell__up)~" + T + ",:is([rst-shell-sidebar],.rst-shell-sidebar):has([rst-shell-up],.rst-shell__up)>:is([rst-shell-rail],.rst-shell__rail)>" + T;
169 function cut(n) {
170 var all = [n].concat([].slice.call(n.querySelectorAll("*"))), i;
171 for (i = 0; i < all.length; i++) if (all[i].scrollWidth > all[i].clientWidth) return true;
172 return false;
173 }
174 function fit() {
175 var names = document.querySelectorAll(NAME), i, n;
176 for (i = 0; i < names.length; i++) {
177 n = names[i];
178 n.hidden = false;
179 n.hidden = matchMedia(NARROW).matches && n.getClientRects().length > 0 && cut(n);
180 }
181 }
182 if (window.ResizeObserver) new ResizeObserver(fit).observe(document.documentElement);
183 window.addEventListener("load", fit);
184})();
185