A platform for community discussion. Free, open, simple.
FIX: Features relying on the post stream in mega topics
Régis Hanole225d3f96cd6
diff --git a/frontend/discourse/app/components/modal/share-topic.gjs b/frontend/discourse/app/components/modal/share-topic.gjsindex 2545fd5faa8..3acf5a37cd6 100644--- a/frontend/discourse/app/components/modal/share-topic.gjs+++ b/frontend/discourse/app/components/modal/share-topic.gjs@@ -95,10 +95,8 @@ export default class ShareTopicModal extends Component {}@action- replyAsNewTopic() {- const postStream = this.topic.postStream;- const postId = this.post?.id || postStream.findPostIdForPostNumber(1);- const post = postStream.findLoadedPost(postId);+ async replyAsNewTopic() {+ const post = this.post || (await this.topic.firstPost());const topicController = getOwner(this).lookup("controller:topic");topicController.actions.replyAsNewTopic.call(topicController, post);this.closeModal();diff --git a/frontend/discourse/app/components/topic-progress.gjs b/frontend/discourse/app/components/topic-progress.gjsindex df8fb2cf9b3..cf2423c527b 100644--- a/frontend/discourse/app/components/topic-progress.gjs+++ b/frontend/discourse/app/components/topic-progress.gjs@@ -49,16 +49,26 @@ export default class TopicProgress extends Component {);}- @computed("progressPosition", "topic.last_read_post_id")+ @computed(+ "progressPosition",+ "topic.last_read_post_id",+ "topic.last_read_post_number",+ "postStream.filteredPostsCount"+ )get showBackButton() {if (!this.topic?.last_read_post_id) {return;}- const stream = this.get("postStream.stream");- const readPos = stream.indexOf(this.topic?.last_read_post_id) || 0;+ const readPos = this.postStream.progressIndexOfPostId({+ id: this.topic.last_read_post_id,+ post_number: this.topic.last_read_post_number,+ });- return readPos < stream.length - 1 && readPos > this.progressPosition;+ return (+ readPos < this.postStream.filteredPostsCount &&+ readPos > this.progressPosition + 1+ );}@computed("_streamPercentage")diff --git a/frontend/discourse/app/components/topic-timeline/container.gjs b/frontend/discourse/app/components/topic-timeline/container.gjsindex cfd6faeb882..5a6967eebf7 100644--- a/frontend/discourse/app/components/topic-timeline/container.gjs+++ b/frontend/discourse/app/components/topic-timeline/container.gjs@@ -262,29 +262,19 @@ export default class TopicTimelineScrollArea extends Component {this.current = this.clamp(this.scrollPosition, 1, this.total);const daysAgo = postStream.closestDaysAgoFor(this.current);- let date;- if (daysAgo === undefined) {- const post = postStream.posts.find(- (p) => p.id === postStream.stream[this.current]- );-- if (post) {- date = new Date(post.created_at);- }- } else if (daysAgo !== null) {- date = new Date();- date.setDate(date.getDate() - daysAgo || 0);- } else {- date = null;- }-- this.date = date;+ this.date =+ daysAgo === undefined+ ? null+ : moment().subtract(daysAgo, "days").toDate();const lastReadNumber = topic.last_read_post_number;const lastReadId = topic.last_read_post_id;if (lastReadId && lastReadNumber) {- const idx = postStream.stream.indexOf(lastReadId) + 1;+ const idx = postStream.progressIndexOfPostId({+ id: lastReadId,+ post_number: lastReadNumber,+ });this.lastRead = idx;this.lastReadPercentage = this._percentFor(topic, idx);}diff --git a/frontend/discourse/app/controllers/topic.js b/frontend/discourse/app/controllers/topic.jsindex 98881ecfc2f..02cd8d2161f 100644--- a/frontend/discourse/app/controllers/topic.js+++ b/frontend/discourse/app/controllers/topic.js@@ -2175,31 +2175,16 @@ export default class TopicController extends Controller {postStream.loadNearestPostToDate(date)- .then((post) => {- DiscourseURL.routeTo(- this.model.urlForPostNumber(post.get("post_number"))- );- })+ .then((post) => this._jumpToPostNumber(post.post_number)).catch(() => {this._jumpToIndex(postStream.get("topic.highest_post_number"));});}_jumpToPostNumber(postNumber) {- const postStream = this.get("model.postStream");- const post = postStream- .get("posts")- .find((item) => item.post_number === postNumber);-- if (post) {- DiscourseURL.routeTo(- this.model.urlForPostNumber(post.get("post_number"))- );- } else {- postStream.loadPostByPostNumber(postNumber).then((p) => {- DiscourseURL.routeTo(this.model.urlForPostNumber(p.get("post_number")));- });- }+ DiscourseURL.routeTo(this.model.urlForPostNumber(postNumber), {+ keepFilter: true,+ });}async _jumpToPostId(postId) {@@ -2225,9 +2210,7 @@ export default class TopicController extends Controller {}}- DiscourseURL.routeTo(this.model.urlForPostNumber(post.post_number), {- keepFilter: true,- });+ this._jumpToPostNumber(post.post_number);}_modifyTopicBookmark(bookmark) {diff --git a/frontend/discourse/app/deprecation-workflow.js b/frontend/discourse/app/deprecation-workflow.jsindex 42b80acc611..abbca181ac3 100644--- a/frontend/discourse/app/deprecation-workflow.js+++ b/frontend/discourse/app/deprecation-workflow.js@@ -383,6 +383,7 @@ const workflows = ["discourse.plugin-outlet-classic-args-clash","discourse.plugin-outlet-classic-hooks","discourse.plugin-outlet-context-get",+ "discourse.post-stream.first-post-id","discourse.post-stream.trigger-new-post","discourse.pretty-text.registerOption","discourse.qunit-helpers.jquery-selector",diff --git a/frontend/discourse/app/models/post-stream.ts b/frontend/discourse/app/models/post-stream.tsindex 3ec4e9f8ca7..ce2e4177ce9 100644--- a/frontend/discourse/app/models/post-stream.ts+++ b/frontend/discourse/app/models/post-stream.ts@@ -159,8 +159,6 @@ export default interface PostStream {_loadingPostIds?: number[] | null;/** Initialized before excerpt callbacks run; callbacks assume the cache is retained. */_excerpts?: ExcerptCache;- /** TODO(typescript-pending): Core never supplies this nextWindow bound; remove when its source is established. */- highest_post_number?: number;}// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging@@ -287,7 +285,11 @@ export default class PostStream extends RestModel {@dependentKeyCompatget firstPostId(): number | undefined {- return this.stream[0];+ deprecated(+ "`postStream.firstPostId` is deprecated, use `topic.firstPost()` instead",+ { id: "discourse.post-stream.first-post-id" }+ );+ return this.findPostIdForPostNumber(1);}@dependentKeyCompat@@ -391,10 +393,6 @@ export default class PostStream extends RestModel {if (lastIndex === -1) {return [];}- // Preserve the numeric comparison against the currently unsupplied stream bound.- if (lastIndex + 1 >= (this.highest_post_number as number)) {- return [];- }// find our window of postsreturn this.stream.slice(@@ -1184,7 +1182,7 @@ export default class PostStream extends RestModel {}/** Returns the progress index of a Post object, despite the method name; mega topics use its post_number. */- progressIndexOfPostId(post: Post) {+ progressIndexOfPostId(post: Pick<Post, "id" | "post_number">) {const postId = post.id;if (this.isMegaTopic) {@@ -1251,6 +1249,10 @@ export default class PostStream extends RestModel {/** Find a postId for a postNumber, respecting gaps */findPostIdForPostNumber(postNumber: number): number | undefined {+ if (this.isMegaTopic) {+ return this.postForPostNumber(postNumber)?.id;+ }+const beforeLookup = this.gaps?.before;let sum = 1;diff --git a/frontend/discourse/app/services/composer.js b/frontend/discourse/app/services/composer.jsindex 533a9411a0c..f39af72dfac 100644--- a/frontend/discourse/app/services/composer.js+++ b/frontend/discourse/app/services/composer.js@@ -1094,9 +1094,10 @@ export default class ComposerService extends Service {const postStream = this.get("topic.postStream");let postId = this.get("model.post.id");- // If there is no current post, use the first post id from the streamif (!postId && postStream) {- postId = postStream.firstPostId;+ postId =+ postStream.findPostIdForPostNumber(1) ??+ (await this.get("topic").firstPost()).id;}// If we're editing a post, fetch the reply when importing a quotediff --git a/frontend/discourse/tests/acceptance/share-topic-test.js b/frontend/discourse/tests/acceptance/share-topic-test.jsindex 786a6c8aa4a..7aff70e0793 100644--- a/frontend/discourse/tests/acceptance/share-topic-test.js+++ b/frontend/discourse/tests/acceptance/share-topic-test.js@@ -1,3 +1,4 @@+import { getOwner } from "@ember/owner";import { click, currentURL, visit } from "@ember/test-helpers";import { test } from "qunit";import CategoryFixtures from "discourse/tests/fixtures/category-fixtures";@@ -14,6 +15,10 @@ acceptance("Share and Invite modal", function (needs) {}));+ server.get("/posts/by_number/280/1", () =>+ helper.response({ id: 398, post_number: 1, topic_id: 280 })+ );+server.get(`/c/2/visible_groups.json`, () =>helper.response(200, {groups: [],@@ -58,6 +63,19 @@ acceptance("Share and Invite modal", function (needs) {assert.dom(".create-invite-modal").exists();});+ test("New topic button on mega topics", async function (assert) {+ await visit("/t/internationalization-localization/280");+ await click("#topic-footer-button-share-and-invite");++ const { postStream } = getOwner(this).lookup("controller:topic").model;+ postStream.isMegaTopic = true;+ postStream.posts.shift();++ await click(".share-topic-modal .new-topic");++ assert.dom("#reply-control .d-editor-input").exists();+ });+test("Post date link", async function (assert) {await visit("/t/short-topic-with-two-posts/54077");assertdiff --git a/frontend/discourse/tests/integration/components/topic-progress-test.gjs b/frontend/discourse/tests/integration/components/topic-progress-test.gjsnew file mode 100644index 00000000000..41070873ea6--- /dev/null+++ b/frontend/discourse/tests/integration/components/topic-progress-test.gjs@@ -0,0 +1,23 @@+import { getOwner } from "@ember/owner";+import { render } from "@ember/test-helpers";+import { module, test } from "qunit";+import TopicProgress from "discourse/components/topic-progress";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";++module("Integration | Component | topic-progress", function (hooks) {+ setupRenderingTest(hooks);++ test("shows the back button on mega topics", async function (assert) {+ const topic = getOwner(this).lookup("service:store").createRecord("topic", {+ id: 1,+ highest_post_number: 100,+ last_read_post_id: 5500,+ last_read_post_number: 80,+ });+ topic.postStream.isMegaTopic = true;++ await render(<template><TopicProgress @topic={{topic}} /></template>);++ assert.dom(".progress-back").exists();+ });+});diff --git a/frontend/discourse/tests/integration/components/topic-timeline-test.gjs b/frontend/discourse/tests/integration/components/topic-timeline-test.gjsindex db90bdb1cbb..35c1d95db56 100644--- a/frontend/discourse/tests/integration/components/topic-timeline-test.gjs+++ b/frontend/discourse/tests/integration/components/topic-timeline-test.gjs@@ -1,5 +1,5 @@import { getOwner } from "@ember/owner";-import { render } from "@ember/test-helpers";+import { click, render } from "@ember/test-helpers";import { module, test } from "qunit";import sinon from "sinon";import TopicTimeline from "discourse/components/topic-timeline";@@ -42,4 +42,25 @@ module("Integration | Component | topic-timeline", function (hooks) {assert.dom(".show-summary").doesNotExist();assert.dom(".post-excerpt").hasText("Last post");});++ test("the back button jumps to the last read post", async function (assert) {+ const topic = createMegaTopic(this, {+ last_read_post_id: 5500,+ last_read_post_number: 55,+ });+ const jumpToIndex = sinon.spy();++ await render(+ <template>+ <TopicTimeline+ @enteredIndex={{10}}+ @jumpToIndex={{jumpToIndex}}+ @model={{topic}}+ />+ </template>+ );+ await click(".timeline-last-read .back-button");++ assert.true(jumpToIndex.calledOnceWith(55));+ });});diff --git a/frontend/discourse/tests/unit/controllers/topic-test.js b/frontend/discourse/tests/unit/controllers/topic-test.jsindex 4aedbbcbc36..dc5e4ec4997 100644--- a/frontend/discourse/tests/unit/controllers/topic-test.js+++ b/frontend/discourse/tests/unit/controllers/topic-test.js@@ -8,6 +8,7 @@ import { removeValueFromArray } from "discourse/lib/array-tools";import { forceMobile } from "discourse/lib/mobile";import { registerOptimisticPostUpdate } from "discourse/lib/optimistic-post-updates";import { withPluginApi } from "discourse/lib/plugin-api";+import DiscourseURL from "discourse/lib/url";import { Placeholder } from "discourse/models/post-stream";import pretender, {response,@@ -27,6 +28,19 @@ module("Unit | Controller | topic", function (hooks) {this.store = getOwner(this).lookup("service:store");});+ test("jumpToIndex on mega topics routes to the post number and keeps filters", function (assert) {+ const controller = getOwner(this).lookup("controller:topic");+ const model = topicWithStream.call(this, { isMegaTopic: true });+ controller.setProperties({ model });+ const routeTo = sinon.stub(DiscourseURL, "routeTo");++ controller.jumpToIndex(9999);++ assert.true(+ routeTo.calledOnceWith(model.urlForPostNumber(9999), { keepFilter: true })+ );+ });+test("revised messages skip only the originating optimistic refresh", function (assert) {const controller = getOwner(this).lookup("controller:topic");const model = this.store.createRecord("topic", { id: 1 });diff --git a/frontend/discourse/tests/unit/models/post-stream-test.js b/frontend/discourse/tests/unit/models/post-stream-test.jsindex 05e349c4016..73830f3c930 100644--- a/frontend/discourse/tests/unit/models/post-stream-test.js+++ b/frontend/discourse/tests/unit/models/post-stream-test.js@@ -351,6 +351,22 @@ module("Unit | Model | post-stream", function (hooks) {60,"it respects gaps");++ postStream.set("isMegaTopic", true);+ postStream.appendPost(+ postStream.store.createRecord("post", { id: 99, post_number: 1 })+ );++ assert.strictEqual(+ postStream.findPostIdForPostNumber(1),+ 99,+ "it finds loaded posts on mega topics"+ );+ assert.strictEqual(+ postStream.findPostIdForPostNumber(5),+ undefined,+ "it ignores the stream on mega topics"+ );});test("fillGapBefore", function (assert) {diff --git a/frontend/discourse/tests/unit/services/composer-test.js b/frontend/discourse/tests/unit/services/composer-test.jsindex 71c48f0d27b..667f1e89e4d 100644--- a/frontend/discourse/tests/unit/services/composer-test.js+++ b/frontend/discourse/tests/unit/services/composer-test.js@@ -1,7 +1,10 @@+import { settled } from "@ember/test-helpers";import { setupTest } from "ember-qunit";import { module, test } from "qunit";+import sinon from "sinon";import { USER_OPTION_COMPOSITION_MODES } from "discourse/lib/constants";import Composer from "discourse/models/composer";+import pretender, { response } from "discourse/tests/helpers/create-pretender";import { logIn } from "discourse/tests/helpers/qunit-helpers";module("Unit | Service | composer", function (hooks) {@@ -27,6 +30,29 @@ module("Unit | Service | composer", function (hooks) {);}+ test("importQuote quotes the first post of a mega topic", async function (assert) {+ setComposerModel(this);+ const topic = this.owner+ .lookup("service:store")+ .createRecord("topic", { id: 280 });+ topic.postStream.isMegaTopic = true;+ topic.postStream.stream = [9001];+ this.composer.set("topic", topic);+ pretender.get("/posts/by_number/280/1", () =>+ response({ id: 398, post_number: 1, topic_id: 280 })+ );+ const toolbarEvent = { addText: sinon.spy() };++ await this.composer.importQuote(toolbarEvent);+ await settled();++ assert.true(+ toolbarEvent.addText.calledOnceWith(+ sinon.match("Any plans to support localization")+ )+ );+ });+test("predicts the markdown preview before a composer model exists", function (assert) {assert.true(this.composer.allowPreview,diff --git a/lib/topic_view.rb b/lib/topic_view.rbindex fa6139cd21c..3ab95f8f873 100644--- a/lib/topic_view.rb+++ b/lib/topic_view.rb@@ -658,7 +658,7 @@ class TopicViewdef participant_count@participant_count ||=- if participants.size == MAX_PARTICIPANTS+ if is_mega_topic? || participants.size == MAX_PARTICIPANTSif @topic.posts_count > MAX_POSTS_COUNT_PARTICIPANTS@topic.participant_countelsediff --git a/plugins/discourse-post-voting/assets/javascripts/discourse/components/post-voting-answer-header.gjs b/plugins/discourse-post-voting/assets/javascripts/discourse/components/post-voting-answer-header.gjsindex 99e237e33bc..45323333569 100644--- a/plugins/discourse-post-voting/assets/javascripts/discourse/components/post-voting-answer-header.gjs+++ b/plugins/discourse-post-voting/assets/javascripts/discourse/components/post-voting-answer-header.gjs@@ -19,11 +19,12 @@ export default class PostVotingAnswerHeader extends Component {const positionInStream =repliesToPostNumber && parseInt(repliesToPostNumber, 10) !== 1 ? 2 : 1;const answersCount = post.topic.posts_count - 1;+ const { isMegaTopic, posts, stream } = post.topic.postStream;+ const answerId = isMegaTopic+ ? posts[0]?.post_number === 1 && posts[positionInStream]?.id+ : stream[positionInStream];- return (- answersCount > 0 &&- post.id === post.topic.postStream.stream[positionInStream]- );+ return answersCount > 0 && post.id === answerId;}get post() {diff --git a/plugins/discourse-post-voting/test/javascripts/unit/components/post-voting-answer-header-test.js b/plugins/discourse-post-voting/test/javascripts/unit/components/post-voting-answer-header-test.jsnew file mode 100644index 00000000000..71c66b266fe--- /dev/null+++ b/plugins/discourse-post-voting/test/javascripts/unit/components/post-voting-answer-header-test.js@@ -0,0 +1,46 @@+import { getOwner } from "@ember/owner";+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import PostVotingAnswerHeader from "discourse/plugins/discourse-post-voting/discourse/components/post-voting-answer-header";++function createMegaTopic(context, postNumbers) {+ const store = getOwner(context).lookup("service:store");+ const topic = store.createRecord("topic", {+ id: 1,+ is_post_voting: true,+ posts_count: 10_000,+ });+ topic.postStream.isMegaTopic = true;++ return postNumbers.map((postNumber) =>+ topic.postStream.appendPost(+ store.createRecord("post", {+ id: 10 + postNumber,+ post_number: postNumber,+ })+ )+ );+}++module("Unit | Component | post-voting-answer-header", function (hooks) {+ setupTest(hooks);++ test("renders above the first answer on mega topics", function (assert) {+ const [, answer] = createMegaTopic(this, [1, 2]);++ assert.true(+ PostVotingAnswerHeader.shouldRender({+ post: answer,+ topicPageQueryParams: {},+ })+ );+ });++ test("does not render on mega topics loaded past the first post", function (assert) {+ const [, post] = createMegaTopic(this, [500, 501]);++ assert.false(+ PostVotingAnswerHeader.shouldRender({ post, topicPageQueryParams: {} })+ );+ });+});diff --git a/spec/lib/topic_view_spec.rb b/spec/lib/topic_view_spec.rbindex fba4853eda7..7fd060a7b1f 100644--- a/spec/lib/topic_view_spec.rb+++ b/spec/lib/topic_view_spec.rb@@ -553,6 +553,14 @@ RSpec.describe TopicView doendend+ describe ".participant_count" do+ it "uses the cached participant count on mega topics" do+ topic.update!(posts_count: TopicView::MEGA_TOPIC_POSTS_COUNT, participant_count: 42)++ expect(topic_view.participant_count).to eq(42)+ end+ end+describe ".all_post_actions" doit "is blank at first" doexpect(topic_view.all_post_actions).to be_blank