A platform for community discussion. Free, open, simple.
DEV: Modernize the remaining of the post stream to Glimmer components (#32653)
Sérgio Saquetimefd01c18cf99
diff --git a/app/assets/javascripts/discourse/app/components/avatar-flair.js b/app/assets/javascripts/discourse/app/components/avatar-flair.jsindex e7c51953dc1..7c2ceff2a32 100644--- a/app/assets/javascripts/discourse/app/components/avatar-flair.js+++ b/app/assets/javascripts/discourse/app/components/avatar-flair.js@@ -1,6 +1,7 @@import { observes } from "@ember-decorators/object";import MountWidget from "discourse/components/mount-widget";+// TODO (glimmer-post-stream): this component needs to be converted to Glimmerexport default class AvatarFlair extends MountWidget {widget = "avatar-flair";diff --git a/app/assets/javascripts/discourse/app/components/glimmer-site-header.gjs b/app/assets/javascripts/discourse/app/components/glimmer-site-header.gjsindex 616977800c7..0ac14230106 100644--- a/app/assets/javascripts/discourse/app/components/glimmer-site-header.gjs+++ b/app/assets/javascripts/discourse/app/components/glimmer-site-header.gjs@@ -155,6 +155,7 @@ export default class GlimmerSiteHeader extends Component {parseInt(docStyle.getPropertyValue("--header-offset"), 10) || 0;const newHeaderOffset = Math.floor(headerWrapBottom);if (currentHeaderOffset !== newHeaderOffset) {+ this.header.headerOffset = newHeaderOffset;docStyle.setProperty("--header-offset", `${newHeaderOffset}px`);}@@ -164,6 +165,7 @@ export default class GlimmerSiteHeader extends Component {headerWrapBottom + mainOutletOffsetTop);if (currentMainOutletOffset !== newMainOutletOffset) {+ this.header.mainOutletOffset = newMainOutletOffset;docStyle.setProperty("--main-outlet-offset", `${newMainOutletOffset}px`);}}@@ -199,6 +201,10 @@ export default class GlimmerSiteHeader extends Component {);this._resizeObserver.observe(document.querySelector(".discourse-root"));}++ // the resize observer will not trigger on the first render, so we need to call it manually to get the initial value+ // set just after the header is inserted+ this.recalculateHeaderOffset();}_handleArrowKeysNav(event) {diff --git a/app/assets/javascripts/discourse/app/components/invite-panel.gjs b/app/assets/javascripts/discourse/app/components/invite-panel.gjsindex e98e04c28c2..d966090e1c6 100644--- a/app/assets/javascripts/discourse/app/components/invite-panel.gjs+++ b/app/assets/javascripts/discourse/app/components/invite-panel.gjs@@ -348,6 +348,7 @@ export default class InvitePanel extends Component {.then(() => {model.setProperties({ saving: false, finished: true });this.inviteModel.reload().then(() => {+ // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this eventthis.appEvents.trigger("post-stream:refresh");});})@@ -361,6 +362,7 @@ export default class InvitePanel extends Component {this.get("inviteModel.details.allowed_users").pushObject(EmberObject.create(result.user));+ // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this eventthis.appEvents.trigger("post-stream:refresh", { force: true });} else if (this.invitingToTopic &&diff --git a/app/assets/javascripts/discourse/app/components/modal/history.gjs b/app/assets/javascripts/discourse/app/components/modal/history.gjsindex b12cb542097..88bb5f95c68 100644--- a/app/assets/javascripts/discourse/app/components/modal/history.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/history.gjs@@ -193,11 +193,10 @@ export default class History extends Component {return;}- postStream- .triggerChangedPost(postId, this.args.model)- .then(() =>- this.appEvents.trigger("post-stream:refresh", { id: postId })- );+ postStream.triggerChangedPost(postId, this.args.model).then(() =>+ // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event+ this.appEvents.trigger("post-stream:refresh", { id: postId })+ );} finally {this.loading = false;this.initialLoad = false;diff --git a/app/assets/javascripts/discourse/app/components/post-stream.gjs b/app/assets/javascripts/discourse/app/components/post-stream.gjsnew file mode 100644index 00000000000..f4e9836c809--- /dev/null+++ b/app/assets/javascripts/discourse/app/components/post-stream.gjs@@ -0,0 +1,330 @@+import Component from "@glimmer/component";+import { cached, tracked } from "@glimmer/tracking";+import { concat, fn, get, hash } from "@ember/helper";+import { action } from "@ember/object";+import { schedule } from "@ember/runloop";+import { service } from "@ember/service";+import { and, not } from "truth-helpers";+import ConditionalLoadingSpinner from "discourse/components/conditional-loading-spinner";+import LoadMore from "discourse/components/load-more";+import PostFilteredNotice from "discourse/components/post/filtered-notice";+import { bind } from "discourse/lib/decorators";+import offsetCalculator from "discourse/lib/offset-calculator";+import { Placeholder } from "discourse/lib/posts-with-placeholders";+import PostStreamViewportTracker from "discourse/modifiers/post-stream-viewport-tracker";+import Post from "./post";+import PostGap from "./post/gap";+import PostPlaceholder from "./post/placeholder";+import PostSmallAction from "./post/small-action";+import PostTimeGap from "./post/time-gap";+import PostVisitedLine from "./post/visited-line";++const DAY_MS = 1000 * 60 * 60 * 24;++export default class PostStream extends Component {+ @service appEvents;+ @service capabilities;+ @service header;+ @service screenTrack;+ @service search;+ @service site;+ @service siteSettings;++ @tracked cloakAbove;+ @tracked cloakBelow;++ viewportTracker = new PostStreamViewportTracker();++ willDestroy() {+ super.willDestroy(...arguments);++ // clear pending references in the observer+ this.viewportTracker.destroy();+ }++ get gapsBefore() {+ return this.args.gaps?.before || {};+ }++ get gapsAfter() {+ return this.args.gaps?.after || {};+ }++ @cached+ get posts() {+ const postsToRender = this.capabilities.isAndroid+ ? this.args.postStream.posts+ : this.args.postStream.postsWithPlaceholders;++ // TODO (glimmer-post-stream) ideally args.posts should be a TrackedArray+ return postsToRender.toArray();+ }++ get firstAvailablePost() {+ return this.posts[0];+ }++ get highlightTerm() {+ return this.search.highlightTerm;+ }++ get lastAvailablePost() {+ return this.posts.at(-1);+ }++ @cached+ get postTuples() {+ const posts = this.posts;++ const length = posts.length;+ const result = [];++ let i = 0;+ let previousPost = null;++ while (i < length) {+ const post = posts[i];+ const nextPost = i < length - 1 ? posts[i + 1] : null;++ result.push({ post, previousPost, nextPost });++ previousPost = post;+ ++i;+ }++ return result;+ }++ get shouldShowFilteredNotice() {+ return (+ this.args.streamFilters &&+ Object.keys(this.args.streamFilters).length &&+ (Object.keys(this.gapsBefore).length > 0 ||+ Object.keys(this.gapsAfter).length > 0)+ );+ }++ isPlaceholder(post) {+ return post instanceof Placeholder;+ }++ daysBetween(post1, post2) {+ const time1 = post1 ? new Date(post1.createdAt).getTime() : null;+ const time2 = post2 ? new Date(post2.createdAt).getTime() : null;++ if (!time1 || !time2) {+ return null;+ }++ return Math.floor((time2 - time1) / DAY_MS);+ }++ @bind+ shouldShowTimeGap(daysSince) {+ return daysSince > this.siteSettings.show_time_gap_days;+ }++ @bind+ shouldShowVisitedLine(post, arrayIndex) {+ const postsLength = this.posts.length;+ const maxPostNumber = postsLength > 0 ? this.posts.at(-1).post_number : 0;++ return (+ arrayIndex !== postsLength - 1 && // do not show on the last post displayed+ maxPostNumber <= this.args.highestPostNumber && // do not show in the last existing post+ this.args.lastReadPostNumber === post.post_number+ );+ }++ @action+ loadMoreAbove(post) {+ this.args.topVisibleChanged({+ post,+ refresh: () => {+ const refreshedElem =+ this.viewportTracker.postsOnScreen[post.post_number]?.element;++ if (!refreshedElem) {+ 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(),+ });++ // 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.+ schedule("afterRender", () => {+ window.scrollTo({+ top: getOffsetTop(refreshedElem) - offsetCalculator(),+ });+ });+ },+ });+ }++ @action+ loadMoreBelow(post) {+ this.args.bottomVisibleChanged({ post });+ }++ @action+ setCloakingBoundaries(above, below) {+ // requesting an animation frame to update the cloaking boundaries prevents Chrome from logging+ // [Violation] 'setTimeout' handler took <N>ms when scrolling fast+ requestAnimationFrame(() => {+ this.cloakAbove = above;+ this.cloakBelow = below;+ });+ }++ <template>+ <ConditionalLoadingSpinner @condition={{@postStream.loadingAbove}} />+ <div+ class="post-stream"+ {{this.viewportTracker.setup+ currentPostChanged=@currentPostChanged+ currentPostScrolled=@currentPostScrolled+ headerOffset=this.header.headerOffset+ screenTrack=this.screenTrack+ setCloakingBoundaries=this.setCloakingBoundaries+ }}+ >+ {{#if (and (not @postStream.loadingAbove) @postStream.canPrependMore)}}+ <LoadMore @action={{fn this.loadMoreAbove this.firstAvailablePost}} />+ {{/if}}++ {{#each this.postTuples key="post.id" as |tuple index|}}+ {{#let+ tuple.post tuple.previousPost tuple.nextPost+ as |post previousPost nextPost|+ }}+ {{#if (this.isPlaceholder post)}}+ <PostPlaceholder />+ {{else}}+ {{#let (get this.gapsBefore post.id) as |gap|}}+ {{#if gap}}+ <PostGap+ @post={{post}}+ @gap={{gap}}+ @fillGap={{fn @fillGapBefore (hash post=post gap=gap)}}+ />+ {{/if}}+ {{/let}}++ {{#let (this.daysBetween previousPost post) as |daysSince|}}+ {{#if (this.shouldShowTimeGap daysSince)}}+ <PostTimeGap @daysSince={{daysSince}} />+ {{/if}}+ {{/let}}++ {{#let+ (if post.isSmallAction PostSmallAction Post)+ (this.viewportTracker.getCloakingData+ post above=this.cloakAbove below=this.cloakBelow+ )+ as |PostComponent cloakingData|+ }}+ <PostComponent+ id={{concat "post_" post.post_number}}+ class={{if cloakingData.active "post-stream--cloaked"}}+ style={{cloakingData.style}}+ @cloaked={{cloakingData.active}}+ @post={{post}}+ @prevPost={{previousPost}}+ @nextPost={{nextPost}}+ @canCreatePost={{@canCreatePost}}+ @cancelFilter={{fn @cancelFilter post}}+ @changeNotice={{fn @changeNotice post}}+ @changePostOwner={{fn @changePostOwner post}}+ @deletePost={{fn @deletePost post}}+ @editPost={{fn @editPost post}}+ @expandHidden={{fn @expandHidden post}}+ @filteringRepliesToPostNumber={{@filteringRepliesToPostNumber}}+ @grantBadge={{fn @grantBadge post}}+ @highlightTerm={{this.highlightTerm}}+ @lockPost={{fn @lockPost post}}+ @multiSelect={{@multiSelect}}+ @permanentlyDeletePost={{fn @permanentlyDeletePost post}}+ @rebakePost={{fn @rebakePost post}}+ @recoverPost={{fn @recoverPost post}}+ @removeAllowedGroup={{fn @removeAllowedGroup post}}+ @removeAllowedUser={{fn @removeAllowedUser post}}+ @replyToPost={{fn @replyToPost post}}+ @selectBelow={{fn @selectBelow post}}+ @selectReplies={{fn @selectReplies post}}+ @selected={{if @multiSelect (@postSelected post)}}+ @showFlags={{fn @showFlags post}}+ @showHistory={{fn @showHistory post}}+ @showInvite={{fn @showInvite post}}+ @showLogin={{fn @showLogin post}}+ @showPagePublish={{fn @showPagePublish post}}+ @showRawEmail={{fn @showRawEmail post}}+ @showReadIndicator={{@showReadIndicator}}+ @togglePostSelection={{fn @togglePostSelection post}}+ @togglePostType={{fn @togglePostType post}}+ @toggleReplyAbove={{fn @toggleReplyAbove post}}+ @toggleWiki={{fn @toggleWiki post}}+ @topicPageQueryParams={{@topicPageQueryParams}}+ @unhidePost={{fn @unhidePost post}}+ @unlockPost={{fn @unlockPost post}}+ @updateTopicPageQueryParams={{@updateTopicPageQueryParams}}+ {{this.viewportTracker.registerPost post}}+ />+ {{/let}}++ {{#let (get this.gapsAfter post.id) as |gap|}}+ {{#if gap}}+ <PostGap+ @post={{post}}+ @gap={{gap}}+ @fillGap={{fn @fillGapAfter (hash post=post gap=gap)}}+ />+ {{/if}}+ {{/let}}++ {{#if (this.shouldShowVisitedLine post index)}}+ <PostVisitedLine @post={{post}} />+ {{/if}}+ {{/if}}+ {{/let}}+ {{/each}}++ {{#unless @postStream.loadingBelow}}+ {{#if @postStream.canAppendMore}}+ <LoadMore @action={{fn this.loadMoreBelow this.lastAvailablePost}} />+ {{else}}+ <div+ class="post-stream__bottom-boundary"+ {{this.viewportTracker.registerBottomBoundary [email protected]}}+ ></div>+ {{/if}}+ {{/unless}}++ {{#if this.shouldShowFilteredNotice}}+ <PostFilteredNotice+ @posts={{this.posts}}+ @cancelFilter={{@cancelFilter}}+ @streamFilters={{@streamFilters}}+ @filteredPostsCount={{@filteredPostsCount}}+ />+ {{/if}}+ </div>+ <ConditionalLoadingSpinner @condition={{@postStream.loadingBelow}} />+ </template>+}diff --git a/app/assets/javascripts/discourse/app/components/post.gjs b/app/assets/javascripts/discourse/app/components/post.gjsindex 567fb83df2e..146c5db021c 100644--- a/app/assets/javascripts/discourse/app/components/post.gjs+++ b/app/assets/javascripts/discourse/app/components/post.gjs@@ -7,7 +7,6 @@ import { getOwner } from "@ember/owner";import { service } from "@ember/service";import { TrackedArray } from "@ember-compat/tracked-built-ins";import { TrackedAsyncData } from "ember-async-data";-import Modifier from "ember-modifier";import { and, eq, not, or } from "truth-helpers";import DButton from "discourse/components/d-button";import ShareTopicModal from "discourse/components/modal/share-topic";@@ -23,6 +22,7 @@ import PostMetaDataReplyToTab from "discourse/components/post/meta-data/reply-toimport PostNotice from "discourse/components/post/notice";import TopicMap from "discourse/components/topic-map";import concatClass from "discourse/helpers/concat-class";+import lazyHash from "discourse/helpers/lazy-hash";import { isTesting } from "discourse/lib/environment";import getURL, { getAbsoluteURL } from "discourse/lib/get-url";import postActionFeedback from "discourse/lib/post-action-feedback";@@ -326,301 +326,280 @@ export default class Post extends Component {}<template>- {{#if @cloaked}}- {{! temporary workaround to set the parent class using the modifier while the post stream widget is not modernized }}- {{! TODO (glimmer-post-stream): remove when the post stream is modernized and move the class to the outer div }}- <article- {{parentClass "post--cloaked cloaked-post" parentSelector="div"}}- ></article>- {{else}}- {{#let- (hash- post=@post- actions=(hash updateTopicPageQueryParams=@updateTopicPageQueryParams)- topicPageQueryParams=@topicPageQueryParams+ <div+ ...attributes+ class={{unless+ @cloaked+ (concatClass+ "topic-post"+ "clearfix"+ (unless this.site.mobileView "post--sticky-avatar sticky-avatar")+ (if this.staged "post--staged staged")+ (if @selected "post--selected selected")+ (if @post.topicOwner "post--topic-owner topic-owner")+ (if this.isFromCurrentUser "post--current-user current-user-post")+ (if+ @post.group_moderator "post--category-moderator category-moderator"+ )+ (if @post.hidden "post--hidden post-hidden")+ (if @post.deleted "post--deleted deleted")+ (if+ @post.primary_group_name+ (concatClass+ (concat "post--group-" @post.primary_group_name)+ (concat "group-" @post.primary_group_name)+ )+ )+ (if @post.wiki "post--wiki wiki")+ (if @post.isWhisper "post--whisper whisper")+ (if+ (or @post.isModeratorAction (and @post.isWarning @post.firstPost))+ "post--moderator moderator"+ "post--regular regular"+ )+ (if @post.user_suspended "post--user-suspended user-suspended")+ this.additionalClasses)- as |postOutletArgs|}}- <PluginOutlet @name="post-article" @outletArgs={{postOutletArgs}}>- <article- {{parentClass- (concatClass- "topic-post"- "clearfix"- (if this.staged "post--staged staged")- (if @selected "post--selected selected")- (if @post.topicOwner "post--topic-owner topic-owner")+ data-post-number={{@post.post_number}}+ >+ {{#unless @cloaked}}+ {{#let+ (lazyHash+ post=@post+ actions=(hash+ updateTopicPageQueryParams=@updateTopicPageQueryParams+ )+ topicPageQueryParams=@topicPageQueryParams+ )+ as |postOutletArgs|+ }}+ <PluginOutlet @name="post-article" @outletArgs={{postOutletArgs}}>+ <article+ id={{this.id}}+ class={{concatClass+ "boxed"+ "onscreen-post"(if- this.isFromCurrentUser "post--current-user current-user-post"+ this.hasRepliesAbove "post--has-replies-above replies-above")(if- @post.group_moderator- "post--category-moderator category-moderator"+ @post.is_auto_generated+ "post--auto-generated is-auto-generated")- (if @post.hidden "post--hidden post-hidden")- (if @post.deleted "post--deleted deleted")- (if- @post.primary_group_name- (concatClass- (concat "post--group-" @post.primary_group_name)- (concat "group-" @post.primary_group_name)- )- )- (if @post.wiki "post--wiki wiki")- (if @post.isWhisper "post--whisper whisper")- (if- (or- @post.isModeratorAction- (and @post.isWarning @post.firstPost)- )- "post--moderator moderator"- "post--regular regular"- )- (if @post.user_suspended "post--user-suspended user-suspended")- this.additionalClasses- )- parentSelector="div"- }}- ...attributes- id={{this.id}}- class={{concatClass- "boxed"- "onscreen-post"- (if this.hasRepliesAbove "post--has-replies-above replies-above")- (if- @post.is_auto_generated "post--auto-generated is-auto-generated"- )- (if @post.via_email "post--via-email via-email")- }}- aria-label={{i18n- "share.post"- (hash [email protected]_number [email protected])- }}- role="region"- data-post-id={{@post.id}}- data-topic-id={{@post.topicId}}- data-user-id={{@post.user_id}}- >- {{#if this.hasRepliesAbove}}- <div class="post__row row">- <section- id={{concat "embedded-posts__top--" @post.post_number}}- class="post__embedded-posts post__embedded-posts--top post__body embedded-posts top topic-body"- >- <DButton- class="post__collapse-button post__collapse-button-down collapse-down"- @action={{this.toggleReplyAbove}}- @icon="chevron-down"- @title="post.collapse"- />- {{#each this.repliesAbove.value key="id" as |reply|}}- <PostEmbedded- @post={{reply}}- @above={{true}}- @highlightTerm={{this.search.highlightTerm}}+ (if @post.via_email "post--via-email via-email")+ }}+ aria-label={{i18n+ "share.post"+ (hash [email protected]_number [email protected])+ }}+ role="region"+ data-post-id={{@post.id}}+ data-topic-id={{@post.topicId}}+ data-user-id={{@post.user_id}}+ >+ {{#if this.hasRepliesAbove}}+ <div class="post__row row">+ <section+ id={{concat "embedded-posts__top--" @post.post_number}}+ class="post__embedded-posts post__embedded-posts--top post__body embedded-posts top topic-body"+ >+ <DButton+ class="post__collapse-button post__collapse-button-down collapse-down"+ @action={{this.toggleReplyAbove}}+ @icon="chevron-down"+ @title="post.collapse"/>- {{/each}}- </section>- </div>- {{/if}}- {{#if (and (not @post.deletedAt) @post.notice)}}+ {{#each this.repliesAbove.value key="id" as |reply|}}+ <PostEmbedded+ @post={{reply}}+ @above={{true}}+ @highlightTerm={{@highlightTerm}}+ />+ {{/each}}+ </section>+ </div>+ {{/if}}+ {{#if (and (not @post.deletedAt) @post.notice)}}+ <div class="post__row row">+ <PostNotice @post={{@post}} />+ </div>+ {{/if}}<div class="post__row row">- <PostNotice @post={{@post}} />- </div>- {{/if}}- <div class="post__row row">- <PostAvatar @post={{@post}} />- <div class="post__body topic-body clearfix">- <PluginOutlet- @name="post-metadata"- @outletArgs={{postOutletArgs}}- >- <PostMetaData- @post={{@post}}- @editPost={{@editPost}}- @hasRepliesAbove={{this.hasRepliesAbove}}- @isReplyingDirectlyToPostAbove={{this.isReplyingDirectlyToPostAbove}}- @multiSelect={{@multiSelect}}- @repliesAbove={{this.repliesAbove}}- @selectBelow={{@selectBelow}}- @selectReplies={{@selectReplies}}- @selected={{@selected}}- @showHistory={{@showHistory}}- @showRawEmail={{@showRawEmail}}- @togglePostSelection={{@togglePostSelection}}- @toggleReplyAbove={{this.toggleReplyAbove}}- />- </PluginOutlet>- <div- class={{concatClass- "post__regular regular"- (unless this.repliesShown "post__contents contents")- (if- this.isReplyToTabDisplayed- "post__contents--avoid-tab avoid-tab"- )- }}- >+ <PostAvatar @post={{@post}} />+ <div class="post__body topic-body clearfix"><PluginOutlet- @name="post-content-cooked-html"+ @name="post-metadata"@outletArgs={{postOutletArgs}}>- <PostCookedHtml- @post={{@post}}- @highlightTerm={{this.search.highlightTerm}}- />- </PluginOutlet>-- {{#if @post.requestedGroupName}}- <div class="post__group-request group-request">- <a href={{this.groupRequestUrl}}>- {{i18n "groups.requests.handle"}}- </a>- </div>- {{/if}}-- {{#if (and @post.cooked_hidden @post.can_see_hidden_post)}}- {{! template-lint-disable no-invalid-interactive }}- <a- class="post__expand-hidden expand-hidden"- {{on "click" @expandHidden}}- >- {{i18n "post.show_hidden"}}- </a>- {{/if}}-- {{#if- (and- (not this.expandedFirstPost.isResolved)- @post.expandablePost- )- }}- <DButton- class="post__expand-button expand-post"- @action={{this.expandFirstPost}}- @translatedLabel={{if- this.expandedFirstPost.isPending- (i18n "loading")- (concat (i18n "post.show_full") "...")- }}- />- {{/if}}-- <section class="post__menu-area post-menu-area clearfix">- <PostMenu+ <PostMetaData@post={{@post}}- @prevPost={{@prevPost}}- @nextPost={{@nextPost}}- @canCreatePost={{@canCreatePost}}- @changeNotice={{@changeNotice}}- @changePostOwner={{@changePostOwner}}- @copyLink={{this.copyLink}}- @deletePost={{@deletePost}}@editPost={{@editPost}}- @filteredRepliesView={{this.filteredRepliesView}}- @grantBadge={{@grantBadge}}- @lockPost={{@lockPost}}- @permanentlyDeletePost={{@permanentlyDeletePost}}- @rebakePost={{@rebakePost}}- @recoverPost={{@recoverPost}}- @repliesShown={{this.repliesShown}}- @replyToPost={{@replyToPost}}- @share={{this.share}}- @showFlags={{@showFlags}}- @showLogin={{@showLogin}}- @showPagePublish={{@showPagePublish}}- @showReadIndicator={{@showReadIndicator}}- @toggleLike={{this.toggleLike}}- @togglePostType={{@togglePostType}}- @toggleReplies={{this.toggleReplies}}- @toggleWiki={{@toggleWiki}}- @unhidePost={{@unhidePost}}- @unlockPost={{@unlockPost}}+ @hasRepliesAbove={{this.hasRepliesAbove}}+ @isReplyingDirectlyToPostAbove={{this.isReplyingDirectlyToPostAbove}}+ @multiSelect={{@multiSelect}}+ @repliesAbove={{this.repliesAbove}}+ @selectBelow={{@selectBelow}}+ @selectReplies={{@selectReplies}}+ @selected={{@selected}}+ @showHistory={{@showHistory}}+ @showRawEmail={{@showRawEmail}}+ @togglePostSelection={{@togglePostSelection}}+ @toggleReplyAbove={{this.toggleReplyAbove}}/>- </section>-- {{#if this.repliesBelow}}- <section- id={{concat "embedded-posts__bottom--" @post.post_number}}- class="post__embedded-posts post__embedded-posts--bottom embedded-posts bottom"+ </PluginOutlet>+ <div+ class={{concatClass+ "post__regular regular"+ (unless this.repliesShown "post__contents contents")+ (if+ this.isReplyToTabDisplayed+ "post__contents--avoid-tab avoid-tab"+ )+ }}+ >+ <PluginOutlet+ @name="post-content-cooked-html"+ @outletArgs={{postOutletArgs}}>- {{#each this.repliesBelow key="id" as |reply|}}- <PostEmbedded- role="region"- aria-label={{i18n- "post.sr_embedded_reply_description"- [email protected]_number- username=reply.username- }}- @post={{reply}}- @highlightTerm={{this.search.highlightTerm}}- />- {{/each}}-+ <PostCookedHtml+ @post={{@post}}+ @highlightTerm={{@highlightTerm}}+ />+ </PluginOutlet>++ {{#if @post.requestedGroupName}}+ <div class="post__group-request group-request">+ <a href={{this.groupRequestUrl}}>+ {{i18n "groups.requests.handle"}}+ </a>+ </div>+ {{/if}}++ {{#if (and @post.cooked_hidden @post.can_see_hidden_post)}}+ {{! template-lint-disable no-invalid-interactive }}+ <a+ class="post__expand-hidden expand-hidden"+ {{on "click" @expandHidden}}+ >+ {{i18n "post.show_hidden"}}+ </a>+ {{/if}}++ {{#if+ (and+ (not this.expandedFirstPost.isResolved)+ @post.expandablePost+ )+ }}<DButton- class="post__collapse-button post__collapse-button-up collapse-up"- @action={{this.toggleRepliesBelow}}- @ariaLabel="post.sr_collapse_replies"- @icon="chevron-up"- @title="post.collapse"+ class="post__expand-button expand-post"+ @action={{this.expandFirstPost}}+ @translatedLabel={{if+ this.expandedFirstPost.isPending+ (i18n "loading")+ (concat (i18n "post.show_full") "...")+ }}/>+ {{/if}}++ <section class="post__menu-area post-menu-area clearfix">+ <PostMenu+ @post={{@post}}+ @prevPost={{@prevPost}}+ @nextPost={{@nextPost}}+ @canCreatePost={{@canCreatePost}}+ @changeNotice={{@changeNotice}}+ @changePostOwner={{@changePostOwner}}+ @copyLink={{this.copyLink}}+ @deletePost={{@deletePost}}+ @editPost={{@editPost}}+ @filteredRepliesView={{this.filteredRepliesView}}+ @grantBadge={{@grantBadge}}+ @lockPost={{@lockPost}}+ @permanentlyDeletePost={{@permanentlyDeletePost}}+ @rebakePost={{@rebakePost}}+ @recoverPost={{@recoverPost}}+ @repliesShown={{this.repliesShown}}+ @replyToPost={{@replyToPost}}+ @share={{this.share}}+ @showFlags={{@showFlags}}+ @showLogin={{@showLogin}}+ @showPagePublish={{@showPagePublish}}+ @showReadIndicator={{@showReadIndicator}}+ @toggleLike={{this.toggleLike}}+ @togglePostType={{@togglePostType}}+ @toggleReplies={{this.toggleReplies}}+ @toggleWiki={{@toggleWiki}}+ @unhidePost={{@unhidePost}}+ @unlockPost={{@unlockPost}}+ />+ </section>++ {{#if this.repliesBelow}}+ <section+ id={{concat+ "embedded-posts__bottom--"+ @post.post_number+ }}+ class="post__embedded-posts post__embedded-posts--bottom embedded-posts bottom"+ >+ {{#each this.repliesBelow key="id" as |reply|}}+ <PostEmbedded+ role="region"+ aria-label={{i18n+ "post.sr_embedded_reply_description"+ [email protected]_number+ username=reply.username+ }}+ @post={{reply}}+ @highlightTerm={{@highlightTerm}}+ />+ {{/each}}- {{#if this.canLoadMoreRepliesBelow}}<DButton- class="post__load-more load-more-replies"- @label="post.load_more_replies"- @action={{this.loadMoreReplies}}+ class="post__collapse-button post__collapse-button-up collapse-up"+ @action={{this.toggleRepliesBelow}}+ @ariaLabel="post.sr_collapse_replies"+ @icon="chevron-up"+ @title="post.collapse"/>- {{/if}}- </section>- {{/if}}- </div>- <section class="post__actions post-actions">- <PostActionsSummary @post={{@post}} />- </section>- <PostLinks @post={{@post}} />- </div>- </div>- {{#if this.shouldShowTopicMap}}- <div class="post__topic-map topic-map --op">- <TopicMap- @model={{@post.topic}}- @cancelFilter={{@cancelFilter}}- @topicDetails={{@post.topic.details}}- @postStream={{@post.topic.postStream}}- @showPMMap={{eq @post.topic.archetype "private_message"}}- @showInvite={{@showInvite}}- @removeAllowedGroup={{@removeAllowedGroup}}- @removeAllowedUser={{@removeAllowedUser}}- />+ {{#if this.canLoadMoreRepliesBelow}}+ <DButton+ class="post__load-more load-more-replies"+ @label="post.load_more_replies"+ @action={{this.loadMoreReplies}}+ />+ {{/if}}+ </section>+ {{/if}}+ </div>++ <section class="post__actions post-actions">+ <PostActionsSummary @post={{@post}} />+ </section>+ <PostLinks @post={{@post}} />+ </div></div>- {{/if}}- </article>- </PluginOutlet>- {{/let}}- {{/if}}+ {{#if this.shouldShowTopicMap}}+ <div class="post__topic-map topic-map --op">+ <TopicMap+ @model={{@post.topic}}+ @cancelFilter={{@cancelFilter}}+ @topicDetails={{@post.topic.details}}+ @postStream={{@post.topic.postStream}}+ @showPMMap={{eq @post.topic.archetype "private_message"}}+ @showInvite={{@showInvite}}+ @removeAllowedGroup={{@removeAllowedGroup}}+ @removeAllowedUser={{@removeAllowedUser}}+ />+ </div>+ {{/if}}+ </article>+ </PluginOutlet>+ {{/let}}+ {{/unless}}+ </div></template>}--// This modifier is just a temporary workaround to set the classes in the parent component while we have to use it-// as a wrapper due to the render glimmer helper.-// DO NOT export it to be used outside of this class. The code will be removed as soon as the post stream widget is-// modernized.-const parentClass = class extends Modifier {- @service elementClasses;-- modify(element, classes, { parentSelector }) {- const parent = element.closest(parentSelector);-- if (!parent) {- return;- }-- this.elementClasses.registerClasses(- this,- parent,- classes.flatMap((c) => c?.split(" ")).filter(Boolean)- );- }-};diff --git a/app/assets/javascripts/discourse/app/components/post/notice/returning-user.gjs b/app/assets/javascripts/discourse/app/components/post/notice/returning-user.gjsindex 02fa69e4c2a..19b29f2bb79 100644--- a/app/assets/javascripts/discourse/app/components/post/notice/returning-user.gjs+++ b/app/assets/javascripts/discourse/app/components/post/notice/returning-user.gjs@@ -6,7 +6,7 @@ import PostNoticeNewUser from "./new-user";export default class PostNoticeReturningUser extends PostNoticeNewUser {get time() {const timeAgo =- (new Date() - new Date(this.args.notice.lastPostedAt)) / 1000;+ (new Date() - new Date(this.args.notice.last_posted_at)) / 1000;return relativeAgeMediumSpan(timeAgo, true);}diff --git a/app/assets/javascripts/discourse/app/components/post/small-action.gjs b/app/assets/javascripts/discourse/app/components/post/small-action.gjsindex 476041b6310..e0c8b6aebd5 100644--- a/app/assets/javascripts/discourse/app/components/post/small-action.gjs+++ b/app/assets/javascripts/discourse/app/components/post/small-action.gjs@@ -1,6 +1,5 @@import Component from "@glimmer/component";import { cached } from "@glimmer/tracking";-import { concat } from "@ember/helper";import { htmlSafe } from "@ember/template";import DButton from "discourse/components/d-button";import PostCookedHtml from "discourse/components/post/cooked-html";@@ -128,12 +127,15 @@ export default class PostSmallAction extends Component {<template><article- id={{concat "post_" @post.post_number}}- class={{concatClass- "small-action"- "onscreen-post"- (if @post.deleted "deleted")- this.additionalClasses+ ...attributes+ class={{unless+ @cloaked+ (concatClass+ "small-action"+ "onscreen-post"+ (if @post.deleted "deleted")+ this.additionalClasses+ )}}aria-label={{i18n"share.post"@@ -141,62 +143,65 @@ export default class PostSmallAction extends Component {}}role="region"+ data-post-number={{@post.post_number}}>- <div class="topic-avatar">- {{icon this.icon}}- </div>- <div class="small-action-desc">- <div class="small-action-contents">- <UserAvatar- @ariaHidden={{false}}- @size="small"- @user={{@post.user}}- />- {{#if this.CustomComponent}}- <this.CustomComponent- @code={{this.code}}- @post={{this.post}}- @createdAt={{this.createdAt}}- @path={{this.path}}- @username={{this.username}}- />- {{else}}- <p>{{htmlSafe this.description}}</p>- {{/if}}+ {{#unless @cloaked}}+ <div class="topic-avatar">+ {{icon this.icon}}</div>- <div class="small-action-buttons">- {{#if @post.canRecover}}- <DButton- class="btn-flat small-action-recover"- @icon="arrow-rotate-left"- @action={{@recoverPost}}- @title="post.controls.undelete"- />- {{else if @post.can_edit}}- <DButton- class="btn-flat small-action-edit"- @icon="pencil"- @action={{@editPost}}- @title="post.controls.edit"- />- {{/if}}- {{#if @post.canDelete}}- <DButton- class="btn-flat btn-danger small-action-delete"- @icon="trash-can"- @action={{@deletePost}}- @title="post.controls.delete"+ <div class="small-action-desc">+ <div class="small-action-contents">+ <UserAvatar+ @ariaHidden={{false}}+ @size="small"+ @user={{@post.user}}/>- {{/if}}+ {{#if this.CustomComponent}}+ <this.CustomComponent+ @code={{this.code}}+ @post={{this.post}}+ @createdAt={{this.createdAt}}+ @path={{this.path}}+ @username={{this.username}}+ />+ {{else}}+ <p>{{htmlSafe this.description}}</p>+ {{/if}}+ </div>+ <div class="small-action-buttons">+ {{#if @post.canRecover}}+ <DButton+ class="btn-flat small-action-recover"+ @icon="arrow-rotate-left"+ @action={{@recoverPost}}+ @title="post.controls.undelete"+ />+ {{else if @post.can_edit}}+ <DButton+ class="btn-flat small-action-edit"+ @icon="pencil"+ @action={{@editPost}}+ @title="post.controls.edit"+ />+ {{/if}}+ {{#if @post.canDelete}}+ <DButton+ class="btn-flat btn-danger small-action-delete"+ @icon="trash-can"+ @action={{@deletePost}}+ @title="post.controls.delete"+ />+ {{/if}}+ </div>+ {{#unless this.CustomComponent}}+ {{#if @post.cooked}}+ <div class="small-action-custom-message">+ <PostCookedHtml @post={{@post}} />+ </div>+ {{/if}}+ {{/unless}}</div>- {{#unless this.CustomComponent}}- {{#if @post.cooked}}- <div class="small-action-custom-message">- <PostCookedHtml @post={{@post}} />- </div>- {{/if}}- {{/unless}}- </div>+ {{/unless}}</article></template>}diff --git a/app/assets/javascripts/discourse/app/components/search-menu.gjs b/app/assets/javascripts/discourse/app/components/search-menu.gjsindex a91bdf9cd6b..26991311104 100644--- a/app/assets/javascripts/discourse/app/components/search-menu.gjs+++ b/app/assets/javascripts/discourse/app/components/search-menu.gjs@@ -325,6 +325,7 @@ export default class SearchMenu extends Component {// when starting the queryif (results) {if (this.searchContext) {+ // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this eventthis.appEvents.trigger("post-stream:refresh", {force: true,});diff --git a/app/assets/javascripts/discourse/app/components/topic-timeline/container.gjs b/app/assets/javascripts/discourse/app/components/topic-timeline/container.gjsindex 8b020a938df..12710482ead 100644--- a/app/assets/javascripts/discourse/app/components/topic-timeline/container.gjs+++ b/app/assets/javascripts/discourse/app/components/topic-timeline/container.gjs@@ -92,6 +92,7 @@ export default class TopicTimelineScrollArea extends Component {this.appEvents.on("composer:resized", this.calculatePosition);this.appEvents.on("composer:closed", this.calculatePosition);this.appEvents.on("composer:preview-toggled", this.calculatePosition);+ // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this eventthis.appEvents.on("post-stream:posted", this.calculatePosition);}@@ -132,6 +133,7 @@ export default class TopicTimelineScrollArea extends Component {this.appEvents.off("composer:closed", this.calculatePosition);this.appEvents.off("composer:preview-toggled", this.calculatePosition);this.appEvents.off("topic:current-post-scrolled", this.postScrolled);+ // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this eventthis.appEvents.off("post-stream:posted", this.calculatePosition);}}diff --git a/app/assets/javascripts/discourse/app/controllers/topic.js b/app/assets/javascripts/discourse/app/controllers/topic.jsindex fe2220758b0..cb0b700997f 100644--- a/app/assets/javascripts/discourse/app/controllers/topic.js+++ b/app/assets/javascripts/discourse/app/controllers/topic.js@@ -32,6 +32,7 @@ import { deepMerge } from "discourse/lib/object";import { buildQuote } from "discourse/lib/quote";import QuoteState from "discourse/lib/quote-state";import { extractLinkMeta } from "discourse/lib/render-topic-featured-link";+import { trackedArray } from "discourse/lib/tracked-tools";import DiscourseURL, { userPath } from "discourse/lib/url";import { escapeExpression } from "discourse/lib/utilities";import Bookmark, { AUTO_DELETE_PREFERENCES } from "discourse/models/bookmark";@@ -73,6 +74,10 @@ export default class TopicController extends Controller {@tracked model;+ @tracked multiSelect = false;+ @tracked hasScrolled = null;+ @trackedArray selectedPostIds = [];+queryParams = ["filter", "username_filters", "replies_to_post_number"];@and("canEditTopicFeaturedLink", "buffered.featured_link")@@ -86,14 +91,11 @@ export default class TopicController extends Controller {@or("model.postStream.loadedAllPosts", "model.postStream.loadingLastPost")loadedAllPosts;- multiSelect = false;- selectedPostIds = [];editingTopic = false;enteredAt = null;enteredIndex = null;retrying = false;userTriggeredProgress = null;- hasScrolled = null;username_filters = null;replies_to_post_number = null;filter = null;@@ -112,6 +114,7 @@ export default class TopicController extends Controller {this.appEvents.on("post:show-revision", this, "_showRevision");this.appEvents.on("post:created", this, () => {this._removeDeleteOnOwnerReplyBookmarks();+ // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this eventthis.appEvents.trigger("post-stream:refresh", { force: true });});}@@ -162,6 +165,7 @@ export default class TopicController extends Controller {return mobileView && postsCount > 3;}+ // TODO (glimmer-post-stream) this method is not used in the Glimmer Post Stream@discourseComputed("model.postStream.posts","model.postStream.postsWithPlaceholders"@@ -170,6 +174,7 @@ export default class TopicController extends Controller {return this.capabilities.isAndroid ? posts : postsWithPlaceholders;}+ // TODO (glimmer-post-stream) is this still used?@discourseComputed("model.postStream.loadingFilter")androidLoading(loading) {return this.capabilities.isAndroid && loading;@@ -304,15 +309,18 @@ export default class TopicController extends Controller {}_forceRefreshPostStream() {+ // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this eventthis.appEvents.trigger("post-stream:refresh", { force: true });}_updateSelectedPostIds(postIds) {const smallActionsPostIds = this._smallActionPostIds();- this.selectedPostIds.pushObjects(- postIds.filter((postId) => !smallActionsPostIds.has(postId))+ this.selectedPostIds = Array.from(+ new Set([+ ...this.selectedPostIds,+ ...postIds.filter((postId) => !smallActionsPostIds.has(postId)),+ ]));- this.set("selectedPostIds", [...new Set(this.selectedPostIds)]);this._forceRefreshPostStream();}@@ -390,18 +398,18 @@ export default class TopicController extends Controller {selectAll(event) {event?.preventDefault();const smallActionsPostIds = this._smallActionPostIds();- this.set("selectedPostIds", [+ this.selectedPostIds = [...this.get("model.postStream.stream").filter((postId) => !smallActionsPostIds.has(postId)),- ]);+ ];this._forceRefreshPostStream();}@actiondeselectAll(event) {event?.preventDefault();- this.set("selectedPostIds", []);+ this.selectedPostIds = [];this._forceRefreshPostStream();}@@ -550,7 +558,7 @@ export default class TopicController extends Controller {}if (firstLoadedPost && firstLoadedPost === post) {- postStream.prependMore().then(() => refresh());+ postStream.prependMore().then(() => refresh?.());}}@@ -567,9 +575,11 @@ export default class TopicController extends Controller {lastLoadedPost === post &&postStream.get("canAppendMore")) {- postStream.appendMore().then(() => refresh());+ // TODO (glimmer-post-stream) the Glimmer Post stream doesn't pass a refresh function+ postStream.appendMore().then(() => refresh?.());// show loading stuff- refresh();+ // TODO (glimmer-post-stream) the Glimmer Post stream doesn't pass a refresh function+ refresh?.();}}@@ -742,7 +752,9 @@ export default class TopicController extends Controller {}const user = this.currentUser;- const refresh = () => this.appEvents.trigger("post-stream:refresh");+ const refresh = () =>+ // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event+ this.appEvents.trigger("post-stream:refresh");const hasReplies = post.get("reply_count") > 0;const loadedPosts = this.get("model.postStream.posts");@@ -913,6 +925,7 @@ export default class TopicController extends Controller {return;}changedIds.forEach((id) =>+ // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this eventthis.appEvents.trigger("post-stream:refresh", { id }));});@@ -996,8 +1009,9 @@ export default class TopicController extends Controller {selectReplies(post) {ajax(`/posts/${post.id}/reply-ids.json`).then((replies) => {const replyIds = replies.map((r) => r.id);- const postIds = [...this.selectedPostIds, post.id, ...replyIds];- this.set("selectedPostIds", [...new Set(postIds)]);+ this.selectedPostIds = [+ ...new Set([...this.selectedPostIds, post.id, ...replyIds]),+ ];this._forceRefreshPostStream();});}@@ -1050,7 +1064,7 @@ export default class TopicController extends Controller {@actionchangePostOwner(post) {- this.set("selectedPostIds", [post.id]);+ this.selectedPostIds = [post.id];this.send("changeOwner");}@@ -1066,7 +1080,7 @@ export default class TopicController extends Controller {@actiongrantBadge(post) {- this.set("selectedPostIds", [post.id]);+ this.selectedPostIds = [post.id];this.send("showGrantBadgeModal");}@@ -1619,9 +1633,10 @@ export default class TopicController extends Controller {@observes("multiSelect")_multiSelectChanged() {- this.set("selectedPostIds", []);+ this.selectedPostIds = [];}+ @bindpostSelected(post) {return this.selectedAllPost || this.selectedPostIds.includes(post.id);}@@ -1740,6 +1755,7 @@ export default class TopicController extends Controller {onMessage(data) {const topic = this.model;const refresh = (args) =>+ // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this eventthis.appEvents.trigger("post-stream:refresh", args);if (isPresent(data.notification_level_change)) {@@ -1890,6 +1906,7 @@ export default class TopicController extends Controller {postStream.get("posts").forEach((post) => {if (!post.read && postNumbers.includes(post.post_number)) {post.set("read", true);+ // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this eventthis.appEvents.trigger("post-stream:refresh", { id: post.get("id") });}});diff --git a/app/assets/javascripts/discourse/app/lib/codeblock-buttons.js b/app/assets/javascripts/discourse/app/lib/codeblock-buttons.jsindex e53e9bb1190..545faa421f1 100644--- a/app/assets/javascripts/discourse/app/lib/codeblock-buttons.js+++ b/app/assets/javascripts/discourse/app/lib/codeblock-buttons.js@@ -106,6 +106,8 @@ export default class CodeblockButtons {codeBlocks.forEach((codeBlock) => {const wrapperEl = document.createElement("div");wrapperEl.classList.add("codeblock-button-wrapper");++ codeBlock.parentElement.classList.add("codeblock-buttons");codeBlock.before(wrapperEl);if (this.showCopy) {@@ -131,8 +133,6 @@ export default class CodeblockButtons {fullscreenButton.innerHTML = iconHTML("discourse-expand");wrapperEl.appendChild(fullscreenButton);}-- codeBlock.parentElement.classList.add("codeblock-buttons");});}diff --git a/app/assets/javascripts/discourse/app/lib/keyboard-shortcuts.js b/app/assets/javascripts/discourse/app/lib/keyboard-shortcuts.jsindex 6444c240dbc..451ff1eb906 100644--- a/app/assets/javascripts/discourse/app/lib/keyboard-shortcuts.js+++ b/app/assets/javascripts/discourse/app/lib/keyboard-shortcuts.js@@ -613,6 +613,7 @@ export default {const result = actionMethod.call(topicController, post);if (result && result.then) {+ // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this eventthis.appEvents.trigger("post-stream:refresh", { id: selectedPostId });}}diff --git a/app/assets/javascripts/discourse/app/lib/plugin-api.gjs b/app/assets/javascripts/discourse/app/lib/plugin-api.gjsindex f20a5b56243..06e29fd76c7 100644--- a/app/assets/javascripts/discourse/app/lib/plugin-api.gjs+++ b/app/assets/javascripts/discourse/app/lib/plugin-api.gjs@@ -134,6 +134,7 @@ import {addSaveableUserField,addSaveableUserOptionField,} from "discourse/models/user";+import { preventCloaking } from "discourse/modifiers/post-stream-viewport-tracker";import { setNewCategoryDefaultColors } from "discourse/routes/new-category";import { setNotificationsLimit } from "discourse/routes/user-notifications";import { addComposerSaveErrorCallback } from "discourse/services/composer";@@ -1179,17 +1180,26 @@ class PluginApi {}/**- * Prevents an element in the post stream from being cloaked.- * This is useful if you are using a plugin such as youtube- * and don't want the video removed once it has begun- * playing.+ * Prevents a specific post from being cloaked during scroll.*+ * This is useful, for example, for posts that apply customizations that hold state which+ * would be lost if the nodes were removed from the DOM, e.g., a playing video.+ *+ * Note that the set of prevented posts is reset whenever the topic being displayed changes.+ *+ * @param {number} postId - The ID of the post to prevent from cloaking+ * @param {boolean} prevent - Whether to prevent (true) or allow (false) cloaking+ *+ * @example* ```javascript- * api.preventCloak(1234);+ * api.preventCloak(1234); // Prevent post 1234 from being cloaked+ * api.preventCloak(1234, false); // Allow post 1234 to be cloaked again* ```**/- preventCloak(postId) {- preventCloak(postId);+ preventCloak(postId, prevent = true) {+ // TODO (glimmer-post-stream) remove the call to the widget version of preventCloak below+ preventCloak(postId); // widgets+ preventCloaking(postId, prevent); // glimmer-post-stream}/**diff --git a/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/quote-controls.js b/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/quote-controls.jsindex a9040dc7835..08f7c31b235 100644--- a/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/quote-controls.js+++ b/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/quote-controls.js@@ -6,6 +6,7 @@ import { iconHTML } from "discourse/lib/icon-library";import { postUrl } from "discourse/lib/utilities";import { i18n } from "discourse-i18n";+// TODO (glimmer-post-stream): investigate whether all this complex logic can be replaced with a proper Glimmer componentexport default function (element, context) {const { state } = context;diff --git a/app/assets/javascripts/discourse/app/lib/tracked-tools.js b/app/assets/javascripts/discourse/app/lib/tracked-tools.jsindex 503c915982c..d6de667068b 100644--- a/app/assets/javascripts/discourse/app/lib/tracked-tools.js+++ b/app/assets/javascripts/discourse/app/lib/tracked-tools.js@@ -1,6 +1,6 @@import { tracked } from "@glimmer/tracking";import { next } from "@ember/runloop";-import { TrackedSet } from "@ember-compat/tracked-built-ins";+import { TrackedArray, TrackedSet } from "@ember-compat/tracked-built-ins";/*** Define a tracked property on an object without needing to use the @tracked decorator.@@ -176,3 +176,61 @@ export class DeferredTrackedSet {next(() => this.#set.clear());}}++/**+ * Converts a value to TrackedArray if needed and validates the type+ *+ * @param {*} value - Value to convert+ * @returns {TrackedArray|null} Converted value+ * @throws {Error} If value is not an array, TrackedArray, or null+ */+function ensureTrackedArray(value) {+ if (value === null) {+ return null;+ }++ if (value instanceof TrackedArray) {+ return value;+ }++ if (Array.isArray(value)) {+ return new TrackedArray(value);+ }++ throw new Error(`Expected an array or TrackedArray, got ${typeof value}`);+}++/**+ * @decorator+ * Same as @tracked, but initializes the value as a TrackedArray.+ *+ * @param {Object} target - The target object+ * @param {string|Symbol} key - The property key+ * @param {Object} desc - The property descriptor+ * @returns {Object} Modified property descriptor that wraps arrays in TrackedArray+ *+ * @example+ * class TodoList {+ * @trackedArray todos = ['Buy milk', 'Walk dog'];+ * }+ */+export function trackedArray(target, key, desc) {+ if (desc.initializer) {+ const originalInitializer = desc.initializer;+ desc.initializer = function () {+ const initialValue = originalInitializer.apply(this);+ return ensureTrackedArray(initialValue);+ };+ }++ const { get, set } = tracked(target, key, desc);++ return {+ get() {+ return get.call(this);+ },+ set(value) {+ set.call(this, ensureTrackedArray(value));+ },+ };+}diff --git a/app/assets/javascripts/discourse/app/models/composer.js b/app/assets/javascripts/discourse/app/models/composer.jsindex 1da2afc1601..c597a7cf8de 100644--- a/app/assets/javascripts/discourse/app/models/composer.js+++ b/app/assets/javascripts/discourse/app/models/composer.js@@ -1113,6 +1113,7 @@ export default class Composer extends RestModel {const cooked = this.getCookedHtml();post.setProperties({ cooked, staged: true });+ // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this eventthis.appEvents.trigger("post-stream:refresh", { id: post.id });return promise@@ -1125,6 +1126,7 @@ export default class Composer extends RestModel {.catch(rollback).finally(() => {post.set("staged", false);+ // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this eventthis.appEvents.trigger("post-stream:refresh", { id: post.id });});}diff --git a/app/assets/javascripts/discourse/app/models/post-stream.js b/app/assets/javascripts/discourse/app/models/post-stream.jsindex 0aa0dc7e6e0..ea744a60891 100644--- a/app/assets/javascripts/discourse/app/models/post-stream.js+++ b/app/assets/javascripts/discourse/app/models/post-stream.js@@ -1,8 +1,10 @@+import { tracked } from "@glimmer/tracking";import { get } from "@ember/object";import { and, equal, not, or } from "@ember/object/computed";import { schedule } from "@ember/runloop";import { service } from "@ember/service";import { isEmpty } from "@ember/utils";+import { TrackedObject } from "@ember-compat/tracked-built-ins";import { Promise } from "rsvp";import { ajax } from "discourse/lib/ajax";import discourseComputed from "discourse/lib/decorators";@@ -36,21 +38,22 @@ export default class PostStream extends RestModel {@service currentUser;@service store;- posts = null;- stream = null;- userFilters = null;- loaded = null;- loadingAbove = null;- loadingBelow = null;- loadingFilter = null;- loadingNearPost = null;- stagingPost = null;- postsWithPlaceholders = null;- timelineLookup = null;- filterRepliesToPostNumber = null;- filterUpwardsPostID = null;- filter = null;- lastId = null;+ @tracked filter;+ @tracked filterRepliesToPostNumber;+ @tracked filterUpwardsPostID;+ @tracked gaps;+ @tracked lastId;+ @tracked loaded;+ @tracked loadingAbove;+ @tracked loadingBelow;+ @tracked loadingFilter;+ @tracked loadingNearPost;+ @tracked postsWithPlaceholders;+ @tracked stagingPost;+ @tracked stream;+ @tracked timelineLookup;+ @tracked userFilters;+ @tracked posts;@or("loadingAbove", "loadingBelow", "loadingFilter", "stagingPost") loading;@not("loading") notLoading;@@ -281,6 +284,7 @@ export default class PostStream extends RestModel {? element.getBoundingClientRect().top: null;+ // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this eventthis.appEvents.trigger("post-stream:refresh");DiscourseURL.jumpToPost(postNumber, {@@ -301,6 +305,7 @@ export default class PostStream extends RestModel {post_id: postID,});return this.refresh({ refreshInPlace: true }).then(() => {+ // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this eventthis.appEvents.trigger("post-stream:refresh");if (this.posts && this.posts.length > 1) {@@ -435,6 +440,7 @@ export default class PostStream extends RestModel {}gapExpanded() {+ // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this eventthis.appEvents.trigger("post-stream:refresh");// resets the reply count in posts-filtered-notice@@ -1050,6 +1056,11 @@ export default class PostStream extends RestModel {delete postStreamData.posts;// Update our attributes+ const trackedGaps = {+ before: new TrackedObject(postStreamData.gaps?.before || {}),+ after: new TrackedObject(postStreamData.gaps?.after || {}),+ };+ postStreamData.gaps = trackedGaps;this.setProperties(postStreamData);}}diff --git a/app/assets/javascripts/discourse/app/models/post.js b/app/assets/javascripts/discourse/app/models/post.jsindex cad4e3c88f9..515136b0a45 100644--- a/app/assets/javascripts/discourse/app/models/post.js+++ b/app/assets/javascripts/discourse/app/models/post.js@@ -179,6 +179,7 @@ export default class Post extends RestModel {@trackedPostProperty expandedExcerpt;@trackedPostProperty group_moderator;@trackedPostProperty hidden;+ @trackedPostProperty id;@trackedPostProperty is_auto_generated;@trackedPostProperty last_wiki_edit;@trackedPostProperty likeAction;@@ -195,6 +196,7 @@ export default class Post extends RestModel {@trackedPostProperty reply_count;@trackedPostProperty reply_to_user;@trackedPostProperty staff;+ @trackedPostProperty staged;@trackedPostProperty title_is_group;@trackedPostProperty trust_level;@trackedPostProperty updated_at;@@ -642,6 +644,7 @@ export default class Post extends RestModel {target: "post",targetId: this.id,});+ // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this eventthis.appEvents.trigger("post-stream:refresh", { id: this.id });}diff --git a/app/assets/javascripts/discourse/app/modifiers/observe-intersection.js b/app/assets/javascripts/discourse/app/modifiers/observe-intersection.jsindex 6fdc851de38..9d0f277b673 100644--- a/app/assets/javascripts/discourse/app/modifiers/observe-intersection.js+++ b/app/assets/javascripts/discourse/app/modifiers/observe-intersection.js@@ -6,7 +6,13 @@ export default modifier([callback],{ threshold = 1, rootMargin = "0px 0px 0px 0px", root = null }) => {- const rootElement = root ? document.querySelector(root) : null;+ if (Array.isArray(rootMargin)) {+ rootMargin = rootMargin+ .map((margin) => (typeof margin === "number" ? `${margin}px` : margin))+ .join(" ");+ }++ const rootElement = root ? document.querySelector(root) : document;const observer = new IntersectionObserver((entries) => {diff --git a/app/assets/javascripts/discourse/app/modifiers/post-stream-viewport-tracker.js b/app/assets/javascripts/discourse/app/modifiers/post-stream-viewport-tracker.jsnew file mode 100644index 00000000000..dc7588a247d--- /dev/null+++ b/app/assets/javascripts/discourse/app/modifiers/post-stream-viewport-tracker.js@@ -0,0 +1,811 @@+import { schedule } from "@ember/runloop";+import { htmlSafe } from "@ember/template";+import { modifier } from "ember-modifier";+import discourseDebounce from "discourse/lib/debounce";+import { bind } from "discourse/lib/decorators";+import DiscourseURL from "discourse/lib/url";++/**+ * PostStreamViewportTracker+ * -----------------------+ *+ * This class implements a performance optimization system for the post stream by+ * tracking which posts are visible on screen and implementing a "cloaking" mechanism+ * that hides posts far from the viewport.+ *+ * How Cloaking Works:+ * -------------------+ * 1. Intersection Observers track which posts are visible in the viewport+ * 2. Posts that are far from the viewport (beyond the cloakOffset) are "cloaked"+ * 3. Cloaked posts are replaced with placeholder divs of the same height+ * 4. As the user scrolls, posts are dynamically uncloaked when they approach the viewport+ * 5. This significantly reduces DOM nodes and improves performance for long topics+ *+ * The system also tracks the current post being viewed using an "eyeline" - a+ * calculated position in the viewport that determines which post is considered current+ * and the percentage of the current post that is scrolled.+ */++// Debounce time for resize events in milliseconds+const RESIZE_DEBOUNCE_MS = 100;++// Debounce time for batching scroll events in milliseconds+const SCROLL_BATCH_INTERVAL_MS = 10;++// Factor to determine how far beyond viewport to keep posts uncloaked.+// A lower number implies that fewer posts are uncloaked at any given time, and as a consequence, the users will notice+// posts uncloaking more frequently as they scroll. On the other hand, big jumps will be rendered fast.+// A higher number implies that there will be more posts uncloaked. That reduces the frequency which users will notice+// uncloaking while scrolling. However, big jumps will need to rerender many posts, and that will be noticeable with the+// system feeling sluggish.+const SLACK_FACTOR = 1;++// Set to true to visualize the eyeline position with a red line+const DEBUG_EYELINE = false;++// Global flag to enable/disable the cloaking mechanism+let cloakingEnabled = true;++/**+ * Globally disables the cloaking mechanism for all posts+ *+ * USE ONLY FOR TESTING PURPOSES.+ */+export function disableCloaking() {+ cloakingEnabled = false;+}++// Dictionary containing the set of post IDs that should never be cloaked.+// The topicId is used to clear the set when the topic changes.+const cloakingPrevented = { topicId: null, posts: new Set() };++/**+ * Prevents a specific post from being cloaked+ * Useful for posts that need to remain visible regardless of scroll position because removing+ * the DOM nodes can cause side effects, e.g., a video playing+ *+ * @param {number} postId - The ID of the post to prevent from cloaking+ */+export function preventCloaking(postId, prevent = true) {+ if (prevent) {+ cloakingPrevented.posts.add(postId);+ } else {+ cloakingPrevented.posts.delete(postId);+ }+}++/**+ * A WeakMap storing post models for DOM elements.+ * Maps elements in the post stream to their corresponding post.+ * Uses WeakMap to avoid memory leaks when elements are removed.+ *+ * @type {WeakMap<HTMLElement, Object>}+ */+const elementsToPost = new WeakMap();++export default class PostStreamViewportTracker {+ /**+ * Reference to the bottom boundary element used for eyeline calculations+ * @type {HTMLElement}+ */+ #bottomBoundaryElement;++ /**+ * Distance beyond viewport to keep posts uncloaked (calculated from viewport height)+ * @type {number}+ */+ #cloakOffset;++ /**+ * Map of post IDs to their heights when cloaked+ * Used to maintain correct scroll position when posts are cloaked+ * @type {Object<number, number>}+ */+ #cloakedPostsHeight = {};++ /**+ * IntersectionObserver that tracks which posts should be cloaked/uncloaked+ * @type {IntersectionObserver}+ */+ #cloakingObserver;++ /**+ * Callback function to notify when the current post changes+ * @type {Function}+ */+ #currentPostChanged;++ /**+ * Reference to the DOM element of the current post being viewed+ * @type {HTMLElement}+ */+ #currentPostElement;++ /**+ * Callback function to notify when the scroll position within the current post changes+ * @type {Function}+ */+ #currentPostScrolled;++ /**+ * Debug element used to visualize the eyeline position+ * @type {HTMLElement}+ */+ #eyelineDebugElement;++ /**+ * Offset from the top of the viewport for the site header+ * Used in calculations to determine visible posts+ * @type {number}+ */+ #headerOffset;++ /**+ * Set of posts' DOM nodes being observed by the intersection observers+ * @type {Set<HTMLElement>}+ */+ #observedPostElements = new Set();++ /**+ * Map of post numbers to their post models and DOM elements that are currently on screen+ * Used to track which posts are visible in the viewport for eyeline calculations and screen tracking+ * @type {Object<number, {post: Object, element: HTMLElement}>}+ */+ #postsOnScreen = {};++ /**+ * Reference to the screen track service for tracking post visibility+ * @type {Object}+ */+ #screenTrackService;++ /**+ * Callback function to update the cloaking boundaries in the parent component+ * @type {Function}+ */+ #setCloakingBoundaries;++ /**+ * Set of post numbers that are currently uncloaked (visible or near viewport)+ * @type {Set<number>}+ */+ #uncloakedPostNumbers = new Set();++ /**+ * IntersectionObserver that tracks which posts are visible in the viewport+ * @type {IntersectionObserver}+ */+ #viewportObserver;++ /**+ * Reference to the wrapper element containing all posts+ * @type {HTMLElement}+ */+ #wrapperElement;++ /**+ * Ember modifier that registers the bottom boundary element for eyeline calculations+ * This element marks the end of the post stream and is used to determine the eyeline position+ *+ * @type {Modifier}+ * @param {HTMLElement} element - The element to register as the bottom boundary+ * @param {Array} _ - Modifier positional params (unused)+ * @param {Object} trackedArgs - Additional tracked arguments that trigger cleanup when changed+ * @returns {Function} Cleanup function that removes the reference when the element is destroyed+ */+ #registerBottomBoundary = modifier((element, _, trackedArgs) => {+ this.#bottomBoundaryElement = element;++ // Consume the remaining properties to track them and run the cleanup functions when their values change+ // https://github.com/emberjs/ember.js/issues/19277+ trackedArgs && Object.values(trackedArgs);++ // clean-up+ return () => {+ this.#bottomBoundaryElement = null;+ };+ });++ /**+ * Ember modifier that registers a post element for tracking+ * Attaches the post model to the element and adds it to the intersection observers+ *+ * @type {Modifier}+ * @param {HTMLElement} element - The post element to register+ * @param {Array} [post] - The post model associated with the element+ * @returns {Function} Cleanup function that removes observers when the element is destroyed+ */+ #registerPost = modifier((element, [post]) => {+ elementsToPost.set(element, post);++ if (!this.#observedPostElements.has(element)) {+ this.#observedPostElements.add(element);+ this.#cloakingObserver?.observe(element);+ this.#viewportObserver?.observe(element);+ }++ // clean-up+ return () => {+ elementsToPost.delete(element);++ if (this.#observedPostElements.has(element)) {+ this.#observedPostElements.delete(element);+ this.#cloakingObserver?.unobserve(element);+ this.#viewportObserver?.unobserve(element);+ }+ };+ });++ /**+ * Main setup modifier that initializes the scroll tracker+ * Sets up event listeners, intersection observers, and initializes tracking+ *+ * @type {Modifier}+ * @param {HTMLElement} element - The wrapper element containing all posts+ * @param {Array} _ - Modifier positional params (unused)+ * @param {Object} options - Named arguments for the modifier+ * @param {Function} options.currentPostChanged - Callback when current post changes+ * @param {Function} options.currentPostScrolled - Callback when scroll position within current post changes+ * @param {number} options.headerOffset - Offset from top of viewport for site header+ * @param {Object} options.screenTrack - Screen tracking service+ * @param {Function} options.setCloakingBoundaries - Callback to update cloaking boundaries+ * @param {Object} options.trackedArgs - Additional tracked arguments that trigger cleanup when changed+ * @returns {Function} Cleanup function that removes observers, event listeners and clears state+ */+ #setup = modifier(+ (+ element,+ _,+ {+ currentPostChanged,+ currentPostScrolled,+ headerOffset,+ screenTrack,+ setCloakingBoundaries,+ topicId,+ ...trackedArgs+ }+ ) => {+ this.#wrapperElement = element;++ this.#currentPostChanged = currentPostChanged;+ this.#currentPostScrolled = currentPostScrolled;+ this.#headerOffset = headerOffset;+ this.#screenTrackService = screenTrack;+ this.#setCloakingBoundaries = setCloakingBoundaries;++ this.#updateCloakOffset();+ this.#setupEventListeners();++ // intersection observers+ this.#resetViewportObservers();+ // eyeline+ this.#setupEyelineDebugElement();++ // clear the list of posts with cloaking prevented when the topic changes+ if (cloakingPrevented.topicId !== topicId) {+ cloakingPrevented.topicId = topicId;+ cloakingPrevented.posts.clear();+ }++ // consume the remaining properties to track them and run the cleanup functions when their values change+ // https://github.com/emberjs/ember.js/issues/19277+ trackedArgs && Object.values(trackedArgs);++ schedule("afterRender", () => {+ // forces updates performed when the scroll is triggered+ this.#scrollTriggered();+ });++ // cleanup+ return () => {+ // clear observers+ this.#cloakingObserver?.disconnect();+ this.#viewportObserver?.disconnect();++ // clear event listeners+ this.#setupEventListeners(false);+ // remove the eyeline debug element+ this.#setupEyelineDebugElement(false);++ // clear collections+ this.#cloakedPostsHeight = {};+ this.#postsOnScreen = {};+ this.#uncloakedPostNumbers.clear();++ // clear instance properties+ this.#currentPostElement = null;+ };+ }+ );++ /**+ * Cleans up resources when the tracker is destroyed+ * Disconnects intersection observers and clears DOM references+ */+ destroy() {+ // disconnect the intersection observers+ this.#viewportObserver?.disconnect();+ this.#cloakingObserver?.disconnect();++ // clear DOM references+ this.#observedPostElements.clear();++ // clear the set of posts with cloaking prevented+ cloakingPrevented.topicId = null;+ cloakingPrevented.posts.clear();+ }++ /**+ * Returns a map of post numbers to their post models and DOM elements that are currently on screen+ * @returns {Object<number, {post: Object, element: HTMLElement}>}+ */+ get postsOnScreen() {+ return this.#postsOnScreen;+ }++ /**+ * Returns the modifier for registering the bottom boundary element+ * @returns {Modifier}+ */+ get registerBottomBoundary() {+ return this.#registerBottomBoundary;+ }++ /**+ * Returns the modifier for registering post elements+ * @returns {Modifier}+ */+ get registerPost() {+ return this.#registerPost;+ }++ /**+ * Returns the main setup modifier+ * @returns {Modifier}+ */+ get setup() {+ return this.#setup;+ }++ /**+ * Determines if a post should be cloaked based on its position relative to the viewport boundaries+ * Returns an object containing cloaking state and optional height style when cloaking is active+ *+ * @param {Object} post - The post model+ * @param {Object} options - Cloaking boundary options+ * @param {number} options.above - The minimum post number to keep visible+ * @param {number} options.below - The maximum post number to keep visible+ * @returns {Object} Object with active boolean and optional style string+ * {active: boolean, style?: string}+ */+ @bind+ getCloakingData(post, { above, below }) {+ if (!cloakingEnabled || !post || cloakingPrevented.posts.has(post.id)) {+ return { active: false };+ }++ const height = this.#cloakedPostsHeight[post.id];++ return height && (post.post_number < above || post.post_number > below)+ ? { active: true, style: htmlSafe("height: " + height + "px;") }+ : { active: false };+ }++ /**+ * Intersection observer callback for tracking which posts should be cloaked+ * Updates the cloaking state based on post visibility+ *+ * @param {IntersectionObserverEntry} entry - The intersection observer entry+ */+ @bind+ trackCloakedPosts(entry) {+ const { target, isIntersecting } = entry;+ const post = elementsToPost.get(target);++ if (!post) {+ return;+ }++ const postNumber = post.post_number;++ if (isIntersecting) {+ // entering the visibility area+ this.#uncloakedPostNumbers.add(postNumber);+ delete this.#cloakedPostsHeight[post.id];+ } else {+ // entering the cloaking area+ this.#uncloakedPostNumbers.delete(postNumber);++ // saves the current post height to prevent jumps while scrolling with existing cloaked posts+ this.#cloakedPostsHeight[post.id] = target.offsetHeight;+ }++ // update the cloaking boundaries+ discourseDebounce(+ this,+ this.#updateCloakBoundaries,+ SCROLL_BATCH_INTERVAL_MS+ );+ }++ /**+ * Intersection observer callback for tracking which posts are visible in the viewport+ * Updates the postsOnScreen map, triggers screen tracking updates, and calls the scroll handler+ * to update the current post and eyeline position+ *+ * @param {IntersectionObserverEntry} entry - The intersection observer entry+ */+ @bind+ trackVisiblePosts(entry) {+ const { target, isIntersecting } = entry;+ const post = elementsToPost.get(target);++ if (isIntersecting) {+ // entered the viewport+ this.#postsOnScreen[post.post_number] = { post, element: target };+ } else {+ // exited the viewport+ delete this.#postsOnScreen[post.post_number];+ }++ // update the screen tracking information+ discourseDebounce(+ this,+ this.#updateScreenTracking,+ SCROLL_BATCH_INTERVAL_MS+ );++ // forces updates performed when the scroll is triggered+ this.#scrollTriggered();+ }++ /**+ * Event handler for scroll events+ * Debounces scroll events to avoid performance issues+ */+ @bind+ onScroll() {+ discourseDebounce(this, this.#scrollTriggered, SCROLL_BATCH_INTERVAL_MS);+ }++ /**+ * Event handler for window resize events+ * Debounces resize events and updates cloaking boundaries+ *+ * @param {Event} event - The resize event+ */+ @bind+ onWindowResize(event) {+ discourseDebounce(+ this,+ this.#windowResizeTriggered,+ event,+ RESIZE_DEBOUNCE_MS+ );+ }++ /**+ * Calculates the position of the "eyeline" - the horizontal line in the viewport+ * that determines which post is considered the current post+ *+ * The eyeline position is dynamically calculated based on scroll position and+ * moves from the top of the viewport (when at the beginning of the topic)+ * to the bottom of the viewport (when at the end of the topic)+ *+ * @returns {number} The vertical offset of the eyeline in viewport coordinates+ */+ #calculateEyelineViewportOffset() {+ // Get viewport and scroll data+ const viewportHeight = window.innerHeight;+ const scrollPosition = window.scrollY;+ const documentHeight = Math.max(+ document.body.scrollHeight,+ document.documentElement.scrollHeight+ );++ // Calculate boundaries+ const topBoundary = Math.max(+ this.#headerOffset,+ this.#wrapperElement.getBoundingClientRect().top+ );+ const bottomBoundary =+ this.#bottomBoundaryElement?.getBoundingClientRect()?.top ??+ viewportHeight;++ // Calculate distance from topic bottom to document bottom+ const topicBottomAbsolute = bottomBoundary + scrollPosition;+ const distanceToBottom = documentHeight - topicBottomAbsolute;++ // Calculate scroll area and progress+ const scrollableArea = Math.min(+ viewportHeight,+ distanceToBottom,+ documentHeight - viewportHeight+ );+ const remainingScroll = documentHeight - viewportHeight - scrollPosition;+ const progress =+ scrollableArea > 0+ ? 1 - Math.min(1, Math.max(0, remainingScroll / scrollableArea))+ : 1;++ // Return interpolated position between boundaries based on progress+ return topBoundary + progress * (bottomBoundary - topBoundary);+ }++ /**+ * Notifies the parent component that the current post has changed+ *+ * @param {Object} event - Event data containing the new current post+ */+ #currentPostWasChanged(event) {+ this.#currentPostChanged(event);+ }++ /**+ * Notifies the parent component about scroll position changes within the current post+ * Only triggers if the element matches the current post element+ *+ * @param {Object} params - Parameters containing element and scroll data+ * @param {HTMLElement} params.element - The post element+ */+ #currentPostWasScrolled({ element, ...event }) {+ if (element !== this.#currentPostElement) {+ return;+ }++ this.#currentPostScrolled(event);+ }++ /**+ * Finds the post that contains the eyeline position and updates the current post+ * Also calculates the percentage scrolled within that post+ *+ * @param {number} eyeLineOffset - The vertical position of the eyeline+ */+ #findPostMatchingEyeline(eyeLineOffset) {+ let target, percentScrolled;+ for (const { element } of Object.values(this.#postsOnScreen)) {+ const { top, bottom } = element.getBoundingClientRect();++ if (eyeLineOffset >= top && eyeLineOffset <= bottom) {+ target = element;+ percentScrolled = (eyeLineOffset - top) / (bottom - top);+ break;+ }+ }++ if (target) {+ this.#updateCurrentPost(target);+ this.#currentPostWasScrolled({+ element: target,+ percent: percentScrolled,+ });+ }+ }++ /**+ * Creates a new IntersectionObserver with the specified callback and options+ *+ * @param {Function} callback - The function to call when intersection changes+ * @param {Object} options - Observer configuration options+ * @param {string} options.rootMargin - Margin around the root element+ * @param {Array<number>} options.threshold - Intersection thresholds+ * @returns {IntersectionObserver} The initialized observer+ */+ #initializeObserver(callback, { rootMargin, threshold }) {+ return new IntersectionObserver(+ (entries) => {+ entries.forEach(callback);+ },+ // Explicitly specifying the root as `document` is important.+ // Otherwise, the root margin won't be respected correctly+ { threshold, rootMargin, root: document }+ );+ }++ /**+ * Resets and reinitializes the viewport observers+ * Creates two observers:+ * 1. cloakingObserver - tracks which posts should be cloaked/uncloaked+ * 2. viewportObserver - tracks which posts are visible in the viewport+ */+ #resetViewportObservers() {+ this.#cloakingObserver?.disconnect();+ this.#viewportObserver?.disconnect();++ const headerMargin = this.#headerOffset * -1;++ this.#cloakingObserver = this.#initializeObserver(this.trackCloakedPosts, {+ rootMargin: `${this.#cloakOffset}px 0px`,+ threshold: [0, 1],+ });+ this.#viewportObserver = this.#initializeObserver(this.trackVisiblePosts, {+ rootMargin: `${headerMargin}px 0px 0px 0px`,+ threshold: [0, 1],+ });++ for (const element of this.#observedPostElements) {+ this.#cloakingObserver.observe(element);+ this.#viewportObserver.observe(element);+ }+ }++ /**+ * Sets up or removes event listeners for scroll and resize events+ * Also handles page show events for back-forward cache+ *+ * @param {boolean} addListeners - Whether to add (true) or remove (false) listeners+ */+ #setupEventListeners(addListeners = true) {+ if (!addListeners) {+ window.removeEventListener("resize", this.onWindowResize);+ window.removeEventListener("scroll", this.onScroll);++ window.onpageshow = null;++ return;+ }++ const opts = {+ passive: true,+ };++ window.addEventListener("resize", this.onWindowResize, opts);+ window.addEventListener("scroll", this.onScroll, opts);++ // restore scroll position on browsers with aggressive BFCaches (like Safari)+ window.onpageshow = function (event) {+ if (event.persisted) {+ DiscourseURL.routeTo(this.location.pathname);+ }+ };+ }++ /**+ * Creates or removes the debug element that visualizes the eyeline position+ * Only active when DEBUG_EYELINE is true+ *+ * @param {boolean} addElement - Whether to add (true) or remove (false) the debug element+ */+ #setupEyelineDebugElement(addElement = true) {+ if (DEBUG_EYELINE) {+ if (!addElement) {+ this.#eyelineDebugElement.remove();++ return;+ }++ this.#eyelineDebugElement = document.createElement("div");+ this.#eyelineDebugElement.classList.add("post-stream__bottom-eyeline");+ document.body.prepend(this.#eyelineDebugElement);+ }+ }++ /**+ * Handles scroll events by calculating the new eyeline position+ * and finding the post that matches that position+ * Also updates the debug element if enabled+ */+ #scrollTriggered() {+ const eyelineOffset = this.#calculateEyelineViewportOffset();++ discourseDebounce(+ this,+ this.#findPostMatchingEyeline,+ eyelineOffset,+ SCROLL_BATCH_INTERVAL_MS+ );++ if (DEBUG_EYELINE) {+ this.#updateEyelineDebugElementPosition(eyelineOffset);+ }+ }++ /**+ * Updates the cloaking boundaries based on which posts are currently uncloaked+ * Finds the minimum and maximum post numbers that should remain uncloaked+ * and notifies the parent component+ */+ #updateCloakBoundaries() {+ const uncloakedPostNumbers = Array.from(this.#uncloakedPostNumbers);++ let above = uncloakedPostNumbers[0] || 0;+ let below = above;++ for (let i = 1; i < uncloakedPostNumbers.length; i++) {+ const postNumber = uncloakedPostNumbers[i];+ above = Math.min(postNumber, above);+ below = Math.max(postNumber, below);+ }++ this.#setCloakingBoundaries(above, below);+ }++ /**+ * Updates the cloak offset based on the current viewport height+ * The cloak offset determines how far beyond the viewport posts remain uncloaked+ *+ * @returns {boolean} Whether the offset was changed+ */+ #updateCloakOffset() {+ const newOffset = Math.ceil(window.innerHeight * SLACK_FACTOR);++ if (newOffset === this.#cloakOffset) {+ return false;+ }++ this.#cloakOffset = newOffset;+ return true;+ }++ /**+ * Updates the current post element reference and notifies the parent component+ * if the post model has changed+ *+ * @param {HTMLElement} newElement - The new post element to set as current+ */+ #updateCurrentPost(newElement) {+ if (this.#currentPostElement === newElement) {+ return;+ }++ const currentPost =+ this.#currentPostElement && elementsToPost.get(this.#currentPostElement);+ const newPost = newElement && elementsToPost.get(newElement);++ this.#currentPostElement = newElement;++ if (currentPost !== newPost) {+ this.#currentPostWasChanged({ post: newPost });+ }+ }++ /**+ * Updates the screen tracking service with the list of posts currently on screen+ * Separates posts into all visible posts and read posts+ */+ #updateScreenTracking() {+ const onScreenPostsNumbers = [];+ const readPostNumbers = [];++ Object.values(this.#postsOnScreen).forEach(({ post }) => {+ onScreenPostsNumbers.push(post.post_number);++ if (post.read) {+ readPostNumbers.push(post.post_number);+ }+ });++ this.#screenTrackService.setOnscreen(onScreenPostsNumbers, readPostNumbers);+ }++ /**+ * Handles window resize events by updating the cloak offset+ * and resetting the viewport observers if needed+ */+ #windowResizeTriggered() {+ if (this.#updateCloakOffset()) {+ this.#resetViewportObservers();+ }+ }++ /**+ * Updates the position of the eyeline debug element+ * Only used when DEBUG_EYELINE is true+ *+ * @param {number} viewportOffset - The vertical position for the eyeline+ */+ #updateEyelineDebugElementPosition(viewportOffset) {+ if (this.#eyelineDebugElement) {+ Object.assign(this.#eyelineDebugElement.style, {+ position: "fixed",+ top: `${viewportOffset}px`,+ width: "100%",+ border: "1px solid red",+ opacity: 1,+ zIndex: 999999,+ });+ }+ }+}diff --git a/app/assets/javascripts/discourse/app/modifiers/sticky-avatars.js b/app/assets/javascripts/discourse/app/modifiers/sticky-avatars.jsdeleted file mode 100644index edb9a7d3eeb..00000000000--- a/app/assets/javascripts/discourse/app/modifiers/sticky-avatars.js+++ /dev/null@@ -1,120 +0,0 @@-import { registerDestructor } from "@ember/destroyable";-import { schedule } from "@ember/runloop";-import { service } from "@ember/service";-import Modifier from "ember-modifier";-import {- addWidgetCleanCallback,- removeWidgetCleanCallback,-} from "discourse/components/mount-widget";-import { bind } from "discourse/lib/decorators";-import { headerOffset } from "discourse/lib/offset-calculator";--const STICKY_CLASS = "sticky-avatar";-const TOPIC_POST_SELECTOR = ".post-stream .topic-post";--export default class StickyAvatars extends Modifier {- @service site;- @service appEvents;-- element;- intersectionObserver;-- constructor() {- super(...arguments);- registerDestructor(this, (instance) => instance.cleanup());- }-- modify(element) {- if (this.site.mobileView || !("IntersectionObserver" in window)) {- return;- }-- this.element = element;-- this.appEvents.on(- "topic:current-post-scrolled",- this,- this._handlePostNodes- );- this.appEvents.on("topic:scrolled", this, this._handleScroll);- this.appEvents.on(- "page:topic-loaded",- this,- this._initIntersectionObserver- );-- addWidgetCleanCallback("post-stream", this._clearIntersectionObserver);- }-- cleanup() {- if (this.site.mobileView || !("IntersectionObserver" in window)) {- return;- }-- this.appEvents.off(- "topic:current-post-scrolled",- this,- this._handlePostNodes- );- this.appEvents.off("topic:scrolled", this, this._handleScroll);- this.appEvents.off(- "page:topic-loaded",- this,- this._initIntersectionObserver- );-- removeWidgetCleanCallback("post-stream", this._clearIntersectionObserver);- }-- @bind- _handleScroll(offset) {- if (offset <= 0) {- this.element- .querySelectorAll(`${TOPIC_POST_SELECTOR}.${STICKY_CLASS}`)- .forEach((node) => node.classList.remove(STICKY_CLASS));- }- }-- @bind- _handlePostNodes() {- this._clearIntersectionObserver();- this._initIntersectionObserver();-- schedule("afterRender", () => {- this.element.querySelectorAll(TOPIC_POST_SELECTOR).forEach((postNode) => {- this.intersectionObserver.observe(postNode);- });- });- }-- @bind- _initIntersectionObserver() {- schedule("afterRender", () => {- const offset = headerOffset();- const headerOffsetInPx = offset <= 0 ? "0px" : `-${offset}px`;-- this.intersectionObserver = new IntersectionObserver(- (entries) => {- entries.forEach((entry) => {- if (!entry.isIntersecting || entry.intersectionRatio === 1) {- entry.target.classList.remove(STICKY_CLASS);- return;- }-- entry.target.classList.add(STICKY_CLASS);- });- },- {- threshold: [0.0, 1.0],- rootMargin: `${headerOffsetInPx} 0px 0px 0px`,- }- );- });- }-- @bind- _clearIntersectionObserver() {- this.intersectionObserver?.disconnect();- this.intersectionObserver = null;- }-}diff --git a/app/assets/javascripts/discourse/app/services/composer.js b/app/assets/javascripts/discourse/app/services/composer.jsindex 67b614fac90..ecdc0ab2d0b 100644--- a/app/assets/javascripts/discourse/app/services/composer.js+++ b/app/assets/javascripts/discourse/app/services/composer.js@@ -1192,6 +1192,7 @@ export default class ComposerService extends Service {return this.destroyDraft().then(() => {this.close();+ // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this eventthis.appEvents.trigger("post-stream:refresh");return result;});@@ -1199,6 +1200,7 @@ export default class ComposerService extends Service {if (this.get("model.editingPost")) {this.appEvents.trigger("composer:edited-post");+ // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this eventthis.appEvents.trigger("post-stream:refresh", {id: parseInt(result.responseJson.id, 10),});@@ -1206,6 +1208,7 @@ export default class ComposerService extends Service {this.appEvents.trigger("header:update-topic", composer.topic);}} else {+ // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this eventthis.appEvents.trigger("post-stream:refresh");}@@ -1272,6 +1275,7 @@ export default class ComposerService extends Service {staged = composer.get("stagedPost");}+ // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this eventthis.appEvents.trigger("post-stream:posted", staged);this.messageBus.pause();diff --git a/app/assets/javascripts/discourse/app/services/header.js b/app/assets/javascripts/discourse/app/services/header.jsindex 8f301239c80..bba03d62a94 100644--- a/app/assets/javascripts/discourse/app/services/header.js+++ b/app/assets/javascripts/discourse/app/services/header.js@@ -15,6 +15,9 @@ export default class Header extends Service {@service scrollDirection;@service site;+ @tracked headerOffset = 0;+ @tracked mainOutletOffset = 0;+/*** The topic currently viewed on the page.*diff --git a/app/assets/javascripts/discourse/app/templates/topic.gjs b/app/assets/javascripts/discourse/app/templates/topic.gjsindex 3302691fd36..f4931c2c315 100644--- a/app/assets/javascripts/discourse/app/templates/topic.gjs+++ b/app/assets/javascripts/discourse/app/templates/topic.gjs@@ -14,6 +14,7 @@ import DiscourseBanner from "discourse/components/discourse-banner";import DiscourseTopic from "discourse/components/discourse-topic";import MoreTopics from "discourse/components/more-topics";import PluginOutlet from "discourse/components/plugin-outlet";+import PostStream from "discourse/components/post-stream";import PostTextSelection from "discourse/components/post-text-selection";import PrivateMessageGlyph from "discourse/components/private-message-glyph";import ReviewableCreatedBy from "discourse/components/reviewable-created-by";@@ -43,7 +44,6 @@ import htmlSafe from "discourse/helpers/html-safe";import lazyHash from "discourse/helpers/lazy-hash";import routeAction from "discourse/helpers/route-action";import autoFocus from "discourse/modifiers/auto-focus";-import stickyAvatars from "discourse/modifiers/sticky-avatars";import { i18n } from "discourse-i18n";import CategoryChooser from "select-kit/components/category-chooser";import MiniTagChooser from "select-kit/components/mini-tag-chooser";@@ -57,7 +57,6 @@ export default RouteTemplate({{/let}}<DiscourseTopic- {{stickyAvatars}}@multiSelect={{@controller.multiSelect}}@enteredAt={{@controller.enteredAt}}@topic={{@controller.model}}@@ -431,80 +430,152 @@ export default RouteTemplate(data-topic-id={{@controller.model.id}}>- <div class="posts-wrapper">- <ConditionalLoadingSpinner- @condition={{@controller.model.postStream.loadingAbove}}- />-- <span>- <PluginOutlet- @name="topic-above-posts"- @connectorTagName="div"- @outletArgs={{lazyHash [email protected]}}+ {{#if @controller.site.useGlimmerPostStream}}+ <div class="posts-wrapper">+ <span>+ <PluginOutlet+ @name="topic-above-posts"+ @connectorTagName="div"+ @outletArgs={{lazyHash [email protected]}}+ />+ </span>++ {{#unless @controller.model.postStream.loadingFilter}}+ <PostStream+ @postStream={{@controller.model.postStream}}+ @posts={{@controller.postsToRender}}+ @canCreatePost={{@controller.model.details.can_create_post}}+ @multiSelect={{@controller.multiSelect}}+ @selectedPostsCount={{@controller.selectedPostsCount}}+ @filteredPostsCount={{@controller.model.postStream.filteredPostsCount}}+ @selectedQuery={{@controller.selectedQuery}}+ @gaps={{@controller.model.postStream.gaps}}+ @showReadIndicator={{@controller.model.show_read_indicator}}+ @streamFilters={{@controller.model.postStream.streamFilters}}+ @lastReadPostNumber={{@controller.userLastReadPostNumber}}+ @highestPostNumber={{@controller.highestPostNumber}}+ @showFlags={{@controller.showPostFlags}}+ @editPost={{@controller.editPost}}+ @showHistory={{routeAction "showHistory"}}+ @showLogin={{routeAction "showLogin"}}+ @showRawEmail={{routeAction "showRawEmail"}}+ @deletePost={{@controller.deletePost}}+ @permanentlyDeletePost={{@controller.permanentlyDeletePost}}+ @recoverPost={{@controller.recoverPost}}+ @expandHidden={{@controller.expandHidden}}+ @toggleBookmark={{@controller.toggleBookmark}}+ @togglePostType={{@controller.togglePostType}}+ @rebakePost={{@controller.rebakePost}}+ @changePostOwner={{@controller.changePostOwner}}+ @grantBadge={{@controller.grantBadge}}+ @changeNotice={{@controller.changeNotice}}+ @lockPost={{@controller.lockPost}}+ @unlockPost={{@controller.unlockPost}}+ @unhidePost={{@controller.unhidePost}}+ @replyToPost={{@controller.replyToPost}}+ @toggleWiki={{@controller.toggleWiki}}+ @showTopReplies={{@controller.showTopReplies}}+ @cancelFilter={{@controller.cancelFilter}}+ @removeAllowedUser={{@controller.removeAllowedUser}}+ @removeAllowedGroup={{@controller.removeAllowedGroup}}+ @topVisibleChanged={{@controller.topVisibleChanged}}+ @currentPostChanged={{@controller.currentPostChanged}}+ @currentPostScrolled={{@controller.currentPostScrolled}}+ @bottomVisibleChanged={{@controller.bottomVisibleChanged}}+ @togglePostSelection={{@controller.togglePostSelection}}+ @selectReplies={{@controller.selectReplies}}+ @selectBelow={{@controller.selectBelow}}+ @fillGapBefore={{@controller.fillGapBefore}}+ @fillGapAfter={{@controller.fillGapAfter}}+ @showInvite={{routeAction "showInvite"}}+ @showPagePublish={{routeAction "showPagePublish"}}+ @filteringRepliesToPostNumber={{@controller.replies_to_post_number}}+ @updateTopicPageQueryParams={{@controller.updateTopicPageQueryParams}}+ @postSelected={{@controller.postSelected}}+ @topicPageQueryParams={{getProperties+ @controller+ @controller.queryParams+ }}+ @topic={{@controller.model}}+ />+ {{/unless}}+ </div>+ {{else}}+ <div class="posts-wrapper">+ <ConditionalLoadingSpinner+ @condition={{@controller.model.postStream.loadingAbove}}/>- </span>- {{#unless @controller.model.postStream.loadingFilter}}- <ScrollingPostStream- @posts={{@controller.postsToRender}}- @canCreatePost={{@controller.model.details.can_create_post}}- @multiSelect={{@controller.multiSelect}}- @selectedPostsCount={{@controller.selectedPostsCount}}- @filteredPostsCount={{@controller.model.postStream.filteredPostsCount}}- @selectedQuery={{@controller.selectedQuery}}- @gaps={{@controller.model.postStream.gaps}}- @showReadIndicator={{@controller.model.show_read_indicator}}- @streamFilters={{@controller.model.postStream.streamFilters}}- @lastReadPostNumber={{@controller.userLastReadPostNumber}}- @highestPostNumber={{@controller.highestPostNumber}}- @showFlags={{@controller.showPostFlags}}- @editPost={{@controller.editPost}}- @showHistory={{routeAction "showHistory"}}- @showLogin={{routeAction "showLogin"}}- @showRawEmail={{routeAction "showRawEmail"}}- @deletePost={{@controller.deletePost}}- @permanentlyDeletePost={{@controller.permanentlyDeletePost}}- @recoverPost={{@controller.recoverPost}}- @expandHidden={{@controller.expandHidden}}- @toggleBookmark={{@controller.toggleBookmark}}- @togglePostType={{@controller.togglePostType}}- @rebakePost={{@controller.rebakePost}}- @changePostOwner={{@controller.changePostOwner}}- @grantBadge={{@controller.grantBadge}}- @changeNotice={{@controller.changeNotice}}- @lockPost={{@controller.lockPost}}- @unlockPost={{@controller.unlockPost}}- @unhidePost={{@controller.unhidePost}}- @replyToPost={{@controller.replyToPost}}- @toggleWiki={{@controller.toggleWiki}}- @showTopReplies={{@controller.showTopReplies}}- @cancelFilter={{@controller.cancelFilter}}- @removeAllowedUser={{@controller.removeAllowedUser}}- @removeAllowedGroup={{@controller.removeAllowedGroup}}- @topVisibleChanged={{@controller.topVisibleChanged}}- @currentPostChanged={{@controller.currentPostChanged}}- @currentPostScrolled={{@controller.currentPostScrolled}}- @bottomVisibleChanged={{@controller.bottomVisibleChanged}}- @togglePostSelection={{@controller.togglePostSelection}}- @selectReplies={{@controller.selectReplies}}- @selectBelow={{@controller.selectBelow}}- @fillGapBefore={{@controller.fillGapBefore}}- @fillGapAfter={{@controller.fillGapAfter}}- @showInvite={{routeAction "showInvite"}}- @showPagePublish={{routeAction "showPagePublish"}}- @filteringRepliesToPostNumber={{@controller.replies_to_post_number}}- @updateTopicPageQueryParams={{@controller.updateTopicPageQueryParams}}- @topicPageQueryParams={{getProperties- @controller- @controller.queryParams- }}- />- {{/unless}}+ <span>+ <PluginOutlet+ @name="topic-above-posts"+ @connectorTagName="div"+ @outletArgs={{lazyHash [email protected]}}+ />+ </span>++ {{#unless @controller.model.postStream.loadingFilter}}+ <ScrollingPostStream+ @posts={{@controller.postsToRender}}+ @canCreatePost={{@controller.model.details.can_create_post}}+ @multiSelect={{@controller.multiSelect}}+ @selectedPostsCount={{@controller.selectedPostsCount}}+ @filteredPostsCount={{@controller.model.postStream.filteredPostsCount}}+ @selectedQuery={{@controller.selectedQuery}}+ @gaps={{@controller.model.postStream.gaps}}+ @showReadIndicator={{@controller.model.show_read_indicator}}+ @streamFilters={{@controller.model.postStream.streamFilters}}+ @lastReadPostNumber={{@controller.userLastReadPostNumber}}+ @highestPostNumber={{@controller.highestPostNumber}}+ @showFlags={{@controller.showPostFlags}}+ @editPost={{@controller.editPost}}+ @showHistory={{routeAction "showHistory"}}+ @showLogin={{routeAction "showLogin"}}+ @showRawEmail={{routeAction "showRawEmail"}}+ @deletePost={{@controller.deletePost}}+ @permanentlyDeletePost={{@controller.permanentlyDeletePost}}+ @recoverPost={{@controller.recoverPost}}+ @expandHidden={{@controller.expandHidden}}+ @toggleBookmark={{@controller.toggleBookmark}}+ @togglePostType={{@controller.togglePostType}}+ @rebakePost={{@controller.rebakePost}}+ @changePostOwner={{@controller.changePostOwner}}+ @grantBadge={{@controller.grantBadge}}+ @changeNotice={{@controller.changeNotice}}+ @lockPost={{@controller.lockPost}}+ @unlockPost={{@controller.unlockPost}}+ @unhidePost={{@controller.unhidePost}}+ @replyToPost={{@controller.replyToPost}}+ @toggleWiki={{@controller.toggleWiki}}+ @showTopReplies={{@controller.showTopReplies}}+ @cancelFilter={{@controller.cancelFilter}}+ @removeAllowedUser={{@controller.removeAllowedUser}}+ @removeAllowedGroup={{@controller.removeAllowedGroup}}+ @topVisibleChanged={{@controller.topVisibleChanged}}+ @currentPostChanged={{@controller.currentPostChanged}}+ @currentPostScrolled={{@controller.currentPostScrolled}}+ @bottomVisibleChanged={{@controller.bottomVisibleChanged}}+ @togglePostSelection={{@controller.togglePostSelection}}+ @selectReplies={{@controller.selectReplies}}+ @selectBelow={{@controller.selectBelow}}+ @fillGapBefore={{@controller.fillGapBefore}}+ @fillGapAfter={{@controller.fillGapAfter}}+ @showInvite={{routeAction "showInvite"}}+ @showPagePublish={{routeAction "showPagePublish"}}+ @filteringRepliesToPostNumber={{@controller.replies_to_post_number}}+ @updateTopicPageQueryParams={{@controller.updateTopicPageQueryParams}}+ @topicPageQueryParams={{getProperties+ @controller+ @controller.queryParams+ }}+ />+ {{/unless}}- <ConditionalLoadingSpinner- @condition={{@controller.model.postStream.loadingBelow}}- />- </div>+ <ConditionalLoadingSpinner+ @condition={{@controller.model.postStream.loadingBelow}}+ />+ </div>+ {{/if}}<div id="topic-bottom"></div><ConditionalLoadingSpinnerdiff --git a/app/assets/javascripts/discourse/app/widgets/post-stream.js b/app/assets/javascripts/discourse/app/widgets/post-stream.jsindex c48f8a3608b..5429df90bb1 100644--- a/app/assets/javascripts/discourse/app/widgets/post-stream.js+++ b/app/assets/javascripts/discourse/app/widgets/post-stream.js@@ -1,9 +1,7 @@-import { getOwner } from "@ember/owner";import { hbs } from "ember-cli-htmlbars";import $ from "jquery";import { h } from "virtual-dom";import { addWidgetCleanCallback } from "discourse/components/mount-widget";-import PostPlaceholder from "discourse/components/post/placeholder";import discourseDebounce from "discourse/lib/debounce";import { registerDeprecationHandler } from "discourse/lib/deprecated";import { iconNode } from "discourse/lib/icon-library";@@ -216,11 +214,9 @@ createWidget("filter-show-all", {});export default createWidget("post-stream", {- tagName: "div.post-stream",+ tagName: "div.post-stream.widget-post-stream",html(attrs) {- getOwner(this).lookup("service:site").useGlimmerPostStream;-const posts = attrs.posts || [];const postArray = posts.toArray();const postArrayLength = postArray.length;@@ -238,13 +234,7 @@ export default createWidget("post-stream", {const post = postArray[i];if (post instanceof Placeholder) {- this.site.useGlimmerPostStream- ? new RenderGlimmer(- this,- "div.post-placeholder-shim",- PostPlaceholder- )- : result.push(this.attach("post-placeholder"));+ result.push(this.attach("post-placeholder"));continue;}@@ -278,26 +268,11 @@ export default createWidget("post-stream", {const beforeGap = before[post.id];if (beforeGap) {result.push(- this.site.useGlimmerPostStream- ? new RenderGlimmer(- this,- "div.post-gap-shim",- hbs`<Post::Gap @post={{@data.post}} @gap={{@data.gap}} @fillGap={{@data.fillGap}} />`,- {- post,- gap: beforeGap,- fillGap: () =>- this.sendWidgetAction("fillGapBefore", {- post,- gap: beforeGap,- }),- }- )- : this.attach(- "post-gap",- { pos: "before", postId: post.id, gap: beforeGap },- { model: post }- )+ this.attach(+ "post-gap",+ { pos: "before", postId: post.id, gap: beforeGap },+ { model: post }+ ));}@@ -325,116 +300,22 @@ export default createWidget("post-stream", {if (transformed.isSmallAction) {result.push(- this.site.useGlimmerPostStream- ? new RenderGlimmer(- this,- "div.post-small-action-shim",- hbs`<Post::SmallAction @post={{@data.post}}- @deletePost={{@data.deletePost}}- @editPost={{@data.editPost}}- @recoverPost={{@data.recoverPost}} />`,- {- post,- deletePost: () => this.sendWidgetAction("deletePost", post),- editPost: () => this.sendWidgetAction("editPost", post),- recoverPost: () => this.sendWidgetAction("recoverPost", post),- }- )- : this.attach("post-small-action", transformed, { model: post })+ this.attach("post-small-action", transformed, { model: post }));} else {- if (this.site.useGlimmerPostStream) {- let multiSelect, selected;- if (post.canManage || post.canSplitMergeTopic) {- multiSelect = attrs.multiSelect;-- if (multiSelect) {- selected = attrs.selectedQuery(post);- }- }-- result.push(- this.attach("glimmer-post", {- post,- prevPost,- nextPost,- canCreatePost: attrs.canCreatePost, //ok- cancelFilter: (nearestPost) =>- this.sendWidgetAction("cancelFilter", nearestPost),- changeNotice: () => this.sendWidgetAction("changeNotice", post),- changePostOwner: () =>- this.sendWidgetAction("changePostOwner", post),- deletePost: () => this.sendWidgetAction("deletePost", post),- editPost: () => this.sendWidgetAction("editPost", post),- expandHidden: () => this.sendWidgetAction("expandHidden", post),- filteringRepliesToPostNumber: attrs.filteringRepliesToPostNumber,- grantBadge: () => this.sendWidgetAction("grantBadge", post),- lockPost: () => this.sendWidgetAction("lockPost", post),- multiSelect,- permanentlyDeletePost: () =>- this.sendWidgetAction("permanentlyDeletePost", post),- rebakePost: () => this.sendWidgetAction("rebakePost", post),- recoverPost: () => this.sendWidgetAction("recoverPost", post),- removeAllowedGroup: () =>- this.sendWidgetAction("removeAllowedGroup", post),- removeAllowedUser: () =>- this.sendWidgetAction("removeAllowedUser", post),- replyToPost: () => this.sendWidgetAction("replyToPost", post),- selectBelow: () => this.sendWidgetAction("selectBelow", post),- selectReplies: () => this.sendWidgetAction("selectReplies", post),- selected,- showFlags: () => this.sendWidgetAction("showFlags", post),- showHistory: () => this.sendWidgetAction("showHistory", post),- showInvite: () => this.sendWidgetAction("showInvite", post),- showLogin: () => this.sendWidgetAction("showLogin", post),- showPagePublish: () =>- this.sendWidgetAction("showPagePublish", post),- showRawEmail: () => this.sendWidgetAction("showRawEmail", post),- showReadIndicator: attrs.showReadIndicator,- togglePostSelection: () =>- this.sendWidgetAction("togglePostSelection", post),- togglePostType: () =>- this.sendWidgetAction("togglePostType", post),- toggleReplyAbove: () =>- this.sendWidgetAction("toggleReplyAbove", post),- toggleWiki: () => this.sendWidgetAction("toggleWiki", post),- topicPageQueryParams: attrs.topicPageQueryParams,- unhidePost: () => this.sendWidgetAction("unhidePost", post),- unlockPost: () => this.sendWidgetAction("unlockPost", post),- updateTopicPageQueryParams: () =>- this.sendWidgetAction("updateTopicPageQueryParams"),- })- );- } else {- transformed.showReadIndicator = attrs.showReadIndicator;- result.push(this.attach("post", transformed, { model: post }));- }+ transformed.showReadIndicator = attrs.showReadIndicator;+ result.push(this.attach("post", transformed, { model: post }));}// Post gap - afterconst afterGap = after[post.id];if (afterGap) {result.push(- this.site.useGlimmerPostStream- ? new RenderGlimmer(- this,- "div.post-gap-shim",- hbs`<Post::Gap @post={{@data.post}} @gap={{@data.gap}} @fillGap={{@data.fillGap}} />`,- {- post,- gap: afterGap,- fillGap: () =>- this.sendWidgetAction("fillGapAfter", {- post,- gap: afterGap,- }),- }- )- : this.attach(- "post-gap",- { pos: "after", postId: post.id, gap: afterGap },- { model: post }- )+ this.attach(+ "post-gap",+ { pos: "after", postId: post.id, gap: afterGap },+ { model: post }+ ));}@@ -444,18 +325,9 @@ export default createWidget("post-stream", {attrs.lastReadPostNumber === post.post_number) {result.push(- this.site.useGlimmerPostStream- ? new RenderGlimmer(- this,- "div.post-visited-line-shim",- hbs`<Post::VisitedLine @post={{@data.post}} />`,- {- post,- }- )- : this.attach("topic-post-visited-line", {- post_number: post.post_number,- })+ this.attach("topic-post-visited-line", {+ post_number: post.post_number,+ }));}@@ -468,26 +340,11 @@ export default createWidget("post-stream", {(Object.keys(before).length > 0 || Object.keys(after).length > 0)) {result.push(- this.site.useGlimmerPostStream- ? new RenderGlimmer(- this,- "div.post-filtered-notice-shim",- hbs`<Post::FilteredNotice @posts={{@data.posts}}- @cancelFilter={{@data.cancelFilter}}- @streamFilters={{@data.streamFilters}}- @filteredPostsCount={{@data.filteredPostsCount}} />`,- {- posts: postArray,- streamFilters: attrs.streamFilters,- filteredPostsCount: attrs.filteredPostsCount,- cancelFilter: () => this.sendWidgetAction("cancelFilter"),- }- )- : this.attach("posts-filtered-notice", {- posts: postArray,- streamFilters: attrs.streamFilters,- filteredPostsCount: attrs.filteredPostsCount,- })+ this.attach("posts-filtered-notice", {+ posts: postArray,+ streamFilters: attrs.streamFilters,+ filteredPostsCount: attrs.filteredPostsCount,+ }));}diff --git a/app/assets/javascripts/discourse/app/widgets/post.js b/app/assets/javascripts/discourse/app/widgets/post.jsindex ff1938f28f3..d90a6b85607 100644--- a/app/assets/javascripts/discourse/app/widgets/post.js+++ b/app/assets/javascripts/discourse/app/widgets/post.js@@ -1091,9 +1091,11 @@ export default createWidget("post", {shadowTree: true,buildAttributes(attrs) {- return attrs.height+ const heightStyle = attrs.height? { style: `min-height: ${attrs.height}px` }: undefined;++ return { "data-post-number": attrs.post_number, ...heightStyle };},buildId(attrs) {@@ -1106,6 +1108,9 @@ export default createWidget("post", {}const classNames = ["topic-post", "clearfix"];+ if (!attrs.mobileView) {+ classNames.push("sticky-avatar");+ }if (attrs.id === -1 || attrs.isSaving || attrs.staged) {classNames.push("staged");}diff --git a/app/assets/javascripts/discourse/tests/acceptance/composer-draft-saving-test.js b/app/assets/javascripts/discourse/tests/acceptance/composer-draft-saving-test.jsindex 0812f40812a..a11e42acdac 100644--- a/app/assets/javascripts/discourse/tests/acceptance/composer-draft-saving-test.js+++ b/app/assets/javascripts/discourse/tests/acceptance/composer-draft-saving-test.js@@ -25,8 +25,10 @@ import { i18n } from "discourse-i18n";test("Shows a warning if a draft wasn't saved", async function (assert) {await visit("/t/internationalization-localization/280");- await click(".topic-post:nth-of-type(1) button.show-more-actions");- await click(".topic-post:nth-of-type(1) button.edit");+ await click(+ ".topic-post[data-post-number='1'] button.show-more-actions"+ );+ await click(".topic-post[data-post-number='1'] button.edit");await fillIn(".d-editor-input", draftThatWillBeSaved);diff --git a/app/assets/javascripts/discourse/tests/acceptance/composer-edit-conflict-test.js b/app/assets/javascripts/discourse/tests/acceptance/composer-edit-conflict-test.jsindex 72fcfd63d7d..3e5043671cf 100644--- a/app/assets/javascripts/discourse/tests/acceptance/composer-edit-conflict-test.js+++ b/app/assets/javascripts/discourse/tests/acceptance/composer-edit-conflict-test.js@@ -22,7 +22,7 @@ import { acceptance } from "discourse/tests/helpers/qunit-helpers";test("Should not send 'original_text' when posting a new reply", async function (assert) {await visit("/t/internationalization-localization/280");- await click(".topic-post:nth-of-type(1) button.reply");+ await click(".topic-post[data-post-number='1'] button.reply");await fillIn(".d-editor-input","hello world hello world hello world hello world hello world"@@ -32,8 +32,10 @@ import { acceptance } from "discourse/tests/helpers/qunit-helpers";test("Should send 'original_text' when editing a reply", async function (assert) {await visit("/t/internationalization-localization/280");- await click(".topic-post:nth-of-type(1) button.show-more-actions");- await click(".topic-post:nth-of-type(1) button.edit");+ await click(+ ".topic-post[data-post-number='1'] button.show-more-actions"+ );+ await click(".topic-post[data-post-number='1'] button.edit");await fillIn(".d-editor-input","hello world hello world hello world hello world hello world"diff --git a/app/assets/javascripts/discourse/tests/acceptance/composer-hyperlink-test.js b/app/assets/javascripts/discourse/tests/acceptance/composer-hyperlink-test.jsindex 6c629d23b0a..0e71d0de05e 100644--- a/app/assets/javascripts/discourse/tests/acceptance/composer-hyperlink-test.js+++ b/app/assets/javascripts/discourse/tests/acceptance/composer-hyperlink-test.js@@ -13,7 +13,7 @@ import { acceptance } from "discourse/tests/helpers/qunit-helpers";test("add a hyperlink to a reply", async function (assert) {await visit("/t/internationalization-localization/280");- await click(".topic-post:first-child button.reply");+ await click(".topic-post[data-post-number='1'] button.reply");await fillIn(".d-editor-input", "This is a link to ");assertdiff --git a/app/assets/javascripts/discourse/tests/acceptance/composer-test.js b/app/assets/javascripts/discourse/tests/acceptance/composer-test.jsindex 45506944e28..85912e489ed 100644--- a/app/assets/javascripts/discourse/tests/acceptance/composer-test.js+++ b/app/assets/javascripts/discourse/tests/acceptance/composer-test.js@@ -8,6 +8,7 @@ import {triggerEvent,triggerKeyEvent,visit,+ waitFor,} from "@ember/test-helpers";import { test } from "qunit";import sinon from "sinon";@@ -330,7 +331,7 @@ import { i18n } from "discourse-i18n";await fillIn(".d-editor-input", "this is the content of my reply");await click("#reply-control button.create");assert- .dom(".topic-post:last-of-type .cooked p")+ .dom(".topic-post:nth-last-child(1 of .topic-post) .cooked p").hasText("this is the content of my reply");});@@ -354,8 +355,10 @@ import { i18n } from "discourse-i18n";await click("#topic-footer-buttons .create");await fillIn(".d-editor-input", "this is the content of my reply");- await click(".topic-post:nth-of-type(1) button.show-more-actions");- await click(".topic-post:nth-of-type(1) button.edit");+ await click(+ ".topic-post[data-post-number='1'] button.show-more-actions"+ );+ await click(".topic-post[data-post-number='1'] button.edit");await click(".d-modal__footer button.keep-editing");assert.dom(".discard-draft-modal.modal").doesNotExist();@@ -366,7 +369,7 @@ import { i18n } from "discourse-i18n";"composer does not switch when using Keep Editing button");- await click(".topic-post:nth-of-type(1) button.edit");+ await click(".topic-post[data-post-number='1'] button.edit");assert.dom(".d-modal__footer button.save-draft").doesNotExist();await click(".d-modal__footer button.discard-draft");assert.dom(".discard-draft-modal.modal").doesNotExist();@@ -374,7 +377,7 @@ import { i18n } from "discourse-i18n";assert.dom(".d-editor-input").hasValue(- find(".topic-post:nth-of-type(1) .cooked > p").innerText,+ find(".topic-post[data-post-number='1'] .cooked > p").innerText,"composer has contents of post to be edited");});@@ -430,7 +433,7 @@ import { i18n } from "discourse-i18n";await click(".btn-reply-here");assert- .dom(".topic-post:last-of-type .cooked p")+ .dom(".topic-post:nth-last-child(1 of .topic-post) .cooked p").hasText("If you use gettext format you could leverage Launchpad translations and the community behind it.");@@ -510,7 +513,7 @@ import { i18n } from "discourse-i18n";await click("#reply-control button.create");assert- .dom(".topic-post:last-of-type .cooked p")+ .dom(".topic-post:nth-last-child(1 of .topic-post) .cooked p").hasText("this is the updated content of the reply");});@@ -538,7 +541,7 @@ import { i18n } from "discourse-i18n";await fillIn(".d-editor-input", "enqueue this content please");await click("#reply-control button.create");assert- .dom(".topic-post:last-of-type .cooked p")+ .dom(".topic-post:nth-last-child(1 of .topic-post) .cooked p").doesNotIncludeText("enqueue this content please","doesn't insert the post"@@ -554,11 +557,13 @@ import { i18n } from "discourse-i18n";await visit("/t/internationalization-localization/280");assert- .dom(".topic-post:nth-of-type(1) .post-info.edits")+ .dom(".topic-post[data-post-number='1'] .post-info.edits").doesNotExist("has no edits icon at first");- await click(".topic-post:nth-of-type(1) button.show-more-actions");- await click(".topic-post:nth-of-type(1) button.edit");+ await click(+ ".topic-post[data-post-number='1'] button.show-more-actions"+ );+ await click(".topic-post[data-post-number='1'] button.edit");assert.dom(".d-editor-input").hasValue(@@ -571,7 +576,7 @@ import { i18n } from "discourse-i18n";await click("#reply-control button.create");assert.dom(".d-editor-input").doesNotExist("closes the composer");assert- .dom(".topic-post:nth-of-type(1) .post-info.edits")+ .dom(".topic-post[data-post-number='1'] .post-info.edits").exists("has the edits icon");assert.dom("#topic-title h1")@@ -580,7 +585,7 @@ import { i18n } from "discourse-i18n";"shows the new title");assert- .dom(".topic-post:nth-of-type(1) .cooked")+ .dom(".topic-post[data-post-number='1'] .cooked").includesText("This is the new text for the post","updates the post"@@ -595,14 +600,19 @@ import { i18n } from "discourse-i18n";await fillIn(".d-editor-input", "will return empty json");await fillIn("#reply-title", "This is the new text for the title");+ const done = assert.async();+pretender.put("/posts/:post_id", async () => {// at this point, request is in flight, so post is staged- assert.dom(".topic-post").exists();- assert.dom(".topic-post").hasClass("staged");+ await waitFor(".topic-post.staged");++ assert.dom(".topic-post.staged").exists();assert.dom(".topic-post.staged .cooked").hasText("will return empty json");+ done();+return response(200, {});});@@ -615,14 +625,14 @@ import { i18n } from "discourse-i18n";test("Composer can switch between edits", async function (assert) {await visit("/t/this-is-a-test-topic/9");- await click(".topic-post:nth-of-type(1) button.edit");+ await click(".topic-post[data-post-number='1'] button.edit");assert.dom(".d-editor-input").hasValue(/^This is the first post\./,"populates the input with the post text");- await click(".topic-post:nth-of-type(2) button.edit");+ await click(".topic-post[data-post-number='2'] button.edit");assert.dom(".d-editor-input").hasValue(@@ -634,9 +644,9 @@ import { i18n } from "discourse-i18n";test("Composer with dirty edit can toggle to another edit", async function (assert) {await visit("/t/this-is-a-test-topic/9");- await click(".topic-post:nth-of-type(1) button.edit");+ await click(".topic-post[data-post-number='1'] button.edit");await fillIn(".d-editor-input", "This is a dirty reply");- await click(".topic-post:nth-of-type(2) button.edit");+ await click(".topic-post[data-post-number='2'] button.edit");assert.dom(".discard-draft-modal.modal").exists("pops up a confirmation dialog");@@ -653,7 +663,7 @@ import { i18n } from "discourse-i18n";test("Composer can toggle between edit and reply on the OP", async function (assert) {await visit("/t/this-is-a-test-topic/9");- await click(".topic-post:nth-of-type(1) button.edit");+ await click(".topic-post[data-post-number='1'] button.edit");assert.dom(".d-editor-input").hasValue(@@ -661,10 +671,10 @@ import { i18n } from "discourse-i18n";"populates the input with the post text");- await click(".topic-post:nth-of-type(1) button.reply");+ await click(".topic-post[data-post-number='1'] button.reply");assert.dom(".d-editor-input").hasNoValue("clears the composer input");- await click(".topic-post:nth-of-type(1) button.edit");+ await click(".topic-post[data-post-number='1'] button.edit");assert.dom(".d-editor-input").hasValue(@@ -676,7 +686,7 @@ import { i18n } from "discourse-i18n";test("Composer can toggle between edit and reply on a reply", async function (assert) {await visit("/t/this-is-a-test-topic/9");- await click(".topic-post:nth-of-type(2) button.edit");+ await click(".topic-post[data-post-number='2'] button.edit");assert.dom(".d-editor-input").hasValue(@@ -684,10 +694,10 @@ import { i18n } from "discourse-i18n";"populates the input with the post text");- await click(".topic-post:nth-of-type(2) button.reply");+ await click(".topic-post[data-post-number='2'] button.reply");assert.dom(".d-editor-input").hasNoValue("clears the composer input");- await click(".topic-post:nth-of-type(2) button.edit");+ await click(".topic-post[data-post-number='2'] button.edit");assert.dom(".d-editor-input").hasValue(@@ -700,7 +710,7 @@ import { i18n } from "discourse-i18n";const menu = selectKit(".toolbar-popup-menu-options");await visit("/t/this-is-a-test-topic/9");- await click(".topic-post:nth-of-type(1) button.reply");+ await click(".topic-post[data-post-number='1'] button.reply");await menu.expand();await menu.selectRowByName("toggle-whisper");@@ -731,7 +741,7 @@ import { i18n } from "discourse-i18n";test("Composer can toggle layouts (open, fullscreen and draft)", async function (assert) {await visit("/t/this-is-a-test-topic/9");- await click(".topic-post:nth-of-type(1) button.reply");+ await click(".topic-post[data-post-number='1'] button.reply");assert.dom("#reply-control.open")@@ -769,7 +779,7 @@ import { i18n } from "discourse-i18n";test("Composer fullscreen submit button", async function (assert) {await visit("/t/this-is-a-test-topic/9");- await click(".topic-post:nth-of-type(1) button.reply");+ await click(".topic-post[data-post-number='1'] button.reply");assert.dom("#reply-control.open")@@ -791,7 +801,7 @@ import { i18n } from "discourse-i18n";test("Composer can toggle between reply and createTopic", async function (assert) {await visit("/t/this-is-a-test-topic/9");- await click(".topic-post:nth-of-type(1) button.reply");+ await click(".topic-post[data-post-number='1'] button.reply");await selectKit(".toolbar-popup-menu-options").expand();@@ -824,7 +834,7 @@ import { i18n } from "discourse-i18n";await visit("/t/this-is-a-test-topic/9");- await click(".topic-post:nth-of-type(1) button.reply");+ await click(".topic-post[data-post-number='1'] button.reply");assert.dom(".reply-details .whisper").doesNotExist("should reset the state of the composer's model");@@ -833,7 +843,7 @@ import { i18n } from "discourse-i18n";test("Composer can toggle whisper when switching from reply to whisper to reply to topic", async function (assert) {await visit("/t/topic-with-whisper/960");- await click(".topic-post:nth-of-type(3) button.reply");+ await click(".topic-post[data-post-number='3'] button.reply");await click(".reply-details summary div");assert.dom('.reply-details li[data-value="toggle_whisper"]')@@ -850,7 +860,7 @@ import { i18n } from "discourse-i18n";test("Composer can toggle whisper when clicking reply to topic after reply to whisper", async function (assert) {await visit("/t/topic-with-whisper/960");- await click(".topic-post:nth-of-type(3) button.reply");+ await click(".topic-post[data-post-number='3'] button.reply");await click("#reply-control .save-or-cancel button.cancel");await click(".topic-footer-main-buttons button.create");await click(".reply-details summary div");@@ -862,10 +872,10 @@ import { i18n } from "discourse-i18n";test("Composer draft with dirty reply can toggle to edit", async function (assert) {await visit("/t/this-is-a-test-topic/9");- await click(".topic-post:nth-of-type(1) button.reply");+ await click(".topic-post[data-post-number='1'] button.reply");await fillIn(".d-editor-input", "This is a dirty reply");await click(".toggler");- await click(".topic-post:nth-of-type(2) button.edit");+ await click(".topic-post[data-post-number='2'] button.edit");assert.dom(".discard-draft-modal.modal").exists("pops up a confirmation dialog");@@ -888,7 +898,7 @@ import { i18n } from "discourse-i18n";test("Composer draft can switch to draft in new context without destroying current draft", async function (assert) {await visit("/t/this-is-a-test-topic/9");- await click(".topic-post:nth-of-type(1) button.reply");+ await click(".topic-post[data-post-number='1'] button.reply");await fillIn(".d-editor-input", "This is a dirty reply");await click("#site-logo");@@ -917,8 +927,10 @@ import { i18n } from "discourse-i18n";test("Does not check for existing draft", async function (assert) {await visit("/t/internationalization-localization/280");- await click(".topic-post:nth-of-type(1) button.show-more-actions");- await click(".topic-post:nth-of-type(1) button.edit");+ await click(+ ".topic-post[data-post-number='1'] button.show-more-actions"+ );+ await click(".topic-post[data-post-number='1'] button.edit");assert.dom(".dialog-body").doesNotExist("does not open the dialog");assert.dom(".d-editor-input").exists("the composer input is visible");@@ -1305,7 +1317,7 @@ import { i18n } from "discourse-i18n";test("Focusing a composer which is not open that has a draft", async function (assert) {await visit("/t/this-is-a-test-topic/9");- await click(".topic-post:nth-of-type(1) button.edit");+ await click(".topic-post[data-post-number='1'] button.edit");await fillIn(".d-editor-input", "This is a dirty reply");await click(".toggle-minimize");diff --git a/app/assets/javascripts/discourse/tests/acceptance/flag-post-test.js b/app/assets/javascripts/discourse/tests/acceptance/flag-post-test.jsindex 0c7f6805951..eb69032c9b8 100644--- a/app/assets/javascripts/discourse/tests/acceptance/flag-post-test.js+++ b/app/assets/javascripts/discourse/tests/acceptance/flag-post-test.js@@ -6,11 +6,13 @@ import selectKit from "discourse/tests/helpers/select-kit-helper";async function openFlagModal() {if (- document.querySelector(".topic-post:first-child button.show-more-actions")+ document.querySelector(+ ".topic-post[data-post-number='1'] button.show-more-actions"+ )) {- await click(".topic-post:first-child button.show-more-actions");+ await click(".topic-post[data-post-number='1'] button.show-more-actions");}- await click(".topic-post:first-child button.create-flag");+ await click(".topic-post[data-post-number='1'] button.create-flag");}async function pressEnter(selector, modifier) {diff --git a/app/assets/javascripts/discourse/tests/acceptance/page-publishing-test.js b/app/assets/javascripts/discourse/tests/acceptance/page-publishing-test.jsindex 9817a3a2a50..dc61a984a68 100644--- a/app/assets/javascripts/discourse/tests/acceptance/page-publishing-test.js+++ b/app/assets/javascripts/discourse/tests/acceptance/page-publishing-test.js@@ -33,8 +33,12 @@ import { acceptance } from "discourse/tests/helpers/qunit-helpers";test("can publish a page via modal", async function (assert) {await visit("/t/internationalization-localization/280");- await click(".topic-post:nth-of-type(1) button.show-more-actions");- await click(".topic-post:nth-of-type(1) button.show-post-admin-menu");+ await click(+ ".topic-post[data-post-number='1'] button.show-more-actions"+ );+ await click(+ ".topic-post[data-post-number='1'] button.show-post-admin-menu"+ );await click(".publish-page");await fillIn(".publish-slug", "bad-slug");diff --git a/app/assets/javascripts/discourse/tests/acceptance/post-stream-test.gjs b/app/assets/javascripts/discourse/tests/acceptance/post-stream-test.gjsnew file mode 100644index 00000000000..f81e7576e24--- /dev/null+++ b/app/assets/javascripts/discourse/tests/acceptance/post-stream-test.gjs@@ -0,0 +1,75 @@+import { click, visit } from "@ember/test-helpers";+import { test } from "qunit";+import { withPluginApi } from "discourse/lib/plugin-api";+import { acceptance } from "discourse/tests/helpers/qunit-helpers";++acceptance("Post-Stream | @topicPageQueryParams reactivity", function (needs) {+ needs.user();+ needs.settings({+ enable_filtered_replies_view: true,+ glimmer_post_stream_mode: "enabled",+ });++ needs.hooks.beforeEach(function () {+ withPluginApi((api) => {+ api.renderBeforeWrapperOutlet(+ "post-article",+ <template>+ <div class="topic-page-query-params-test">+ <span class="topic-page-query-params-value">+ {{@topicPageQueryParams.replies_to_post_number}}+ </span>+ </div>+ </template>+ );+ });+ });++ test("topicPageQueryParams is reactive", async function (assert) {+ await visit("/t/internationalization-localization/280");++ assert+ .dom(".topic-page-query-params-test")+ .exists("The test component is rendered");++ // get the initial value of replies_to_post_number+ const initialValue = document.querySelector(+ ".topic-page-query-params-value"+ ).textContent;++ // click on a post to filter replies+ await click("#post_1 .show-replies");++ // get the updated value of replies_to_post_number+ let updatedValue = document+ .querySelector(".topic-page-query-params-value")+ .textContent.trim();++ // verify that the value has changed+ assert.notStrictEqual(+ initialValue,+ updatedValue,+ "topicPageQueryParams value changes when filtering replies"+ );++ assert.strictEqual(+ updatedValue,+ "1",+ "replies_to_post_number parameter is updated to 1"+ );++ // click on another post to filter replies+ await click("#post_3 .show-replies");++ updatedValue = document+ .querySelector(".topic-page-query-params-value")+ .textContent.trim();++ // verify that the value has changed again+ assert.strictEqual(+ updatedValue,+ "3",+ "replies_to_post_number parameter is updated to 3"+ );+ });+});diff --git a/app/assets/javascripts/discourse/tests/acceptance/post-table-wrapper-test.js b/app/assets/javascripts/discourse/tests/acceptance/post-table-wrapper-test.jsindex 81f9f88a5a3..f32d6d7e0c8 100644--- a/app/assets/javascripts/discourse/tests/acceptance/post-table-wrapper-test.js+++ b/app/assets/javascripts/discourse/tests/acceptance/post-table-wrapper-test.js@@ -13,7 +13,8 @@ import { acceptance } from "discourse/tests/helpers/qunit-helpers";test("fullscreen table wrapper appears on post with large table", async function (assert) {await visit("/t/54081");- const postWithLargeTable = ".post-stream .topic-post:first-child";+ const postWithLargeTable =+ ".post-stream .topic-post[data-post-number='1']";assert.dom(`${postWithLargeTable} .fullscreen-table-wrapper`).exists("The wrapper is present on the post with the large table");diff --git a/app/assets/javascripts/discourse/tests/acceptance/topic-test.js b/app/assets/javascripts/discourse/tests/acceptance/topic-test.jsindex 1b281ebd5fc..4fd11f1cbb5 100644--- a/app/assets/javascripts/discourse/tests/acceptance/topic-test.js+++ b/app/assets/javascripts/discourse/tests/acceptance/topic-test.js@@ -87,7 +87,7 @@ import { i18n } from "discourse-i18n";test("Share Modal", async function (assert) {await visit("/t/internationalization-localization/280");- await click(".topic-post:first-child button.share");+ await click(".topic-post[data-post-number='1'] button.share");assert.dom(".share-topic-modal").exists("shows the share modal");});@@ -95,7 +95,7 @@ import { i18n } from "discourse-i18n";test("Copy Link Button", async function (assert) {await visit("/t/internationalization-localization/280");await click(- ".topic-post:first-child button.post-action-menu__copy-link"+ ".topic-post[data-post-number='1'] button.post-action-menu__copy-link");assert@@ -142,8 +142,12 @@ import { i18n } from "discourse-i18n";assert.dom("a.wiki").doesNotExist("does not show the wiki icon");- await click(".topic-post:nth-of-type(1) button.show-more-actions");- await click(".topic-post:nth-of-type(1) button.show-post-admin-menu");+ await click(+ ".topic-post[data-post-number='1'] button.show-more-actions"+ );+ await click(+ ".topic-post[data-post-number='1'] button.show-post-admin-menu"+ );await click(".btn.wiki");assert.dom("button.wiki").exists("shows the wiki icon");@@ -220,8 +224,10 @@ import { i18n } from "discourse-i18n";test("Deleting a topic", async function (assert) {this.siteSettings.min_topic_views_for_delete_confirm = 10000;await visit("/t/internationalization-localization/280");- await click(".topic-post:nth-of-type(1) button.show-more-actions");- await click(".topic-post:nth-of-type(1) button.delete");+ await click(+ ".topic-post[data-post-number='1'] button.show-more-actions"+ );+ await click(".topic-post[data-post-number='1'] button.delete");await click(".toggle-admin-menu");assert.dom(".topic-admin-recover").exists("shows the recover button");});@@ -229,8 +235,10 @@ import { i18n } from "discourse-i18n";test("Deleting a popular topic displays confirmation modal", async function (assert) {this.siteSettings.min_topic_views_for_delete_confirm = 10;await visit("/t/internationalization-localization/280");- await click(".topic-post:nth-of-type(1) button.show-more-actions");- await click(".topic-post:nth-of-type(1) button.delete");+ await click(+ ".topic-post[data-post-number='1'] button.show-more-actions"+ );+ await click(".topic-post[data-post-number='1'] button.delete");assert.dom(".delete-topic-confirm-modal").exists("shows the delete confirmation modal");@@ -239,7 +247,7 @@ import { i18n } from "discourse-i18n";assert.dom(".delete-topic-confirm-modal").doesNotExist("hides the delete confirmation modal");- await click(".topic-post:nth-of-type(1) button.delete");+ await click(".topic-post[data-post-number='1'] button.delete");await click(".delete-topic-confirm-modal .btn-danger");await click(".toggle-admin-menu");assert.dom(".topic-admin-recover").exists("shows the recover button");diff --git a/app/assets/javascripts/discourse/tests/integration/components/post/post-test.gjs b/app/assets/javascripts/discourse/tests/integration/components/post/post-test.gjsindex 2ddefa2b599..b66a2f2295e 100644--- a/app/assets/javascripts/discourse/tests/integration/components/post/post-test.gjs+++ b/app/assets/javascripts/discourse/tests/integration/components/post/post-test.gjs@@ -668,7 +668,7 @@ module("Integration | Component | Post", function (hooks) {this.post.created_at = new Date();this.post.notice = {type: "returning_user",- lastPostedAt: twoDaysAgo,+ last_posted_at: twoDaysAgo,};await renderComponent(this.post);diff --git a/app/assets/javascripts/discourse/tests/integration/components/widgets/post-stream-test.gjs b/app/assets/javascripts/discourse/tests/integration/components/widgets/post-stream-test.gjsindex 6a498dd8891..c23f100aac9 100644--- a/app/assets/javascripts/discourse/tests/integration/components/widgets/post-stream-test.gjs+++ b/app/assets/javascripts/discourse/tests/integration/components/widgets/post-stream-test.gjs@@ -95,7 +95,7 @@ function postStreamTest(name, attrs) {assert.dom(".post-stream").exists({ count: 1 });assert.dom(".topic-post").exists({ count: 1 }, "renders all posts");assert- .dom(".topic-post:nth-of-type(1) button.hot-coffee")+ .dom(".topic-post[data-post-number='1'] button.hot-coffee").exists("it transforms posts");assert.strictEqual(lastTransformedPost.topic.id,@@ -166,25 +166,25 @@ function postStreamTest(name, attrs) {// look for special class bindingsassert- .dom(".topic-post:nth-of-type(1).topic-owner")+ .dom(".topic-post[data-post-number='1'].topic-owner").exists({ count: 1 }, "applies the topic owner class");assert- .dom(".topic-post:nth-of-type(1).group-trout")+ .dom(".topic-post[data-post-number='1'].group-trout").exists({ count: 1 }, "applies the primary group class");assert- .dom(".topic-post:nth-of-type(1).regular")+ .dom(".topic-post[data-post-number='1'].regular").exists({ count: 1 }, "applies the regular class");assert- .dom(".topic-post:nth-of-type(2).moderator")+ .dom(".topic-post[data-post-number='2'].moderator").exists({ count: 1 }, "applies the moderator class");assert- .dom(".topic-post:nth-of-type(3).post-hidden")+ .dom(".topic-post[data-post-number='3'].post-hidden").exists({ count: 1 }, "applies the hidden class");assert- .dom(".topic-post:nth-of-type(4).whisper")+ .dom(".topic-post[data-post-number='4'].whisper").exists({ count: 1 }, "applies the whisper class");assert- .dom(".topic-post:nth-of-type(5).wiki")+ .dom(".topic-post[data-post-number='5'].wiki").exists({ count: 1 }, "applies the wiki class");// it renders an article for the body with appropriate attributesdiff --git a/app/assets/javascripts/discourse/tests/setup-tests.js b/app/assets/javascripts/discourse/tests/setup-tests.jsindex c791ea28ad0..3a9d181b2c4 100644--- a/app/assets/javascripts/discourse/tests/setup-tests.js+++ b/app/assets/javascripts/discourse/tests/setup-tests.js@@ -43,7 +43,8 @@ import {} from "discourse/tests/helpers/qunit-helpers";import { configureRaiseOnDeprecation } from "discourse/tests/helpers/raise-on-deprecation";import { resetSettings } from "discourse/tests/helpers/site-settings";-import { disableCloaking } from "discourse/widgets/post-stream";+import { disableCloaking } from "discourse/modifiers/post-stream-viewport-tracker";+import { disableCloaking as disableWidgetCloaking } from "discourse/widgets/post-stream";import deprecated from "discourse/lib/deprecated";import { setDefaultOwner } from "discourse/lib/get-owner";import { setupS3CDN, setupURL } from "discourse/lib/get-url";@@ -205,6 +206,7 @@ function writeSummaryLine(message) {export default function setupTests(config) {disableCloaking();+ disableWidgetCloaking();setupDeprecationCounter(QUnit);diff --git a/app/assets/javascripts/discourse/tests/unit/lib/tracked-tools-test.gjs b/app/assets/javascripts/discourse/tests/unit/lib/tracked-tools-test.gjsindex 69d9a08d839..4d499579958 100644--- a/app/assets/javascripts/discourse/tests/unit/lib/tracked-tools-test.gjs+++ b/app/assets/javascripts/discourse/tests/unit/lib/tracked-tools-test.gjs@@ -1,8 +1,13 @@import { cached } from "@glimmer/tracking";import { run } from "@ember/runloop";import { settled } from "@ember/test-helpers";+import { TrackedArray } from "@ember-compat/tracked-built-ins";import { module, test } from "qunit";-import { dedupeTracked, DeferredTrackedSet } from "discourse/lib/tracked-tools";+import {+ dedupeTracked,+ DeferredTrackedSet,+ trackedArray,+} from "discourse/lib/tracked-tools";module("Unit | tracked-tools", function () {test("@dedupeTracked", async function (assert) {@@ -116,4 +121,177 @@ module("Unit | tracked-tools", function () {assert.strictEqual(player.evaluationsCount, 4, "getter evaluated");assert.deepEqual([...player.letters], ["a", "b", "c", "d", "e", "f"]);});++ module("@trackedArray", function () {+ test("initializes with an array", function (assert) {+ class TestClass {+ @trackedArray items = ["a", "b", "c"];+ }++ const instance = new TestClass();+ assert.true(+ instance.items instanceof TrackedArray,+ "should wrap initial array in TrackedArray"+ );+ assert.deepEqual(+ Array.from(instance.items),+ ["a", "b", "c"],+ "should preserve array contents"+ );+ });++ test("accepts null as initial value", function (assert) {+ class TestClass {+ @trackedArray items = null;+ }++ const instance = new TestClass();+ assert.strictEqual(+ instance.items,+ null,+ "should allow null as initial value"+ );+ });++ test("handles setting regular arrays", function (assert) {+ class TestClass {+ @trackedArray items;+ }++ const instance = new TestClass();+ instance.items = ["x", "y", "z"];++ assert.true(+ instance.items instanceof TrackedArray,+ "should wrap new array in TrackedArray"+ );+ assert.deepEqual(+ Array.from(instance.items),+ ["x", "y", "z"],+ "should contain new array values"+ );+ });++ test("accepts TrackedArray instances directly", function (assert) {+ class TestClass {+ @trackedArray items = [];+ }++ const instance = new TestClass();+ const trackedArr = new TrackedArray(["foo", "bar"]);+ instance.items = trackedArr;++ assert.strictEqual(+ instance.items,+ trackedArr,+ "should use the provided TrackedArray instance"+ );+ assert.deepEqual(+ Array.from(instance.items),+ ["foo", "bar"],+ "should contain correct values"+ );+ });++ test("allows setting to null", function (assert) {+ class TestClass {+ @trackedArray items = ["initial"];+ }++ const instance = new TestClass();+ instance.items = null;++ assert.strictEqual(instance.items, null, "should allow setting to null");+ });++ test("throws error for invalid values", function (assert) {+ class TestClass {+ @trackedArray items = [];+ }++ const instance = new TestClass();++ assert.throws(+ () => {+ instance.items = "not an array";+ },+ /Expected an array or TrackedArray, got string/,+ "should throw for strings"+ );++ assert.throws(+ () => {+ instance.items = 42;+ },+ /Expected an array or TrackedArray, got number/,+ "should throw for numbers"+ );++ assert.throws(+ () => {+ instance.items = {};+ },+ /Expected an array or TrackedArray, got object/,+ "should throw for plain objects"+ );++ assert.throws(+ () => {+ instance.items = undefined;+ },+ /Expected an array or TrackedArray, got undefined/,+ "should throw for undefined"+ );+ });++ test("tracks changes to array contents", function (assert) {+ class TestClass {+ evaluationsCount = 0;+ @trackedArray items = ["a"];++ @cached+ get itemCount() {+ this.evaluationsCount++;+ return this.items.length;+ }++ addItem(item) {+ this.items = [...this.items, item];+ }+ }++ const instance = new TestClass();+ assert.strictEqual(instance.itemCount, 1, "initial count is correct");+ assert.strictEqual(instance.evaluationsCount, 1, "getter evaluated once");++ assert.strictEqual(+ instance.itemCount,+ 1,+ "count not updated when reading the value again."+ );+ assert.strictEqual(+ instance.evaluationsCount,+ 1,+ "getter wasn't evaluated again"+ );++ instance.addItem("b"); // Adding same item+ assert.strictEqual(+ instance.itemCount,+ 2,+ "count updated after duplicate add"+ );+ assert.strictEqual(+ instance.evaluationsCount,+ 2,+ "getter re-evaluated after change"+ );++ assert.deepEqual(+ Array.from(instance.items),+ ["a", "b"],+ "array contains correct items"+ );+ });+ });});diff --git a/app/assets/stylesheets/common/base/topic.scss b/app/assets/stylesheets/common/base/topic.scssindex 5619a84524f..509df413a3e 100644--- a/app/assets/stylesheets/common/base/topic.scss+++ b/app/assets/stylesheets/common/base/topic.scss@@ -37,7 +37,7 @@grid-area: timeline;align-self: start;position: sticky;- top: calc(var(--header-offset, 60px) + 2em);+ top: calc(var(--header-offset, 60px) + 1.5em);margin-left: 1em;z-index: z("timeline");diff --git a/app/assets/stylesheets/desktop/topic-post.scss b/app/assets/stylesheets/desktop/topic-post.scssindex eb791cd93ee..6e6032f469d 100644--- a/app/assets/stylesheets/desktop/topic-post.scss+++ b/app/assets/stylesheets/desktop/topic-post.scss@@ -524,7 +524,7 @@ video {.topic-avatar {border-top: 1px solid var(--primary-low);padding-top: 15px;- width: $topic-avatar-width;+ width: var(--topic-avatar-width);float: left;z-index: z("base") + 1;height: 100%;@@ -537,9 +537,11 @@ video {.topic-area > .loading-container {// 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`width: calc(var(--topic-body-width) + var(--topic-avatar-width) +- (var(--topic-body-width-padding) * 2)+ (var(--topic-body-width-padding) * 2) + 1px);max-width: 100%;}diff --git a/plugins/discourse-presence/test/javascripts/acceptance/discourse-presence-test.js b/plugins/discourse-presence/test/javascripts/acceptance/discourse-presence-test.jsindex 5db6df80b57..96bada44ce5 100644--- a/plugins/discourse-presence/test/javascripts/acceptance/discourse-presence-test.js+++ b/plugins/discourse-presence/test/javascripts/acceptance/discourse-presence-test.js@@ -107,13 +107,13 @@ acceptance("Discourse Presence Plugin", function (needs) {test("Uses the edit channel for editing", async function (assert) {await visit("/t/internationalization-localization/280");- await click(".topic-post:nth-of-type(1) button.show-more-actions");- await click(".topic-post:nth-of-type(1) button.edit");+ await click(".topic-post[data-post-number='1'] button.show-more-actions");+ await click(".topic-post[data-post-number='1'] button.edit");assert.dom(".d-editor-input").hasValue(- document.querySelector(".topic-post:nth-of-type(1) .cooked > p")+ document.querySelector(".topic-post[data-post-number='1'] .cooked > p").innerText,"composer has contents of post to be edited");diff --git a/spec/system/post_stream_spec.rb b/spec/system/post_stream_spec.rbnew file mode 100644index 00000000000..b49d38f18a0--- /dev/null+++ b/spec/system/post_stream_spec.rb@@ -0,0 +1,46 @@+# frozen_string_literal: true++describe "Post stream", type: :system do+ fab!(:topic)+ fab!(:user)+ fab!(:posts) { Fabricate.times(20, :post, topic: topic) }++ before do+ sign_in(user)+ SiteSetting.glimmer_post_stream_mode = "enabled"+ end++ it "cloaks posts that are far from the viewport" do+ # Visit the topic page+ visit "/t/#{topic.slug}/#{topic.id}/1"++ # Ensure there are visible posts+ expect(page).to have_css(".topic-post")++ post_stream = find(".post-stream")++ # Ensure the first post is uncloaked+ expect(post_stream).to have_css("> [data-post-number='1']")+ expect(post_stream).to have_no_css("> [data-post-number='1'].post-stream--cloaked")++ # Check that some posts are cloaked (not all posts should be fully rendered at once)+ # The posts that are far from the viewport should have the "post-stream--cloaked" class+ expect(post_stream).to have_css(".post-stream--cloaked")++ # Get the number of the last post+ last_post_number = topic.highest_post_number++ # Scroll to the bottom of the page to load more posts+ # We use the :end key to scroll to the bottom+ send_keys(:end)++ # Verify that the last post is not cloaked+ expect(post_stream).to have_no_css(+ "> [data-post-number='#{last_post_number}'].post-stream--cloaked",+ )++ # Verify that some posts at the top are now cloaked+ # we can check the first post to see if it's cloaked+ expect(post_stream).to have_css("> [data-post-number='1'].post-stream--cloaked")+ end+end