oficina / estilo Public

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

Plain git — no account needed to clone.

Download

Download this file

1// chrome/chrome.js: optional behaviour for estilo-bar and the one top-level
2// menu group. Load it with <script defer>. Everything already works
3// without it; this only adds what <details> and the platform cannot do for
4// themselves:
5//
6// - Escape closes the open member of the group (name="estilo-menus": the
7// bar's Menu, switcher and account, and every menubar menu) and returns
8// focus to its title;
9// - a click outside the open member closes it;
10// - Escape in the editable title restores the saved value and leaves
11// the field;
12// - a row or button that opens a dialog (command="show-modal") closes
13// the menu it sat in, returns focus to that menu's title when the
14// dialog closes, and opens the dialog itself on an engine without
15// invoker commands;
16// - a stacked bar's title field (the one with a size attribute) is
17// fitted to its title: the size the server rendered is the first
18// paint's guess, and this measures the field and corrects it (except
19// in a compact bar while it is narrow, where the field fills its
20// room and ends in an ellipsis);
21// - Appearance switches in place: the page takes the scheme at once and
22// the choice is saved by the same POST, sent in the background, with
23// no navigation and no spinner. With scripts off the form posts and
24// redirects as it always has.
25//
26// The group is one group in every app, so closing it is estilo's job, not
27// each app's: Sheets' menubar lost Escape and outside-click entirely when
28// it left rastrillo's dropdown.
29//
30// Both listen in the capture phase. A document app has to stop key
31// events from propagating out of its menus — Sheets' grid library acts on
32// every key it hears on document, so an arrow in an open menu would walk
33// the cell cursor too — and a bubble-phase listener on document never
34// hears the Escape such an app stops. Capture hears it first. An app that
35// closes its own menu on Escape (Docs' menubar) finds nothing open and
36// does nothing, so nothing is handled twice.
37;(() => {
38 const group = 'details[name="estilo-menus"][open]'
39 const openPanel = () => document.querySelector(group)
40
41 // Focus returns to a menu's title; in a menubar with a roving tab stop
42 // (one title tabbable, the rest tabindex=-1) the stop moves with it, so
43 // Tab then Shift+Tab comes back to the menu you were in, not to File
44 // (Astra, estilo #11). A menubar without one is left without one.
45 const returnTo = (title) => {
46 title.focus()
47 const bar = title.closest('[estilo-menubar]')
48 if (!bar) return
49 const titles = bar.querySelectorAll('[estilo-menubar-title]')
50 if (!Array.prototype.some.call(titles, (t) => t.hasAttribute('tabindex'))) return
51 Array.prototype.forEach.call(titles, (t) => { t.tabIndex = t === title ? 0 : -1 })
52 }
53
54 document.addEventListener('keydown', (e) => {
55 if (e.key !== 'Escape' || e.defaultPrevented) return
56 const input = e.target.closest && e.target.closest('[estilo-bar-title-input]')
57 if (input) {
58 input.value = input.defaultValue
59 if (input.hasAttribute('size')) fit(input)
60 input.blur()
61 e.preventDefault()
62 return
63 }
64 const open = openPanel()
65 if (!open) return
66 open.open = false
67 const summary = open.querySelector('summary')
68 if (summary) returnTo(summary)
69 e.preventDefault()
70 }, true)
71
72 document.addEventListener('click', (e) => {
73 const open = openPanel()
74 if (open && !open.contains(e.target)) open.open = false
75 }, true)
76
77 const invokers = typeof HTMLButtonElement !== 'undefined' && 'command' in HTMLButtonElement.prototype
78 document.addEventListener('click', (e) => {
79 const button = e.target.closest && e.target.closest('button[commandfor][command="show-modal"]')
80 if (!button || button.disabled) return
81 const dialog = document.getElementById(button.getAttribute('commandfor'))
82 const holder = button.closest('details[name="estilo-menus"]')
83 if (holder) {
84 holder.open = false
85 const summary = holder.querySelector('summary')
86 if (dialog && summary) dialog.addEventListener('close', () => returnTo(summary), { once: true })
87 }
88 if (invokers || !dialog || typeof dialog.showModal !== 'function' || dialog.open) return
89 dialog.showModal()
90 e.preventDefault()
91 })
92
93 // The stacked bar's title field is as wide as its title (Paul: "It
94 // should grow according to the title, not start out full-width"). The
95 // field measures itself, at zero width, where its scroll width is its
96 // own text as it draws it. The engines measure that in different boxes:
97 // WebKit's scroll and client widths are the padding box, so its scroll
98 // width holds both paddings; Chromium's are the content box (its inner
99 // editor), so its scroll width is the text alone and its client width
100 // 0. Measured on Chromium 158 and WebKit 27.2, "Brightwater Labs":
101 // scroll width 127 and 141, client width 0 and 13. Adding only the
102 // borders, as this once did, cut the last letter off in Chromium (the
103 // field 12.8px short: both paddings). So whatever of the field lies
104 // outside the box the scroll width is measured in goes on top,
105 // offsetWidth less clientWidth: the borders in WebKit, the borders and
106 // paddings in Chromium. Then 2px for the caret at the end of the text.
107 // field-sizing: content, a canvas and a mirror span in the same font
108 // all came out short in WebKit; this did not. CSS caps the width at the
109 // room the field has (max-inline-size, which from 800px allows for the
110 // field's pulled-back start margin), so a longer title still scrolls
111 // inside the field. Nothing after the title on its row moves when it
112 // changes: the stack takes the room. make test-browser holds it in
113 // both engines (title_browser_test.go).
114 // Where a compact bar is the phone's one row, chrome.css's own query:
115 // below 704px, or a phone held sideways. Its title field fills the room
116 // there and is not fitted.
117 const compact = window.matchMedia && window.matchMedia('(max-width: 703.98px), (max-height: 480px) and (pointer: coarse)')
118 const FIT = '[estilo-bar-title-input][size]'
119 const CARET = 2
120 const fit = (input) => {
121 if (compact && compact.matches && input.closest('[estilo-bar~="compact"]')) {
122 input.style.inlineSize = ''
123 return
124 }
125 input.style.inlineSize = '0px'
126 const w = input.scrollWidth + input.offsetWidth - input.clientWidth
127 input.style.inlineSize = Math.ceil(w + CARET) + 'px'
128 }
129 const fitAll = () => { Array.prototype.forEach.call(document.querySelectorAll(FIT), fit) }
130 document.addEventListener('input', (e) => {
131 const input = e.target.closest && e.target.closest(FIT)
132 if (input) fit(input)
133 })
134 // Again on resize, once everything has loaded, and once fonts settle:
135 // the first measure, at script time, can come out a few pixels short.
136 window.addEventListener('resize', fitAll)
137 window.addEventListener('load', fitAll)
138 if (compact && compact.addEventListener) compact.addEventListener('change', fitAll)
139 if (document.fonts && document.fonts.ready) document.fonts.ready.then(fitAll)
140 fitAll()
141
142 // Below 800px a stacked bar is the one-row bar with the app's menus as a
143 // second row, and that row wraps where the menus do not fit (English
144 // at 320px). CSS publishes the one-row-of-menus height; this publishes
145 // the header's real one, so whatever sticks under it (Docs' strip)
146 // sticks under all of it. Only below 800px: from there the header's
147 // height is the variable itself, and publishing its measure back would
148 // hold it at whatever it measured last.
149 // Not a compact bar's: its height is the CSS's own at every width (52px
150 // as one row, 56px as the header from 704px), and a measure published
151 // while it was one row held it at 52px once widened into the 704-799px
152 // band, where it is the 56px header (Fable, on 4757ccc).
153 const stacked = Array.prototype.find.call(document.querySelectorAll('[estilo-bar~="stacked"]'),
154 (bar) => (' ' + bar.getAttribute('estilo-bar') + ' ').indexOf(' compact ') < 0)
155 const narrow = window.matchMedia && window.matchMedia('(max-width: 799.98px)')
156 if (stacked && narrow && typeof ResizeObserver === 'function') {
157 const root = document.documentElement
158 const publish = () => {
159 const h = stacked.getBoundingClientRect().height
160 if (narrow.matches && h > 0) root.style.setProperty('--estilo-bar-block-size', h + 'px')
161 else root.style.removeProperty('--estilo-bar-block-size')
162 }
163 new ResizeObserver(publish).observe(stacked)
164 if (narrow.addEventListener) narrow.addEventListener('change', publish)
165 }
166
167 // Appearance switches at once (Paul: "They're not doing an action ...
168 // they should just switch immediately"). The page takes the scheme as
169 // chrome.ThemeAttr writes it, data-theme="light" or "dark" on <html> and
170 // no attribute for System; whatever was mid-transition lands in it at
171 // once; the pressed segment moves; and the same form data is POSTed to
172 // the form's action in the background to save it, without following
173 // the server's redirect back to the page. The form is
174 // data-busy="false", so the busy rule holds nothing. If the POST fails
175 // the page stays switched for this visit and says nothing; the next load
176 // shows the saved choice (spec, P3). Each switch aborts the save before
177 // it, so two quick clicks cannot reach the server in the wrong order
178 // and leave the first choice saved. Capture phase, like the rest: an
179 // app's own submit handler cannot swallow it.
180 //
181 // land() is rastrillo's shim's, for its own scheme menu: a change of
182 // scheme would otherwise retarget running colour transitions while the
183 // text changes at once. getAnimations() flushes style, which starts the
184 // transitions the change causes, and cancelling one lands it on its end
185 // value. Transitions only, told by transitionProperty: cancelling an
186 // animation would stop a spinner for good.
187 const land = () => {
188 if (!document.getAnimations) return
189 document.getAnimations().forEach((a) => { if (typeof a.transitionProperty === 'string') a.cancel() })
190 }
191 let saving = null
192 document.addEventListener('submit', (e) => {
193 const form = e.target
194 const button = e.submitter
195 if (e.defaultPrevented || !form.hasAttribute || !form.hasAttribute('estilo-appearance')) return
196 if (!button || button.getAttribute('name') !== 'mode') return
197 const mode = button.value
198 if (mode !== 'light' && mode !== 'dark' && mode !== 'system') return
199 e.preventDefault()
200 const root = document.documentElement
201 if (mode === 'system') root.removeAttribute('data-theme')
202 else root.setAttribute('data-theme', mode)
203 land()
204 Array.prototype.forEach.call(form.querySelectorAll('button[name="mode"]'), (b) => {
205 b.setAttribute('aria-pressed', b === button ? 'true' : 'false')
206 })
207 const body = new URLSearchParams(new FormData(form))
208 body.set('mode', mode)
209 if (saving) saving.abort()
210 saving = typeof AbortController === 'function' ? new AbortController() : null
211 fetch(form.getAttribute('action'), { method: 'POST', body, credentials: 'same-origin', redirect: 'manual', signal: saving ? saving.signal : undefined }).catch(() => {})
212 }, true)
213})()
214