A platform for community discussion. Free, open, simple.
UX: Improve post stream scrolling stability and layout control (#37788)
Sérgio Saquetimbb02dc58258a
diff --git a/app/assets/stylesheets/common/base/topic-post.scss b/app/assets/stylesheets/common/base/topic-post.scssindex b85524ebaf8..9e5f81a50d9 100644--- a/app/assets/stylesheets/common/base/topic-post.scss+++ b/app/assets/stylesheets/common/base/topic-post.scss@@ -1004,6 +1004,14 @@ aside.quote {.post-stream--cloaked {min-height: 1px; // ensures that cloaked items have a minimum height to force the intersection observers to work+ overflow-anchor: none; // cloaked posts are empty placeholders with approximate height and must not be used as scroll anchors+}++// these elements appear/disappear dynamically inside the post stream and must+// not be used as scroll anchors by the browser's native scroll anchoring+.post-stream .load-more-sentinel,+.post-stream .post-stream-load-more-accessible {+ overflow-anchor: none;}.quote-button {@@ -2326,6 +2334,7 @@ span.post-count {}.topic-area > .loading-container {+ overflow-anchor: none; // the loading spinner appears/disappears dynamically and must not be used as a scroll anchor// loader needs to be same width as posts// the extra 1px is to account for the left transparent border set to// .topic_post in `keyboard_shortcuts.scss`diff --git a/frontend/discourse/app/components/post-stream.gjs b/frontend/discourse/app/components/post-stream.gjsindex 74c21b3fee1..13d1e8595ec 100644--- a/frontend/discourse/app/components/post-stream.gjs+++ b/frontend/discourse/app/components/post-stream.gjs@@ -10,7 +10,6 @@ import PostFilteredNotice from "discourse/components/post/filtered-notice";import concatClass from "discourse/helpers/concat-class";import lazyHash from "discourse/helpers/lazy-hash";import { bind } from "discourse/lib/decorators";-import offsetCalculator from "discourse/lib/offset-calculator";import { Placeholder } from "discourse/models/post-stream";import PostStreamViewportTracker from "discourse/modifiers/post-stream-viewport-tracker";import { and, not } from "discourse/truth-helpers";@@ -35,6 +34,7 @@ export default class PostStream extends Component {@tracked cloakAbove;@tracked cloakBelow;@tracked keyboardSelection;+ @tracked suppressLoadAbove = false;viewportTracker = new PostStreamViewportTracker();@@ -163,40 +163,56 @@ export default class PostStream extends Component {@actionloadMoreAbove(post) {+ const anchorElement =+ this.viewportTracker.postsOnScreen[post.post_number]?.element;++ // anchorTop is captured by the captureAnchor callback, which is called+ // inside prependMore after the fetch completes (when the loading spinner is+ // visible) but before new posts are inserted into the DOM.+ let anchorTop;+this.args.topVisibleChanged({post,+ captureAnchor: () => {+ anchorTop = anchorElement?.getBoundingClientRect().top;+ // Suppress the load-more sentinel until the scroll compensation completes.+ // Without this, the sentinel could re-appear between loadingAbove=false+ // (spinner removed) and scrollBy (position compensated), triggering+ // another load before the user's viewport is restored.+ if (anchorTop != null) {+ this.suppressLoadAbove = true;+ }+ },refresh: () => {- const refreshedElem =- this.viewportTracker.postsOnScreen[post.post_number]?.element;-- if (!refreshedElem) {+ if (anchorTop == null) {return;}- // The getOffsetTop function calculates the total offset distance of an element from the top of the document.- // Unlike `element.offsetTop` which only returns the offset relative to its nearest positioned ancestor, this- // function recursively accumulates the offsetTop of an element and all of its offset parents(ancestors).- // This ensures the total distance is measured from the very top of the document, accounting for any nested- // elements and their respective offsets.- const getOffsetTop = (element) => {- if (!element) {- return 0;- }- return element.offsetTop + getOffsetTop(element.offsetParent);- };-- window.scrollTo({- top: getOffsetTop(refreshedElem) - offsetCalculator(),- });+ // Chrome and Firefox natively support scroll anchoring (overflow-anchor)+ // which should keep the viewport stable when posts are prepended above.+ // From the major Browsers, currently only Safari won't support it.+ // We compensate manually as a fallback — the code is browser-agnostic+ // because themes or plugins can inadvertently break native anchoring by+ // styling elements in the post-stream, and the shift check ensures this+ // is a no-op when anchoring works correctly.+ const shift = anchorElement.getBoundingClientRect().top - anchorTop;+ if (shift !== 0) {+ window.scrollBy(0, shift);+ }- // This seems weird, but somewhat infrequently a rerender- // will cause the browser to scroll to the top of the document- // in Chrome. This makes sure the scroll works correctly if that- // happens.+ // The primary scrollBy above compensates for newly prepended posts,+ // but `prependMore` also sets `loadingAbove = false` which removes+ // the loading spinner. Since Ember renders that change asynchronously,+ // the spinner is still in the DOM during the primary compensation.+ // Once Ember removes it in the next render pass, the layout shifts+ // again. This afterRender pass catches that secondary shift.schedule("afterRender", () => {- window.scrollTo({- top: getOffsetTop(refreshedElem) - offsetCalculator(),- });+ const renderShift =+ anchorElement.getBoundingClientRect().top - anchorTop;+ if (renderShift !== 0) {+ window.scrollBy(0, renderShift);+ }+ this.suppressLoadAbove = false;});},});@@ -225,10 +241,26 @@ export default class PostStream extends Component {@actionupdateKeyboardSelectedPostNumber({ selectedArticle: element }) {next(() => {+ const postNumber = parseInt(element.dataset.postNumber, 10);this.keyboardSelection = {topicId: this.args.topic.id,- postNumber: parseInt(element.dataset.postNumber, 10),+ postNumber,};++ // When keyboard navigation reaches a boundary post, trigger loading+ // more posts in that direction. Double-loading is prevented by the+ // existing canPrependMore/canAppendMore guards in the model.+ if (+ this.firstAvailablePost?.post_number === postNumber &&+ this.args.postStream.canPrependMore+ ) {+ this.loadMoreAbove(this.firstAvailablePost);+ } else if (+ this.lastAvailablePost?.post_number === postNumber &&+ this.args.postStream.canAppendMore+ ) {+ this.loadMoreBelow(this.lastAvailablePost);+ }});}@@ -263,7 +295,13 @@ export default class PostStream extends Component {}}>- {{#if (and (not @postStream.loadingAbove) @postStream.canPrependMore)}}+ {{#if+ (and+ @postStream.canPrependMore+ (not @postStream.loadingAbove)+ (not this.suppressLoadAbove)+ )+ }}<PostLoadMoreAccessible@action={{fn this.loadMoreAbove this.firstAvailablePost}}@canLoadMore={{@postStream.canPrependMore}}diff --git a/frontend/discourse/app/controllers/application.js b/frontend/discourse/app/controllers/application.jsindex 60dd86dcebd..94b44af739f 100644--- a/frontend/discourse/app/controllers/application.js+++ b/frontend/discourse/app/controllers/application.js@@ -15,6 +15,7 @@ export default class ApplicationController extends Controller {@service footer;// eslint-disable-next-line discourse/no-unused-services@service router; // used in the route template+ @service scrollState;@service sidebarState;@service siteSettings;@@ -65,6 +66,14 @@ export default class ApplicationController extends Controller {this.footer.showFooter = value;}+ get shouldHideScrollableContentAbove() {+ return this.scrollState.shouldHideContentAbove;+ }++ get shouldHideScrollableContentBelow() {+ return this.scrollState.shouldHideContentBelow;+ }+get showPoweredBy() {return this.showFooter && this.siteSettings.enable_powered_by_discourse;}diff --git a/frontend/discourse/app/controllers/topic.js b/frontend/discourse/app/controllers/topic.jsindex 3d9e895a14e..844dc0012d4 100644--- a/frontend/discourse/app/controllers/topic.js+++ b/frontend/discourse/app/controllers/topic.js@@ -78,6 +78,7 @@ export default class TopicController extends Controller {@service modal;@service router;@service screenTrack;+ @service scrollState;@service site;@service siteSettings;@@ -149,6 +150,10 @@ export default class TopicController extends Controller {return this.selectedPostIds.length;}+ get shouldHideScrollableContentAbove() {+ return this.scrollState.shouldHideContentAbove;+ }+get titleIsVisibleOnHeader() {return !this.header.mainTopicTitleVisible;}@@ -626,7 +631,7 @@ export default class TopicController extends Controller {// Called when the topmost visible post on the page changes.@actionasync topVisibleChanged(event) {- const { post, refresh } = event;+ const { post, captureAnchor, refresh } = event;if (!post) {return;}@@ -639,7 +644,7 @@ export default class TopicController extends Controller {}if (firstLoadedPost && firstLoadedPost === post) {- await postStream.prependMore();+ await postStream.prependMore({ beforePrepend: captureAnchor });refresh?.();}}diff --git a/frontend/discourse/app/helpers/hide-scrollable-content.js b/frontend/discourse/app/helpers/hide-scrollable-content.jsnew file mode 100644index 00000000000..be4284e7480--- /dev/null+++ b/frontend/discourse/app/helpers/hide-scrollable-content.js@@ -0,0 +1,27 @@+import Helper from "@ember/component/helper";+import { service } from "@ember/service";++const VALID_DIRECTIONS = ["above", "below"];++export default class HideScrollableContent extends Helper {+ @service scrollState;++ #registered = false;++ compute([direction]) {+ if (!this.#registered) {+ if (!VALID_DIRECTIONS.includes(direction)) {+ throw new Error(+ `{{hideScrollableContent}}: invalid direction "${direction}", expected "above" or "below"`+ );+ }++ if (direction === "above") {+ this.scrollState.hideScrollableContentAbove(this);+ } else {+ this.scrollState.hideScrollableContentBelow(this);+ }+ this.#registered = true;+ }+ }+}diff --git a/frontend/discourse/app/models/post-stream.js b/frontend/discourse/app/models/post-stream.jsindex fd39c1769a2..d935d48f2b8 100644--- a/frontend/discourse/app/models/post-stream.js+++ b/frontend/discourse/app/models/post-stream.js@@ -512,7 +512,7 @@ export default class PostStream extends RestModel {}// Prepend the previous window of posts to the stream. Call it when scrolling upwards.- async prependMore() {+ async prependMore({ beforePrepend } = {}) {// Make sure we can append more postsif (!this.canPrependMore) {return;@@ -522,7 +522,14 @@ export default class PostStream extends RestModel {this.loadingAbove = true;try {+ let captured = false;await this.fetchNextWindow(this.posts[0].post_number, false, (p) => {+ // Capture the anchor position before the first post is inserted.+ // The network await above gave Ember time to render the spinner.+ if (!captured) {+ beforePrepend?.();+ captured = true;+ }this.prependPost(p);});} finally {@@ -537,6 +544,9 @@ export default class PostStream extends RestModel {try {const posts = await this.findPostsByIds(postIds.reverse());+ // Capture the anchor position after the fetch (spinner rendered during+ // the await) and before inserting new posts into the stream.+ beforePrepend?.();posts.forEach((p) => this.prependPost(p));} finally {this.loadingAbove = false;diff --git a/frontend/discourse/app/services/scroll-state.js b/frontend/discourse/app/services/scroll-state.jsnew file mode 100644index 00000000000..0604590b9ac--- /dev/null+++ b/frontend/discourse/app/services/scroll-state.js@@ -0,0 +1,35 @@+import { tracked } from "@glimmer/tracking";+import { registerDestructor } from "@ember/destroyable";+import { next } from "@ember/runloop";+import Service from "@ember/service";+import { disableImplicitInjections } from "discourse/lib/implicit-injections";++@disableImplicitInjections+export default class ScrollStateService extends Service {+ @tracked _hideScrollableContentAboveCount = 0;+ @tracked _hideScrollableContentBelowCount = 0;++ get shouldHideContentAbove() {+ return this._hideScrollableContentAboveCount > 0;+ }++ get shouldHideContentBelow() {+ return this._hideScrollableContentBelowCount > 0;+ }++ hideScrollableContentAbove(destroyable) {+ next(() => this._hideScrollableContentAboveCount++);+ registerDestructor(destroyable, () => {+ // Deferred to avoid backtracking re-render assertion — the destructor+ // runs during the same render cycle that already read the counter.+ next(() => this._hideScrollableContentAboveCount--);+ });+ }++ hideScrollableContentBelow(destroyable) {+ next(() => this._hideScrollableContentBelowCount++);+ registerDestructor(destroyable, () => {+ next(() => this._hideScrollableContentBelowCount--);+ });+ }+}diff --git a/frontend/discourse/app/templates/application.gjs b/frontend/discourse/app/templates/application.gjsindex 193608b10b4..60488a680e3 100644--- a/frontend/discourse/app/templates/application.gjs+++ b/frontend/discourse/app/templates/application.gjs@@ -97,44 +97,48 @@ export default <template><PluginOutlet @name="before-main-outlet" /><div id="main-outlet">- <PluginOutlet @name="above-main-container" @connectorTagName="div" />-- {{#if @controller.siteSettings.enable_site_owner_onboarding}}- <AdminOnboardingBanner />- {{/if}}-- {{#if- (eq- @controller.siteSettings.welcome_banner_location- "above_topic_content"- )- }}- <WelcomeBanner />- {{/if}}-- <div class="container" id="main-container">- {{#if @controller.showTop}}- <CustomHtml @name="top" />+ {{#unless @controller.shouldHideScrollableContentAbove}}+ <PluginOutlet @name="above-main-container" @connectorTagName="div" />++ {{#if @controller.siteSettings.enable_site_owner_onboarding}}+ <AdminOnboardingBanner />+ {{/if}}++ {{#if+ (eq+ @controller.siteSettings.welcome_banner_location+ "above_topic_content"+ )+ }}+ <WelcomeBanner />{{/if}}- <NotificationConsentBanner />- <PwaInstallBanner />- <GlobalNotice />- <PluginOutlet- @name="top-notices"- @connectorTagName="div"- @outletArgs={{lazyHash- [email protected]._router.currentPath- }}- />- </div>++ <div class="container" id="main-container">+ {{#if @controller.showTop}}+ <CustomHtml @name="top" />+ {{/if}}+ <NotificationConsentBanner />+ <PwaInstallBanner />+ <GlobalNotice />+ <PluginOutlet+ @name="top-notices"+ @connectorTagName="div"+ @outletArgs={{lazyHash+ [email protected]._router.currentPath+ }}+ />+ </div>+ {{/unless}}{{outlet}}+ {{#unless @controller.shouldHideScrollableContentBelow}}+ <PluginOutlet+ @name="main-outlet-bottom"+ @outletArgs={{lazyHash [email protected]}}+ />+ {{/unless}}<CardContainer />- <PluginOutlet- @name="main-outlet-bottom"- @outletArgs={{lazyHash [email protected]}}- /></div><PluginOutlet @name="after-main-outlet" />diff --git a/frontend/discourse/app/templates/topic.gjs b/frontend/discourse/app/templates/topic.gjsindex 596c66690ac..18638ddc553 100644--- a/frontend/discourse/app/templates/topic.gjs+++ b/frontend/discourse/app/templates/topic.gjs@@ -39,6 +39,7 @@ import ageWithTooltip from "discourse/helpers/age-with-tooltip";import bodyClass from "discourse/helpers/body-class";import icon from "discourse/helpers/d-icon";import hideApplicationFooter from "discourse/helpers/hide-application-footer";+import hideScrollableContent from "discourse/helpers/hide-scrollable-content";import lazyHash from "discourse/helpers/lazy-hash";import routeAction from "discourse/helpers/route-action";import CategoryChooser from "discourse/select-kit/components/category-chooser";@@ -71,28 +72,32 @@ export default <template>/><AddTopicStatusClasses @topic={{@controller.model}} />{{bodyClass (concat "archetype-" @controller.model.archetype)}}- <div class="container">- <DiscourseBanner- @overlay={{@controller.hasScrolled}}- @hide={{@controller.model.errorLoading}}- />- </div>+ {{#unless @controller.shouldHideScrollableContentAbove}}+ <div class="container">+ <DiscourseBanner+ @overlay={{@controller.hasScrolled}}+ @hide={{@controller.model.errorLoading}}+ />+ </div>+ {{/unless}}{{/if}}- {{#if @controller.showSharedDraftControls}}- <SharedDraftControls @topic={{@controller.model}} />- {{/if}}+ {{#unless @controller.shouldHideScrollableContentAbove}}+ {{#if @controller.showSharedDraftControls}}+ <SharedDraftControls @topic={{@controller.model}} />+ {{/if}}- <span>- <PluginOutlet- @name="topic-above-post-stream"- @connectorTagName="div"- @outletArgs={{lazyHash- }}- />- </span>+ <span>+ <PluginOutlet+ @name="topic-above-post-stream"+ @connectorTagName="div"+ @outletArgs={{lazyHash+ }}+ />+ </span>+ {{/unless}}{{#if @controller.model.postStream.loaded}}{{#if @controller.model.postStream.firstPostPresent}}@@ -421,6 +426,10 @@ export default <template>/></span>+ {{#if @controller.model.postStream.firstPostNotLoaded}}+ {{hideScrollableContent "above"}}+ {{/if}}+{{#unless @controller.model.postStream.loadingFilter}}<PostStream@postStream={{@controller.model.postStream}}@@ -479,6 +488,10 @@ export default <template>@topic={{@controller.model}}/>{{/unless}}++ {{#if @controller.model.postStream.lastPostNotLoaded}}+ {{hideScrollableContent "below"}}+ {{/if}}</div><div id="topic-bottom"></div>diff --git a/frontend/discourse/tests/unit/models/post-stream-test.js b/frontend/discourse/tests/unit/models/post-stream-test.jsindex 0ad29b65826..3bb3474c5dc 100644--- a/frontend/discourse/tests/unit/models/post-stream-test.js+++ b/frontend/discourse/tests/unit/models/post-stream-test.js@@ -44,7 +44,9 @@ module("Unit | Model | post-stream", function (hooks) {assert.false(postStream.hasPosts, "there are no posts by default");assert.false(postStream.firstPostPresent, "the first post is not loaded");+ assert.true(postStream.firstPostNotLoaded, "firstPostNotLoaded is true");assert.false(postStream.loadedAllPosts, "the last post is not loaded");+ assert.true(postStream.lastPostNotLoaded, "lastPostNotLoaded is true");assert.strictEqual(postStream.posts.length, 0, "it has no posts initially");postStream.appendPost(@@ -64,7 +66,15 @@ module("Unit | Model | post-stream", function (hooks) {store.createRecord("post", { id: 4, post_number: 4 }));assert.false(postStream.firstPostPresent, "the first post is still loaded");+ assert.true(+ postStream.firstPostNotLoaded,+ "firstPostNotLoaded remains true"+ );assert.true(postStream.loadedAllPosts, "the last post is now loaded");+ assert.false(+ postStream.lastPostNotLoaded,+ "lastPostNotLoaded is now false"+ );assert.strictEqual(postStream.posts.length,2,@@ -100,10 +110,18 @@ module("Unit | Model | post-stream", function (hooks) {postStream.firstPostPresent,"the first post no longer loaded since the stream changed.");+ assert.true(+ postStream.firstPostNotLoaded,+ "firstPostNotLoaded is true after stream change"+ );assert.true(postStream.loadedAllPosts,"the last post is still the last post in the new stream");+ assert.false(+ postStream.lastPostNotLoaded,+ "lastPostNotLoaded is still false after stream change"+ );});test("closestPostNumberFor", function (assert) {diff --git a/spec/system/post_stream_spec.rb b/spec/system/post_stream_spec.rbindex 1d0291d03ce..835ec81654c 100644--- a/spec/system/post_stream_spec.rb+++ b/spec/system/post_stream_spec.rb@@ -52,6 +52,31 @@ describe "Post stream", type: :system doendend+ context "when hiding scrollable content" do+ let!(:topic) { Fabricate(:topic) }+ let!(:posts) { Fabricate.times(60, :post, topic: topic) }+ let(:topic_page) { PageObjects::Pages::Topic.new }++ before { sign_in(user) }++ it "hides and shows content above the post stream based on loaded posts" do+ topic_page.visit_topic(topic, post_number: 30)+ expect(page).to have_css("[data-post-number='30']")+ expect(page).to have_no_css("#main-container")++ topic_page.visit_topic(topic, post_number: 1)+ expect(page).to have_css("[data-post-number='1']")+ expect(page).to have_css("#main-container")++ topic_page.visit_topic(topic, post_number: 30)+ expect(page).to have_css("[data-post-number='30']")+ expect(page).to have_no_css("#main-container")++ visit "/"+ expect(page).to have_css("#main-container")+ end+ end+context "when scrolling" dolet!(:topic) { Fabricate(:topic) }let!(:posts) { Fabricate.times(20, :post, topic: topic) }