Skip to content

A platform for community discussion. Free, open, simple.

DEV: Modernize post-stream to remove Ember array deprecations (#35100)

Sérgio Saquetim075d0b8ea118
diff --git a/app/assets/javascripts/discourse/app/components/post-stream.gjs b/app/assets/javascripts/discourse/app/components/post-stream.gjs
index 505d78572c2..c900eb62d11 100644
--- a/app/assets/javascripts/discourse/app/components/post-stream.gjs
+++ b/app/assets/javascripts/discourse/app/components/post-stream.gjs
@@ -13,7 +13,7 @@ import concatClass from "discourse/helpers/concat-class";
import lazyHash from "discourse/helpers/lazy-hash";
import { bind } from "discourse/lib/decorators";
import offsetCalculator from "discourse/lib/offset-calculator";
-import { Placeholder } from "discourse/lib/posts-with-placeholders";
+import { Placeholder } from "discourse/models/post-stream";
import PostStreamViewportTracker from "discourse/modifiers/post-stream-viewport-tracker";
import Post from "./post";
import PostGap from "./post/gap";
@@ -63,12 +63,9 @@ export default class PostStream extends Component {
@cached
get posts() {
- const postsToRender = this.capabilities.isAndroid
+ return 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() {
diff --git a/app/assets/javascripts/discourse/app/controllers/topic.js b/app/assets/javascripts/discourse/app/controllers/topic.js
index 900a9c2e71c..72fbf387264 100644
--- a/app/assets/javascripts/discourse/app/controllers/topic.js
+++ b/app/assets/javascripts/discourse/app/controllers/topic.js
@@ -553,7 +553,7 @@ export default class TopicController extends Controller {
}
const postStream = this.get("model.postStream");
- const firstLoadedPost = postStream.get("posts.firstObject");
+ const firstLoadedPost = postStream.posts[0];
if (post.get && post.get("post_number") === 1) {
return;
@@ -570,7 +570,7 @@ export default class TopicController extends Controller {
const { post, refresh } = event;
const postStream = this.get("model.postStream");
- const lastLoadedPost = postStream.get("posts.lastObject");
+ const lastLoadedPost = postStream.posts.at(-1);
if (
lastLoadedPost &&
diff --git a/app/assets/javascripts/discourse/app/lib/array-tools.js b/app/assets/javascripts/discourse/app/lib/array-tools.js
index 1f628a16689..b541791915a 100644
--- a/app/assets/javascripts/discourse/app/lib/array-tools.js
+++ b/app/assets/javascripts/discourse/app/lib/array-tools.js
@@ -14,3 +14,19 @@ export function removeValueFromArray(array, value) {
}
return array;
}
+
+/**
+ * Removes multiple objects from an array by iterating through the provided values
+ * and removing each value from the given array.
+ *
+ * @param {Array} array - The array from which objects will be removed.
+ * @param {Array} values - An array of objects to be removed from the given array.
+ * @return {Array} The updated array with specified objects removed.
+ */
+export function removeValuesFromArray(array, values) {
+ for (let i = values.length - 1; i >= 0; i--) {
+ removeValueFromArray(array, values[i]);
+ }
+
+ return array;
+}
diff --git a/app/assets/javascripts/discourse/app/lib/posts-with-placeholders.js b/app/assets/javascripts/discourse/app/lib/posts-with-placeholders.js
deleted file mode 100644
index 0f34d408db8..00000000000
--- a/app/assets/javascripts/discourse/app/lib/posts-with-placeholders.js
+++ /dev/null
@@ -1,92 +0,0 @@
-import {
- arrayContentDidChange,
- arrayContentWillChange,
-} from "@ember/-internals/metal";
-import EmberArray from "@ember/array";
-import EmberObject from "@ember/object";
-import discourseComputed from "discourse/lib/decorators";
-
-export function Placeholder(viewName) {
- this.viewName = viewName;
-}
-
-export default class PostsWithPlaceholders extends EmberObject.extend(
- EmberArray
-) {
- posts = null;
- _appendingIds = {};
-
- @discourseComputed
- length() {
- return (
- this.get("posts.length") + Object.keys(this._appendingIds || {}).length
- );
- }
-
- nextObject(index) {
- return this.objectAt(index);
- }
-
- _changeArray(cb, offset, removed, inserted) {
- arrayContentWillChange(this, offset, removed, inserted);
- cb();
- arrayContentDidChange(this, offset, removed, inserted);
- this.notifyPropertyChange("length");
- }
-
- clear(cb) {
- this._changeArray(cb, 0, this.get("posts.length"), 0);
- }
-
- appendPost(cb) {
- this._changeArray(cb, this.get("posts.length"), 0, 1);
- }
-
- removePost(cb) {
- this._changeArray(cb, this.get("posts.length") - 1, 1, 0);
- }
-
- insertPost(insertAtIndex, cb) {
- this._changeArray(cb, insertAtIndex, 0, 1);
- }
-
- refreshAll(cb) {
- const length = this.get("posts.length");
- this._changeArray(cb, 0, length, length);
- }
-
- appending(postIds) {
- this._changeArray(
- () => {
- const appendingIds = this._appendingIds;
- postIds.forEach((pid) => (appendingIds[pid] = true));
- },
- this.length,
- 0,
- postIds.length
- );
- }
-
- finishedAppending(postIds) {
- this._changeArray(
- () => {
- const appendingIds = this._appendingIds;
- postIds.forEach((pid) => delete appendingIds[pid]);
- },
- this.get("posts.length") - postIds.length,
- postIds.length,
- postIds.length
- );
- }
-
- finishedPrepending(postIds) {
- this._changeArray(function () {}, 0, 0, postIds.length);
- }
-
- objectAt(index) {
- const posts = this.posts;
- return index < posts.length
- ? posts[index]
- : new Placeholder("post-placeholder");
- }
-}
diff --git a/app/assets/javascripts/discourse/app/models/category.js b/app/assets/javascripts/discourse/app/models/category.js
index e5e0f3b1d05..eb336cbd954 100644
--- a/app/assets/javascripts/discourse/app/models/category.js
+++ b/app/assets/javascripts/discourse/app/models/category.js
@@ -20,6 +20,8 @@ const CATEGORY_ASYNC_SEARCH_CACHE = {};
const CATEGORY_ASYNC_HIERARCHICAL_SEARCH_CACHE = {};
const pluginSaveProperties = new Set();
+let _uncategorized;
+
/**
* @internal
* Adds a tracked property to the post model.
@@ -40,7 +42,7 @@ export default class Category extends RestModel {
categories.forEach((category) => {
const parentId = parseInt(category.parent_category_id, 10) || -1;
const group = children.get(parentId) || [];
- group.pushObject(category);
+ group.push(category);
children.set(parentId, group);
});
@@ -907,8 +909,6 @@ export default class Category extends RestModel {
}
}
-let _uncategorized;
-
const categoryMultiCache = new MultiCache(async (ids) => {
const result = await ajax("/categories/find", { data: { ids } });
diff --git a/app/assets/javascripts/discourse/app/models/post-stream.js b/app/assets/javascripts/discourse/app/models/post-stream.js
index a92c6d8c31a..3e4f155ea5d 100644
--- a/app/assets/javascripts/discourse/app/models/post-stream.js
+++ b/app/assets/javascripts/discourse/app/models/post-stream.js
@@ -1,5 +1,6 @@
-import { tracked } from "@glimmer/tracking";
+import { cached, tracked } from "@glimmer/tracking";
import { get } from "@ember/object";
+import { dependentKeyCompat } from "@ember/object/compat";
import { and, equal, not, or } from "@ember/object/computed";
import { schedule } from "@ember/runloop";
import { service } from "@ember/service";
@@ -7,10 +8,13 @@ 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";
+import {
+ removeValueFromArray,
+ removeValuesFromArray,
+} from "discourse/lib/array-tools";
import deprecated from "discourse/lib/deprecated";
import { deepMerge } from "discourse/lib/object";
-import PostsWithPlaceholders from "discourse/lib/posts-with-placeholders";
+import { trackedArray } from "discourse/lib/tracked-tools";
import { applyBehaviorTransformer } from "discourse/lib/transformer";
import DiscourseURL from "discourse/lib/url";
import { highlightPost } from "discourse/lib/utilities";
@@ -20,6 +24,10 @@ import { i18n } from "discourse-i18n";
let _lastEditNotificationClick = null;
+export function Placeholder(viewName) {
+ this.viewName = viewName;
+}
+
export function setLastEditNotificationClick(
topicId,
postNumber,
@@ -37,25 +45,33 @@ export function resetLastEditNotificationClick() {
}
export default class PostStream extends RestModel {
+ static PLACEHOLDER = new Placeholder("post-placeholder");
+
@service currentUser;
@service store;
+ @tracked appendingPlaceholders = 0;
@tracked filter;
- @tracked filterRepliesToPostNumber;
- @tracked filterUpwardsPostID;
+ @tracked
+ filterRepliesToPostNumber =
+ parseInt(this.topic.replies_to_post_number, 10) || false;
+ @tracked filterUpwardsPostID = false;
@tracked gaps;
+ @tracked isMegaTopic;
@tracked lastId;
- @tracked loaded;
- @tracked loadingAbove;
- @tracked loadingBelow;
- @tracked loadingFilter;
+ @tracked lastAppended;
+ @tracked loaded = false;
+ @tracked loadingAbove = false;
+ @tracked loadingBelow = false;
+ @tracked loadingFilter = false;
+ @tracked loadingLastPost = false;
@tracked loadingNearPost;
- @tracked postsWithPlaceholders;
- @tracked stagingPost;
- @tracked stream;
- @tracked timelineLookup;
- @tracked userFilters;
- @tracked posts;
+ @tracked stagingPost = false;
+ @tracked timelineLookup = [];
+
+ @trackedArray posts = [];
+ @trackedArray stream = [];
+ @trackedArray userFilters = [];
@or("loadingAbove", "loadingBelow", "loadingFilter", "stagingPost") loading;
@not("loading") notLoading;
@@ -65,90 +81,74 @@ export default class PostStream extends RestModel {
@not("firstPostPresent") firstPostNotLoaded;
@not("loadedAllPosts") lastPostNotLoaded;
- _identityMap = null;
+ _identityMap = {};
- init() {
- this._identityMap = {};
- const posts = [];
- const postsWithPlaceholders = PostsWithPlaceholders.create({
- posts,
- store: this.store,
- });
-
- this.setProperties({
- posts,
- postsWithPlaceholders,
- stream: [],
- userFilters: [],
- filterRepliesToPostNumber:
- parseInt(this.get("topic.replies_to_post_number"), 10) || false,
- filterUpwardsPostID: false,
- loaded: false,
- loadingAbove: false,
- loadingBelow: false,
- loadingFilter: false,
- stagingPost: false,
- timelineLookup: [],
- });
+ @cached
+ @dependentKeyCompat
+ get postsWithPlaceholders() {
+ return this.posts.concat(
+ Array.from(
+ { length: this.appendingPlaceholders },
+ () => PostStream.PLACEHOLDER
+ )
+ );
}
- @discourseComputed(
- "isMegaTopic",
- "stream.length",
- "topic.highest_post_number"
- )
- filteredPostsCount(isMegaTopic, streamLength, topicHighestPostNumber) {
- return isMegaTopic ? topicHighestPostNumber : streamLength;
+ @dependentKeyCompat
+ get filteredPostsCount() {
+ return this.isMegaTopic
+ ? this.topic.highest_post_number
+ : this.stream.length;
}
- @discourseComputed("posts.[]")
- hasPosts() {
- return this.get("posts.length") > 0;
+ @dependentKeyCompat
+ get hasPosts() {
+ return this.posts.length > 0;
}
- @discourseComputed("hasPosts", "filteredPostsCount")
- hasLoadedData(hasPosts, filteredPostsCount) {
- return hasPosts && filteredPostsCount > 0;
+ @dependentKeyCompat
+ get hasLoadedData() {
+ return this.hasPosts && this.filteredPostsCount > 0;
}
- @discourseComputed("hasLoadedData", "posts.[]")
- firstPostPresent(hasLoadedData) {
- if (!hasLoadedData) {
+ @dependentKeyCompat
+ get firstPostPresent() {
+ if (!this.hasLoadedData) {
return false;
}
return !!this.posts.find((item) => item.post_number === 1);
}
- @discourseComputed("isMegaTopic", "stream.lastObject", "lastId")
- lastPostId(isMegaTopic, streamLastId, lastId) {
- return isMegaTopic ? lastId : streamLastId;
+ @dependentKeyCompat
+ get firstPostId() {
+ return this.stream[0];
+ }
+
+ @dependentKeyCompat
+ get lastPostId() {
+ return this.isMegaTopic ? this.lastId : this.stream.at(-1);
}
- @discourseComputed("hasLoadedData", "lastPostId", "[email protected]")
- loadedAllPosts(hasLoadedData, lastPostId) {
- if (!hasLoadedData) {
+ @dependentKeyCompat
+ get loadedAllPosts() {
+ if (!this.hasLoadedData) {
return false;
}
- if (lastPostId === -1) {
+ if (this.lastPostId === -1) {
return true;
}
- return !!this.posts.find((item) => item.id === lastPostId);
+ return !!this.posts.find((item) => item.id === this.lastPostId);
}
/**
Returns a JS Object of current stream filter options. It should match the query
params for the stream.
**/
- @discourseComputed(
- "filter",
- "userFilters.[]",
- "filterRepliesToPostNumber",
- "filterUpwardsPostID"
- )
- streamFilters() {
- const result = {};
+ @dependentKeyCompat
+ get streamFilters() {
+ const result = new TrackedObject();
if (this.filter) {
result.filter = this.filter;
@@ -170,8 +170,8 @@ export default class PostStream extends RestModel {
return result;
}
- @discourseComputed("streamFilters.[]", "topic.posts_count", "posts.length")
- hasNoFilters() {
+ @dependentKeyCompat
+ get hasNoFilters() {
const streamFilters = this.streamFilters;
return !(
streamFilters &&
@@ -183,8 +183,8 @@ export default class PostStream extends RestModel {
Returns the window of posts above the current set in the stream, bound to the top of the stream.
This is the collection we'll ask for when scrolling upwards.
**/
- @discourseComputed("posts.[]", "stream.[]")
- previousWindow() {
+ @dependentKeyCompat
+ get previousWindow() {
if (!this.posts) {
return [];
}
@@ -202,7 +202,7 @@ export default class PostStream extends RestModel {
return [];
}
- let startIndex = firstIndex - this.get("topic.chunk_size");
+ let startIndex = firstIndex - this.topic.chunk_size;
if (startIndex < 0) {
startIndex = 0;
}
@@ -213,8 +213,10 @@ export default class PostStream extends RestModel {
Returns the window of posts below the current set in the stream, bound by the bottom of the
stream. This is the collection we use when scrolling downwards.
**/
- @discourseComputed("posts.lastObject", "stream.[]")
- nextWindow(lastLoadedPost) {
+ @dependentKeyCompat
+ get nextWindow() {
+ const lastLoadedPost = this.posts.at(-1);
+
// If we can't find the last post loaded, bail
if (!lastLoadedPost) {
return [];
@@ -231,10 +233,7 @@ export default class PostStream extends RestModel {
}
// find our window of posts
- return stream.slice(
- lastIndex + 1,
- lastIndex + this.get("topic.chunk_size") + 1
- );
+ return stream.slice(lastIndex + 1, lastIndex + this.topic.chunk_size + 1);
}
cancelFilter() {
@@ -250,30 +249,34 @@ export default class PostStream extends RestModel {
refreshAndJumpToSecondVisible() {
return this.refresh({}).then(() => {
if (this.posts && this.posts.length > 1) {
- DiscourseURL.jumpToPost(this.posts[1].get("post_number"));
+ DiscourseURL.jumpToPost(this.posts[1].post_number);
}
});
}
showTopReplies() {
this.cancelFilter();
- this.set("filter", "summary");
+ this.filter = "summary";
return this.refreshAndJumpToSecondVisible();
}
// Filter the stream to a particular user.
filterParticipant(username) {
this.cancelFilter();
- this.userFilters.addObject(username);
+
+ if (!this.userFilters.includes(username)) {
+ this.userFilters.push(username);
+ }
+
return this.refreshAndJumpToSecondVisible();
}
filterReplies(postNumber, postId) {
this.cancelFilter();
- this.set("filterRepliesToPostNumber", postNumber);
+ this.filterRepliesToPostNumber = postNumber;
this.appEvents.trigger("post-stream:filter-replies", {
- topic_id: this.get("topic.id"),
+ topic_id: this.topic.id,
post_number: postNumber,
post_id: postId,
});
@@ -301,9 +304,9 @@ export default class PostStream extends RestModel {
filterUpwards(postID) {
this.cancelFilter();
- this.set("filterUpwardsPostID", postID);
+ this.filterUpwardsPostID = postID;
this.appEvents.trigger("post-stream:filter-upwards", {
- topic_id: this.get("topic.id"),
+ topic_id: this.topic.id,
post_id: postID,
});
return this.refresh({ refreshInPlace: true }).then(() => {
@@ -311,7 +314,7 @@ export default class PostStream extends RestModel {
this.appEvents.trigger("post-stream:refresh");
if (this.posts && this.posts.length > 1) {
- const postNumber = this.posts[1].get("post_number");
+ const postNumber = this.posts[1].post_number;
DiscourseURL.jumpToPost(postNumber, { skipIfOnScreen: true });
schedule("afterRender", () => {
@@ -340,7 +343,7 @@ export default class PostStream extends RestModel {
// Do we already have the post in our list of posts? Jump there.
if (opts.forceLoad) {
- this.set("loaded", false);
+ this.loaded = false;
} else {
const postWeWant = this.posts.find(
(p) => p.post_number === opts.nearPost
@@ -352,9 +355,9 @@ export default class PostStream extends RestModel {
// TODO: if we have all the posts in the filter, don't go to the server for them.
if (!opts.refreshInPlace) {
- this.set("loadingFilter", true);
+ this.loadingFilter = true;
}
- this.set("loadingNearPost", opts.nearPost);
+ this.loadingNearPost = opts.nearPost;
opts = deepMerge(opts, this.streamFilters);
@@ -383,66 +386,65 @@ export default class PostStream extends RestModel {
throw new Error(result);
})
.finally(() => {
- this.set("loadingNearPost", null);
+ this.loadingNearPost = null;
});
}
// Fill in a gap of posts before a particular post
- fillGapBefore(post, gap) {
- const postId = post.get("id"),
- stream = this.stream,
- idx = stream.indexOf(postId),
- currentPosts = this.posts;
-
- if (idx !== -1) {
- // Insert the gap at the appropriate place
-
- let postIdx = currentPosts.indexOf(post);
-
- let headGap = gap.slice(0, this.topic.chunk_size);
- let tailGap = gap.slice(this.topic.chunk_size);
- stream.splice.apply(stream, [idx, 0].concat(headGap));
- if (postIdx !== -1) {
- return this.findPostsByIds(headGap).then((posts) => {
- posts.forEach((p) => {
- this._initUserModels(p);
- const stored = this.storePost(p);
- if (!currentPosts.includes(stored)) {
- const insertAtIndex = postIdx++;
- this.postsWithPlaceholders.insertPost(insertAtIndex, () => {
- currentPosts.insertAt(insertAtIndex, stored);
- });
- }
- });
+ async fillGapBefore(post, gap) {
+ const postId = post.id;
+ const stream = this.stream;
+ const idx = stream.indexOf(postId);
+ const currentPosts = this.posts;
- if (tailGap.length > 0) {
- this.get("gaps.before")[postId] = tailGap;
- } else {
- delete this.get("gaps.before")[postId];
- }
+ if (idx === -1) {
+ return;
+ }
- post.set("hasGap", false);
- this.gapExpanded();
- });
+ // Insert the gap at the appropriate place
+ let postIdx = currentPosts.indexOf(post);
+
+ const headGap = gap.slice(0, this.topic.chunk_size);
+ const tailGap = gap.slice(this.topic.chunk_size);
+ stream.splice.apply(stream, [idx, 0].concat(headGap));
+
+ if (postIdx !== -1) {
+ const posts = await this.findPostsByIds(headGap);
+ posts.forEach((p) => {
+ this._initUserModels(p);
+ const stored = this.storePost(p);
+ if (!currentPosts.includes(stored)) {
+ const insertAtIndex = postIdx++;
+ currentPosts.splice(insertAtIndex, 0, stored);
+ }
+ });
+
+ if (tailGap.length > 0) {
+ this.gaps.before[postId] = tailGap;
+ } else {
+ delete this.gaps.before[postId];
}
+
+ post.hasGap = false;
+ this.gapExpanded();
}
- return Promise.resolve();
}
// Fill in a gap of posts after a particular post
- fillGapAfter(post, gap) {
- const postId = post.get("id"),
- stream = this.stream,
- idx = stream.indexOf(postId);
-
- if (idx !== -1) {
- stream.pushObjects(gap);
- return this.appendMore().then(() => {
- delete this.get("gaps.after")[postId];
- this.gapExpanded();
- });
+ async fillGapAfter(post, gap) {
+ const postId = post.id;
+ const stream = this.stream;
+ const idx = stream.indexOf(postId);
+
+ if (idx === -1) {
+ return;
}
- return Promise.resolve();
+
+ stream.push(...gap);
+
+ await this.appendMore();
+ delete this.gaps.after[postId];
+ this.gapExpanded();
}
gapExpanded() {
@@ -452,96 +454,79 @@ export default class PostStream extends RestModel {
// resets the reply count in posts-filtered-notice
// because once a gap has been expanded that count is no longer exact
if (this.streamFilters && this.streamFilters.replies_to_post_number) {
- this.set("streamFilters.mixedHiddenPosts", true);
+ this.streamFilters.mixedHiddenPosts = true;
}
}
// Appends the next window of posts to the stream. Call it when scrolling downwards.
- appendMore() {
+ async appendMore() {
// Make sure we can append more posts
if (!this.canAppendMore) {
- return Promise.resolve();
+ return;
}
- const postsWithPlaceholders = this.postsWithPlaceholders;
-
if (this.isMegaTopic) {
- this.set("loadingBelow", true);
+ this.loadingBelow = true;
+ this.appendingPlaceholders += this.topic.chunk_size - 1;
- const fakePostIds = [
- ...Array(this.get("topic.chunk_size") - 1).keys(),
- ].map((i) => -i - 1);
- postsWithPlaceholders.appending(fakePostIds);
-
- return this.fetchNextWindow(
- this.get("posts.lastObject.post_number"),
- true,
- (p) => {
+ try {
+ await this.fetchNextWindow(this.posts.at(-1).post_number, true, (p) => {
this.appendPost(p);
- }
- ).finally(() => {
- postsWithPlaceholders.finishedAppending(fakePostIds);
- this.set("loadingBelow", false);
- });
+ });
+ } finally {
+ this.appendingPlaceholders -= this.topic.chunk_size - 1;
+ this.loadingBelow = false;
+ }
} else {
const postIds = this.nextWindow;
if (isEmpty(postIds)) {
- return Promise.resolve();
+ return;
}
- this.set("loadingBelow", true);
- postsWithPlaceholders.appending(postIds);
- return this.findPostsByIds(postIds)
- .then((posts) => {
- posts.forEach((p) => this.appendPost(p));
- return posts;
- })
- .finally(() => {
- postsWithPlaceholders.finishedAppending(postIds);
- this.set("loadingBelow", false);
- });
+ this.loadingBelow = true;
+ this.appendingPlaceholders += postIds.length;
+
+ try {
+ const posts = await this.findPostsByIds(postIds);
+ posts.forEach((p) => this.appendPost(p));
+ return posts;
+ } finally {
+ this.appendingPlaceholders -= postIds.length;
+ this.loadingBelow = false;
+ }
}
}
// Prepend the previous window of posts to the stream. Call it when scrolling upwards.
- prependMore() {
+ async prependMore() {
// Make sure we can append more posts
if (!this.canPrependMore) {
- return Promise.resolve();
+ return;
}
if (this.isMegaTopic) {
- this.set("loadingAbove", true);
- let prependedIds = [];
+ this.loadingAbove = true;
- return this.fetchNextWindow(
- this.get("posts.firstObject.post_number"),
- false,
- (p) => {
+ try {
+ await this.fetchNextWindow(this.posts[0].post_number, false, (p) => {
this.prependPost(p);
- prependedIds.push(p.get("id"));
- }
- ).finally(() => {
- const postsWithPlaceholders = this.postsWithPlaceholders;
- postsWithPlaceholders.finishedPrepending(prependedIds);
- this.set("loadingAbove", false);
- });
+ });
+ } finally {
+ this.loadingAbove = false;
+ }
} else {
const postIds = this.previousWindow;
if (isEmpty(postIds)) {
- return Promise.resolve();
+ return;
}
- this.set("loadingAbove", true);
+ this.loadingAbove = true;
- return this.findPostsByIds(postIds.reverse())
- .then((posts) => {
- posts.forEach((p) => this.prependPost(p));
- })
- .finally(() => {
- const postsWithPlaceholders = this.postsWithPlaceholders;
- postsWithPlaceholders.finishedPrepending(postIds);
- this.set("loadingAbove", false);
- });
+ try {
+ const posts = await this.findPostsByIds(postIds.reverse());
+ posts.forEach((p) => this.prependPost(p));
+ } finally {
+ this.loadingAbove = false;
+ }
}
}
@@ -556,18 +541,18 @@ export default class PostStream extends RestModel {
return "alreadyStaging";
}
- this.set("stagingPost", true);
+ this.stagingPost = true;
const topic = this.topic;
topic.setProperties({
- posts_count: (topic.get("posts_count") || 0) + 1,
+ posts_count: (topic.posts_count || 0) + 1,
last_posted_at: new Date(),
"details.last_poster": user,
- highest_post_number: (topic.get("highest_post_number") || 0) + 1,
+ highest_post_number: (topic.highest_post_number || 0) + 1,
});
post.setProperties({
- post_number: topic.get("highest_post_number"),
+ post_number: topic.highest_post_number,
topic,
created_at: new Date(),
id: -1,
@@ -576,7 +561,10 @@ export default class PostStream extends RestModel {
// If we're at the end of the stream, add the post
if (this.loadedAllPosts) {
this.appendPost(post);
- this.stream.addObject(post.get("id"));
+ if (!this.stream.includes(post.id)) {
+ this.stream.push(post.id);
+ }
+
return "staged";
}
@@ -585,16 +573,18 @@ export default class PostStream extends RestModel {
// Commit the post we staged. Call this after a save succeeds.
commitPost(post) {
- if (this.get("topic.id") === post.get("topic_id")) {
+ if (this.topic.id === post.topic_id) {
if (this.loadedAllPosts) {
this.appendPost(post);
- this.stream.addObject(post.get("id"));
+ if (!this.stream.includes(post.id)) {
+ this.stream.push(post.id);
+ }
}
}
- this.stream.removeObject(-1);
+ removeValueFromArray(this.stream, -1);
this._identityMap[-1] = null;
- this.set("stagingPost", false);
+ this.stagingPost = false;
}
/**
@@ -602,16 +592,16 @@ export default class PostStream extends RestModel {
state we changed.
**/
undoPost(post) {
- this.stream.removeObject(-1);
- this.postsWithPlaceholders.removePost(() => this.posts.removeObject(post));
+ removeValueFromArray(this.stream, -1);
+ removeValueFromArray(this.posts, post);
this._identityMap[-1] = null;
const topic = this.topic;
- this.set("stagingPost", false);
+ this.stagingPost = false;
topic.setProperties({
- highest_post_number: (topic.get("highest_post_number") || 0) - 1,
- posts_count: (topic.get("posts_count") || 0) - 1,
+ highest_post_number: (topic.highest_post_number || 0) - 1,
+ posts_count: (topic.posts_count || 0) - 1,
});
// TODO unfudge reply count on parent post
@@ -620,9 +610,9 @@ export default class PostStream extends RestModel {
prependPost(post) {
this._initUserModels(post);
const stored = this.storePost(post);
- if (stored) {
- const posts = this.posts;
- posts.unshiftObject(stored);
+
+ if (stored && !this.posts.includes(stored)) {
+ this.posts.unshift(stored);
}
return post;
@@ -631,21 +621,17 @@ export default class PostStream extends RestModel {
appendPost(post) {
this._initUserModels(post);
const stored = this.storePost(post);
- if (stored) {
- const posts = this.posts;
- if (!posts.includes(stored)) {
- if (!this.loadingBelow) {
- this.postsWithPlaceholders.appendPost(() => posts.pushObject(stored));
- } else {
- posts.pushObject(stored);
- }
+ if (stored) {
+ if (!this.posts.includes(stored)) {
+ this.posts.push(stored);
}
- if (stored.get("id") !== -1) {
- this.set("lastAppended", stored);
+ if (stored.id !== -1) {
+ this.lastAppended = stored;
}
}
+
return post;
}
@@ -654,15 +640,13 @@ export default class PostStream extends RestModel {
return;
}
- this.postsWithPlaceholders.refreshAll(() => {
- const allPosts = this.posts;
- const postIds = posts.map((p) => p.get("id"));
- const identityMap = this._identityMap;
+ const allPosts = this.posts;
+ const postIds = posts.map((p) => p.id);
+ const identityMap = this._identityMap;
- this.stream.removeObjects(postIds);
- allPosts.removeObjects(posts);
- postIds.forEach((id) => delete identityMap[id]);
- });
+ removeValuesFromArray(this.stream, postIds);
+ removeValuesFromArray(allPosts, posts);
+ postIds.forEach((id) => delete identityMap[id]);
}
// Returns a post from the identity map if it's been inserted.
@@ -671,7 +655,7 @@ export default class PostStream extends RestModel {
}
loadPostByPostNumber(postNumber) {
- const url = `/posts/by_number/${this.get("topic.id")}/${postNumber}`;
+ const url = `/posts/by_number/${this.topic.id}/${postNumber}`;
const store = this.store;
return ajax(url).then((post) => {
@@ -680,7 +664,7 @@ export default class PostStream extends RestModel {
}
loadNearestPostToDate(date) {
- const url = `/posts/by-date/${this.get("topic.id")}/${date}`;
+ const url = `/posts/by-date/${this.topic.id}/${date}`;
const store = this.store;
return ajax(url).then((post) => {
@@ -720,106 +704,108 @@ export default class PostStream extends RestModel {
from the message bus indicating there's a new post. We'll only insert it if we currently
have no filters.
**/
- triggerNewPostsInStream(postIds, opts) {
- const resolved = Promise.resolve();
-
+ async triggerNewPostsInStream(postIds, opts) {
+ // Early return if no posts or empty array
if (!postIds || postIds.length === 0) {
- return resolved;
+ return;
}
- // We only trigger if there are no filters active
+ // Early return if there are filters active
if (!this.hasNoFilters) {
- return resolved;
+ return;
}
const loadedAllPosts = this.loadedAllPosts;
this._loadingPostIds = this._loadingPostIds || [];
- let missingIds = [];
-
- postIds.forEach((postId) => {
- if (postId && !this.stream.includes(postId)) {
- missingIds.push(postId);
- }
- });
+ // Find missing post IDs that aren't in the stream
+ const missingIds = postIds.filter(
+ (postId) => postId && !this.stream.includes(postId)
+ );
if (missingIds.length === 0) {
- return resolved;
+ return;
}
if (loadedAllPosts) {
+ // Add missing posts to loading queue if not already loading
missingIds.forEach((postId) => {
if (!this._loadingPostIds.includes(postId)) {
this._loadingPostIds.push(postId);
}
});
- this.set("loadingLastPost", true);
- return this.findPostsByIds(this._loadingPostIds, opts)
- .then((posts) => {
- this._loadingPostIds = null;
- const ignoredUsers = this.currentUser?.ignored_users;
- posts.forEach((p) => {
- if (ignoredUsers?.includes(p.username)) {
- this.stream.removeObject(p.id);
- return;
- }
- this.stream.addObject(p.id);
- this.appendPost(p);
- });
- })
- .finally(() => {
- this.set("loadingLastPost", false);
+
+ this.loadingLastPost = true;
+
+ try {
+ const posts = await this.findPostsByIds(this._loadingPostIds, opts);
+ this._loadingPostIds = null;
+
+ const ignoredUsers = this.currentUser?.ignored_users;
+ posts.forEach((p) => {
+ if (ignoredUsers?.includes(p.username)) {
+ removeValueFromArray(this.stream, p.id);
+ return;
+ }
+
+ if (!this.stream.includes(p.id)) {
+ this.stream.push(p.id);
+ }
+ this.appendPost(p);
});
+ } finally {
+ this.loadingLastPost = false;
+ }
} else {
- missingIds.forEach((postId) => this.stream.addObject(postId));
+ // Simply add missing post IDs to the stream
+ missingIds.forEach((postId) => {
+ if (!this.stream.includes(postId)) {
+ this.stream.push(postId);
+ }
+ });
}
-
- return resolved;
}
- triggerRecoveredPost(postId) {
+ async triggerRecoveredPost(postId) {
const existing = this._identityMap[postId];
if (existing) {
return this.triggerChangedPost(postId, new Date());
- } else {
- // need to insert into stream
- const url = `/posts/${postId}`;
- const store = this.store;
+ }
- return ajax(url).then((p) => {
- const post = store.createRecord("post", p);
- const stream = this.stream;
- const posts = this.posts;
- this.storePost(post);
+ // need to insert into stream
+ const url = `/posts/${postId}`;
+ const store = this.store;
- // we need to zip this into the stream
- let index = 0;
- stream.forEach((pid) => {
- if (pid < p.id) {
- index += 1;
- }
- });
+ const p = await ajax(url);
+ const post = store.createRecord("post", p);
+ const stream = this.stream;
+ const posts = this.posts;
+ this.storePost(post);
- stream.insertAt(index, p.id);
+ // we need to zip this into the stream
+ let index = 0;
+ stream.forEach((pid) => {
+ if (pid < p.id) {
+ index += 1;
+ }
+ });
- index = 0;
- posts.forEach((_post) => {
- if (_post.id < p.id) {
- index += 1;
- }
- });
+ stream.splice(index, 0, p.id);
- if (index < posts.length) {
- this.postsWithPlaceholders.refreshAll(() => {
- posts.insertAt(index, post);
- });
- } else {
- if (post.post_number < posts[posts.length - 1].post_number + 5) {
- this.appendMore();
- }
- }
- });
+ index = 0;
+ posts.forEach((_post) => {
+ if (_post.id < p.id) {
+ index += 1;
+ }
+ });
+
+ if (index < posts.length) {
+ posts.splice(index, 0, post);
+ } else {
+ if (post.post_number < posts[posts.length - 1].post_number + 5) {
+ await this.appendMore();
+ }
}
}
@@ -902,7 +888,7 @@ export default class PostStream extends RestModel {
resolved.then(() => {
const post = this.findLoadedPost(postId);
if (post && readersCount > post.readers_count) {
- post.set("readers_count", readersCount);
+ post.readers_count = readersCount;
this.storePost(post);
}
});
@@ -927,7 +913,7 @@ export default class PostStream extends RestModel {
}
return this.posts.find((p) => {
- return p.get("post_number") === postNumber;
+ return p.post_number === postNumber;
});
}
@@ -949,8 +935,8 @@ export default class PostStream extends RestModel {
}
if (
- Math.abs(postNumber - p.get("post_number")) <
- Math.abs(closest.get("post_number") - postNumber)
+ Math.abs(postNumber - p.post_number) <
+ Math.abs(closest.post_number - postNumber)
) {
closest = p;
}
@@ -966,10 +952,10 @@ export default class PostStream extends RestModel {
// Get the index in the stream of a post id. (Use this for the topic progress bar.)
progressIndexOfPostId(post) {
- const postId = post.get("id");
+ const postId = post.id;
if (this.isMegaTopic) {
- return post.get("post_number");
+ return post.post_number;
} else {
const index = this.stream.indexOf(postId);
return index + 1;
@@ -992,14 +978,13 @@ export default class PostStream extends RestModel {
return;
}
if (!closest) {
- closest = p.get("post_number");
+ closest = p.post_number;
}
if (
- Math.abs(postNumber - p.get("post_number")) <
- Math.abs(closest - postNumber)
+ Math.abs(postNumber - p.post_number) < Math.abs(closest - postNumber)
) {
- closest = p.get("post_number");
+ closest = p.post_number;
}
});
@@ -1033,9 +1018,9 @@ export default class PostStream extends RestModel {
// Find a postId for a postNumber, respecting gaps
findPostIdForPostNumber(postNumber) {
- const stream = this.stream,
- beforeLookup = this.get("gaps.before"),
- streamLength = stream.length;
+ const stream = this.stream;
+ const beforeLookup = this.gaps?.before;
+ const streamLength = stream.length;
let sum = 1;
for (let i = 0; i < streamLength; i++) {
@@ -1062,12 +1047,9 @@ export default class PostStream extends RestModel {
}
updateFromJson(postStreamData) {
- const posts = this.posts;
-
- const postsWithPlaceholders = this.postsWithPlaceholders;
- postsWithPlaceholders.clear(() => posts.clear());
+ this.posts.length = 0;
- this.set("gaps", null);
+ this.gaps = null;
if (postStreamData) {
// Load posts if present
const store = this.store;
@@ -1099,16 +1081,13 @@ export default class PostStream extends RestModel {
const postId = get(post, "id");
if (postId) {
- const existing = this._identityMap[post.get("id")];
+ const existing = this._identityMap[post.id];
// Update the `highest_post_number` if this post is higher.
- const postNumber = post.get("post_number");
- if (
- postNumber &&
- postNumber > (this.get("topic.highest_post_number") || 0)
- ) {
- this.set("topic.highest_post_number", postNumber);
- this.set("topic.last_posted_at", post.get("created_at"));
+ const postNumber = post.post_number;
+ if (postNumber && postNumber > (this.topic.highest_post_number || 0)) {
+ this.topic.highest_post_number = postNumber;
+ this.topic.last_posted_at = post.created_at;
}
if (existing) {
@@ -1120,15 +1099,15 @@ export default class PostStream extends RestModel {
if (post.topic !== this.topic) {
post.topic = this.topic;
}
- this._identityMap[post.get("id")] = post;
+ this._identityMap[post.id] = post;
}
return post;
}
fetchNextWindow(postNumber, asc, callback) {
- let includeSuggested = !this.get("topic.suggested_topics");
+ let includeSuggested = !this.topic.suggested_topics;
- const url = `/t/${this.get("topic.id")}/posts.json`;
+ const url = `/t/${this.topic.id}/posts.json`;
let data = {
post_number: postNumber,
asc,
@@ -1170,9 +1149,9 @@ export default class PostStream extends RestModel {
return Promise.resolve([]);
}
- let includeSuggested = !this.get("topic.suggested_topics");
+ let includeSuggested = !this.topic.suggested_topics;
- const url = "/t/" + this.get("topic.id") + "/posts.json";
+ const url = "/t/" + this.topic.id + "/posts.json";
const data = { post_ids: postIds, include_suggested: includeSuggested };
const store = this.store;
@@ -1230,10 +1209,9 @@ export default class PostStream extends RestModel {
post_ids: postIds,
};
- this._excerpts.loading = ajax(
- "/t/" + this.get("topic.id") + "/excerpts.json",
- { data }
- )
+ this._excerpts.loading = ajax("/t/" + this.topic.id + "/excerpts.json", {
+ data,
+ })
.then((excerpts) => {
excerpts.forEach((obj) => {
this._excerpts[obj.post_id] = obj;
@@ -1270,7 +1248,7 @@ export default class PostStream extends RestModel {
}
indexOf(post) {
- return this.stream.indexOf(post.get("id"));
+ return this.stream.indexOf(post.id);
}
// Handles an error loading a topic based on a HTTP status code. Updates
@@ -1280,8 +1258,8 @@ export default class PostStream extends RestModel {
"post-stream-error-loading",
() => {
const topic = this.topic;
- this.set("loadingFilter", false);
- topic.set("errorLoading", true);
+ this.loadingFilter = false;
+ topic.errorLoading = true;
if (!error.jqXHR) {
throw error;
@@ -1289,11 +1267,11 @@ export default class PostStream extends RestModel {
const json = error.jqXHR.responseJSON;
if (json && json.extras && json.extras.html) {
- topic.set("errorTitle", json.extras.title);
- topic.set("errorHtml", json.extras.html);
+ topic.errorTitle = json.extras.title;
+ topic.errorHtml = json.extras.html;
} else {
- topic.set("errorMessage", i18n("topic.server_error.description"));
- topic.set("noRetry", error.jqXHR.status === 403);
+ topic.errorMessage = i18n("topic.server_error.description");
+ topic.noRetry = error.jqXHR.status === 403;
}
},
{
diff --git a/app/assets/javascripts/discourse/app/models/post.js b/app/assets/javascripts/discourse/app/models/post.js
index a60d936810a..566bc5bc8ea 100644
--- a/app/assets/javascripts/discourse/app/models/post.js
+++ b/app/assets/javascripts/discourse/app/models/post.js
@@ -178,6 +178,7 @@ export default class Post extends RestModel {
@trackedPostProperty excerpt;
@trackedPostProperty expandedExcerpt;
@trackedPostProperty group_moderator;
+ @trackedPostProperty hasGap;
@trackedPostProperty hidden;
@trackedPostProperty id;
@trackedPostProperty is_auto_generated;
@@ -194,6 +195,7 @@ export default class Post extends RestModel {
@trackedPostProperty primary_group_name;
@trackedPostProperty quoted;
@trackedPostProperty read;
+ @trackedPostProperty readers_count;
@trackedPostProperty reply_count;
@trackedPostProperty reply_to_user;
@trackedPostProperty staff;
diff --git a/app/assets/javascripts/discourse/app/models/site.js b/app/assets/javascripts/discourse/app/models/site.js
index 39e8afe5df6..fefdfd7c3fc 100644
--- a/app/assets/javascripts/discourse/app/models/site.js
+++ b/app/assets/javascripts/discourse/app/models/site.js
@@ -1,4 +1,4 @@
-import { tracked } from "@glimmer/tracking";
+import { cached } from "@glimmer/tracking";
import EmberObject, { computed, get } from "@ember/object";
import { dependentKeyCompat } from "@ember/object/compat";
import { alias, sort } from "@ember/object/computed";
@@ -12,6 +12,7 @@ import { getOwnerWithFallback } from "discourse/lib/get-owner";
import Mobile from "discourse/lib/mobile";
import PreloadStore from "discourse/lib/preload-store";
import singleton from "discourse/lib/singleton";
+import { trackedArray } from "discourse/lib/tracked-tools";
import Archetype from "discourse/models/archetype";
import Category from "discourse/models/category";
import PostActionType from "discourse/models/post-action-type";
@@ -85,7 +86,7 @@ export default class Site extends RestModel {
@service currentUser;
@service capabilities;
- @tracked categories;
+ @trackedArray categories;
@alias("is_readonly") isReadOnly;
@@ -279,9 +280,9 @@ export default class Site extends RestModel {
}
// Sort subcategories under parents
- @discourseComputed("categoriesByCount", "categories.[]")
- sortedCategories(categories) {
- return Category.sortCategories(categories);
+ @cached
+ get sortedCategories() {
+ return Category.sortCategories(this.categoriesByCount);
}
// Returns it in the correct order, by setting
diff --git a/app/assets/javascripts/discourse/app/models/topic.js b/app/assets/javascripts/discourse/app/models/topic.js
index fa6b156f6e7..086b07e74e2 100644
--- a/app/assets/javascripts/discourse/app/models/topic.js
+++ b/app/assets/javascripts/discourse/app/models/topic.js
@@ -301,11 +301,22 @@ export default class Topic extends RestModel {
@service currentUser;
@service siteSettings;
- @tracked deleted_by;
+ @tracked chunk_size;
@tracked deleted_at;
+ @tracked deleted_by;
+ @tracked errorHtml;
+ @tracked errorLoading = false;
+ @tracked errorMessage;
+ @tracked errorTitle;
+ @tracked highest_post_number;
+ @tracked last_posted_at;
+ @tracked last_read_post_number;
+ @tracked noRetry;
+ @tracked posts_count;
+ @tracked replies_to_post_number;
+ @tracked suggested_topics;
message = null;
- errorLoading = false;
@alias("lastPoster.user") lastPosterUser;
@alias("lastPoster.primary_group") lastPosterGroup;
@@ -666,7 +677,7 @@ export default class Topic extends RestModel {
firstPost() {
const postStream = this.postStream;
- let firstPost = postStream.get("posts.firstObject");
+ let firstPost = postStream.posts[0];
if (firstPost && firstPost.post_number === 1) {
return Promise.resolve(firstPost);
diff --git a/app/assets/javascripts/discourse/app/routes/topic.js b/app/assets/javascripts/discourse/app/routes/topic.js
index df9220651c0..d9291ae1422 100644
--- a/app/assets/javascripts/discourse/app/routes/topic.js
+++ b/app/assets/javascripts/discourse/app/routes/topic.js
@@ -341,12 +341,12 @@ export default class TopicRoute extends DiscourseRoute {
const postStream = topic.get("postStream");
postStream.set("filter", get(params, "filter"));
- const usernames = get(params, "username_filters"),
- userFilters = postStream.get("userFilters");
+ const usernames = get(params, "username_filters");
- userFilters.clear();
if (!isEmpty(usernames) && usernames !== "undefined") {
- userFilters.addObjects(usernames.split(","));
+ postStream.userFilters = [...new Set(usernames.split(","))];
+ } else {
+ postStream.userFilters = [];
}
return topic;
diff --git a/app/assets/javascripts/discourse/app/services/composer.js b/app/assets/javascripts/discourse/app/services/composer.js
index 7b0c45ad836..b4a5228b993 100644
--- a/app/assets/javascripts/discourse/app/services/composer.js
+++ b/app/assets/javascripts/discourse/app/services/composer.js
@@ -859,7 +859,7 @@ export default class ComposerService extends Service {
// If there is no current post, use the first post id from the stream
if (!postId && postStream) {
- postId = postStream.get("stream.firstObject");
+ postId = postStream.firstPostId;
}
// If we're editing a post, fetch the reply when importing a quote
diff --git a/app/assets/javascripts/discourse/app/widgets/post-stream.js b/app/assets/javascripts/discourse/app/widgets/post-stream.js
index 6160bd085b3..9b47b1405b5 100644
--- a/app/assets/javascripts/discourse/app/widgets/post-stream.js
+++ b/app/assets/javascripts/discourse/app/widgets/post-stream.js
@@ -5,12 +5,10 @@ import { addWidgetCleanCallback } from "discourse/components/mount-widget";
import discourseDebounce from "discourse/lib/debounce";
import { registerDeprecationHandler } from "discourse/lib/deprecated";
import { iconNode } from "discourse/lib/icon-library";
-import PostsWithPlaceholders, {
- Placeholder,
-} from "discourse/lib/posts-with-placeholders";
import { consolePrefix } from "discourse/lib/source-identifier";
import transformPost from "discourse/lib/transform-post";
import DiscourseURL from "discourse/lib/url";
+import { Placeholder } from "discourse/models/post-stream";
import { avatarFor } from "discourse/widgets/post";
import RenderGlimmer from "discourse/widgets/render-glimmer";
import {
@@ -215,9 +213,7 @@ export default createWidget("post-stream", {
tagName: "div.post-stream.widget-post-stream",
html(attrs) {
- const posts = attrs.posts || [];
- const postArray =
- posts instanceof PostsWithPlaceholders ? posts.toArray() : posts;
+ const postArray = attrs.posts || [];
const postArrayLength = postArray.length;
const maxPostNumber =
postArrayLength > 0 ? postArray[postArrayLength - 1].post_number : 0;
diff --git a/app/assets/javascripts/discourse/tests/unit/controllers/topic-test.js b/app/assets/javascripts/discourse/tests/unit/controllers/topic-test.js
index c4b0ef070cd..daf01732f76 100644
--- a/app/assets/javascripts/discourse/tests/unit/controllers/topic-test.js
+++ b/app/assets/javascripts/discourse/tests/unit/controllers/topic-test.js
@@ -5,7 +5,7 @@ import { setupTest } from "ember-qunit";
import { module, test } from "qunit";
import sinon from "sinon";
import { forceMobile } from "discourse/lib/mobile";
-import { Placeholder } from "discourse/lib/posts-with-placeholders";
+import { Placeholder } from "discourse/models/post-stream";
import pretender, { response } from "discourse/tests/helpers/create-pretender";
function topicWithStream(streamDetails) {
diff --git a/app/assets/javascripts/discourse/tests/unit/lib/array-tools-test.js b/app/assets/javascripts/discourse/tests/unit/lib/array-tools-test.js
index 10191c4cf0b..93998f5288d 100644
--- a/app/assets/javascripts/discourse/tests/unit/lib/array-tools-test.js
+++ b/app/assets/javascripts/discourse/tests/unit/lib/array-tools-test.js
@@ -1,6 +1,9 @@
import { TrackedArray } from "@ember-compat/tracked-built-ins";
import { module, test } from "qunit";
-import { removeValueFromArray } from "discourse/lib/array-tools";
+import {
+ removeValueFromArray,
+ removeValuesFromArray,
+} from "discourse/lib/array-tools";
module("Unit | Lib | array-tools", function () {
module("removeValueFromArray()", function () {
@@ -96,4 +99,81 @@ module("Unit | Lib | array-tools", function () {
assert.deepEqual(twice, [2, 3], "second removal is a no-op");
});
});
+
+ module("removeValuesFromArray()", function () {
+ test("removes multiple primitive values from a plain array", function (assert) {
+ const input = [1, 2, 3, 2, 4, 5, 3, 6];
+ const result = removeValuesFromArray(input, [2, 3]);
+
+ assert.strictEqual(result, input, "returns the same array reference");
+ assert.deepEqual(result, [1, 4, 5, 6], "removes all listed values");
+ });
+
+ test("works when values contains duplicates", function (assert) {
+ const input = [1, 2, 3, 2, 3, 4];
+ const result = removeValuesFromArray(input, [2, 2, 3]);
+
+ assert.strictEqual(result, input, "returns the same array reference");
+ assert.deepEqual(result, [1, 4], "duplicates in values don't matter");
+ });
+
+ test("does nothing when values list is empty", function (assert) {
+ const input = [1, 2, 3];
+ const result = removeValuesFromArray(input, []);
+
+ assert.strictEqual(result, input, "returns the same array reference");
+ assert.deepEqual(result, [1, 2, 3], "array remains unchanged");
+ });
+
+ test("removes by strict equality including objects and symbols", function (assert) {
+ const a = { id: 1 };
+ const b = { id: 2 };
+ const dupA = { id: 1 };
+ const sym1 = Symbol("x");
+ const sym2 = Symbol("x");
+
+ const input = [a, b, dupA, sym1, sym2, a];
+ const result = removeValuesFromArray(input, [a, sym2]);
+
+ assert.strictEqual(result, input, "returns the same array reference");
+ assert.deepEqual(
+ result,
+ [b, dupA, sym1],
+ "removes only strictly-equal instances"
+ );
+ });
+
+ test("works with TrackedArray and maintains same instance", function (assert) {
+ const tracked = new TrackedArray([1, 2, 3, 4, 5, 2, 4]);
+ const result = removeValuesFromArray(tracked, [2, 4]);
+
+ assert.strictEqual(result, tracked, "same TrackedArray instance");
+ assert.deepEqual(Array.from(result), [1, 3, 5], "values removed");
+ });
+
+ test("handles heterogeneous arrays and order of removal", function (assert) {
+ const sym = Symbol("s");
+ const input = [0, false, null, undefined, "", sym, 0, false, "x"];
+
+ const result = removeValuesFromArray(input, [false, 0, sym]);
+
+ assert.strictEqual(result, input, "returns the same array reference");
+ assert.deepEqual(
+ result,
+ [null, undefined, "", "x"],
+ "removes all specified values regardless of order"
+ );
+ });
+
+ test("idempotent when called repeatedly with same values list", function (assert) {
+ const input = [1, 1, 2, 3, 1];
+
+ const once = removeValuesFromArray(input, [1, 2]);
+ assert.deepEqual(once, [3], "first call removes 1 and 2");
+
+ const twice = removeValuesFromArray(once, [1, 2]);
+ assert.strictEqual(twice, once, "same reference returned");
+ assert.deepEqual(twice, [3], "second call is a no-op");
+ });
+ });
});
diff --git a/app/assets/javascripts/discourse/tests/unit/models/post-stream-test.js b/app/assets/javascripts/discourse/tests/unit/models/post-stream-test.js
index 21d86cbad1d..92b67a76b00 100644
--- a/app/assets/javascripts/discourse/tests/unit/models/post-stream-test.js
+++ b/app/assets/javascripts/discourse/tests/unit/models/post-stream-test.js
@@ -1,4 +1,3 @@
-import ArrayProxy from "@ember/array/proxy";
import { getOwner } from "@ember/owner";
import { setupTest } from "ember-qunit";
import { module, test } from "qunit";
@@ -541,9 +540,9 @@ module("Unit | Model | post-stream", function (hooks) {
// Find posts by ids uses the identity map
const result = await postStream.findPostsByIds([1, 2, 3]);
assert.strictEqual(result.length, 3);
- assert.strictEqual(result.objectAt(0), p1);
- assert.strictEqual(result.objectAt(1).post_number, 2);
- assert.strictEqual(result.objectAt(2), p3);
+ assert.strictEqual(result[0], p1);
+ assert.strictEqual(result[1].post_number, 2);
+ assert.strictEqual(result[2], p3);
});
test("loadIntoIdentityMap with no data", async function (assert) {
@@ -947,10 +946,8 @@ module("Unit | Model | post-stream", function (hooks) {
4964,
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
);
- const postsWithPlaceholders = postStream.postsWithPlaceholders;
- const store = getOwner(this).lookup("service:store");
- const testProxy = ArrayProxy.create({ content: postsWithPlaceholders });
+ const store = getOwner(this).lookup("service:store");
const p1 = store.createRecord("post", { id: 1, post_number: 1 });
const p2 = store.createRecord("post", { id: 2, post_number: 2 });
@@ -962,36 +959,31 @@ module("Unit | Model | post-stream", function (hooks) {
postStream.appendPost(p3);
// Test enumerable and array access
- assert.strictEqual(postsWithPlaceholders.length, 3);
- assert.strictEqual(testProxy.length, 3);
- assert.strictEqual(postsWithPlaceholders.nextObject(0), p1);
- assert.strictEqual(postsWithPlaceholders.objectAt(0), p1);
- assert.strictEqual(postsWithPlaceholders.nextObject(1, p1), p2);
- assert.strictEqual(postsWithPlaceholders.objectAt(1), p2);
- assert.strictEqual(postsWithPlaceholders.nextObject(2, p2), p3);
- assert.strictEqual(postsWithPlaceholders.objectAt(2), p3);
+ assert.strictEqual(postStream.postsWithPlaceholders.length, 3);
+ assert.strictEqual(postStream.postsWithPlaceholders[0], p1);
+ assert.strictEqual(postStream.postsWithPlaceholders[1], p2);
+ assert.strictEqual(postStream.postsWithPlaceholders[2], p3);
const promise = postStream.appendMore();
assert.strictEqual(
- postsWithPlaceholders.length,
+ postStream.postsWithPlaceholders.length,
8,
"we immediately have a larger placeholder window"
);
- assert.strictEqual(testProxy.length, 8);
- assert.true(!!postsWithPlaceholders.nextObject(3, p3));
- assert.true(!!postsWithPlaceholders.objectAt(4));
- assert.notStrictEqual(postsWithPlaceholders.objectAt(3), p4);
- assert.notStrictEqual(testProxy.objectAt(3), p4);
+ assert.strictEqual(postStream.postsWithPlaceholders.length, 8);
+ assert.true(!!postStream.postsWithPlaceholders[3]);
+ assert.true(!!postStream.postsWithPlaceholders[4]);
+ assert.notStrictEqual(postStream.postsWithPlaceholders[3], p4);
await promise;
- assert.strictEqual(postsWithPlaceholders.objectAt(3), p4);
+ assert.strictEqual(postStream.postsWithPlaceholders[3], p4);
assert.strictEqual(
- postsWithPlaceholders.length,
+ postStream.postsWithPlaceholders.length,
8,
"have a larger placeholder window when loaded"
);
- assert.strictEqual(testProxy.length, 8);
- assert.strictEqual(testProxy.objectAt(3), p4);
+ assert.strictEqual(postStream.postsWithPlaceholders.length, 8);
+ assert.strictEqual(postStream.postsWithPlaceholders[3], p4);
});
test("filteredPostsCount", function (assert) {
diff --git a/app/assets/javascripts/select-kit/addon/components/composer-actions.js b/app/assets/javascripts/select-kit/addon/components/composer-actions.js
index 02c00fb793b..d68862f916b 100644
--- a/app/assets/javascripts/select-kit/addon/components/composer-actions.js
+++ b/app/assets/javascripts/select-kit/addon/components/composer-actions.js
@@ -352,7 +352,7 @@ export default class ComposerActions extends DropdownSelectBoxComponent {
const stream = this.get("composerModel.topic.postStream");
if (stream.get("firstPostPresent")) {
- const post = stream.get("posts.firstObject");
+ const post = stream.posts[0];
if (post && !post.get("yours") && post.get("username")) {
usernames = post.get("username");
}