diff --git a/.github/workflows/ad-remover-check.yml b/.github/workflows/ad-remover-check.yml
new file mode 100644
index 00000000..ffcfd7ee
--- /dev/null
+++ b/.github/workflows/ad-remover-check.yml
@@ -0,0 +1,154 @@
+name: Ad remover check
+
+# The published "JTech Ad Remover" Chrome extension
+# (github.com/the-curious-2025/jtech-ad-remover) against the ad space, every
+# day, at its latest commit: spec/system/ads_remover_spec.rb runs their
+# files the way Chrome would and checks the ad still shows, with core's
+# theme and the JTech theme. Red means a new version of theirs gets past
+# the fallback (assets/.../above-main-container/jt-lines-fallback.gts);
+# a scheduled run then opens an issue saying which of their commits did it.
+on:
+ schedule:
+ - cron: "17 6 * * *"
+ workflow_dispatch:
+ pull_request:
+ paths:
+ - "assets/javascripts/discourse/connectors/above-main-container/jt-lines-fallback.gts"
+ - "assets/javascripts/discourse/components/jt-line.gts"
+ - "assets/javascripts/discourse/services/jt-lines.ts"
+ - "assets/stylesheets/lines.scss"
+ - "themes/jtech/javascripts/discourse/components/jt-hero.gts"
+ - "spec/system/ads_remover_spec.rb"
+ - ".github/workflows/ad-remover-check.yml"
+
+permissions:
+ contents: read
+ issues: write
+
+jobs:
+ check:
+ name: ad_remover
+ runs-on: jtechtools-ci
+ container: discourse/discourse_test:slim-browsers
+ timeout-minutes: 30
+
+ env:
+ RUBY_GLOBAL_METHOD_CACHE_SIZE: 131072
+ RAILS_ENV: test
+ PGUSER: discourse
+ PGPASSWORD: discourse
+ # lowercase: see feature-screenshots.yml
+ PLUGIN_NAME: jtech-tools
+ CHEAP_SOURCE_MAPS: "1"
+ USES_PARALLEL_DATABASES: "false"
+ PARALLEL_TEST_PROCESSORS: 1
+ LOAD_PLUGINS: 1
+ CAPYBARA_DEFAULT_MAX_WAIT_TIME: 10
+ JTECH_THEME_SPECS: "1"
+
+ steps:
+ - name: Set working directory owner
+ run: chown root:root .
+
+ - name: Checkout Discourse
+ uses: actions/checkout@v7
+ with:
+ repository: discourse/discourse
+ fetch-depth: 1
+ ref: latest
+
+ - name: Install plugin
+ uses: actions/checkout@v7
+ with:
+ path: plugins/${{ env.PLUGIN_NAME }}
+ fetch-depth: 1
+
+ - name: Fetch the ad remover
+ id: remover
+ run: |
+ git clone --depth 1 https://github.com/the-curious-2025/jtech-ad-remover.git ad-remover
+ sha=$(git -C ad-remover rev-parse --short HEAD)
+ version=$(ruby -rjson -e 'puts JSON.parse(File.read("ad-remover/manifest.json"))["version"]')
+ echo "JTECH_AD_REMOVER_DIR=$PWD/ad-remover" >> $GITHUB_ENV
+ echo "sha=$sha" >> $GITHUB_OUTPUT
+ echo "version=$version" >> $GITHUB_OUTPUT
+ echo "Ad remover $version at $sha" >> $GITHUB_STEP_SUMMARY
+
+ - name: Setup Git
+ run: |
+ git config --global user.email "ci@ci.invalid"
+ git config --global user.name "Discourse CI"
+
+ - name: Start redis
+ run: redis-server /etc/redis/redis.conf &
+
+ - name: Start Postgres
+ run: |
+ chown -R postgres /var/run/postgresql
+ sudo -E -u postgres script/start_test_db.rb
+ sudo -u postgres psql -c "CREATE ROLE $PGUSER LOGIN SUPERUSER PASSWORD '$PGPASSWORD';"
+
+ - name: Container envs
+ id: container-envs
+ run: |
+ echo "ruby_version=$RUBY_VERSION" >> $GITHUB_OUTPUT
+ echo "debian_release=$DEBIAN_RELEASE" >> $GITHUB_OUTPUT
+
+ - name: Bundler cache
+ uses: actions/cache@v6
+ with:
+ path: vendor/bundle
+ key: ${{ runner.os }}-${{ steps.container-envs.outputs.ruby_version }}-${{ steps.container-envs.outputs.debian_release }}-gem-${{ hashFiles('**/Gemfile.lock') }}
+ restore-keys: |
+ ${{ runner.os }}-${{ steps.container-envs.outputs.ruby_version }}-${{ steps.container-envs.outputs.debian_release }}-gem-
+
+ - name: Setup gems
+ run: |
+ bundle config --local path vendor/bundle
+ bundle config --local deployment true
+ bundle config --local without development
+ bundle install --jobs 4
+ bundle clean
+
+ - name: Install JS Dependencies
+ run: if [ -f yarn.lock ]; then yarn install --frozen-lockfile; else pnpm install --frozen-lockfile; fi
+
+ - name: Install playwright
+ run: |
+ if pnpm playwright -V; then
+ pnpm playwright install --with-deps --no-shell chromium
+ fi
+
+ - name: Create and migrate database
+ run: |
+ bin/rake db:create
+ bin/rake db:migrate
+
+ - name: Ember Build
+ env:
+ EMBER_ENV: development
+ run: |
+ export DISCOURSE_DOWNLOAD_PRE_BUILT_ASSETS=$(bin/rails runner 'puts(Discourse.has_needed_version?(Discourse::VERSION::STRING, "2026.3.0-latest") ? 1 : 0)')
+ script/assemble_ember_build.rb
+
+ - name: Run the ad remover against the ads
+ run: bundle exec rspec --format documentation plugins/${{ env.PLUGIN_NAME }}/spec/system/ads_remover_spec.rb
+
+ - name: Open an issue when it gets past the ads
+ if: failure() && github.event_name == 'schedule'
+ env:
+ GH_TOKEN: ${{ github.token }}
+ GH_REPO: ${{ github.repository }}
+ run: |
+ title="Ad remover ${{ steps.remover.outputs.version }} gets past the ads"
+ if ! gh issue list --state open --search "in:title \"$title\"" --json number --jq '.[].number' | grep -q .; then
+ gh issue create --title "$title" --body "The ad remover at the-curious-2025/jtech-ad-remover@${{ steps.remover.outputs.sha }} hides the ad: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}. Update jt-lines-fallback.gts until spec/system/ads_remover_spec.rb passes again."
+ fi
+
+ - name: Upload screenshots
+ if: failure()
+ uses: actions/upload-artifact@v7
+ with:
+ name: ad-remover-screenshots
+ path: tmp/capybara/*.png
+ if-no-files-found: ignore
diff --git a/assets/javascripts/discourse/connectors/above-main-container/jt-lines-fallback.gts b/assets/javascripts/discourse/connectors/above-main-container/jt-lines-fallback.gts
index fdba6818..15296905 100644
--- a/assets/javascripts/discourse/connectors/above-main-container/jt-lines-fallback.gts
+++ b/assets/javascripts/discourse/connectors/above-main-container/jt-lines-fallback.gts
@@ -1,118 +1,168 @@
import Component from "@glimmer/component";
+import type Owner from "@ember/owner";
import type RouterService from "@ember/routing/router-service";
import { service } from "@ember/service";
import { modifier } from "ember-modifier";
-import { i18n } from "discourse-i18n";
+import JtLine from "../../components/jt-line.gts";
import { onWelcomeRoute } from "../../lib/jt-lines-route.ts";
-import type {
- default as JtLinesService,
- JtLine,
-} from "../../services/jt-lines.ts";
+import type JtLinesService from "../../services/jt-lines.ts";
-// Only when the welcome area's line was hidden by a rule of the browser's
-// (a blocker): the line again, at the top of the page, inside a closed
-// shadow root, which page-level hiding rules can't reach into. Styled with
-// the theme's own colour variables, which do reach in. One fallback, no
-// nagging: if this is hidden too, nothing more happens.
+// Only when the welcome area's ad was hidden by something in the browser
+// (a blocker or an extension): the same card again, at the top of the page,
+// inside a closed shadow root. Everything a hiding rule or script keys on
+// is kept out of the page: no fixed class, id or data attribute on what's
+// outside the root, and nothing of the card is in the page itself. If a
+// script still sets it hidden, that's undone. One fallback, no nagging.
+//
+// .github/workflows/ad-remover-check.yml runs the published remover
+// extension against this every day (spec/system/ads_remover_spec.rb).
export default class JtLinesFallback extends Component {
@service("jt-lines") declare lines: JtLinesService;
@service declare router: RouterService;
- mount = modifier((host: HTMLElement, [line]: [JtLine]) => {
- // closed roots can't be looked up again, so the element keeps its own
- let root = ROOTS.get(host);
- if (!root) {
- root = host.attachShadow({ mode: "closed" });
- root.innerHTML = `
`;
- ROOTS.set(host, root);
- }
- const box = root.querySelector(".box")!;
- box.innerHTML = `${line.h}
${
- line.t ? `${line.t}
` : ""
- }`;
- box.querySelector(".tag")!.textContent = this.lines.label;
- if (this.lines.canVoteOn(line)) {
- const row = document.createElement("div");
- row.className = "row";
- const status = document.createElement("span");
- status.setAttribute("role", "status");
- row.append(status);
- for (const [value, key] of [
- [1, "jt_lines.up"],
- [-1, "jt_lines.down"],
- ] as const) {
- const button = document.createElement("button");
- button.type = "button";
- button.textContent = value > 0 ? "▲" : "▼";
- button.title = i18n(key);
- button.dataset.vote = String(value);
- button.setAttribute("aria-label", i18n(key));
- button.addEventListener("click", () => this.lines.setVote(line, value));
- row.append(button);
- }
- box.append(row);
- }
- return () => (box.innerHTML = "");
- });
+ // A fresh class every page load, so no page rule can name it
+ hostClass = `c${Math.random().toString(36).slice(2, 9)}`;
+ host = document.createElement("div");
+ inner = document.createElement("div");
- updateFeedback = modifier((host: HTMLElement, [line]: [JtLine]) => {
- const row = ROOTS.get(host)?.querySelector(".row");
- if (row) {
- const vote = this.lines.vote(line);
- const pending = this.lines.isVotePending(line);
- row.querySelector('[role="status"]')!.textContent =
- this.lines.voteFeedback(line);
- for (const button of row.querySelectorAll("button")) {
- button.setAttribute(
- "aria-pressed",
- String(vote === Number(button.dataset.vote))
- );
- button.setAttribute("aria-disabled", String(pending));
- }
- }
+ place = modifier((slot: HTMLElement) => {
+ slot.append(this.host);
+ const heal = new MutationObserver(() => this.#heal(slot));
+ heal.observe(slot, { attributes: true });
+ heal.observe(this.host, { attributes: true });
+ this.#heal(slot);
+
+ // the thumbs' icons point into the page's sprite, which a shadow root
+ // can't see: the root carries its own copies
+ const icons = new MutationObserver(() => this.#icons());
+ icons.observe(this.inner, { childList: true, subtree: true });
+ this.#icons();
+
+ const stops = [this.lines.rotate(this.inner)];
+ return () => {
+ heal.disconnect();
+ icons.disconnect();
+ stops.forEach((stop) => stop());
+ this.host.remove();
+ };
});
- get line(): JtLine | null {
+ #root: ShadowRoot;
+ #sprite = document.createElementNS("http://www.w3.org/2000/svg", "svg");
+
+ constructor(owner: Owner, args: object) {
+ super(owner, args);
+ this.host.className = this.hostClass;
+ this.#root = this.host.attachShadow({ mode: "closed" });
+ this.#root.adoptedStyleSheets = [sheet()];
+ this.#sprite.setAttribute("hidden", "");
+ this.inner.className = "jt-lines";
+ this.#root.append(this.#sprite, this.inner);
+ }
+
+ get shown() {
if (!this.lines.hidden || !onWelcomeRoute(this.router, false)) {
return null;
}
- return this.lines.line;
+ return this.lines.line ? this.lines.shown : null;
+ }
+
+ // Put back what a hiding script changes: its inline style, its marks
+ #heal(slot: HTMLElement) {
+ for (const element of [slot, this.host]) {
+ const style = element.style;
+ if (
+ style.display ||
+ style.visibility ||
+ style.opacity ||
+ style.height ||
+ style.position
+ ) {
+ element.removeAttribute("style");
+ }
+ if (element.hidden) {
+ element.hidden = false;
+ }
+ for (const attribute of Array.from(element.attributes)) {
+ if (attribute.name !== "class") {
+ element.removeAttribute(attribute.name);
+ }
+ }
+ }
+ if (slot.className !== this.hostClass) {
+ slot.className = this.hostClass;
+ }
+ if (this.host.className !== this.hostClass) {
+ this.host.className = this.hostClass;
+ }
+ }
+
+ #icons() {
+ for (const use of this.inner.querySelectorAll("use")) {
+ const id = (use.getAttribute("href") ?? "").replace(/^#/, "");
+ if (id && !this.#sprite.querySelector(`[id="${CSS.escape(id)}"]`)) {
+ const symbol = document.getElementById(id);
+ if (symbol) {
+ this.#sprite.append(symbol.cloneNode(true));
+ }
+ }
+ }
}
- {{#if this.line}}
-
+ {{#if this.shown}}
+
+ {{#in-element this.inner insertBefore=null}}
+ {{#each this.shown key="line.k" as |item|}}
+
+ {{/each}}
+ {{/in-element}}
{{/if}}
}
-const ROOTS = new WeakMap();
+// The card's own rules (lines.scss) and the bits of core's it uses (the
+// thumbs' buttons and icons), copied once from the forum's own stylesheets
+// into a sheet the root adopts. Only sheets the forum serves: never a rule
+// something else put in the page.
+let copied: CSSStyleSheet | null = null;
+function sheet(): CSSStyleSheet {
+ if (copied) {
+ return copied;
+ }
+ const wanted = /\.jt-lines|\.jl-|@keyframes jl-|\.btn-flat|\.d-icon/;
+ const rules: string[] = [
+ ":host { display: block; margin: 0 0 1em; }",
+ ".jt-lines { box-sizing: border-box; }",
+ ];
+ for (const styleSheet of Array.from(document.styleSheets)) {
+ if (!ours(styleSheet)) {
+ continue;
+ }
+ let list: CSSRuleList;
+ try {
+ list = styleSheet.cssRules;
+ } catch {
+ continue;
+ }
+ for (const rule of Array.from(list)) {
+ if (wanted.test(rule.cssText)) {
+ rules.push(rule.cssText);
+ }
+ }
+ }
+ copied = new CSSStyleSheet();
+ copied.replaceSync(rules.join("\n"));
+ return copied;
+}
-// Line headlines and text are already cleaned to inline tags on the server
-const STYLE = `
- :host { display: block; margin: 0 0 1em; }
- .box {
- display: flex; flex-wrap: wrap; align-items: baseline; gap: .25em .75em;
- padding: .75em 1em; border: 1px solid var(--primary-low, #ddd);
- border-radius: var(--d-border-radius, 6px);
- background: var(--secondary, #fff); color: var(--primary, #222);
- font: inherit;
+function ours(styleSheet: CSSStyleSheet): boolean {
+ if (!styleSheet.href) {
+ return false;
}
- .tag { font-size: .75em; font-weight: 600; color: var(--primary-medium, #888); }
- .head { margin: 0; font-weight: 600; }
- .text { margin: 0; flex-basis: 100%; color: var(--primary-high, #444); }
- a { color: var(--tertiary, #08c); }
- .row { margin-left: auto; display: flex; align-items: center; gap: .25em; }
- [role="status"] { font-size: .875em; }
- button {
- border: 0; background: none; color: var(--primary-medium, #888);
- cursor: pointer; padding: .25em .4em; border-radius: 4px;
+ try {
+ return new URL(styleSheet.href).pathname.includes("/stylesheets/");
+ } catch {
+ return false;
}
- button:hover { background: var(--primary-very-low, #f3f3f3); }
- button[aria-pressed="true"] { background: var(--tertiary); color: var(--secondary); }
- button[aria-disabled="true"] { cursor: wait; }
-`;
+}
diff --git a/docs/features/ads.md b/docs/features/ads.md
index 214cad46..42693be4 100644
--- a/docs/features/ads.md
+++ b/docs/features/ads.md
@@ -149,7 +149,8 @@ Ad blockers hide elements and block requests by name: anything called ad, ads, a
- **No request of its own.** The ads come inside the page's preloaded site data (`site.jt_lines`), filtered for the person on the server. The thumbs go to `/jtech-lines/:key`.
- **Neutral names** for classes (`jt-lines`, `jl-*`, `jt-hero__lines`), the service and the data (`h`, `t`, `c`).
- **In the JTech theme the ad is the hero**, so a rule that hides it hides the welcome with it.
-- **One fallback.** About a second and a half after the page settles, the space checks it's actually showing. If something hid it, the ad (its headline and text) moves once to the top of the page, inside a closed shadow root, which page-level hiding rules can't reach into. No nagging, no wall, no second attempt.
+- **One fallback.** About a second and a half after the page settles, the space checks it's actually showing. If something hid it, the same card moves once to the top of the page, inside a closed shadow root (`jt-lines-fallback.gts`). Nothing outside that root can be named by a rule: its class is new on every page load, it has no id or data attribute, and the card's label, thumbs and text are only inside the root. If a script sets it hidden anyway (an inline style, a mark), that's undone. No nagging, no wall, no second attempt.
+- **Checked against the remover extension every day.** Someone published a Chrome extension aimed at this forum's ads ([the-curious-2025/jtech-ad-remover](https://github.com/the-curious-2025/jtech-ad-remover)). `.github/workflows/ad-remover-check.yml` fetches its latest commit daily and `spec/system/ads_remover_spec.rb` runs its files the way Chrome would, with core's theme and the JTech theme. When a new version gets past the fallback, the run fails and opens an issue naming their commit; change the fallback until the spec passes again.
Checked against EasyList, uBlock's own filters and Fanboy's annoyances list: nothing matches. A filter written for this forum specifically can still hide it, and since this code is public, someone could write one; that's a limit of any ad on the open web. Keep new names neutral when changing any of this: no `ad`, `ads`, `advert`, `sponsor`, `banner`, `promo` in class names, ids, data attributes, aria labels, file names, connector names, URLs, link targets or JSON keys that reach the browser. The word "Ad" as visible text is fine and stays: people should know.
diff --git a/spec/system/ads_remover_spec.rb b/spec/system/ads_remover_spec.rb
new file mode 100644
index 00000000..9a083a99
--- /dev/null
+++ b/spec/system/ads_remover_spec.rb
@@ -0,0 +1,142 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+# The published "JTech Ad Remover" Chrome extension against the ad space:
+# the ad still shows. Runs their files as they are, from a checkout of
+# their repository (JTECH_AD_REMOVER_DIR), the way Chrome would: the
+# stylesheet in the page from the start, page-hook.js in the page's world
+# and content.js with chrome.dom.openOrClosedShadowRoot, which can see into
+# closed shadow roots. .github/workflows/ad-remover-check.yml fetches their
+# latest every day; when this fails, they've found a way around the
+# fallback (jt-lines-fallback.gts), and it's our turn.
+RSpec.describe "Ads against the ad remover extension", if: ENV["JTECH_AD_REMOVER_DIR"].present? do
+ fab!(:member) { Fabricate(:user, trust_level: TrustLevel[1]) }
+ fab!(:topic)
+ fab!(:post) { Fabricate(:post, topic: topic) }
+
+ let(:dir) { Pathname.new(ENV["JTECH_AD_REMOVER_DIR"]) }
+ let(:manifest) { JSON.parse(dir.join("manifest.json").read) }
+
+ before do
+ SiteSetting.jtech_enabled = true
+ SiteSetting.jtech_ads_enabled = true
+ SiteSetting.jtech_ads_welcome_seconds = 0
+ SiteSetting.jtech_ads_list = [
+ {
+ name: "spring",
+ enabled: true,
+ headline: "Spring sale",
+ card: %(Spring sale
),
+ audience: "everyone",
+ },
+ ].to_json
+ install_extension
+ end
+
+ # Their content scripts, in manifest order, at document start
+ def install_extension
+ scripts = manifest["content_scripts"]
+ css = scripts.flat_map { it["css"] || [] }.map { dir.join(it).read }.join("\n")
+ # document_start in Chrome: once the root element exists, before any
+ # of the page's own scripts
+ js = scripts.flat_map { it["js"] || [] }.map { |file| <<~JS }
+ (function run() {
+ if (!document.documentElement) {
+ new MutationObserver((_, observer) => {
+ if (document.documentElement) { observer.disconnect(); run(); }
+ }).observe(document, { childList: true });
+ return;
+ }
+ #{dir.join(file).read}
+ })();
+ JS
+
+ # chrome.dom.openOrClosedShadowRoot: an extension can open closed roots;
+ # here every root attached is remembered for it. The extension's own
+ # stylesheet isn't one of the page's sheets, as in Chrome.
+ shim = <<~JS
+ (() => {
+ const roots = new WeakMap();
+ const attach = Element.prototype.attachShadow;
+ Element.prototype.attachShadow = function (init) {
+ const root = attach.call(this, init);
+ roots.set(this, root);
+ return root;
+ };
+ window.chrome = window.chrome || {};
+ window.chrome.dom = { openOrClosedShadowRoot: (el) => el.shadowRoot || roots.get(el) || null };
+ window.__jtRoots = roots;
+ const sheet = new CSSStyleSheet();
+ sheet.replaceSync(#{css.to_json});
+ document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];
+ })();
+ JS
+
+ page.driver.with_playwright_page do |pw|
+ ([shim] + js).each { |script| pw.add_init_script(script: script) }
+ end
+ end
+
+ # The ad's headline, wherever it ended up, if a person can see it: in the
+ # page, or in a shadow root, with a box of its own and nothing hiding it
+ def ad_visible?
+ page.evaluate_script(<<~JS)
+ (() => {
+ const seen = (el) => {
+ for (let node = el; node; node = node.parentNode || node.host) {
+ if (node.nodeType !== 1) continue;
+ const s = getComputedStyle(node);
+ if (s.display === "none" || s.visibility === "hidden" || Number(s.opacity) === 0) return false;
+ }
+ const box = el.getBoundingClientRect();
+ return box.width > 0 && box.height > 0;
+ };
+ const found = [...document.querySelectorAll(".jl-title-xl")];
+ for (const el of document.querySelectorAll("*")) {
+ const root = window.__jtRoots.get(el);
+ if (root) found.push(...root.querySelectorAll(".jl-title-xl"));
+ }
+ return found.some((el) => el.textContent.includes("Spring sale") && seen(el));
+ })()
+ JS
+ end
+
+ shared_examples "the ad shows" do
+ it "for a visitor" do
+ visit "/latest"
+ expect(page).to have_css("#main-outlet .topic-list")
+ try_until_success(timeout: 8) { expect(ad_visible?).to eq(true) }
+ end
+
+ it "for a member, who can still vote" do
+ sign_in(member)
+ visit "/latest"
+ expect(page).to have_css("#main-outlet .topic-list")
+ try_until_success(timeout: 8) { expect(ad_visible?).to eq(true) }
+ end
+
+ it "after moving around the forum" do
+ visit topic.relative_url
+ expect(page).to have_css("#post_1")
+ find("#site-logo, .title a", match: :first).click
+ expect(page).to have_css("#main-outlet .topic-list")
+ try_until_success(timeout: 8) { expect(ad_visible?).to eq(true) }
+ end
+ end
+
+ context "with core's theme" do
+ include_examples "the ad shows"
+ end
+
+ context "with the JTech theme", if: ENV["JTECH_THEME_SPECS"].present? do
+ fab!(:jtech_theme) do
+ DiscourseJtechTheme::Installer.sync_now
+ DiscourseJtechTheme::Installer.theme
+ end
+
+ before { jtech_theme.set_default! }
+
+ include_examples "the ad shows"
+ end
+end
diff --git a/spec/system/ads_spec.rb b/spec/system/ads_spec.rb
index 7ab90a0a..812b9393 100644
--- a/spec/system/ads_spec.rb
+++ b/spec/system/ads_spec.rb
@@ -114,16 +114,64 @@
expect(page).to have_no_text("Draft card")
end
- # A blocker's element rule, applied as soon as the page is up: the space
- # checks itself after a second and a half, and moves the ad
- it "moves the ad to the fallback when the space is hidden" do
- visit "/latest"
+ # The fallback's root is closed; in these specs every root is opened, so
+ # they can look inside
+ def open_shadow_roots
+ page.driver.with_playwright_page { |pw| pw.add_init_script(script: <<~JS) }
+ const attachShadow = Element.prototype.attachShadow;
+ Element.prototype.attachShadow = function (options) {
+ return attachShadow.call(this, { ...options, mode: "open" });
+ };
+ JS
+ end
+
+ def hide_space
page.execute_script(<<~JS)
const style = document.createElement("style");
style.textContent = ".jt-lines { display: none !important }";
document.head.append(style);
JS
- expect(page).to have_css("[data-jt-l]", wait: 5)
+ end
+
+ let(:host) do
+ "[...document.querySelectorAll('#main-outlet div')].find((el) => el.shadowRoot?.querySelector('.jt-lines'))"
+ end
+ let(:fallback) { "#{host}?.shadowRoot" }
+
+ # A blocker's element rule, applied as soon as the page is up: the space
+ # checks itself after a second and a half, and moves the ad
+ it "moves the ad to the fallback when the space is hidden" do
+ open_shadow_roots
+ visit "/latest"
+ hide_space
+ try_until_success(timeout: 5) do
+ expect(page.evaluate_script("#{fallback}?.querySelector('.jl-title-xl')?.textContent")).to eq(
+ "Spring sale",
+ )
+ end
+ end
+
+ # Nothing outside the root a page rule could name, and a script that
+ # hides it is undone
+ it "gives the fallback nothing to be named by, and undoes hiding" do
+ open_shadow_roots
+ visit "/latest"
+ hide_space
+ try_until_success(timeout: 5) { expect(page.evaluate_script("!!#{fallback}")).to eq(true) }
+
+ outside = page.evaluate_script(<<~JS)
+ (() => { const host = #{host}; return [host, host.parentElement].map((el) => [...el.attributes].map((a) => a.name + "=" + a.value)); })()
+ JS
+ outside.each { |attributes| expect(attributes).to match([/\Aclass=c[a-z0-9]+\z/]) }
+
+ page.execute_script("#{host}.style.setProperty('display', 'none', 'important')")
+ page.execute_script("#{host}.parentElement.setAttribute('data-jtab-shadow', '')")
+ try_until_success do
+ expect(page.evaluate_script("getComputedStyle(#{host}).display")).to eq("block")
+ expect(page.evaluate_script("#{host}.parentElement.hasAttribute('data-jtab-shadow')")).to eq(
+ false,
+ )
+ end
end
it "keeps the vote and confirms updates on the fallback card" do
@@ -132,24 +180,15 @@
ad_key: DiscourseJtechAds.key_for("spring"),
value: 1,
)
+ open_shadow_roots
sign_in(member)
visit "/latest"
- page.execute_script(<<~JS)
- const attachShadow = Element.prototype.attachShadow;
- Element.prototype.attachShadow = function (options) {
- return attachShadow.call(this, this.matches("[data-jt-l]") ? { mode: "open" } : options);
- };
- const style = document.createElement("style");
- style.textContent = ".jt-lines { display: none !important }";
- document.head.append(style);
- JS
- expect(page).to have_css("[data-jt-l]", wait: 5)
+ hide_space
+ try_until_success(timeout: 5) { expect(page.evaluate_script("!!#{fallback}")).to eq(true) }
- feedback = "document.querySelector('[data-jt-l]').shadowRoot.querySelector('[role=status]')"
+ feedback = "#{fallback}.querySelector('[role=status]')"
expect(page.evaluate_script("#{feedback}.textContent")).to eq("Liked")
- page.execute_script(<<~JS)
- document.querySelector("[data-jt-l]").shadowRoot.querySelector("[aria-label='Not for me']").click();
- JS
+ page.execute_script("#{fallback}.querySelector(\"[aria-label='Not for me']\").click()")
try_until_success { expect(page.evaluate_script("#{feedback}.textContent")).to eq("Disliked") }
expect(DiscourseJtechAds::Vote.find_by(user: member).value).to eq(-1)
end