S058: WIP zap port, test page and smoke

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-14 07:31:21 -06:00
commit 25f7fd2b42
7 changed files with 210 additions and 32 deletions

View file

@ -33,8 +33,8 @@ Port the original, which is the spec: `~/Documents/Apps/Nacre/nacre/services.py`
(grep `__ANIMATE__`), the S049 PROGRESS entry (cosmetic-only engine on WebKit).
## Steps
- [ ] Port `ZAP_JS` detection + overlay + collapse into the cosmetic script (keep the class/id → selectors round trip), options (animate, ms, bg, badge, off) from the browser per page; badge SVG built in Rust from theme colours.
- [ ] Safety rules (players, sizes, off-screen, max 12, paused sites) and Motion off / setting off → plain hide.
- [x] Port `ZAP_JS` detection + overlay + collapse into the cosmetic script (keep the class/id → selectors round trip), options (animate, ms, bg, badge, off) from the browser per page; badge SVG built in Rust from theme colours.
- [x] Safety rules (players, sizes, off-screen, max 12, paused sites) and Motion off / setting off → plain hide.
- [ ] Test page `tests/smoke/pages/ads.html` (a few visible ad boxes matching local cosmetic rules, one inside a fake player, one tiny, one off-screen) + smoke: shots mid-animation (overlay + badge visible) and after (slots collapsed, layout closed), player untouched, Motion off = instant; dark and light.
- [ ] Visible run on a real ad-heavy page (e.g. a news site) on DP-1 (D-045): watch it, read the shots; note anything that flickers or jumps.
- [ ] PROGRESS entry, INDEX line, tracker, commit `S058: …`, push.
@ -48,3 +48,7 @@ Port the original, which is the spec: `~/Documents/Apps/Nacre/nacre/services.py`
## Handoff (→ PROGRESS.md)
What differs from the original, if anything.
## Resume
Boxes 1–2 done (src/inject.rs `COSMETIC_JS`, `App::zap_options` in src/app.rs, `theme::zap_badge`). Box 3 in
progress: `tests/smoke/pages/ads.html` + `tests/smoke/zap.txt` (`SMOKE_SIZE=1280x900 tools/smoke.sh tests/smoke/zap.txt`).

View file

@ -1707,7 +1707,8 @@ impl App {
}
let selectors = self.shared.adblock.generic_selectors(&list("classes"), &list("ids"), &exceptions);
if !selectors.is_empty() {
self.eval(tab_id, inject::call("cosmetic.hide", &[serde_json::json!(selectors)]));
let options = self.zap_options(w);
self.eval(tab_id, inject::call("cosmetic.hide", &[serde_json::json!(selectors), options]));
}
},
"cosmetic_removed" => {
@ -2470,7 +2471,6 @@ impl App {
|| old.web.preload != new.web.preload
|| old.adblock.enabled != new.adblock.enabled
|| old.adblock.cosmetic != new.adblock.cosmetic
|| old.adblock.animate != new.adblock.animate
|| old.adblock.youtube != new.adblock.youtube
|| old.vault.enabled != new.vault.enabled
|| old.spell.enabled != new.spell.enabled

View file

@ -482,7 +482,6 @@ impl App {
preload: s.web.preload,
save_data: s.privacy.save_data,
cosmetic: s.adblock.enabled && s.adblock.cosmetic,
animate_removal: s.adblock.animate && !crate::perf::still(&s),
youtube_ads: s.adblock.enabled && s.adblock.youtube,
autofill: s.vault.enabled,
spell: s.spell.enabled,
@ -882,13 +881,30 @@ impl App {
if selectors.is_empty() {
return;
}
let Some((w, _)) = self.find_webview(id) else { return };
let options = self.zap_options(w);
if let Some(tab) = self.tab_mut(id)
&& let Some(web) = &tab.web
{
web.webview.evaluate_javascript(inject::call("cosmetic.hide", &[serde_json::json!(selectors)]), |_| {});
web.webview.evaluate_javascript(inject::call("cosmetic.hide", &[serde_json::json!(selectors), options]), |_| {});
}
}
/// How a page removes the ads it hides (`cosmetic.hide`): animated in the window's theme colours unless the
/// setting, Motion or still mode says no.
pub fn zap_options(&self, w: WindowId) -> serde_json::Value {
let s = self.shared.settings.borrow();
let motion = crate::theme::motion_scale(&s);
let palette = self.windows.get(&w).map(|win| win.ui.palette()).unwrap_or_else(|| crate::ui::WindowUi::default().palette());
let c = palette.primary_container;
serde_json::json!({
"animate": s.adblock.animate && motion > 0.0 && !crate::perf::still(&s),
"ms": (900.0 * motion.max(0.3)).round() as u32,
"bg": format!("rgba({},{},{},0.92)", c.r(), c.g(), c.b()),
"badge": crate::theme::zap_badge(palette.primary, palette.on_primary),
})
}
fn on_favicon(&mut self, id: ViewId) {
let Some((w, i)) = self.find_webview(id) else { return };
let win = self.windows.get_mut(&w).expect("found");

View file

@ -48,7 +48,6 @@ pub struct Options<'a> {
pub preload: bool,
pub save_data: bool,
pub cosmetic: bool,
pub animate_removal: bool,
pub youtube_ads: bool,
pub autofill: bool,
pub spell: bool,
@ -83,7 +82,7 @@ pub fn page_scripts(o: &Options) -> Vec<String> {
modules.push(SAVE_DATA_JS.to_owned());
}
if o.cosmetic {
modules.push(COSMETIC_JS.replace("__ANIMATE__", if o.animate_removal { "true" } else { "false" }));
modules.push(COSMETIC_JS.to_owned());
}
if o.autofill {
modules.push(AUTOFILL_JS.to_owned());
@ -501,10 +500,18 @@ const SAVE_DATA_JS: &str = r#"(() => { try { const c = navigator.connection; if
document.addEventListener('DOMContentLoaded', () => { for (const v of document.querySelectorAll('video[autoplay],video[preload]')) { v.preload = 'none'; } }, { once: true });
} catch (e) {} })();"#;
/// Cosmetic filtering: the page's classes and ids go to the browser, which answers with selectors.
/// Removal can animate (squish) for visible elements.
/// Cosmetic filtering: the page's classes and ids go to the browser, which answers with selectors and options
/// (`hide(selectors, {animate, ms, bg, badge})`).
///
/// Removal is animated like Pie Adblock (a port of the original Nacre's zapper): rules don't hide elements, they
/// give them a 1 ms `__nz_detect` animation, and the page's own `animationstart` hands over each element as it
/// renders (no selector scanning). A cookie-shaped shield badge covers a visible ad, squishes and spins away, the ad
/// fades under it, then its slot collapses. Never touches an element that is or holds `<video>`/`<audio>`; ad bits
/// inside a known player, tiny, huge and off-screen elements are hidden without animation; at most 12 at once.
/// Without animation the rules simply hide, and matches are counted when the selectors arrive.
const COSMETIC_JS: &str = r#"(() => { if (!window.__nacre || window.__nacre.cosmetic) return;
const ANIMATE = __ANIMATE__; const seen = new Set(); let pending = new Set(), timer = 0, style = null, rules = '';
const seen = new Set(); let pending = new Set(), timer = 0, style = null, opts = null, live = 0, count = 0, countTimer = 0;
const selectors = new Set();
const flush = () => { timer = 0; if (!pending.size) return;
const classes = [], ids = [];
for (const k of pending) (k[0] === '.' ? classes : ids).push(k.slice(1));
@ -514,30 +521,65 @@ const COSMETIC_JS: &str = r#"(() => { if (!window.__nacre || window.__nacre.cosm
const id = el.id; if (id && !seen.has('#' + id)) { seen.add('#' + id); pending.add('#' + id); }
const cl = el.classList; if (cl) for (const c of cl) if (!seen.has('.' + c)) { seen.add('.' + c); pending.add('.' + c); } }
if (pending.size && !timer) timer = setTimeout(flush, 120); };
const counted = n => { count += n; if (!countTimer) countTimer = setTimeout(() => { countTimer = 0; if (count) __send('cosmetic_removed', count); count = 0; }, 200); };
const BASE = '@keyframes __nz_detect{from{outline-color:inherit}to{outline-color:inherit}}' +
'.__nz_gone{display:none!important}' +
'@keyframes __nz_ov{0%{opacity:0;transform:none;clip-path:inset(0 round 12px)}18%{opacity:1}' +
'40%{opacity:1;transform:scale(.97);clip-path:inset(0 round 28px)}70%{opacity:1;transform:scale(.72) rotate(-4deg);' +
'clip-path:inset(8% round 48%)}100%{opacity:0;transform:scale(0) rotate(-14deg);clip-path:inset(30% round 50%)}}\n';
const PLAYER = '.html5-video-player,.video-js,.jwplayer,.plyr,[data-vjs-player],.vjs-tech,.shaka-video-container,.dplayer';
const gone = el => el.classList.add('__nz_gone');
// The slot closes up: only this last step animates size.
const collapse = el => { const st = el.style, set = (k, v) => st.setProperty(k, v, 'important');
set('height', el.offsetHeight + 'px'); set('width', el.offsetWidth + 'px'); set('min-width', '0'); set('min-height', '0');
set('flex', 'none'); set('box-sizing', 'border-box'); set('overflow', 'hidden');
set('transition', 'height .34s cubic-bezier(.3,0,.2,1),width .34s cubic-bezier(.3,0,.2,1),margin .34s,padding .34s');
requestAnimationFrame(() => requestAnimationFrame(() => { set('height', '0px'); set('width', '0px'); set('margin', '0'); set('padding', '0'); }));
setTimeout(() => gone(el), 380); };
const zap = (el, r) => { const o = opts, ov = document.createElement('div');
ov.className = '__nz_ov';
ov.style.cssText = `position:absolute;left:${r.left + scrollX}px;top:${r.top + scrollY}px;width:${r.width}px;height:${r.height}px;` +
`margin:0;z-index:2147483647;pointer-events:none;background:url("${o.badge}") center/min(64px,40%) no-repeat,${o.bg};` +
`animation:__nz_ov ${o.ms}ms cubic-bezier(.3,0,.2,1) forwards;transform-origin:center`;
document.documentElement.append(ov);
el.style.setProperty('transition', 'opacity .22s ease .12s', 'important');
el.style.setProperty('opacity', '0', 'important'); // the ad fades out under the overlay
live++;
setTimeout(() => { ov.remove(); live--; collapse(el); }, o.ms); };
const handle = el => {
if (!(el instanceof Element) || el.__nz || !opts || !opts.animate) return;
el.__nz = 1;
if (el.matches('video,audio') || el.querySelector('video,audio')) return; // never kill a real player
counted(1);
if (el.closest(PLAYER)) return gone(el); // ad UI inside a player: quietly
const r = el.getBoundingClientRect();
const onScreen = r.bottom > 0 && r.right > 0 && r.top < innerHeight && r.left < innerWidth;
const small = r.width < 24 || r.height < 24, huge = r.width * r.height > innerWidth * innerHeight * 0.6;
if (small || huge || !onScreen || live >= 12) return gone(el);
zap(el, r); };
document.addEventListener('animationstart', e => { if (e.animationName === '__nz_detect') handle(e.target); }, true);
window.__nacre.cosmetic = {
hide(selectors) {
if (!selectors || !selectors.length) return 0;
if (!style) { style = document.createElement('style'); style.id = '__nacre_cosmetic'; (document.head || document.documentElement).appendChild(style); }
let removed = 0;
for (const sel of selectors) {
try { for (const el of document.querySelectorAll(sel)) {
if (el.__nacreGone) continue; el.__nacreGone = 1; removed++;
const r = el.getBoundingClientRect();
if (ANIMATE && r.width * r.height > 0 && r.bottom > 0 && r.top < innerHeight) {
el.style.transition = 'opacity .25s, transform .25s'; el.style.transformOrigin = 'center'; el.style.opacity = '0'; el.style.transform = 'scale(.92)';
setTimeout(() => el.style.setProperty('display', 'none', 'important'), 260);
} else el.style.setProperty('display', 'none', 'important');
} } catch (e) { continue; }
rules += sel + '{display:none!important}\n';
}
style.textContent = rules;
if (removed) __send('cosmetic_removed', removed);
return removed;
hide(list, o) {
if (!list || !list.length) return 0;
opts = o || { animate: false };
let added = 0;
for (const sel of list) if (!selectors.has(sel)) { selectors.add(sel); added++;
if (!opts.animate) try { for (const el of document.querySelectorAll(sel)) if (!el.__nz) { el.__nz = 1; counted(1); } } catch (e) {} }
if (!added) return 0;
if (!style) { style = document.createElement('style'); style.id = '__nacre_cosmetic'; }
// One rule per selector, so a bad selector only drops itself.
const rule = opts.animate ? '{animation:__nz_detect 1ms!important}' : '{display:none!important}';
style.textContent = BASE + [...selectors].map(s => s + rule).join('\n');
if (!style.isConnected) (document.head || document.documentElement).appendChild(style);
return added;
}
};
const start = () => { scan(document.documentElement);
new MutationObserver(ms => { for (const m of ms) { if (m.type === 'attributes') scan(m.target); else for (const n of m.addedNodes) if (n.nodeType === 1) scan(n); } })
.observe(document.documentElement, { subtree: true, childList: true, attributes: true, attributeFilter: ['class', 'id'] }); };
.observe(document.documentElement, { subtree: true, childList: true, attributes: true, attributeFilter: ['class', 'id'] });
// pages that rebuild <head> (SPAs) get the rules back
new MutationObserver(() => { if (style && !style.isConnected) (document.head || document.documentElement).appendChild(style); })
.observe(document.documentElement, { childList: true }); };
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start, { once: true }); else start();
})();"#;
@ -687,7 +729,7 @@ mod tests {
assert!(js.contains(r#"const SEED = "se\"ed", NAV = {"platform":"Linux x86_64","oscpu":"Linux x86_64","appVersion":"5.0 (X11)"}, LANGS = ["en-US","en"], PAUSED = ["example.com","a\"b"];"#));
assert!(privacy_script("s", "Custom agent", &[], &[]).contains("NAV = null, LANGS = [], PAUSED = [];"));
// Off by default; cookie-blocking module only with blocking on.
let mut o = Options { token: "t", privacy_mode: false, seed: "s", user_agent: "", privacy_paused: &[], languages: &[], block_third_party: false, dnt: false, force_dark: false, smooth_scroll: false, preload: false, save_data: false, cosmetic: false, animate_removal: false, youtube_ads: false, autofill: false, spell: false, google_signin: false };
let mut o = Options { token: "t", privacy_mode: false, seed: "s", user_agent: "", privacy_paused: &[], languages: &[], block_third_party: false, dnt: false, force_dark: false, smooth_scroll: false, preload: false, save_data: false, cosmetic: false, youtube_ads: false, autofill: false, spell: false, google_signin: false };
assert!(!page_scripts(&o)[0].contains("__nacrePriv") && !page_scripts(&o)[0].contains("'cookie'"));
o.privacy_mode = true;
o.block_third_party = true;

View file

@ -80,6 +80,33 @@ pub fn to_hex(c: Color32) -> String {
format!("#{:02X}{:02X}{:02X}", c.r(), c.g(), c.b())
}
/// The ad removal badge: a cookie (nine lobes) in `primary` with a shield and check mark, as an SVG data URI.
pub fn zap_badge(primary: Color32, on_primary: Color32) -> String {
let (p, on) = (to_hex(primary), to_hex(on_primary));
let points: Vec<String> = (0..90)
.map(|i| {
let t = std::f32::consts::TAU * i as f32 / 90.0;
let r = 46.0 * (1.0 + 0.06 * (9.0 * t).cos());
format!("{:.1},{:.1}", 50.0 + r * t.cos(), 50.0 + r * t.sin())
})
.collect();
let svg = format!(
"<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><polygon points='{}' fill='{p}'/>\
<path d='M50 24 32 31v13c0 12 7.7 22.7 18 26 10.3-3.3 18-14 18-26V31z' fill='{on}'/>\
<path d='m43 50 5 5 10-11' fill='none' stroke='{p}' stroke-width='5' stroke-linecap='round' stroke-linejoin='round'/></svg>",
points.join(" ")
);
let mut uri = String::from("data:image/svg+xml,");
for b in svg.bytes() {
if b.is_ascii_alphanumeric() || b"-_.~".contains(&b) {
uri.push(b as char);
} else {
uri.push_str(&format!("%{b:02X}"));
}
}
uri
}
/// The system accent colour: the Caelestia shell's wallpaper scheme, else KDE's kdeglobals, else GNOME's
/// accent-color setting.
pub fn system_accent() -> Option<Color32> {
@ -466,7 +493,7 @@ pub const SLOW: Spring = Spring { stiffness: 300.0, damping: 0.74 };
pub const EFFECT: Spring = Spring { stiffness: 900.0, damping: 1.0 };
/// Motion setting as a time factor: 1 = Normal, 0 = Off.
fn motion_scale(settings: &Settings) -> f32 {
pub fn motion_scale(settings: &Settings) -> f32 {
match settings.ui.motion {
Motion::Off => 0.0,
Motion::Fast => 0.6,
@ -693,6 +720,10 @@ mod tests {
assert_eq!(parse_css_color("rgb(10, 20, 30)"), Some(Color32::from_rgb(10, 20, 30)));
assert_eq!(parse_css_color("rgba(0, 0, 0, 0)"), None);
assert_eq!(to_hex(Color32::from_rgb(200, 100, 50)), "#C86432");
let badge = zap_badge(Color32::from_rgb(200, 100, 50), Color32::WHITE);
assert!(badge.starts_with("data:image/svg+xml,%3Csvg"));
assert!(badge.contains("%23C86432") && badge.contains("%23FFFFFF"));
assert!(!badge.contains(['"', '\'', '#', '<', ' ']));
}
fn hex(c: Color32) -> String {

View file

@ -0,0 +1,35 @@
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>Zap</title>
<style>
body { font: 16px system-ui, sans-serif; margin: 24px; background: #fafafa; color: #222; }
.zap-ad { background: repeating-linear-gradient(45deg, #f4c542 0 12px, #e0a800 12px 24px); color: #000;
font-weight: 700; display: flex; align-items: center; justify-content: center; margin: 12px 0; }
.row { display: flex; gap: 12px; }
.row .zap-ad { width: 260px; height: 140px; }
#ad-wide { height: 110px; }
#ad-tiny { width: 10px; height: 10px; }
.video-js { position: relative; width: 320px; height: 180px; background: #111; }
.video-js video { width: 100%; height: 100%; }
.video-js .zap-ad { position: absolute; left: 8px; bottom: 8px; width: 140px; height: 40px; margin: 0; }
#spacer { height: 3000px; }
</style></head>
<body>
<h1>Ad removal test</h1>
<p id="p1">Text above the ads.</p>
<div class="zap-ad" id="ad-wide">AD wide</div>
<div class="row"><div class="zap-ad" id="ad-left">AD left</div><div class="zap-ad" id="ad-right">AD right</div></div>
<p id="p2">Text below the ads: it moves up when their slots close.</p>
<div class="zap-ad" id="ad-tiny"></div>
<div class="video-js" id="player"><video id="vid" muted></video><div class="zap-ad" id="ad-in-player">AD in player</div></div>
<div class="zap-ad" id="ad-with-video" style="width:200px;height:100px"><video muted style="width:100px;height:60px"></video></div>
<div id="spacer"></div>
<div class="zap-ad" id="ad-offscreen" style="height:120px">AD off-screen</div>
<script>
// What the test reads: where p2 started, whether an overlay ever showed.
window.p2Top = document.getElementById('p2').getBoundingClientRect().top;
window.ovSeen = false;
new MutationObserver(() => { if (document.querySelector('.__nz_ov')) window.ovSeen = true; })
.observe(document.documentElement, { childList: true, subtree: true });
window.shown = id => getComputedStyle(document.getElementById(id)).display !== 'none';
</script>
</body></html>

50
tests/smoke/zap.txt Normal file
View file

@ -0,0 +1,50 @@
# Ad removal animation (S058, port of the original Nacre's zapper): visible ads matching a cosmetic rule get the
# cookie shield overlay, squish away, and their slots close up; an ad inside a player and the box holding a <video>
# are left to the player; tiny and off-screen ads are hidden without animation; Motion off = plain hide, no overlay.
# Dark and light. Offline (own rules only, no lists). Never Tor or proxies.
# SMOKE_SIZE=1280x900 tools/smoke.sh tests/smoke/zap.txt
wait 3
set /adblock/update_days 0
set /adblock/lists []
set /adblock/own_rules "##.zap-ad"
set /theme/mode "dark"
set /ui/motion "slow"
wait 5
status rules
expect /adblock/ready true
open @PAGES@/ads.html
waitfor 20 document.title === "Zap"
waitfor 10 document.querySelector(".__nz_ov") !== null
shot zap-mid-dark
assert document.querySelectorAll(".__nz_ov").length === 3
waitfor 10 !shown("ad-wide") && !shown("ad-left") && !shown("ad-right")
wait 1
shot zap-after-dark
assert document.querySelectorAll(".__nz_ov").length === 0
assert !shown("ad-tiny") && !shown("ad-offscreen") && !shown("ad-in-player")
assert shown("player") && shown("ad-with-video") && document.getElementById("vid").isConnected
assert document.getElementById("p2").getBoundingClientRect().top < window.p2Top - 300
status dark
expect /active/hidden_elements 6
# Light theme: the overlay follows the theme's colours.
set /theme/mode "light"
wait 2
cmd reload
waitfor 20 document.title === "Zap"
waitfor 10 document.querySelector(".__nz_ov") !== null
shot zap-mid-light
waitfor 10 !shown("ad-wide")
wait 1
shot zap-after-light
# Motion off: hidden at once, no overlay ever.
set /ui/motion "off"
wait 2
cmd reload
waitfor 20 document.title === "Zap"
waitfor 10 !shown("ad-wide") && !shown("ad-left") && !shown("ad-right") && !shown("ad-in-player")
wait 2
shot zap-off
assert window.ovSeen === false
assert shown("player") && shown("ad-with-video")
status off
expect /active/hidden_elements > 4