A platform for community discussion. Free, open, simple.
FIX: Resolve intersection roots that a selector cannot reach (#42378)
Sérgio Saquetim5a7baf839d0f
diff --git a/frontend/discourse/app/ui-kit/d-load-more.gjs b/frontend/discourse/app/ui-kit/d-load-more.gjsindex f47f1027acb..8106d1063c6 100644--- a/frontend/discourse/app/ui-kit/d-load-more.gjs+++ b/frontend/discourse/app/ui-kit/d-load-more.gjs@@ -32,7 +32,9 @@ export function enableLoadMoreObserver() {* during initial content load. Pass this to avoid race conditions during page initialization.* @param {string} [rootMargin="0px 0px 0px 0px"] - Margin around the root element for intersection detection* @param {number} [threshold=0.0] - Threshold at which the intersection callback is triggered- * @param {string} [root=null] - CSS selector for the root element to observe intersection within+ * @param {string|Element} [root=null] - The element to observe intersection within, or a CSS+ * selector for it. Pass the element itself when it mounts in the same render as the+ * sentinel, since a selector cannot resolve a root that does not exist yet.** @example Basic usage with a block:* ```gjs@@ -76,9 +78,21 @@ export function enableLoadMoreObserver() {*/export default class DLoadMore extends Component {observer;- root = this.args.root || null;- rootMargin = this.args.rootMargin || "0px 0px 0px 0px";- threshold = this.args.threshold || 0.0;++ // Getters, not fields: a field snapshots the argument at construction, so an `@root` that+ // is captured after this component mounts (its container and the sentinel rendering in the+ // same pass) would never reach the observer, silently leaving it rooted at the wrong node.+ get root() {+ return this.args.root || null;+ }++ get rootMargin() {+ return this.args.rootMargin || "0px 0px 0px 0px";+ }++ get threshold() {+ return this.args.threshold || 0.0;+ }get enabled() {return this.args.enabled ?? true;diff --git a/frontend/discourse/app/ui-kit/modifiers/d-observe-intersection.js b/frontend/discourse/app/ui-kit/modifiers/d-observe-intersection.jsindex 6dffa31230c..e743d10c758 100644--- a/frontend/discourse/app/ui-kit/modifiers/d-observe-intersection.js+++ b/frontend/discourse/app/ui-kit/modifiers/d-observe-intersection.js@@ -21,7 +21,14 @@ export default modifier(.join(" ");}- const rootElement = root ? document.querySelector(root) : document;+ // A selector is resolved against the live document, so it only works once the root is+ // already mounted. An element can be handed over directly, which is the only race-free+ // option when the root and the observed node mount in the same render.+ let rootElement = document;+ if (root) {+ rootElement =+ typeof root === "string" ? document.querySelector(root) : root;+ }const observer = new IntersectionObserver((entries) => {diff --git a/frontend/discourse/tests/helpers/stub-intersection-observer.js b/frontend/discourse/tests/helpers/stub-intersection-observer.jsindex 0c763fd8744..f2121e848ff 100644--- a/frontend/discourse/tests/helpers/stub-intersection-observer.js+++ b/frontend/discourse/tests/helpers/stub-intersection-observer.js@@ -6,8 +6,9 @@ import sinon from "sinon";* The real one needs viewport scroll state, which the Ember testing container* can't reliably provide.*- * @returns {Array<{element, trigger: (overrides?: object) => Promise<void>}>}- * Entries appended on each `observe()`.+ * @returns {Array<{element, options, trigger: (overrides?: object) => Promise<void>}>}+ * Entries appended on each `observe()`. `options` is the bag the observer was constructed+ * with, so a test can assert how a consumer resolved `root` and `rootMargin`.* `await entry.trigger()` fires an intersection event.*/export default function stubIntersectionObserver() {@@ -15,13 +16,15 @@ export default function stubIntersectionObserver() {sinon.stub(window, "IntersectionObserver").value(class {- constructor(callback) {+ constructor(callback, options) {this.callback = callback;+ this.options = options;}observe(element) {observations.push({element,+ options: this.options,trigger: async (overrides = {}) => {this.callback([{ target: element, isIntersecting: true, ...overrides },diff --git a/frontend/discourse/tests/integration/ui-kit/d-load-more-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-load-more-test.gjsindex e5451a36c4a..158a2bd54b8 100644--- a/frontend/discourse/tests/integration/ui-kit/d-load-more-test.gjs+++ b/frontend/discourse/tests/integration/ui-kit/d-load-more-test.gjs@@ -1,4 +1,8 @@-import { render } from "@ember/test-helpers";+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import { click, render } from "@ember/test-helpers";import { module, test } from "qunit";import { setupRenderingTest } from "discourse/tests/helpers/component-test";import stubIntersectionObserver from "discourse/tests/helpers/stub-intersection-observer";@@ -88,4 +92,97 @@ module("Integration | ui-kit | DLoadMore", function (hooks) {);assert.strictEqual(actionCalled, 0, "does not call the loadMore action");});++ test("accepts an element as @root", async function (assert) {+ const loadMore = () => {};+ const root = document.createElement("div");++ await render(+ <template>+ <DLoadMore @action={{loadMore}} @root={{root}}>+ <div class="rows"></div>+ </DLoadMore>+ </template>+ );++ assert.strictEqual(+ this.observations[0].options.root,+ root,+ "observes within the element it was handed, rather than treating it as a selector"+ );+ });++ test("a @root captured after mount reaches the observer", async function (assert) {+ const loadMore = () => {};++ await render(+ class extends Component {+ @tracked root = null;++ @action+ attach() {+ this.root = document.querySelector(".scroll-container");+ }++ <template>+ <div class="scroll-container">+ <button {{on "click" this.attach}}>Attach</button>+ <DLoadMore @action={{loadMore}} @root={{this.root}}>+ <div class="rows"></div>+ </DLoadMore>+ </div>+ </template>+ }+ );++ assert.strictEqual(+ this.observations[0].options.root,+ document,+ "starts rooted at the document while no root is available"+ );++ await click("button");++ assert.strictEqual(+ this.observations.at(-1).options.root,+ document.querySelector(".scroll-container"),+ "re-observes within the root it was handed after mounting, rather than the null captured at construction"+ );+ });++ test("a changed @rootMargin reaches the observer", async function (assert) {+ const loadMore = () => {};++ await render(+ class extends Component {+ @tracked rootMargin = "10px";++ @action+ widen() {+ this.rootMargin = "500px";+ }++ <template>+ <button {{on "click" this.widen}}>Widen</button>+ <DLoadMore @action={{loadMore}} @rootMargin={{this.rootMargin}}>+ <div class="rows"></div>+ </DLoadMore>+ </template>+ }+ );++ assert.strictEqual(+ this.observations[0].options.rootMargin,+ "10px",+ "starts with the initial margin"+ );++ await click("button");++ assert.strictEqual(+ this.observations.at(-1).options.rootMargin,+ "500px",+ "re-observes with the updated margin instead of the one captured at construction"+ );+ });});diff --git a/frontend/discourse/tests/integration/ui-kit/modifiers/d-observe-intersection-test.gjs b/frontend/discourse/tests/integration/ui-kit/modifiers/d-observe-intersection-test.gjsnew file mode 100644index 00000000000..06f905b61c3--- /dev/null+++ b/frontend/discourse/tests/integration/ui-kit/modifiers/d-observe-intersection-test.gjs@@ -0,0 +1,104 @@+import { render } from "@ember/test-helpers";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import stubIntersectionObserver from "discourse/tests/helpers/stub-intersection-observer";+import dObserveIntersection from "discourse/ui-kit/modifiers/d-observe-intersection";++module(+ "Integration | ui-kit | Modifier | dObserveIntersection",+ function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.observations = stubIntersectionObserver();+ });++ test("observes against the document when no root is given", async function (assert) {+ const callback = () => {};++ await render(+ <template>+ <div class="observed" {{dObserveIntersection callback}}></div>+ </template>+ );++ assert.strictEqual(this.observations[0].options.root, document);+ });++ test("accepts an element as the root", async function (assert) {+ const callback = () => {};+ const root = document.createElement("div");++ await render(+ <template>+ <div+ class="observed"+ {{dObserveIntersection callback root=root}}+ ></div>+ </template>+ );++ assert.strictEqual(+ this.observations[0].options.root,+ root,+ "hands the element straight to the observer"+ );+ });++ test("resolves a selector against the document", async function (assert) {+ const callback = () => {};++ await render(+ <template>+ <div class="scroll-root">+ <div+ class="observed"+ {{dObserveIntersection callback root=".scroll-root"}}+ ></div>+ </div>+ </template>+ );++ assert.strictEqual(+ this.observations[0].options.root,+ document.querySelector(".scroll-root"),+ "an already-mounted root resolves by the time the modifier installs"+ );+ });++ test("falls back to the document for an empty selector", async function (assert) {+ const callback = () => {};++ await render(+ <template>+ <div class="observed" {{dObserveIntersection callback root=""}}></div>+ </template>+ );++ assert.strictEqual(+ this.observations[0].options.root,+ document,+ "an empty selector is not passed to querySelector, which rejects it"+ );+ });++ test("an unmatched selector leaves the observer rooted at the viewport", async function (assert) {+ const callback = () => {};++ await render(+ <template>+ <div+ class="observed"+ {{dObserveIntersection callback root=".not-mounted"}}+ ></div>+ </template>+ );++ assert.strictEqual(+ this.observations[0].options.root,+ null,+ "a root that cannot be resolved degrades silently rather than throwing"+ );+ });+ }+);