forge
Explore
Log in

Don't you dare go Hollow

The client says what is its own, and the morph knows no names

Browse files at this commit

a85a030e78a5f87b31746e252d53eac0c2ea336aAhmet Kaan GümüşParent: 9fb88e0
  • fix
    • the client says what is its own, and the morph knows no names
Show full message
🐛 fix(morph): the client says what is its own, and the morph knows no names

Saving one setting drew every dropdown twice: the styled trigger, and under
it the native select it was built to replace. The live refresh morphs the
server's HTML over the live DOM, and `syncAttrs` copied the server's `class`
wholesale — wiping `dd-native`, which is the only thing hiding that select.
`data-dd-done` survived, because it was on a hand-written exemption list, so
`enhanceAll` skipped the select as already enhanced and never re-hid it.
Half the enhancement survived, which is worse than none of it.

The narrow fix would have been to add `class` to that list. The list is the
defect: it is a fact about dropdowns kept in a file that must not know about
dropdowns, and it is wrong the first time somebody adds an enhancement
without reading it. So the morph now knows no names at all. A node declares
what belongs to the client, at the moment the client takes it —
`__izlekOwn(node, classes, attrs)` for marks on a server-rendered node,
`__izlekAdded(node)` for a node the client built — recorded on a DOM
property, which no morph can strip. `__izlekOwn` applies the classes itself,
so there is no way to add one without registering it.

Three more instances of the same class, found by looking for it: the audio
player's `data-wired` (stripped, so a refresh stacked a second set of
listeners on the same element), the card menu's `card-menu-open` and the
inline `style` holding its position, and the user menu's `user-menu-esc`.

Ownership stops the morph from breaking an enhancement. It does not make the
enhancement follow the data, so `izlek:wire` is now a repair rather than an
install: an already-enhanced select re-asserts `dd-native`, re-reads its
label off the select, and rebuilds its rows when the options changed — an
open panel is left alone, since moving rows under the pointer is worse than
being stale for a moment. Without that, a status somebody else changed would
morph underneath a trigger still announcing the old one.

Verified in Chromium against a throwaway server: on the old build all four
profile selects come back visible with `dd-native` gone after one save; on
this one, zero visible natives and exactly one trigger each, across a save,
eleven morphing refreshes and no console errors.
crates/izlek-web/src/board.rsmodified+1 -1
@@ -448,7 +448,7 @@ async fn card_menu_script(cx: &Cx) -> Result {
448 if (!menu) { return; } \448 if (!menu) { return; } \
449 menu.style.left = e.clientX + 'px'; \449 menu.style.left = e.clientX + 'px'; \
450 menu.style.top = e.clientY + 'px'; \450 menu.style.top = e.clientY + 'px'; \
451- menu.classList.add('card-menu-open'); \451+ window.__izlekOwn(menu, ['card-menu-open'], ['style']); \
452 }; \452 }; \
453 document.addEventListener('click', closeCardMenus); \453 document.addEventListener('click', closeCardMenus); \
454 window.__izlekEsc.register(20, function () { \454 window.__izlekEsc.register(20, function () { \
crates/izlek-web/src/detail.rsmodified+2 -1
@@ -2081,6 +2081,7 @@ async fn audio_player_script(cx: &Cx) -> Result {
2081 function wireAll() { document.querySelectorAll('.audio-player').forEach(wirePlayer); } \2081 function wireAll() { document.querySelectorAll('.audio-player').forEach(wirePlayer); } \
2082 function wirePlayer(player) { \2082 function wirePlayer(player) { \
2083 if (player.dataset.wired) { return; } \2083 if (player.dataset.wired) { return; } \
2084+ window.__izlekOwn(player, [], ['data-wired']); \
2084 player.dataset.wired = '1'; \2085 player.dataset.wired = '1'; \
2085 var audio = player.querySelector('.audio-el'); \2086 var audio = player.querySelector('.audio-el'); \
2086 var play = player.querySelector('.audio-play'); \2087 var play = player.querySelector('.audio-play'); \
@@ -2097,7 +2098,7 @@ async fn audio_player_script(cx: &Cx) -> Result {
2097 if (audio.paused) { audio.play(); } else { audio.pause(); } \2098 if (audio.paused) { audio.play(); } else { audio.pause(); } \
2098 }); \2099 }); \
2099 audio.addEventListener('play', function () { \2100 audio.addEventListener('play', function () { \
2100- player.classList.add('audio-playing'); \2101+ window.__izlekOwn(player, ['audio-playing'], []); \
2101 play.setAttribute('aria-label', play.getAttribute('data-pause')); \2102 play.setAttribute('aria-label', play.getAttribute('data-pause')); \
2102 }); \2103 }); \
2103 audio.addEventListener('pause', function () { \2104 audio.addEventListener('pause', function () { \
crates/izlek-web/src/dropdown.rsmodified+56 -13
@@ -44,7 +44,16 @@ use topcoat::view::{Unescaped, view};
44 44
45 /// Emitted once per page that renders a `<select>`; the enhancement is45 /// Emitted once per page that renders a `<select>`; the enhancement is
46 /// per-element and idempotent (`data-dd-done`), re-run on `izlek:wire` so46 /// per-element and idempotent (`data-dd-done`), re-run on `izlek:wire` so
47-/// selects arriving in a soft page swap get theirs too. Owns its own47+/// 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
48 /// `Escape` resolver on `window.__izlekEsc` (priority 95 — the dropdown57 /// `Escape` resolver on `window.__izlekEsc` (priority 95 — the dropdown
49 /// outranks the modal chain: Escape on an open panel closes just the58 /// outranks the modal chain: Escape on an open panel closes just the
50 /// panel, never the modal above it. The old per-script listeners made59 /// panel, never the modal above it. The old per-script listeners made
@@ -126,8 +135,47 @@ pub async fn dropdown_script(cx: &Cx) -> Result {
126 activate(panel, panel.querySelector('.dd-option-selected') || panel.querySelector('.dd-option'));\135 activate(panel, panel.querySelector('.dd-option-selected') || panel.querySelector('.dd-option'));\
127 if (search) { search.focus(); }\136 if (search) { search.focus(); }\
128 }\137 }\
138+ function fillRows(panel, select) {\
139+ panel.querySelectorAll('.dd-option').forEach(function (r) { r.remove(); });\
140+ opts(select).forEach(function (opt) {\
141+ var row = document.createElement('button');\
142+ row.type = 'button';\
143+ row.className = 'dd-option' + (opt.selected ? ' dd-option-selected' : '');\
144+ row.textContent = opt.textContent;\
145+ row.dataset.value = opt.value;\
146+ row.setAttribute('role', 'option');\
147+ row.setAttribute('aria-selected', opt.selected ? 'true' : 'false');\
148+ panel.appendChild(row);\
149+ });\
150+ }\
151+ function rowsMatch(panel, select) {\
152+ var rows = panel.querySelectorAll('.dd-option');\
153+ var all = opts(select);\
154+ if (rows.length !== all.length) { return false; }\
155+ for (var i = 0; i < all.length; i++) {\
156+ if (rows[i].dataset.value !== all[i].value) { return false; }\
157+ if (rows[i].textContent !== all[i].textContent) { return false; }\
158+ }\
159+ return true;\
160+ }\
161+ function resync(select) {\
162+ var trigger = select.__ddTrigger, panel = select.__ddPanel;\
163+ if (!trigger || !panel) { return; }\
164+ window.__izlekOwn(select, ['dd-native'], []);\
165+ if (panel.classList.contains('dd-open')) { return; }\
166+ if (!rowsMatch(panel, select)) { fillRows(panel, select); }\
167+ var current = select.options[select.selectedIndex];\
168+ var label = current ? current.textContent : '';\
169+ if (trigger.textContent !== label) { trigger.textContent = label; }\
170+ panel.querySelectorAll('.dd-option').forEach(function (r) {\
171+ var on = !!current && r.dataset.value === current.value;\
172+ r.classList.toggle('dd-option-selected', on);\
173+ r.setAttribute('aria-selected', on ? 'true' : 'false');\
174+ });\
175+ }\
129 function enhance(select) {\176 function enhance(select) {\
130- if (select.dataset.ddDone) { return; }\177+ if (select.dataset.ddDone) { resync(select); return; }\
178+ window.__izlekOwn(select, [], ['data-dd-done']);\
131 select.dataset.ddDone = '1';\179 select.dataset.ddDone = '1';\
132 var trigger = document.createElement('button');\180 var trigger = document.createElement('button');\
133 trigger.type = 'button';\181 trigger.type = 'button';\
@@ -136,14 +184,17 @@ pub async fn dropdown_script(cx: &Cx) -> Result {
136 trigger.textContent = current ? current.textContent : '';\184 trigger.textContent = current ? current.textContent : '';\
137 trigger.setAttribute('aria-haspopup', 'listbox');\185 trigger.setAttribute('aria-haspopup', 'listbox');\
138 trigger.setAttribute('aria-expanded', 'false');\186 trigger.setAttribute('aria-expanded', 'false');\
187+ window.__izlekAdded(trigger);\
139 select.parentNode.insertBefore(trigger, select);\188 select.parentNode.insertBefore(trigger, select);\
140- select.classList.add('dd-native');\189+ window.__izlekOwn(select, ['dd-native'], []);\
141 var panel = document.createElement('div');\190 var panel = document.createElement('div');\
142 panel.className = 'dd-panel';\191 panel.className = 'dd-panel';\
143 panel.setAttribute('role', 'listbox');\192 panel.setAttribute('role', 'listbox');\
144 panel.__ddTrigger = trigger;\193 panel.__ddTrigger = trigger;\
145 trigger.__ddPanel = panel;\194 trigger.__ddPanel = panel;\
146 trigger.__ddSelect = select;\195 trigger.__ddSelect = select;\
196+ select.__ddTrigger = trigger;\
197+ select.__ddPanel = panel;\
147 var allOpts = opts(select);\198 var allOpts = opts(select);\
148 var search = null;\199 var search = null;\
149 if (allOpts.length > 7 || select.hasAttribute('data-search')) {\200 if (allOpts.length > 7 || select.hasAttribute('data-search')) {\
@@ -153,16 +204,8 @@ pub async fn dropdown_script(cx: &Cx) -> Result {
153 panel.appendChild(search);\204 panel.appendChild(search);\
154 panel.__ddSearch = search;\205 panel.__ddSearch = search;\
155 }\206 }\
156- allOpts.forEach(function (opt) {\207+ fillRows(panel, select);\
157- var row = document.createElement('button');\208+ window.__izlekAdded(panel);\
158- row.type = 'button';\
159- row.className = 'dd-option' + (opt.selected ? ' dd-option-selected' : '');\
160- row.textContent = opt.textContent;\
161- row.dataset.value = opt.value;\
162- row.setAttribute('role', 'option');\
163- row.setAttribute('aria-selected', opt.selected ? 'true' : 'false');\
164- panel.appendChild(row);\
165- });\
166 document.body.appendChild(panel);\209 document.body.appendChild(panel);\
167 trigger.addEventListener('click', function (e) {\210 trigger.addEventListener('click', function (e) {\
168 e.stopPropagation();\211 e.stopPropagation();\
crates/izlek-web/src/layout.rsmodified+68 -14
@@ -237,6 +237,17 @@ pub async fn soft_nav_script(cx: &Cx) -> Result {
237 (function () { \237 (function () { \
238 if (window.__izlekSoft) { return; } \238 if (window.__izlekSoft) { return; } \
239 window.__izlekSoft = true; \239 window.__izlekSoft = true; \
240+ window.__izlekOwn = function (node, classes, attrs) { \
241+ var own = node.__izlekMine; \
242+ if (!own) { own = node.__izlekMine = { c: [], a: [] }; } \
243+ (classes || []).forEach(function (c) { \
244+ if (own.c.indexOf(c) === -1) { own.c.push(c); } \
245+ node.classList.add(c); \
246+ }); \
247+ (attrs || []).forEach(function (a) { if (own.a.indexOf(a) === -1) { own.a.push(a); } }); \
248+ return node; \
249+ }; \
250+ window.__izlekAdded = function (node) { node.__izlekAdded = true; return node; }; \
240 function wire() { \251 function wire() { \
241 document.querySelectorAll('.comment-list').forEach(function (list) { list.scrollTop = list.scrollHeight; }); \252 document.querySelectorAll('.comment-list').forEach(function (list) { list.scrollTop = list.scrollHeight; }); \
242 document.dispatchEvent(new Event('izlek:wire')); \253 document.dispatchEvent(new Event('izlek:wire')); \
@@ -288,10 +299,7 @@ pub async fn soft_nav_script(cx: &Cx) -> Result {
288 } \299 } \
289 }); \300 }); \
290 } \301 } \
291- function clientMade(node) { \302+ function clientMade(node) { return node.__izlekAdded === true; } \
292- return node.nodeType === 1 && node.classList \
293- && (node.classList.contains('dd-panel') || node.classList.contains('dd-trigger')); \
294- } \
295 function pairable(a, b) { \303 function pairable(a, b) { \
296 if (a.nodeType !== b.nodeType) { return false; } \304 if (a.nodeType !== b.nodeType) { return false; } \
297 if (a.nodeType !== 1) { return true; } \305 if (a.nodeType !== 1) { return true; } \
@@ -299,17 +307,31 @@ pub async fn soft_nav_script(cx: &Cx) -> Result {
299 if (a.id || b.id) { return a.id === b.id; } \307 if (a.id || b.id) { return a.id === b.id; } \
300 return true; \308 return true; \
301 } \309 } \
310+ function syncClass(from, to, own) { \
311+ var want = []; \
312+ to.classList.forEach(function (c) { want.push(c); }); \
313+ if (own) { \
314+ own.c.forEach(function (c) { \
315+ if (from.classList.contains(c) && want.indexOf(c) === -1) { want.push(c); } \
316+ }); \
317+ } \
318+ if (want.length) { from.setAttribute('class', want.join(' ')); } \
319+ else if (from.hasAttribute('class')) { from.removeAttribute('class'); } \
320+ } \
302 function syncAttrs(from, to) { \321 function syncAttrs(from, to) { \
303- var i, at; \322+ var own = from.__izlekMine, i, at; \
304 for (i = to.attributes.length - 1; i >= 0; i--) { \323 for (i = to.attributes.length - 1; i >= 0; i--) { \
305 at = to.attributes[i]; \324 at = to.attributes[i]; \
325+ if (at.name === 'class') { continue; } \
306 if (from.getAttribute(at.name) !== at.value) { from.setAttribute(at.name, at.value); } \326 if (from.getAttribute(at.name) !== at.value) { from.setAttribute(at.name, at.value); } \
307 } \327 } \
308 for (i = from.attributes.length - 1; i >= 0; i--) { \328 for (i = from.attributes.length - 1; i >= 0; i--) { \
309 at = from.attributes[i]; \329 at = from.attributes[i]; \
310- if (at.name.indexOf('data-dd') === 0) { continue; } \330+ if (at.name === 'class') { continue; } \
331+ if (own && own.a.indexOf(at.name) !== -1) { continue; } \
311 if (!to.hasAttribute(at.name)) { from.removeAttribute(at.name); } \332 if (!to.hasAttribute(at.name)) { from.removeAttribute(at.name); } \
312 } \333 } \
334+ syncClass(from, to, own); \
313 } \335 } \
314 function morph(from, to) { \336 function morph(from, to) { \
315 if (from.nodeType !== 1) { \337 if (from.nodeType !== 1) { \
@@ -544,13 +566,45 @@ pub async fn soft_nav_script(cx: &Cx) -> Result {
544 /// panel keeps its position. Not because any of them is special-cased, but566 /// panel keeps its position. Not because any of them is special-cased, but
545 /// because nothing touched them.567 /// because nothing touched them.
546 ///568 ///
547-/// Two kinds of node need naming for this to hold. The dropdown builds a569+/// A `<script>` whose text is unchanged is left alone rather than re-created,
548-/// `.dd-trigger` beside each select and appends a `.dd-panel` to the body, and570+/// so the live path stops re-running every script on the page; the `__izlek*`
549-/// neither exists in the server's HTML — a morph that did not know this would571+/// guards remain the backstop for the full-swap path, which still re-runs them.
550-/// delete them as strays on the first update. And a `<script>` whose text is572+///
551-/// unchanged is left alone rather than re-created, so the live path stops573+/// ## The client declares what is its own
552-/// re-running every script on the page; the `__izlek*` guards remain the574+///
553-/// backstop for the full-swap path, which still re-runs them.575+/// A morph rebuilds the page from HTML that knows nothing about the client.
576+/// Two things it would therefore destroy: nodes the client created, which
577+/// look like strays, and the marks an enhancement leaves on a node the server
578+/// *did* render — `dd-native` hiding a replaced select, `data-wired` on a
579+/// wired player, the position an open context menu was placed at.
580+///
581+/// The first version of this knew their names: `clientMade` tested for
582+/// `.dd-panel`/`.dd-trigger`, and the attribute sweep skipped anything
583+/// starting with `data-dd`. That is a list, and a list is wrong the first
584+/// time somebody adds an enhancement without reading it. It was already
585+/// wrong: `data-dd-done` was on the list and `class` was not, so a save
586+/// unhid every native select underneath its own trigger while `enhanceAll`
587+/// skipped them as already done — one dropdown drawn twice, per field.
588+///
589+/// So the morph knows no names at all. A node says what belongs to the
590+/// client, at the moment the client takes it:
591+///
592+/// - `__izlekOwn(node, classes, attrs)` — the classes and attributes on this
593+/// server-rendered node are the client's. It adds the classes itself, so
594+/// there is no way to apply one without registering it.
595+/// - `__izlekAdded(node)` — this whole node is the client's; it is not a
596+/// stray and must not be deleted.
597+///
598+/// Both record on a DOM *property*, which no morph can strip, and both are
599+/// defined here — before any script that could enhance anything runs.
600+/// `syncAttrs` then merges `class` (the server's list plus whatever owned
601+/// classes are still on the node) instead of overwriting it, and skips owned
602+/// attributes when it sweeps. Nothing in this file mentions a dropdown.
603+///
604+/// The other half of the contract is `izlek:wire`: an enhancement re-derives
605+/// whatever it draws from server data rather than assuming it is still true.
606+/// Ownership keeps the morph from breaking the enhancement; the wire pass is
607+/// how the enhancement follows the server when the data underneath it moves.
554 ///608 ///
555 /// Morphing is used only for the live refresh. Navigations and form posts keep609 /// Morphing is used only for the live refresh. Navigations and form posts keep
556 /// the full replace: they are a different page or a submitted form, where610 /// the full replace: they are a different page or a submitted form, where
@@ -642,7 +696,7 @@ pub async fn escape_script(cx: &Cx) -> Result {
642 window.__izlekEsc.register(40, function () { \696 window.__izlekEsc.register(40, function () { \
643 var menu = document.querySelector('.user-menu'); \697 var menu = document.querySelector('.user-menu'); \
644 if (menu && (menu.matches(':hover') || menu.contains(document.activeElement))) { \698 if (menu && (menu.matches(':hover') || menu.contains(document.activeElement))) { \
645- menu.classList.add('user-menu-esc'); \699+ window.__izlekOwn(menu, ['user-menu-esc'], []); \
646 var focused = document.activeElement; \700 var focused = document.activeElement; \
647 if (focused && focused.closest('.user-menu')) { focused.blur(); } \701 if (focused && focused.closest('.user-menu')) { focused.blur(); } \
648 return true; \702 return true; \
crates/izlek-web/tests/http.rsmodified+79 -0
@@ -1799,6 +1799,85 @@ async fn the_whole_control_box_opens_its_dropdown() {
1799 );1799 );
1800 }1800 }
1801 1801
1802+#[tokio::test]
1803+async fn the_morph_keeps_what_the_client_owns_and_names_none_of_it() {
1804+ // The live refresh morphs the server's HTML over the live DOM. The server
1805+ // knows nothing about the trigger the dropdown built or the class hiding
1806+ // the select underneath it, so a morph that trusted the server's
1807+ // attributes wholesale unhid every select under its own trigger — one
1808+ // dropdown drawn twice, per field, after a single save.
1809+ //
1810+ // The fix is not a longer exemption list. A node declares what belongs to
1811+ // the client at the moment the client takes it, and the morph reads only
1812+ // that. These assertions are the guard on that shape: reintroducing a
1813+ // name into the morph is what makes them fail.
1814+ let app = App::open().await;
1815+ let admin = admin(&app).await;
1816+ let page = app.get("/settings", Some(&admin)).await;
1817+ let page = String::from_utf8_lossy(&page.bytes);
1818+
1819+ assert!(
1820+ page.contains("window.__izlekOwn = function (node, classes, attrs)"),
1821+ "there is no way left for an enhancement to declare what it owns"
1822+ );
1823+ assert!(
1824+ page.contains("window.__izlekAdded = function (node)"),
1825+ "a client-built node can no longer say it is not a stray"
1826+ );
1827+ // The morph asks the node, never a list of names it was told to remember.
1828+ assert!(
1829+ page.contains("function clientMade(node) { return node.__izlekAdded === true; }"),
1830+ "the stray test is back to sniffing class names"
1831+ );
1832+ assert!(
1833+ page.contains("var own = from.__izlekMine"),
1834+ "the attribute sweep no longer reads what the node owns"
1835+ );
1836+ // class is merged, not overwritten. This is the exact line the bug was.
1837+ assert!(
1838+ page.contains("syncClass(from, to, own)") && page.contains("own.c.forEach"),
1839+ "the server's class list is overwriting the client's again"
1840+ );
1841+
1842+ // And the dropdown declares, rather than relying on the morph to know.
1843+ assert!(
1844+ page.contains("window.__izlekOwn(select, ['dd-native'], [])"),
1845+ "the select's hidden state is no longer declared as the client's"
1846+ );
1847+ assert!(
1848+ page.contains("window.__izlekAdded(trigger)") && page.contains("window.__izlekAdded(panel)"),
1849+ "the trigger and panel no longer say they are the client's"
1850+ );
1851+}
1852+
1853+#[tokio::test]
1854+async fn a_rewired_dropdown_repairs_itself_instead_of_being_skipped() {
1855+ // Ownership stops the morph from breaking the enhancement. It does not
1856+ // make the enhancement follow the data: the trigger's label is drawn from
1857+ // the select, so when a live refresh moves the selection the trigger has
1858+ // to re-read it. An already-enhanced select is therefore repaired on
1859+ // `izlek:wire`, not skipped.
1860+ let app = App::open().await;
1861+ let admin = admin(&app).await;
1862+ let page = app.get("/settings", Some(&admin)).await;
1863+ let page = String::from_utf8_lossy(&page.bytes);
1864+
1865+ assert!(
1866+ page.contains("if (select.dataset.ddDone) { resync(select); return; }"),
1867+ "an already-enhanced select is skipped again instead of repaired"
1868+ );
1869+ assert!(
1870+ page.contains("if (!rowsMatch(panel, select)) { fillRows(panel, select); }"),
1871+ "the panel no longer follows the select's option list"
1872+ );
1873+ // Repairing under an open panel would move the rows out from under the
1874+ // pointer; stale for that moment is the better failure.
1875+ assert!(
1876+ page.contains("if (panel.classList.contains('dd-open')) { return; }"),
1877+ "the repair now runs under an open panel"
1878+ );
1879+}
1880+
1802 #[tokio::test]1881 #[tokio::test]
1803 async fn the_parts_have_a_tab_and_a_subtask_is_not_offered_one() {1882 async fn the_parts_have_a_tab_and_a_subtask_is_not_offered_one() {
1804 let app = App::open().await;1883 let app = App::open().await;