forge
Explore
Log in

Don't you dare go Hollow

in_old

Clone
★ 0

0 watching0 forksRustGPL-3.01.1 MiB218b775Tahinli2 months ago90 commits

dropdown.rs313 lines, 18.0 KiBHistoryRawDownload
1//! The house replacement for the native `<select>` popup.
2//!
3//! Every browser engine draws its own `<select>` list, and only Chromium's
4//! `::picker(select)` lets that popup be themed — Firefox/WebKit never see
5//! it, so styling the native popup is not a real cross-browser option.
6//! Instead [`dropdown_script`] progressively enhances any `select.status-select`
7//! or `select.field-input` already on the page: the native element stays in
8//! the DOM (hidden, so its `name`/value still post the same form field
9//! unchanged) while a `<button>` cloning its own classes becomes the
10//! visible trigger — same closed look as the select it replaces — and a
11//! `position: fixed` panel of option rows, portaled onto `<body>`, stands
12//! in for the OS popup.
13//!
14//! ## The whole box is the hit area
15//!
16//! The trigger is one child among several inside a control box — a status
17//! dot before it, a chevron after it, the box's own padding around all of
18//! them — so a button-only listener leaves dead zones exactly where the
19//! control looks clickable. That bug has been fixed one control at a time
20//! before; this is the version that cannot come back. A delegated listener
21//! walks up from whatever was clicked and, on finding the element that
22//! *directly* contains a single `.dd-trigger`, opens that trigger's panel.
23//!
24//! "Directly contains" is the whole of the rule: it pins the hit area to
25//! the visual box and no further, so a click on a field's outer row or on
26//! the modal around it does not reach in and open something. Nothing has to
27//! be marked up for this to work — a new control gets it by existing, which
28//! is what makes it structural rather than another remembered convention.
29//!
30//! Anything else genuinely interactive keeps its own click — a link, a
31//! button, a text field. `<label>` is deliberately *not* on that list: the
32//! new-task modal wraps its status box in one, and bailing on labels put
33//! every dead zone straight back.
34//!
35//! The delegated click also calls `preventDefault`. A `<label>` forwards a
36//! click to the control it labels, so without it the browser delivered a
37//! *second* click straight to the trigger, which toggled the panel shut
38//! again in the same gesture — opening and closing looked exactly like the
39//! dead zone the delegation was added to remove.
40
41use topcoat::Result;
42use topcoat::context::Cx;
43use topcoat::view::{Unescaped, View, ViewExt, view};
44
45/// Emitted once per page that renders a `<select>`; the enhancement is
46/// per-element and idempotent (`data-dd-done`), re-run on `in:wire` so
47/// selects arriving in a soft page swap get theirs too. A select that is
48/// already done is not skipped but repaired: the live refresh morphs the
49/// server's HTML over the live DOM, and what it writes is the select — its
50/// selected option, its option list, its class — while the trigger and panel
51/// standing in for it are the client's and are left untouched. So `resync`
52/// re-asserts `dd-native`, re-reads the label off the select, and rebuilds
53/// the rows when the options themselves changed. Without it the two halves
54/// drift: the select unhides itself under its own trigger, or the trigger
55/// keeps announcing a status somebody else has already changed. An open
56/// panel is left alone — repairing under a pointer is worse than stale. Owns its own
57/// `Escape` resolver on `window.__inEsc` (priority 95 — the dropdown
58/// outranks the modal chain: Escape on an open panel closes just the
59/// panel, never the modal above it. The old per-script listeners made
60/// this order path-dependent — a modal swapped in by soft navigation
61/// registered its listener last and lost to the dropdown; a full load
62/// with `?task=` registered it first and the modal chain won, closing
63/// the whole modal over an open dropdown — the registry pins the correct
64/// order; the whole table lives in `layout.rs`'s `escape_manager_script`).
65/// A panel's rows are `white-space: nowrap`, so a long option never wraps —
66/// `place` caps the open panel's width at `innerWidth − 8`, shaving off the
67/// padding and borders a `max-width` does not cover, or its right edge would
68/// clip on a 320px phone no matter where the left clamp puts it.
69pub async fn dropdown_script<'a>(cx: &'a Cx) -> Result<impl View + 'a> {
70 const JS: &str = "\
71 (function () {\
72 if (window.__inDd) { return; }\
73 window.__inDd = true;\
74 function opts(select) { return Array.prototype.slice.call(select.options); }\
75 function closeAll() {\
76 document.querySelectorAll('.dd-panel.dd-open').forEach(function (panel) {\
77 panel.classList.remove('dd-open');\
78 if (panel.__ddTrigger) { panel.__ddTrigger.setAttribute('aria-expanded', 'false'); }\
79 });\
80 }\
81 function place(panel, trigger) {\
82 var r = trigger.getBoundingClientRect();\
83 var maxW = window.innerWidth - 8;\
84 panel.style.maxWidth = '';\
85 if (panel.offsetWidth > maxW) { panel.style.maxWidth = maxW + 'px'; }\
86 var over = panel.offsetWidth - maxW;\
87 if (over > 0) { panel.style.maxWidth = (maxW - over) + 'px'; }\
88 var h = panel.offsetHeight;\
89 var w = panel.offsetWidth;\
90 var top = r.bottom + 4;\
91 if (top + h > window.innerHeight && r.top - h - 4 >= 0) { top = r.top - h - 4; }\
92 top = Math.max(4, Math.min(top, window.innerHeight - h - 4));\
93 var left = Math.max(4, Math.min(r.left, window.innerWidth - w - 4));\
94 panel.style.left = left + 'px';\
95 panel.style.top = top + 'px';\
96 panel.style.minWidth = Math.min(r.width, maxW) + 'px';\
97 }\
98 function visibleRows(panel) { return Array.prototype.slice.call(panel.querySelectorAll('.dd-option:not(.dd-option-hidden)')); }\
99 function activate(panel, row) {\
100 panel.querySelectorAll('.dd-option-active').forEach(function (r) { r.classList.remove('dd-option-active'); });\
101 if (!row) { return; }\
102 row.classList.add('dd-option-active');\
103 if (panel.__ddSearch) { row.scrollIntoView({ block: 'nearest' }); } else { row.focus(); }\
104 }\
105 function isTypeKey(e) { return e.key && e.key.length === 1 && !e.ctrlKey && !e.altKey && !e.metaKey; }\
106 function typeIntoSearch(search, e) {\
107 search.focus();\
108 search.value += e.key;\
109 search.dispatchEvent(new Event('input', { bubbles: true }));\
110 }\
111 function filterRows(panel, query) {\
112 var qTr = query.toLocaleLowerCase('tr');\
113 var qEn = query.toLowerCase();\
114 panel.querySelectorAll('.dd-option').forEach(function (r) {\
115 var t = r.textContent;\
116 var miss = t.toLocaleLowerCase('tr').indexOf(qTr) === -1 && t.toLowerCase().indexOf(qEn) === -1;\
117 r.classList.toggle('dd-option-hidden', qEn !== '' && miss);\
118 });\
119 var vis = visibleRows(panel);\
120 activate(panel, panel.querySelector('.dd-option-selected:not(.dd-option-hidden)') || vis[0]);\
121 }\
122 function pick(select, trigger, panel, row) {\
123 select.value = row.dataset.value;\
124 panel.querySelectorAll('.dd-option').forEach(function (r) {\
125 r.classList.toggle('dd-option-selected', r === row);\
126 r.setAttribute('aria-selected', r === row ? 'true' : 'false');\
127 });\
128 trigger.textContent = row.textContent;\
129 panel.classList.remove('dd-open');\
130 trigger.setAttribute('aria-expanded', 'false');\
131 trigger.focus();\
132 select.dispatchEvent(new Event('change', { bubbles: true }));\
133 }\
134 function openPanel(select, trigger, panel) {\
135 closeAll();\
136 var search = panel.__ddSearch;\
137 if (search) {\
138 search.value = '';\
139 panel.querySelectorAll('.dd-option').forEach(function (r) { r.classList.remove('dd-option-hidden'); });\
140 }\
141 panel.classList.add('dd-open');\
142 place(panel, trigger);\
143 trigger.setAttribute('aria-expanded', 'true');\
144 activate(panel, panel.querySelector('.dd-option-selected') || panel.querySelector('.dd-option'));\
145 if (search) { search.focus(); }\
146 }\
147 function fillRows(panel, select) {\
148 panel.querySelectorAll('.dd-option').forEach(function (r) { r.remove(); });\
149 opts(select).forEach(function (opt) {\
150 var row = document.createElement('button');\
151 row.type = 'button';\
152 row.className = 'dd-option' + (opt.selected ? ' dd-option-selected' : '');\
153 row.textContent = opt.textContent;\
154 row.dataset.value = opt.value;\
155 row.setAttribute('role', 'option');\
156 row.setAttribute('aria-selected', opt.selected ? 'true' : 'false');\
157 panel.appendChild(row);\
158 });\
159 }\
160 function rowsMatch(panel, select) {\
161 var rows = panel.querySelectorAll('.dd-option');\
162 var all = opts(select);\
163 if (rows.length !== all.length) { return false; }\
164 for (var i = 0; i < all.length; i++) {\
165 if (rows[i].dataset.value !== all[i].value) { return false; }\
166 if (rows[i].textContent !== all[i].textContent) { return false; }\
167 }\
168 return true;\
169 }\
170 function resync(select) {\
171 var trigger = select.__ddTrigger, panel = select.__ddPanel;\
172 if (!trigger || !panel) { return; }\
173 window.__inOwn(select, ['dd-native'], []);\
174 if (panel.classList.contains('dd-open')) { return; }\
175 if (!rowsMatch(panel, select)) { fillRows(panel, select); }\
176 var current = select.options[select.selectedIndex];\
177 var label = current ? current.textContent : '';\
178 if (trigger.textContent !== label) { trigger.textContent = label; }\
179 panel.querySelectorAll('.dd-option').forEach(function (r) {\
180 var on = !!current && r.dataset.value === current.value;\
181 r.classList.toggle('dd-option-selected', on);\
182 r.setAttribute('aria-selected', on ? 'true' : 'false');\
183 });\
184 }\
185 function enhance(select) {\
186 if (select.dataset.ddDone) { resync(select); return; }\
187 window.__inOwn(select, [], ['data-dd-done']);\
188 select.dataset.ddDone = '1';\
189 var trigger = document.createElement('button');\
190 trigger.type = 'button';\
191 trigger.className = select.className + ' dd-trigger';\
192 var current = select.options[select.selectedIndex];\
193 trigger.textContent = current ? current.textContent : '';\
194 trigger.setAttribute('aria-haspopup', 'listbox');\
195 trigger.setAttribute('aria-expanded', 'false');\
196 window.__inAdded(trigger);\
197 select.parentNode.insertBefore(trigger, select);\
198 window.__inOwn(select, ['dd-native'], []);\
199 /* The form's own submit only serves the no-script path of an \
200 autosubmit select; once that select is enhanced it bows out. \
201 A select without autosubmit still needs its button — hiding \
202 it then strands the form with no way to post at all. */ \
203 var sibs = select.parentNode.children; \
204 var go = null; \
205 for (var si = 0; si < sibs.length; si++) { \
206 if (sibs[si].tagName === 'BUTTON' && sibs[si].type === 'submit' && !sibs[si].classList.contains('dd-trigger')) { go = sibs[si]; break; } \
207 } \
208 if (go && select.hasAttribute('data-autosubmit')) { window.__inOwn(go, [], ['style']); go.style.display = 'none'; } \
209 var panel = document.createElement('div');\
210 panel.className = 'dd-panel';\
211 panel.setAttribute('role', 'listbox');\
212 panel.__ddTrigger = trigger;\
213 trigger.__ddPanel = panel;\
214 trigger.__ddSelect = select;\
215 select.__ddTrigger = trigger;\
216 select.__ddPanel = panel;\
217 var allOpts = opts(select);\
218 var search = null;\
219 if (allOpts.length > 7 || select.hasAttribute('data-search')) {\
220 search = document.createElement('input');\
221 search.type = 'text';\
222 search.className = 'dd-search';\
223 panel.appendChild(search);\
224 panel.__ddSearch = search;\
225 }\
226 fillRows(panel, select);\
227 window.__inAdded(panel);\
228 document.body.appendChild(panel);\
229 trigger.addEventListener('click', function (e) {\
230 e.stopPropagation();\
231 if (panel.classList.contains('dd-open')) { closeAll(); } else { openPanel(select, trigger, panel); }\
232 });\
233 trigger.addEventListener('keydown', function (e) {\
234 if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {\
235 e.preventDefault();\
236 if (!panel.classList.contains('dd-open')) { openPanel(select, trigger, panel); return; }\
237 var vis = visibleRows(panel);\
238 var idx = vis.indexOf(panel.querySelector('.dd-option-active')) + (e.key === 'ArrowDown' ? 1 : -1);\
239 if (idx >= 0 && idx < vis.length) { activate(panel, vis[idx]); }\
240 } else if (e.key === 'Enter' && panel.classList.contains('dd-open')) {\
241 e.preventDefault();\
242 var active = panel.querySelector('.dd-option-active');\
243 if (active) { pick(select, trigger, panel, active); }\
244 } else if (search && isTypeKey(e)) {\
245 e.preventDefault();\
246 if (!panel.classList.contains('dd-open')) { openPanel(select, trigger, panel); }\
247 typeIntoSearch(search, e);\
248 }\
249 });\
250 if (search) {\
251 search.addEventListener('input', function () { filterRows(panel, search.value); });\
252 }\
253 panel.addEventListener('keydown', function (e) {\
254 if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {\
255 e.preventDefault();\
256 var vis = visibleRows(panel);\
257 var idx = vis.indexOf(panel.querySelector('.dd-option-active')) + (e.key === 'ArrowDown' ? 1 : -1);\
258 if (idx >= 0 && idx < vis.length) { activate(panel, vis[idx]); }\
259 } else if (e.key === 'Enter') {\
260 e.preventDefault();\
261 var vis = visibleRows(panel);\
262 var active = panel.querySelector('.dd-option-active') || (vis.length === 1 ? vis[0] : null);\
263 if (active) { pick(select, trigger, panel, active); }\
264 } else if (search && e.target !== search && isTypeKey(e)) {\
265 e.preventDefault();\
266 typeIntoSearch(search, e);\
267 }\
268 });\
269 panel.addEventListener('click', function (e) {\
270 e.stopPropagation();\
271 var row = e.target.closest('.dd-option');\
272 if (row) { pick(select, trigger, panel, row); }\
273 });\
274 }\
275 window.__inEsc.register(95, function () {\
276 var panel = document.querySelector('.dd-panel.dd-open');\
277 if (!panel) { return false; }\
278 var trigger = panel.__ddTrigger;\
279 closeAll();\
280 if (trigger) { trigger.focus(); }\
281 return true;\
282 });\
283 document.addEventListener('click', function (e) {\
284 var el = e.target;\
285 if (!el || !el.closest) { return; }\
286 if (el.closest('.dd-panel') || el.closest('.dd-trigger')) { return; }\
287 if (el.closest('a, button, input:not([type=hidden]), textarea')) { return; }\
288 var box = el.nodeType === 1 ? el : el.parentNode;\
289 for (var depth = 0; depth < 3 && box && box.querySelectorAll; depth++) {\
290 var found = box.querySelectorAll('.dd-trigger');\
291 if (found.length === 1 && found[0].parentNode === box && found[0].__ddPanel) {\
292 var t = found[0];\
293 e.stopPropagation();\
294 e.preventDefault();\
295 if (t.__ddPanel.classList.contains('dd-open')) { closeAll(); }\
296 else { openPanel(t.__ddSelect, t, t.__ddPanel); }\
297 return;\
298 }\
299 box = box.parentNode;\
300 }\
301 }, true);\
302 document.addEventListener('click', closeAll);\
303 window.addEventListener('scroll', function (e) {\
304 var t = e.target;\
305 if (t && t.nodeType === 1 && t.classList.contains('dd-panel')) { return; }\
306 closeAll();\
307 }, true);\
308 function enhanceAll() { document.querySelectorAll('select.status-select, select.field-input').forEach(enhance); }\
309 enhanceAll();\
310 document.addEventListener('in:wire', enhanceAll);\
311 })();";
312 Ok(view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }.boxed())
313}