Skip to content

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

DEV: Upgrade the `post` widgets to Glimmer components (#31375)

Sérgio Saquetimc671cfff84fd
diff --git a/app/assets/javascripts/discourse/app/components/actions-summary.gjs b/app/assets/javascripts/discourse/app/components/actions-summary.gjs
deleted file mode 100644
index 8ec40adad40..00000000000
--- a/app/assets/javascripts/discourse/app/components/actions-summary.gjs
+++ /dev/null
@@ -1,30 +0,0 @@
-import avatar from "discourse/helpers/bound-avatar-template";
-import icon from "discourse/helpers/d-icon";
-import formatDate from "discourse/helpers/format-date";
-
-const ActionsSummary = <template>
- {{#each @data.actionsSummary as |as|}}
- <div class="post-action">{{as.description}}</div>
- <div class="clearfix"></div>
- {{/each}}
- {{#if @data.deleted_at}}
- <div class="post-action deleted-post">
- {{icon "trash-can"}}
- <a
- class="trigger-user-card"
- data-user-card={{@data.deletedByUsername}}
- title={{@data.deletedByUsername}}
- aria-hidden="true"
- >
- {{avatar
- @data.deletedByAvatarTemplate
- "tiny"
- }}
- </a>
- {{formatDate @data.deleted_at format="tiny"}}
- </div>
- {{/if}}
-</template>;
-
-export default ActionsSummary;
diff --git a/app/assets/javascripts/discourse/app/components/decorated-html.gjs b/app/assets/javascripts/discourse/app/components/decorated-html.gjs
index bdad05963d3..c134ace98c4 100644
--- a/app/assets/javascripts/discourse/app/components/decorated-html.gjs
+++ b/app/assets/javascripts/discourse/app/components/decorated-html.gjs
@@ -17,6 +17,8 @@ export default class DecoratedHtml extends Component {
const helper = new DecorateHtmlHelper({
renderGlimmerInfos: this.renderGlimmerInfos,
+ model: this.args.model,
+ context: this.args.context,
});
on.cleanup(() => helper.teardown());
@@ -24,6 +26,10 @@ export default class DecoratedHtml extends Component {
untrack(() => decorateFn?.(cookedDiv, helper));
document.adoptNode(cookedDiv);
+
+ const afterAdoptDecorateFn = this.args.decorateAfterAdopt;
+ untrack(() => afterAdoptDecorateFn?.(cookedDiv, helper));
+
return cookedDiv;
});
@@ -57,20 +63,34 @@ export default class DecoratedHtml extends Component {
}
class DecorateHtmlHelper {
- constructor({ renderGlimmerInfos }) {
- this.renderGlimmerInfos = renderGlimmerInfos;
+ #renderGlimmerInfos;
+ #model;
+ #context;
+
+ constructor({ renderGlimmerInfos, model, context }) {
+ this.#renderGlimmerInfos = renderGlimmerInfos;
+ this.#model = model;
+ this.#context = context;
}
renderGlimmer(element, component, data) {
const info = { element, component, data };
- this.renderGlimmerInfos.push(info);
+ this.#renderGlimmerInfos.push(info);
+ }
+
+ get model() {
+ return this.#model;
+ }
+
+ get context() {
+ return this.#context;
}
getModel() {
- return null;
+ return this.model;
}
teardown() {
- this.renderGlimmerInfos.length = 0;
+ this.#renderGlimmerInfos.length = 0;
}
}
diff --git a/app/assets/javascripts/discourse/app/components/group-link.gjs b/app/assets/javascripts/discourse/app/components/group-link.gjs
new file mode 100644
index 00000000000..e5b435bd506
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/group-link.gjs
@@ -0,0 +1,22 @@
+import Component from "@glimmer/component";
+
+export default class GroupLink extends Component {
+ get name() {
+ return this.args.name || this.args.group?.name;
+ }
+
+ get href() {
+ return this.args.href || this.args.group?.url;
+ }
+
+ <template>
+ <a
+ ...attributes
+ class="user-group trigger-group-card"
+ href={{this.href}}
+ data-group-card={{this.name}}
+ >
+ {{yield}}
+ </a>
+ </template>
+}
diff --git a/app/assets/javascripts/discourse/app/components/post.gjs b/app/assets/javascripts/discourse/app/components/post.gjs
new file mode 100644
index 00000000000..307deed6819
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/post.gjs
@@ -0,0 +1,601 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { concat, hash } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+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";
+import PluginOutlet from "discourse/components/plugin-outlet";
+import PostActionsSummary from "discourse/components/post/actions-summary";
+import PostAvatar from "discourse/components/post/avatar";
+import PostCookedHtml from "discourse/components/post/cooked-html";
+import PostEmbedded from "discourse/components/post/embedded";
+import PostLinks from "discourse/components/post/links";
+import PostMenu from "discourse/components/post/menu";
+import PostMetaData from "discourse/components/post/meta-data";
+import PostMetaDataReplyToTab from "discourse/components/post/meta-data/reply-to-tab";
+import PostNotice from "discourse/components/post/notice";
+import TopicMap from "discourse/components/topic-map";
+import concatClass from "discourse/helpers/concat-class";
+import { isTesting } from "discourse/lib/environment";
+import getURL, { getAbsoluteURL } from "discourse/lib/get-url";
+import postActionFeedback from "discourse/lib/post-action-feedback";
+import { nativeShare } from "discourse/lib/pwa-utils";
+import { applyValueTransformer } from "discourse/lib/transformer";
+import DiscourseURL from "discourse/lib/url";
+import { clipboardCopy } from "discourse/lib/utilities";
+import { i18n } from "discourse-i18n";
+
+export default class Post extends Component {
+ @service appEvents;
+ @service capabilities;
+ @service currentUser;
+ @service dialog;
+ @service keyValueStore;
+ @service modal;
+ @service search;
+ @service site;
+ @service siteSettings;
+ @service store;
+
+ @tracked expandedFirstPost;
+ @tracked repliesAbove;
+ @tracked repliesBelow = new TrackedArray();
+
+ get additionalClasses() {
+ return applyValueTransformer("post-class", [], {
+ post: this.args.post,
+ });
+ }
+
+ get canLoadMoreRepliesBelow() {
+ return this.repliesBelow.length < this.args.post.reply_count;
+ }
+
+ get filteredRepliesShown() {
+ return (
+ this.args.filteringRepliesToPostNumber ===
+ this.args.post.post_number.toString()
+ );
+ }
+
+ get filteredRepliesView() {
+ return this.siteSettings.enable_filtered_replies_view;
+ }
+
+ get groupRequestUrl() {
+ return getURL(
+ `/g/${this.args.post.requestedGroupName}/requests?filter=${this.args.post.username}`
+ );
+ }
+
+ get hasRepliesAbove() {
+ return this.repliesAbove?.isResolved && this.repliesAbove.value.length > 0;
+ }
+
+ get id() {
+ return `post_${this.args.post.post_number}`;
+ }
+
+ get isFromCurrentUser() {
+ return this.currentUser && this.currentUser.id === this.args.post.user_id;
+ }
+
+ get isReplyingDirectlyToPostAbove() {
+ return (
+ this.args.prevPost &&
+ this.args.post.reply_to_post_number === this.args.prevPost.post_number &&
+ this.args.post.id !==
+ this.args.post.topic?.postStream?.filterUpwardsPostID
+ );
+ }
+
+ get isReplyToTabDisplayed() {
+ return PostMetaDataReplyToTab.shouldRender(
+ {
+ post: this.args.post,
+ isReplyingDirectlyToPostAbove: this.isReplyingDirectlyToPostAbove,
+ },
+ null,
+ getOwner(this)
+ );
+ }
+
+ get minHeight() {
+ return this.args.height ? `${this.args.height}px` : null;
+ }
+
+ get repliesShown() {
+ return this.filteredRepliesView
+ ? this.filteredRepliesShown
+ : this.repliesBelow.length > 0;
+ }
+
+ get shouldShowTopicMap() {
+ if (this.args.post.post_number !== 1) {
+ return false;
+ }
+
+ const isPM = this.args.post.topic.archetype === "private_message";
+ const isRegular = this.args.post.topic.archetype === "regular";
+ const showWithoutReplies =
+ this.siteSettings.show_topic_map_in_topics_without_replies;
+
+ return applyValueTransformer(
+ "post-show-topic-map",
+ isPM ||
+ (isRegular &&
+ (this.args.post.topic.posts_count > 1 || showWithoutReplies)),
+ { post: this.args.post, isPM, isRegular, showWithoutReplies }
+ );
+ }
+
+ get staged() {
+ return (
+ this.args.post.id === -1 ||
+ this.args.post.isSaving ||
+ this.args.post.staged
+ );
+ }
+
+ @action
+ copyLink() {
+ // Copying the link to clipboard on mobile doesn't make sense.
+ if (this.site.mobileView) {
+ return this.share();
+ }
+
+ const post = this.args.post;
+ const postId = post.id;
+
+ let actionCallback = () => clipboardCopy(getAbsoluteURL(post.shareUrl));
+
+ // Can't use clipboard in JS tests.
+ if (isTesting()) {
+ actionCallback = () => {};
+ }
+
+ postActionFeedback({
+ postId,
+ actionClass: "post-action-menu__copy-link",
+ messageKey: "post.controls.link_copied",
+ actionCallback,
+ errorCallback: () => this.share(),
+ });
+ }
+
+ @action
+ async loadMoreReplies() {
+ const after = this.repliesBelow.length
+ ? this.repliesBelow.at(-1).post_number
+ : 1;
+
+ const replies = await this.store.find("post-reply", {
+ postId: this.args.post.id,
+ after,
+ });
+
+ replies.forEach((reply) => {
+ // the components expect a post model instance
+ const replyAsPost = this.store.createRecord("post", reply);
+ this.repliesBelow.push(replyAsPost);
+ });
+ }
+
+ @action
+ async expandFirstPost() {
+ this.expandedFirstPost = new TrackedAsyncData(this.args.post.expand());
+ }
+
+ @action
+ async share() {
+ const post = this.args.post;
+
+ try {
+ await nativeShare(this.capabilities, { url: post.shareUrl });
+ } catch {
+ // if a native share dialog is not available, fallback to our share modal
+ const topic = post.topic;
+ this.modal.show(ShareTopicModal, {
+ model: { category: topic.category, topic, post },
+ });
+ }
+ }
+
+ @action
+ async toggleFilteredRepliesView() {
+ const post = this.args.post;
+ const currentFilterPostNumber =
+ this.args.post.topic.postStream.filterRepliesToPostNumber;
+
+ if (
+ currentFilterPostNumber &&
+ currentFilterPostNumber === post.post_number
+ ) {
+ this.args.cancelFilter(currentFilterPostNumber);
+ return;
+ }
+
+ await post.get("topic.postStream").filterReplies(post.post_number, post.id);
+ this.args.updateTopicPageQueryParams();
+ }
+
+ @action
+ async toggleLike() {
+ const post = this.args.post;
+ const likeAction = post.likeAction;
+
+ if (likeAction?.canToggle) {
+ const result = await likeAction.togglePromise(post);
+
+ this.appEvents.trigger("page:like-toggled", post, likeAction);
+ return this.#warnIfClose(result);
+ }
+ }
+
+ @action
+ async toggleReplyAbove(goToPost = false) {
+ const replyPostNumber = this.args.post.reply_to_post_number;
+
+ if (this.siteSettings.enable_filtered_replies_view) {
+ await this.args.post.topic?.postStream?.filterUpwards?.(
+ this.args.post.id
+ );
+ this.args.updateTopicPageQueryParams();
+ }
+
+ const topicUrl = this.args.post.topicUrl;
+
+ // jump directly on mobile
+ if (this.site.mobileView) {
+ if (topicUrl) {
+ DiscourseURL.routeTo(`${topicUrl}/${replyPostNumber}`);
+ }
+
+ return;
+ }
+
+ if (this.repliesAbove?.value.length) {
+ this.repliesAbove = null;
+
+ if (goToPost === true) {
+ const { post_number } = this.args.post;
+ DiscourseURL.routeTo(`${topicUrl}/${post_number}`);
+ }
+ } else {
+ this.repliesAbove = new TrackedAsyncData(this.#loadRepliesAbove());
+ }
+ }
+
+ @action
+ async toggleReplies() {
+ return this.filteredRepliesView
+ ? await this.toggleFilteredRepliesView()
+ : await this.toggleRepliesBelow();
+ }
+
+ @action
+ toggleRepliesBelow(goToPost = false) {
+ if (this.repliesBelow.length) {
+ // since repliesBelow is a tracked array, let's truncate it instead of creating another one
+ this.repliesBelow.length = 0;
+
+ if (goToPost === true) {
+ const { topicUrl, post_number } = this.args.post;
+ DiscourseURL.routeTo(`${topicUrl}/${post_number}`);
+ }
+ } else {
+ return this.loadMoreReplies();
+ }
+ }
+
+ #warnIfClose(result) {
+ if (!result || !result.acted) {
+ return;
+ }
+
+ const lastWarnedLikes = this.keyValueStore.get("lastWarnedLikes");
+
+ // only warn once per day
+ const yesterday = Date.now() - 1000 * 60 * 60 * 24;
+ if (lastWarnedLikes && parseInt(lastWarnedLikes, 10) > yesterday) {
+ return;
+ }
+
+ const { remaining, max } = result;
+ const threshold = Math.ceil(max * 0.1);
+
+ if (remaining === threshold) {
+ this.dialog.alert(i18n("post.few_likes_left"));
+ this.keyValueStore.set({ key: "lastWarnedLikes", value: Date.now() });
+ }
+ }
+
+ async #loadRepliesAbove() {
+ const replies = await this.store.find("post-reply-history", {
+ postId: this.args.post.id,
+ });
+
+ return replies.map((reply) => this.store.createRecord("post", reply));
+ }
+
+ <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}}
+ <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")
+ (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
+ )
+ 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"
+ }}
+ 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}}
+ />
+ {{/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">
+ <PostAvatar @post={{@post}} />
+ <div class="post__body topic-body clearfix">
+ <PluginOutlet @name="post-metadata" @outletArgs={{hash post=@post}}>
+ <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"
+ )
+ }}
+ >
+ <PluginOutlet @name="post-content-cooked-html" @post={{@post}}>
+ <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
+ @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"
+ username=reply.username
+ }}
+ @post={{reply}}
+ @highlightTerm={{this.search.highlightTerm}}
+ />
+ {{/each}}
+
+ <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"
+ />
+
+ {{#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 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>
+ {{/if}}
+ </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/actions-summary.gjs b/app/assets/javascripts/discourse/app/components/post/actions-summary.gjs
new file mode 100644
index 00000000000..c8fc5e406f3
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/post/actions-summary.gjs
@@ -0,0 +1,19 @@
+import UserAvatar from "discourse/components/user-avatar";
+import icon from "discourse/helpers/d-icon";
+import formatDate from "discourse/helpers/format-date";
+
+const PostActionsSummary = <template>
+ {{#each @post.actionsSummary key="id" as |actionSummary|}}
+ <div class="post-action">{{actionSummary.description}}</div>
+ <div class="clearfix"></div>
+ {{/each}}
+ {{#if @post.deletedAt}}
+ <div class="post-action deleted-post">
+ {{icon "trash-can"}}
+ <UserAvatar @size="tiny" @user={{@post.deletedBy}} />
+ {{formatDate @post.deletedAt format="tiny"}}
+ </div>
+ {{/if}}
+</template>;
+
+export default PostActionsSummary;
diff --git a/app/assets/javascripts/discourse/app/components/post/avatar.gjs b/app/assets/javascripts/discourse/app/components/post/avatar.gjs
new file mode 100644
index 00000000000..5d5b4cb815e
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/post/avatar.gjs
@@ -0,0 +1,46 @@
+import Component from "@glimmer/component";
+import UserAvatar from "discourse/components/user-avatar";
+import UserAvatarFlair from "discourse/components/user-avatar-flair";
+import icon from "discourse/helpers/d-icon";
+
+export default class PostAvatar extends Component {
+ get userWasDeleted() {
+ return !this.args.post.user_id;
+ }
+
+ get size() {
+ return this.args.size || "large";
+ }
+
+ get user() {
+ return {
+ avatar_template: this.args.post.avatar_template,
+ username: this.args.post.username,
+ name: this.args.post.name,
+ path: this.args.post.usernameUrl,
+ };
+ }
+
+ <template>
+ <div class="topic-avatar">
+ <div class="post-avatar">
+ {{#if this.userWasDeleted}}
+ {{icon "trash-can" class="deleted-user-avatar"}}
+ {{else}}
+ <UserAvatar
+ tabindex="-1"
+ @hideTitle={{true}}
+ @lazy={{true}}
+ @avatarClasses="main-avatar"
+ @size={{this.size}}
+ @user={{this.user}}
+ />
+ <UserAvatarFlair @user={{@post}} />
+ {{/if}}
+ {{#if @displayPosterName}}
+ <div class="post-avatar-user-info"></div>
+ {{/if}}
+ </div>
+ </div>
+ </template>
+}
diff --git a/app/assets/javascripts/discourse/app/components/post/cooked-html.gjs b/app/assets/javascripts/discourse/app/components/post/cooked-html.gjs
new file mode 100644
index 00000000000..8454b913be1
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/post/cooked-html.gjs
@@ -0,0 +1,163 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { getOwner } from "@ember/owner";
+import { service } from "@ember/service";
+import { htmlSafe } from "@ember/template";
+import curryComponent from "ember-curry-component";
+import DecoratedHtml from "discourse/components/decorated-html";
+import { bind } from "discourse/lib/decorators";
+import { makeArray } from "discourse/lib/helpers";
+import decorateLinkCounts from "discourse/lib/post-cooked-html-decorators/link-counts";
+import decorateMentions from "discourse/lib/post-cooked-html-decorators/mentions";
+import decorateQuoteControls from "discourse/lib/post-cooked-html-decorators/quote-controls";
+import decorateSearchHighlight from "discourse/lib/post-cooked-html-decorators/search-highlight";
+import decorateSelectionBarrier from "discourse/lib/post-cooked-html-decorators/selection-barrier";
+import { i18n } from "discourse-i18n";
+
+const detachedDocument = document.implementation.createHTMLDocument("detached");
+
+const POST_COOKED_DECORATORS = [
+ decorateSelectionBarrier,
+ decorateQuoteControls,
+ decorateLinkCounts,
+ decorateSearchHighlight,
+ decorateMentions,
+];
+
+export default class PostCookedHtml extends Component {
+ @service appEvents;
+ @service currentUser;
+
+ @tracked highlighted = false;
+ #decoratorState = new WeakMap();
+ #pendingDecoratorCleanup = [];
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ this.#cleanupDecorations();
+ }
+
+ get isStreamElement() {
+ return this.args.streamElement ?? true;
+ }
+
+ @bind
+ decorateBeforeAdopt(element, helper) {
+ this.#cleanupDecorations();
+
+ [...POST_COOKED_DECORATORS, ...this.extraDecorators].forEach(
+ (decorator) => {
+ if (!this.#decoratorState.has(decorator)) {
+ this.#decoratorState.set(decorator, {});
+ }
+
+ const owner = getOwner(this);
+ const decorationCleanup = decorator(element, {
+ data: {
+ post: this.args.post,
+ cooked: this.cooked,
+ highlightTerm: this.highlightTerm,
+ isIgnored: this.isIgnored,
+ ignoredUsers: this.ignoredUsers,
+ },
+ createDetachedElement: this.#createDetachedElement,
+ currentUser: this.currentUser,
+ helper,
+ renderNestedCookedContent: (
+ nestedElement,
+ cooked,
+ extraDecorators
+ ) => {
+ const nestedArguments = {
+ cooked,
+ post: this.args.post,
+ highlightTerm: this.highlightTerm,
+ extraDecorators: [
+ ...this.extraDecorators,
+ ...makeArray(extraDecorators),
+ ],
+ };
+
+ helper.renderGlimmer(
+ nestedElement,
+ curryComponent(PostCookedHtml, nestedArguments, owner)
+ );
+ },
+ owner,
+ state: this.#decoratorState.get(decorator),
+ });
+
+ if (typeof decorationCleanup === "function") {
+ this.#pendingDecoratorCleanup.push(decorationCleanup);
+ }
+ }
+ );
+
+ this.appEvents.trigger(
+ this.isStreamElement
+ ? "decorate-post-cooked-element:before-adopt"
+ : "decorate-non-stream-cooked-element",
+ element,
+ helper
+ );
+ }
+
+ @bind
+ decorateAfterAdopt(element, helper) {
+ if (this.isStreamElement) {
+ return;
+ }
+
+ this.appEvents.trigger(
+ "decorate-post-cooked-element:after-adopt",
+ element,
+ helper
+ );
+ }
+
+ get cooked() {
+ if (this.isIgnored) {
+ return i18n("post.ignored");
+ }
+
+ return this.args.post.cooked;
+ }
+
+ get highlightTerm() {
+ return this.args.highlightTerm;
+ }
+
+ get extraDecorators() {
+ return makeArray(this.args.extraDecorators);
+ }
+
+ get ignoredUsers() {
+ return this.currentUser?.ignored_users;
+ }
+
+ get isIgnored() {
+ return (
+ (this.args.post.firstPost || this.args.embeddedPost) &&
+ this.ignoredUsers?.includes?.(this.args.post.username)
+ );
+ }
+
+ #cleanupDecorations() {
+ this.#pendingDecoratorCleanup.forEach((teardown) => teardown());
+ this.#pendingDecoratorCleanup = [];
+ }
+
+ #createDetachedElement(nodeName) {
+ return detachedDocument.createElement(nodeName);
+ }
+
+ <template>
+ <DecoratedHtml
+ @className="cooked"
+ @decorate={{this.decorateBeforeAdopt}}
+ @decorateAfterAdopt={{this.decorateAfterAdopt}}
+ @html={{htmlSafe this.cooked}}
+ @model={{@post}}
+ />
+ </template>
+}
diff --git a/app/assets/javascripts/discourse/app/components/post/embedded.gjs b/app/assets/javascripts/discourse/app/components/post/embedded.gjs
new file mode 100644
index 00000000000..a5f9bd4648e
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/post/embedded.gjs
@@ -0,0 +1,43 @@
+import icon from "discourse/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+import PostAvatar from "./avatar";
+import PostCookedHtml from "./cooked-html";
+import PostMetaDataPosterName from "./meta-data/poster-name";
+
+const PostEmbedded = <template>
+ <div ...attributes class="reply" data-post-id={{@post.id}}>
+ <div class="row">
+ <PostAvatar @post={{@post}} />
+ <div class="topic-body">
+ <div class="topic-meta-data embedded-reply">
+ <PostMetaDataPosterName @post={{@post}} />
+ <div class="post-link-arrow">
+ <a
+ class="post-info arrow"
+ aria-label={{i18n
+ "topic.jump_reply_aria"
+ }}
+ href={{@post.shareUrl}}
+ title={{i18n "topic.jump_reply"}}
+ >
+ {{#if @above}}
+ {{icon "arrow-up"}}
+ {{else}}
+ {{icon "arrow-down"}}
+ {{/if}}
+ {{i18n "topic.jump_reply_button"}}
+ </a>
+ </div>
+ </div>
+ <PostCookedHtml
+ @post={{@post}}
+ @highlightTerm={{@highlightTerm}}
+ @streamElement={{false}}
+ />
+ </div>
+ </div>
+ </div>
+</template>;
+
+export default PostEmbedded;
diff --git a/app/assets/javascripts/discourse/app/components/post/filtered-notice.gjs b/app/assets/javascripts/discourse/app/components/post/filtered-notice.gjs
new file mode 100644
index 00000000000..ad30f005ff7
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/post/filtered-notice.gjs
@@ -0,0 +1,133 @@
+import Component from "@glimmer/component";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import DButton from "discourse/components/d-button";
+import PostMetaDataPosterName from "discourse/components/post/meta-data/poster-name";
+import UserAvatar from "discourse/components/user-avatar";
+import DiscourseURL from "discourse/lib/url";
+import { i18n } from "discourse-i18n";
+
+export default class PostFilteredNotice extends Component {
+ get isViewingPostsByUsername() {
+ return this.args.streamFilters.username_filters?.length;
+ }
+
+ get isViewingRepliesToPostNumber() {
+ return !!this.args.streamFilters.replies_to_post_number;
+ }
+
+ get isViewingSubset() {
+ return (
+ this.args.streamFilters.filter_upwards_post_id ||
+ this.args.streamFilters.mixedHiddenPosts
+ );
+ }
+
+ get isViewingSummary() {
+ return this.args.streamFilters.filter === "summary";
+ }
+
+ get firstUserPost() {
+ return this.args.posts[1];
+ }
+
+ get sourcePost() {
+ return this.args.posts.find(
+ (post) =>
+ post.post_number === this.args.streamFilters.replies_to_post_number
+ );
+ }
+
+ get userPostsCount() {
+ return parseInt(this.args.filteredPostsCount, 10) - 1;
+ }
+
+ @action
+ jumpToPost() {
+ DiscourseURL.jumpToPost(this.args.streamFilters.replies_to_post_number);
+ }
+
+ <template>
+ <div class="posts-filtered-notice">
+ {{#if this.isViewingSubset}}
+ <span class="filtered-replies-viewing">
+ {{i18n "post.filtered_replies.viewing_subset"}}
+ <FilterShowAllBtn
+ @streamFilters={{@streamFilters}}
+ @cancelFilter={{@cancelFilter}}
+ />
+ </span>
+ {{else if this.isViewingRepliesToPostNumber}}
+ <span class="filtered-replies-viewing">
+ {{i18n
+ "post.filtered_replies_viewing"
+ count=this.sourcePost.reply_count
+ }}
+ </span>
+ <span class="filtered-user-row">
+ <span class="filtered-avatar">
+ <UserAvatar @size="small" @user={{this.sourcePost}} />
+ </span>
+ <DButton
+ class="filtered-jump-to-post"
+ @translatedLabel={{i18n
+ "post.filtered_replies.post_number"
+ username=this.sourcePost.username
+ [email protected]_to_post_number
+ }}
+ @action={{this.jumpToPost}}
+ />
+ <FilterShowAllBtn
+ @streamFilters={{@streamFilters}}
+ @cancelFilter={{@cancelFilter}}
+ />
+ </span>
+ {{else if this.isViewingSummary}}
+ <span class="filtered-replies-viewing">
+ {{i18n "post.filtered_replies.viewing_summary"}}
+ </span>
+ <FilterShowAllBtn
+ @streamFilters={{@streamFilters}}
+ @cancelFilter={{@cancelFilter}}
+ />
+ {{else if this.isViewingPostsByUsername}}
+ <span class="filtered-replies-viewing">
+ {{i18n
+ "post.filtered_replies.viewing_posts_by"
+ post_count=this.userPostsCount
+ }}
+ </span>
+ <span class="filtered-avatar">
+ <UserAvatar @size="small" @user={{this.firstUserPost}} />
+ </span>
+ <PostMetaDataPosterName @post={{this.firstUserPost}} />
+ <FilterShowAllBtn
+ @streamFilters={{@streamFilters}}
+ @cancelFilter={{@cancelFilter}}
+ />
+ {{/if}}
+ </div>
+ </template>
+}
+
+class FilterShowAllBtn extends Component {
+ @service appEvents;
+
+ @action
+ showAll() {
+ this.args.cancelFilter();
+ this.appEvents.trigger(
+ "post-stream:filter-show-all",
+ this.args.streamFilters
+ );
+ }
+
+ <template>
+ <DButton
+ class="btn-primary filtered-replies-show-all"
+ @icon="up-down"
+ @label="post.filtered_replies.show_all"
+ @action={{this.showAll}}
+ />
+ </template>
+}
diff --git a/app/assets/javascripts/discourse/app/components/post/gap.gjs b/app/assets/javascripts/discourse/app/components/post/gap.gjs
new file mode 100644
index 00000000000..5f8eae1f166
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/post/gap.gjs
@@ -0,0 +1,43 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { i18n } from "discourse-i18n";
+
+export default class PostGap extends Component {
+ @service appEvents;
+
+ @tracked loading = false;
+
+ get label() {
+ return this.loading
+ ? i18n("loading")
+ : i18n("post.gap", { count: this.args.gap.length });
+ }
+
+ @action
+ async fillGap() {
+ if (this.loading) {
+ return;
+ }
+ this.loading = true;
+
+ try {
+ await this.args.fillGap();
+
+ this.appEvents.trigger("post-stream:gap-expanded", {
+ post_id: this.args.post.id,
+ });
+ } finally {
+ this.loading = false;
+ }
+ }
+
+ <template>
+ {{! template-lint-disable no-invalid-interactive }}
+ <div class="gap" {{on "click" this.fillGap}}>
+ {{this.label}}
+ </div>
+ </template>
+}
diff --git a/app/assets/javascripts/discourse/app/components/post/links.gjs b/app/assets/javascripts/discourse/app/components/post/links.gjs
new file mode 100644
index 00000000000..3792af7cd9c
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/post/links.gjs
@@ -0,0 +1,79 @@
+import Component from "@glimmer/component";
+import { cached, tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import DButton from "discourse/components/d-button";
+import icon from "discourse/helpers/d-icon";
+import replaceEmoji from "discourse/helpers/replace-emoji";
+import { i18n } from "discourse-i18n";
+
+const MAX_COLLAPSED_LINKS = 5;
+
+export default class PostLinks extends Component {
+ @tracked collapsed = true;
+
+ @cached
+ get links() {
+ return this.args.post.internalLinks
+ ?.filter((l) => l.reflection)
+ ?.reduce((unique, item) => {
+ if (!unique.find((i) => item.title === i.title)) {
+ unique.push(item);
+ }
+ return unique;
+ }, []);
+ }
+
+ get canExpandList() {
+ return this.links?.length > MAX_COLLAPSED_LINKS && this.collapsed;
+ }
+
+ get displayedLinks() {
+ if (!this.canExpandList) {
+ return this.links;
+ }
+ return this.links.slice(0, MAX_COLLAPSED_LINKS);
+ }
+
+ get remainingCount() {
+ return this.links.length - MAX_COLLAPSED_LINKS;
+ }
+
+ @action
+ expandList() {
+ this.collapsed = false;
+ }
+
+ <template>
+ {{#if this.links}}
+ <div class="post-links-container">
+ <ul class="post-links">
+ {{#each this.displayedLinks key="title" as |link|}}
+ <li>
+ <a
+ class="track-link inbound"
+ data-clicks={{link.clicks}}
+ href={{link.url}}
+ >
+ {{icon "link"}}
+ {{replaceEmoji link.title}}
+ </a>
+ </li>
+ {{/each}}
+ {{#if this.canExpandList}}
+ <li>
+ <DButton
+ class="btn-transparent expand-links"
+ @translatedLabel={{i18n
+ "post_links.title"
+ count=this.remainingCount
+ }}
+ @title="post_links.about"
+ @action={{this.expandList}}
+ />
+ </li>
+ {{/if}}
+ </ul>
+ </div>
+ {{/if}}
+ </template>
+}
diff --git a/app/assets/javascripts/discourse/app/components/post/menu.gjs b/app/assets/javascripts/discourse/app/components/post/menu.gjs
index 8eaf63b48eb..d23d481aba2 100644
--- a/app/assets/javascripts/discourse/app/components/post/menu.gjs
+++ b/app/assets/javascripts/discourse/app/components/post/menu.gjs
@@ -75,13 +75,11 @@ const defaultDagOptions = {
};
export default class PostMenu extends Component {
- @service appEvents;
@service capabilities;
@service currentUser;
@service keyValueStore;
@service modal;
@service menu;
- @service site;
@service siteSettings;
@service store;
diff --git a/app/assets/javascripts/discourse/app/components/post/meta-data.gjs b/app/assets/javascripts/discourse/app/components/post/meta-data.gjs
new file mode 100644
index 00000000000..95f4f784499
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/post/meta-data.gjs
@@ -0,0 +1,82 @@
+import Component from "@glimmer/component";
+import { getOwner } from "@ember/owner";
+import PostMetaDataDate from "./meta-data/date";
+import PostMetaDataEditsIndicator from "./meta-data/edits-indicator";
+import PostMetaDataEmailIndicator from "./meta-data/email-indicator";
+import PostMetaDataLockedIndicator from "./meta-data/locked-indicator";
+import PostMetaDataPosterName from "./meta-data/poster-name";
+import PostMetaDataReadIndicator from "./meta-data/read-indicator";
+import PostMetaDataReplyToTab from "./meta-data/reply-to-tab";
+import PostMetaDataSelectPost from "./meta-data/select-post";
+import PostMetaDataWhisperIndicator from "./meta-data/whisper-indicator";
+
+export default class PostMetaData extends Component {
+ get displayPosterName() {
+ return this.args.displayPosterName ?? true;
+ }
+
+ get shouldDisplayEditsIndicator() {
+ return this.args.post.version > 1 || this.args.post.wiki;
+ }
+
+ get shouldDisplayReplyToTab() {
+ return PostMetaDataReplyToTab.shouldRender(this.args, null, getOwner(this));
+ }
+
+ <template>
+ <div class="topic-meta-data" role="heading" aria-level="2">
+ {{#if this.displayPosterName}}
+ <PostMetaDataPosterName @post={{@post}} />
+ {{/if}}
+
+ <div class="post-infos">
+ {{#if @post.isWhisper}}
+ <PostMetaDataWhisperIndicator @post={{@post}} />
+ {{/if}}
+
+ {{#if @post.via_email}}
+ <PostMetaDataEmailIndicator
+ @post={{@post}}
+ @showRawEmail={{@showRawEmail}}
+ />
+ {{/if}}
+
+ {{#if @post.locked}}
+ <PostMetaDataLockedIndicator @post={{@post}} />
+ {{/if}}
+
+ {{#if this.shouldDisplayEditsIndicator}}
+ <PostMetaDataEditsIndicator
+ @post={{@post}}
+ @editPost={{@editPost}}
+ @showHistory={{@showHistory}}
+ />
+ {{/if}}
+
+ {{#if @multiSelect}}
+ <PostMetaDataSelectPost
+ @post={{@post}}
+ @selected={{@selected}}
+ @selectReplies={{@selectReplies}}
+ @selectBelow={{@selectBelow}}
+ @togglePostSelection={{@togglePostSelection}}
+ />
+ {{/if}}
+
+ {{#if this.shouldDisplayReplyToTab}}
+ <PostMetaDataReplyToTab
+ @post={{@post}}
+ @hasRepliesAbove={{@hasRepliesAbove}}
+ @isReplyingDirectlyToPostAbove={{@isReplyingDirectlyToPostAbove}}
+ @repliesAbove={{@repliesAbove}}
+ @toggleReplyAbove={{@toggleReplyAbove}}
+ />
+ {{/if}}
+
+ <PostMetaDataDate @post={{@post}} />
+
+ <PostMetaDataReadIndicator @post={{@post}} />
+ </div>
+ </div>
+ </template>
+}
diff --git a/app/assets/javascripts/discourse/app/components/post/meta-data/date.gjs b/app/assets/javascripts/discourse/app/components/post/meta-data/date.gjs
new file mode 100644
index 00000000000..b6ced7b07f9
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/post/meta-data/date.gjs
@@ -0,0 +1,49 @@
+import Component from "@glimmer/component";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { and } from "truth-helpers";
+import ShareTopicModal from "discourse/components/modal/share-topic";
+import RelativeDate from "discourse/components/relative-date";
+import concatClass from "discourse/helpers/concat-class";
+import { i18n } from "discourse-i18n";
+
+export default class PostMetaDataDate extends Component {
+ @service modal;
+
+ get date() {
+ if (this.args.post.wiki && this.args.post.lastWikiEdit) {
+ return this.args.post.lastWikiEdit;
+ } else {
+ return this.args.post.created_at;
+ }
+ }
+
+ @action
+ showShareModal(evt) {
+ evt.preventDefault();
+
+ const post = this.args.post;
+ const topic = post.topic;
+
+ this.modal.show(ShareTopicModal, {
+ model: { category: topic.category, topic, post },
+ });
+ }
+
+ <template>
+ <div class="post-info post-date">
+ <a
+ class={{concatClass
+ "post-date"
+ (if (and @post.wiki @post.last_wiki_edit) "last-wiki-edit")
+ }}
+ href={{@post.shareUrl}}
+ title={{i18n "post.sr_date"}}
+ {{on "click" this.showShareModal}}
+ >
+ <RelativeDate @date={{this.date}} />
+ </a>
+ </div>
+ </template>
+}
diff --git a/app/assets/javascripts/discourse/app/components/post/meta-data/edits-indicator.gjs b/app/assets/javascripts/discourse/app/components/post/meta-data/edits-indicator.gjs
new file mode 100644
index 00000000000..8acc9cb8aeb
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/post/meta-data/edits-indicator.gjs
@@ -0,0 +1,91 @@
+import Component from "@glimmer/component";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import DButton from "discourse/components/d-button";
+import concatClass from "discourse/helpers/concat-class";
+import { longDate } from "discourse/lib/formatter";
+import { i18n } from "discourse-i18n";
+
+export default class PostMetaDataEditsIndicator extends Component {
+ @service siteSettings;
+
+ get icon() {
+ return this.args.post.wiki ? "far-pen-to-square" : "pencil";
+ }
+
+ get label() {
+ if (this.args.post.version > 1) {
+ return this.args.post.version - 1;
+ }
+ }
+
+ get title() {
+ const date = longDate(this.updatedAt);
+
+ if (this.args.post.wiki) {
+ if (this.args.post.version > 1) {
+ return i18n("post.wiki_last_edited_on", { dateTime: date });
+ } else {
+ return i18n("post.wiki.about");
+ }
+ } else {
+ return i18n("post.last_edited_on", { dateTime: date });
+ }
+ }
+
+ get updatedAt() {
+ return new Date(this.args.post.updated_at);
+ }
+
+ @action
+ onPostEditsIndicatorClick() {
+ if (this.args.post.wiki && this.args.post.version === 1) {
+ this.args.editPost();
+ } else if (this.args.post.can_view_edit_history) {
+ this.args.showHistory();
+ }
+ }
+
+ <template>
+ <div class="post-info edits">
+ <DButton
+ class={{concatClass
+ "btn-flat"
+ (historyHeat this.siteSettings this.updatedAt)
+ (if @post.wiki "wiki")
+ }}
+ @icon={{this.icon}}
+ @translatedLabel={{this.label}}
+ @translatedTitle={{this.title}}
+ @translatedAriaLabel={{i18n "post.edit_history"}}
+ @action={{this.onPostEditsIndicatorClick}}
+ />
+ </div>
+ </template>
+}
+
+function mult(val) {
+ return 60 * 50 * 1000 * val;
+}
+
+export function historyHeat(siteSettings, updatedAt) {
+ if (!updatedAt) {
+ return;
+ }
+
+ // Show heat on age
+ const rightNow = Date.now();
+ const updatedAtTime = updatedAt.getTime();
+
+ if (updatedAtTime > rightNow - mult(siteSettings.history_hours_low)) {
+ return "heatmap-high";
+ }
+
+ if (updatedAtTime > rightNow - mult(siteSettings.history_hours_medium)) {
+ return "heatmap-med";
+ }
+
+ if (updatedAtTime > rightNow - mult(siteSettings.history_hours_high)) {
+ return "heatmap-low";
+ }
+}
diff --git a/app/assets/javascripts/discourse/app/components/post/meta-data/email-indicator.gjs b/app/assets/javascripts/discourse/app/components/post/meta-data/email-indicator.gjs
new file mode 100644
index 00000000000..3e569f40a64
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/post/meta-data/email-indicator.gjs
@@ -0,0 +1,47 @@
+import Component from "@glimmer/component";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import concatClass from "discourse/helpers/concat-class";
+import icon from "discourse/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+
+export default class PostMetaDataEmailIndicator extends Component {
+ @service currentUser;
+
+ get canViewRawEmail() {
+ return this.currentUser?.can_view_raw_email;
+ }
+
+ get icon() {
+ return this.args.post.is_auto_generated ? "envelope" : "far-envelope";
+ }
+
+ get title() {
+ return this.args.post.is_auto_generated
+ ? i18n("post.via_auto_generated_email")
+ : i18n("post.via_email");
+ }
+
+ @action
+ onShowRawEmail() {
+ if (this.canViewRawEmail) {
+ this.args.showRawEmail();
+ }
+ }
+
+ <template>
+ {{! template-lint-disable no-invalid-interactive }}
+ <div
+ class={{concatClass
+ "post-info"
+ "via-email"
+ (if this.canViewRawEmail "raw-email")
+ }}
+ title={{this.title}}
+ {{on "click" this.onShowRawEmail}}
+ >
+ {{icon this.icon}}
+ </div>
+ </template>
+}
diff --git a/app/assets/javascripts/discourse/app/components/post/meta-data/locked-indicator.gjs b/app/assets/javascripts/discourse/app/components/post/meta-data/locked-indicator.gjs
new file mode 100644
index 00000000000..4e294e860f7
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/post/meta-data/locked-indicator.gjs
@@ -0,0 +1,10 @@
+import icon from "discourse/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+
+const PostMetaDataLockedIndicator = <template>
+ <div class="post-info post-locked" title={{i18n "post.locked"}}>
+ {{icon "lock"}}
+ </div>
+</template>;
+
+export default PostMetaDataLockedIndicator;
diff --git a/app/assets/javascripts/discourse/app/components/post/meta-data/poster-name.gjs b/app/assets/javascripts/discourse/app/components/post/meta-data/poster-name.gjs
new file mode 100644
index 00000000000..413b393256e
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/post/meta-data/poster-name.gjs
@@ -0,0 +1,221 @@
+import Component from "@glimmer/component";
+import { concat, hash } from "@ember/helper";
+import didUpdate from "@ember/render-modifiers/modifiers/did-update";
+import { service } from "@ember/service";
+import { and, or } from "truth-helpers";
+import GroupLink from "discourse/components/group-link";
+import PluginOutlet from "discourse/components/plugin-outlet";
+import UserBadge from "discourse/components/user-badge";
+import UserLink from "discourse/components/user-link";
+import UserStatusMessage from "discourse/components/user-status-message";
+import concatClass from "discourse/helpers/concat-class";
+import icon from "discourse/helpers/d-icon";
+import userPrioritizedName from "discourse/helpers/user-prioritized-name";
+import { bind } from "discourse/lib/decorators";
+import getURL from "discourse/lib/get-url";
+import { applyValueTransformer } from "discourse/lib/transformer";
+import { formatUsername } from "discourse/lib/utilities";
+import { i18n } from "discourse-i18n";
+
+export default class PostMetaDataPosterName extends Component {
+ @service siteSettings;
+ @service userStatus;
+
+ showNameAndGroup = true;
+ showGlyph = true;
+
+ constructor() {
+ super(...arguments);
+ this.#trackUserStatus();
+ }
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ this.#stopTrackingUserStatus();
+ }
+
+ get suppressSimilarName() {
+ return applyValueTransformer(
+ "post-meta-data-poster-name-suppress-similar-name",
+ true,
+ { post: this.args.post, name: this.name }
+ );
+ }
+
+ get name() {
+ return userPrioritizedName(this.args.post);
+ }
+
+ get nameFirst() {
+ return this.name === this.args.post.name;
+ }
+
+ get primaryGroupHref() {
+ return getURL(`/g/${this.args.post.primary_group_name}`);
+ }
+
+ get shouldDisplaySecondName() {
+ return (
+ this.args.post.name &&
+ this.siteSettings.display_name_on_posts &&
+ this.#sanitizeName(this.args.post.name) !==
+ this.#sanitizeName(this.args.post.username)
+ );
+ }
+
+ get user() {
+ // TODO where does user comes from?
+ return this.args.post.user;
+ }
+
+ get titleClassNames() {
+ const classNames = [this.args.post.user_title];
+
+ if (this.args.post.title_is_group && this.args.post.primary_group_name) {
+ classNames.push(this.args.post.primary_group_name);
+ }
+
+ return classNames.map(
+ (className) =>
+ `user-title--${className.replace(/\s+/g, "-").toLowerCase()}`
+ );
+ }
+
+ @bind
+ refreshUserStatus() {
+ this.#stopTrackingUserStatus();
+ this.#trackUserStatus();
+ }
+
+ @bind
+ withBadgeDescription(badge) {
+ // Alter the badge description to show that the badge was granted for this post.
+ badge.description = i18n("post.badge_granted_tooltip", {
+ username: this.args.post.username,
+ badge_name: badge.name,
+ });
+
+ return badge;
+ }
+
+ #sanitizeName(name) {
+ return this.suppressSimilarName
+ ? name.toLowerCase().replace(/[\s._-]/g, "")
+ : name;
+ }
+
+ #trackUserStatus() {
+ if (this.userStatus.isEnabled) {
+ this.user?.statusManager?.trackStatus();
+ }
+ }
+
+ #stopTrackingUserStatus() {
+ if (this.userStatus.isEnabled) {
+ this.user?.statusManager?.stopTrackingStatus();
+ }
+ }
+
+ <template>
+ <div
+ class="names trigger-user-card"
+ {{didUpdate this.refreshUserStatus this.user}}
+ >
+ <PluginOutlet
+ @name="post-meta-data-poster-name"
+ @outletArgs={{hash post=@post}}
+ >
+ <span
+ class={{concatClass
+ "first"
+ (if this.nameFirst "full-name" "username")
+ (if @post.staff "staff")
+ (if @post.admin "admin")
+ (if @post.moderator "moderator")
+ (if @post.group_moderator "category-moderator")
+ (if @post.new_user "new-user")
+ (if
+ @post.primary_group_name
+ (concat "group--" @post.primary_group_name)
+ )
+ }}
+ >
+ {{! use the position argument to choose between the first and second name if needed}}
+ <PluginOutlet
+ @name="post-meta-data-poster-name-user-link"
+ @outletArgs={{hash position="first" name=this.name post=@post}}
+ >
+ <UserLink @user={{@post}}>
+ {{this.name}}
+ {{#if this.showGlyph}}
+ {{#if (or @post.moderator @post.group_moderator)}}
+ {{icon "shield-halved" title=(i18n "user.moderator_tooltip")}}
+ {{/if}}
+ {{/if}}
+ </UserLink>
+ </PluginOutlet>
+ </span>
+
+ {{#if this.showNameAndGroup}}
+ {{#if this.shouldDisplaySecondName}}
+ <span
+ class={{concatClass
+ "second"
+ (if this.nameFirst "username" "full-name")
+ }}
+ >
+ {{! use the position argument to choose between the first and second name if needed}}
+ <PluginOutlet
+ @name="post-meta-data-poster-name-user-link"
+ @outletArgs={{hash position="second" name=this.name post=@post}}
+ >
+ <UserLink @user={{@post}}>
+ {{#if this.nameFirst}}
+ {{formatUsername @post.username}}
+ {{else}}
+ {{@post.name}}
+ {{/if}}
+ </UserLink>
+ </PluginOutlet>
+ </span>
+ {{/if}}
+
+ {{#if @post.user_title}}
+ <span class={{concatClass "user-title" this.titleClassNames}}>
+ {{#if (and @post.primary_group_name @post.title_is_group)}}
+ <GroupLink
+ @name={{@post.primary_group_name}}
+ @href={{this.primaryGroupHref}}
+ >
+ {{@post.user_title}}
+ </GroupLink>
+ {{else}}
+ {{@post.user_title}}
+ {{/if}}
+ </span>
+ {{/if}}
+
+ {{#if (and this.userStatus.isEnabled this.user.status)}}
+ <span class="user-status-message-wrap">
+ <UserStatusMessage @status={{this.user.status}} />
+ </span>
+ {{/if}}
+
+ {{#if @post.badgesGranted}}
+ <span class="user-badge-buttons">
+ {{#each @post.badgesGranted key="id" as |badge|}}
+ <span class={{concat "user-badge-button-" badge.slug}}>
+ <UserBadge
+ @badge={{this.withBadgeDescription badge}}
+ @user={{@post.user}}
+ @showName={{false}}
+ />
+ </span>
+ {{/each}}
+ </span>
+ {{/if}}
+ {{/if}}
+ </PluginOutlet>
+ </div>
+ </template>
+}
diff --git a/app/assets/javascripts/discourse/app/components/post/meta-data/poster-name/icon.gjs b/app/assets/javascripts/discourse/app/components/post/meta-data/poster-name/icon.gjs
new file mode 100644
index 00000000000..f7a09507263
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/post/meta-data/poster-name/icon.gjs
@@ -0,0 +1,52 @@
+import Component from "@glimmer/component";
+import { not } from "truth-helpers";
+import concatClass from "discourse/helpers/concat-class";
+import icon from "discourse/helpers/d-icon";
+import emoji from "discourse/helpers/emoji";
+
+export default class PostMetaDataPosterNameIcon extends Component {
+ get emojis() {
+ if (!this.args.emoji) {
+ return;
+ }
+
+ return this.args.emoji.split("|");
+ }
+
+ get skipEmojiTitle() {
+ return !this.args.emojiTitle;
+ }
+
+ <template>
+ <span class={{concatClass "poster-icon" @className}} title={{@title}}>
+ {{#if @url}}
+ <a href={{@url}}>
+ <Content
+ @icon={{@icon}}
+ @emojis={{this.emojis}}
+ @emojiTitle={{@emojiTitle}}
+ @text={{@text}}
+ />
+ </a>
+ {{else}}
+ <Content
+ @icon={{@icon}}
+ @emojis={{this.emojis}}
+ @emojiTitle={{@emojiTitle}}
+ @text={{@text}}
+ />
+ {{/if}}
+ </span>
+ </template>
+}
+
+const Content = <template>
+ {{#if @icon}}
+ {{icon @icon}}
+ {{else if @emojis}}
+ {{#each @emojis as |emojiName|}}
+ {{emoji emojiName skipEmojiTitle=(not @emojiTitle)}}
+ {{/each}}
+ {{/if}}
+ {{@text}}
+</template>;
diff --git a/app/assets/javascripts/discourse/app/components/post/meta-data/read-indicator.gjs b/app/assets/javascripts/discourse/app/components/post/meta-data/read-indicator.gjs
new file mode 100644
index 00000000000..e7015f7bc33
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/post/meta-data/read-indicator.gjs
@@ -0,0 +1,14 @@
+import concatClass from "discourse/helpers/concat-class";
+import icon from "discourse/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+
+const PostMetaDataReadIndicator = <template>
+ <div
+ class={{concatClass "read-state" (if @post.read "read")}}
+ title={{i18n "post.unread"}}
+ >
+ {{icon "circle"}}
+ </div>
+</template>;
+
+export default PostMetaDataReadIndicator;
diff --git a/app/assets/javascripts/discourse/app/components/post/meta-data/reply-to-tab.gjs b/app/assets/javascripts/discourse/app/components/post/meta-data/reply-to-tab.gjs
new file mode 100644
index 00000000000..9824bc6d9ed
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/post/meta-data/reply-to-tab.gjs
@@ -0,0 +1,45 @@
+import Component from "@glimmer/component";
+import { concat } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { service } from "@ember/service";
+import avatar from "discourse/helpers/avatar";
+import icon from "discourse/helpers/d-icon";
+import userPrioritizedName from "discourse/helpers/user-prioritized-name";
+
+export default class PostMetaDataReplyToTab extends Component {
+ static shouldRender(args, context, owner) {
+ const siteSettings = owner.lookup("service:site-settings");
+
+ return (
+ args.post.reply_to_user?.username &&
+ (!args.isReplyingDirectlyToPostAbove ||
+ !siteSettings.suppress_reply_directly_above)
+ );
+ }
+
+ @service site;
+
+ <template>
+ <a
+ class="reply-to-tab"
+ disabled={{@repliesAbove.isPending}}
+ role={{if this.site.desktopView "button"}}
+ aria-controls={{if
+ this.site.desktopView
+ (concat "embedded-posts__top--" @post.post_number)
+ }}
+ aria-expanded={{if this.site.desktopView @hasRepliesAbove}}
+ tabindex="0"
+ title="post.in_reply_to"
+ {{on "click" @toggleReplyAbove}}
+ >
+ {{#if @repliesAbove.isPending}}
+ <div class="spinner small"></div>
+ {{else}}
+ {{icon "share"}}
+ {{/if}}
+ {{avatar @post.reply_to_user imageSize="small"}}
+ <span>{{userPrioritizedName @post.reply_to_user}}</span>
+ </a>
+ </template>
+}
diff --git a/app/assets/javascripts/discourse/app/components/post/meta-data/select-post.gjs b/app/assets/javascripts/discourse/app/components/post/meta-data/select-post.gjs
new file mode 100644
index 00000000000..3f97605f07d
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/post/meta-data/select-post.gjs
@@ -0,0 +1,39 @@
+import { and, not } from "truth-helpers";
+import DButton from "discourse/components/d-button";
+
+const PostMetaDataSelectPost = <template>
+ <div class="select-posts">
+ {{#if (and (not @selected) (not @post.firstPost))}}
+ {{#if @post.hasReplies}}
+ <DButton
+ class="btn-flat select-replies"
+ @label="topic.multi_select.select_replies.label"
+ @title="topic.multi_select.select_replies.title"
+ @action={{@selectReplies}}
+ />
+ {{/if}}
+ <DButton
+ class="btn-flat select-below"
+ @label="topic.multi_select.select_below.label"
+ @title="topic.multi_select.select_below.title"
+ @action={{@selectBelow}}
+ />
+ {{/if}}
+ <DButton
+ class="btn-flat select-post"
+ @label={{if
+ @selected
+ "topic.multi_select.selected_post.label"
+ "topic.multi_select.select_post.label"
+ }}
+ @title={{if
+ @selected
+ "topic.multi_select.selected_post.title"
+ "topic.multi_select.select_post.title"
+ }}
+ @action={{@togglePostSelection}}
+ />
+ </div>
+</template>;
+
+export default PostMetaDataSelectPost;
diff --git a/app/assets/javascripts/discourse/app/components/post/meta-data/whisper-indicator.gjs b/app/assets/javascripts/discourse/app/components/post/meta-data/whisper-indicator.gjs
new file mode 100644
index 00000000000..4fcac6ec96c
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/post/meta-data/whisper-indicator.gjs
@@ -0,0 +1,28 @@
+import Component from "@glimmer/component";
+import { service } from "@ember/service";
+import icon from "discourse/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+
+export default class PostMetaDataWhisperIndicator extends Component {
+ @service site;
+
+ get groups() {
+ return this.site.whispers_allowed_groups_names;
+ }
+
+ get title() {
+ if (this.groups?.length > 0) {
+ return i18n("post.whisper_groups", {
+ groupNames: this.groups.join(", "),
+ });
+ }
+
+ return i18n("post.whisper");
+ }
+
+ <template>
+ <div class="post-info whisper" title={{this.title}}>
+ {{icon "far-eye-slash"}}
+ </div>
+ </template>
+}
diff --git a/app/assets/javascripts/discourse/app/components/post/notice.gjs b/app/assets/javascripts/discourse/app/components/post/notice.gjs
new file mode 100644
index 00000000000..ecf627391b1
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/post/notice.gjs
@@ -0,0 +1,49 @@
+import Component from "@glimmer/component";
+import { service } from "@ember/service";
+import { dasherize } from "@ember/string";
+import concatClass from "discourse/helpers/concat-class";
+import { applyValueTransformer } from "discourse/lib/transformer";
+import PostNoticeCustom from "./notice/custom";
+import PostNoticeNewUser from "./notice/new-user";
+import PostNoticeReturningUser from "./notice/returning-user";
+
+const POST_NOTICE_COMPONENTS = {
+ custom: PostNoticeCustom,
+ new_user: PostNoticeNewUser,
+ returning_user: PostNoticeReturningUser,
+};
+
+export default class PostNotice extends Component {
+ @service siteSettings;
+
+ get Component() {
+ return applyValueTransformer(
+ "post-notice-component",
+ POST_NOTICE_COMPONENTS[this.type],
+ { type: this.type, post: this.args.post }
+ );
+ }
+
+ get classNames() {
+ const classes = [dasherize(this.type)];
+
+ if (
+ new Date() - new Date(this.args.post.created_at) >
+ this.siteSettings.old_post_notice_days * 86400000
+ ) {
+ classes.push("old");
+ }
+
+ return classes;
+ }
+
+ get type() {
+ return this.args.post.notice.type;
+ }
+
+ <template>
+ <div class={{concatClass "post-notice" this.classNames}}>
+ <this.Component @notice={{@post.notice}} @post={{@post}} />
+ </div>
+ </template>
+}
diff --git a/app/assets/javascripts/discourse/app/components/post/notice/custom.gjs b/app/assets/javascripts/discourse/app/components/post/notice/custom.gjs
new file mode 100644
index 00000000000..842a14cf310
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/post/notice/custom.gjs
@@ -0,0 +1,54 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { htmlSafe } from "@ember/template";
+import { modifier } from "ember-modifier";
+import ConditionalInElement from "discourse/components/conditional-in-element";
+import UserLink from "discourse/components/user-link";
+import icon from "discourse/helpers/d-icon";
+import { prioritizeNameInUx } from "discourse/lib/settings";
+import { i18n } from "discourse-i18n";
+
+// TODO (glimmer-post-stream) needs tests
+export default class PostNoticeCustom extends Component {
+ @tracked createdByAnchorElement;
+
+ registerCreatedByLink = modifier((element) => {
+ this.createdByAnchorElement = element?.querySelector(".custom_created_by");
+ });
+
+ get createdByName() {
+ if (!this.args.post.notice_created_by_user) {
+ return;
+ }
+
+ return prioritizeNameInUx(this.args.post.notice_created_by_user.name)
+ ? this.args.post.notice_created_by_user.name
+ : this.args.post.notice_created_by_user.username;
+ }
+
+ <template>
+ {{icon "user-shield"}}
+ <div class="post-notice-message test" {{this.registerCreatedByLink}}>
+ {{htmlSafe @notice.cooked}}
+ {{#if this.createdByName}}
+ {{htmlSafe
+ (i18n
+ "post.notice.custom_created_by"
+ userLinkHTML="<span class='custom_created_by'></span>"
+ )
+ }}
+ {{/if}}
+ {{! #in-element is used as an strategy to render the HTML content in the string from a real component
+ instead defining it from a string }}
+ <ConditionalInElement @element={{this.createdByAnchorElement}}>
+ <UserLink
+ title={{this.createdByName}}
+ @username={{@post.notice_created_by_user.username}}
+ @ariaHidden={{false}}
+ >
+ {{this.createdByName}}
+ </UserLink>
+ </ConditionalInElement>
+ </div>
+ </template>
+}
diff --git a/app/assets/javascripts/discourse/app/components/post/notice/new-user.gjs b/app/assets/javascripts/discourse/app/components/post/notice/new-user.gjs
new file mode 100644
index 00000000000..4352052876d
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/post/notice/new-user.gjs
@@ -0,0 +1,22 @@
+import Component from "@glimmer/component";
+import { service } from "@ember/service";
+import icon from "discourse/helpers/d-icon";
+import { prioritizeNameInUx } from "discourse/lib/settings";
+import { i18n } from "discourse-i18n";
+
+// TODO (glimmer-post-stream) needs tests
+export default class PostNoticeNewUser extends Component {
+ @service siteSettings;
+
+ get user() {
+ return this.siteSettings.display_name_on_posts &&
+ prioritizeNameInUx(this.args.post.name)
+ ? this.args.post.name
+ : this.args.post.username;
+ }
+
+ <template>
+ {{icon "handshake-angle"}}
+ <p>{{i18n "post.notice.new_user" user=this.user}}</p>
+ </template>
+}
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.gjs
new file mode 100644
index 00000000000..02fa69e4c2a
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/post/notice/returning-user.gjs
@@ -0,0 +1,17 @@
+import icon from "discourse/helpers/d-icon";
+import { relativeAgeMediumSpan } from "discourse/lib/formatter";
+import { i18n } from "discourse-i18n";
+import PostNoticeNewUser from "./new-user";
+
+export default class PostNoticeReturningUser extends PostNoticeNewUser {
+ get time() {
+ const timeAgo =
+ (new Date() - new Date(this.args.notice.lastPostedAt)) / 1000;
+ return relativeAgeMediumSpan(timeAgo, true);
+ }
+
+ <template>
+ {{icon "far-face-smile"}}
+ <p>{{i18n "post.notice.returning_user" user=this.user time=this.time}}</p>
+ </template>
+}
diff --git a/app/assets/javascripts/discourse/app/components/post/placeholder.gjs b/app/assets/javascripts/discourse/app/components/post/placeholder.gjs
new file mode 100644
index 00000000000..d66471e61c2
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/post/placeholder.gjs
@@ -0,0 +1,16 @@
+const PostPlaceholder = <template>
+ <article class="placeholder">
+ <div class="row">
+ <div class="topic-avatar">
+ <div class="placeholder-avatar placeholder-animation"></div>
+ </div>
+ <div class="topic-body">
+ <div class="placeholder-text placeholder-animation"></div>
+ <div class="placeholder-text placeholder-animation"></div>
+ <div class="placeholder-text placeholder-animation"></div>
+ </div>
+ </div>
+ </article>
+</template>;
+
+export default PostPlaceholder;
diff --git a/app/assets/javascripts/discourse/app/components/post/small-action.gjs b/app/assets/javascripts/discourse/app/components/post/small-action.gjs
new file mode 100644
index 00000000000..caa85919ac6
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/post/small-action.gjs
@@ -0,0 +1,206 @@
+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";
+import UserAvatar from "discourse/components/user-avatar";
+import concatClass from "discourse/helpers/concat-class";
+import icon from "discourse/helpers/d-icon";
+import { autoUpdatingRelativeAge } from "discourse/lib/formatter";
+import getURL from "discourse/lib/get-url";
+import { applyValueTransformer } from "discourse/lib/transformer";
+import { userPath } from "discourse/lib/url";
+import { i18n } from "discourse-i18n";
+
+// TODO (glimmer-post-stream) remove the export after removing the legacy widget code
+export const GROUP_ACTION_CODES = ["invited_group", "removed_group"];
+const customGroupActionCodes = [];
+
+export const ICONS = {
+ "closed.enabled": "lock",
+ "closed.disabled": "unlock-keyhole",
+ "autoclosed.enabled": "lock",
+ "autoclosed.disabled": "unlock-keyhole",
+ "archived.enabled": "folder",
+ "archived.disabled": "folder-open",
+ "pinned.enabled": "thumbtack",
+ "pinned.disabled": "thumbtack unpinned",
+ "pinned_globally.enabled": "thumbtack",
+ "pinned_globally.disabled": "thumbtack unpinned",
+ "banner.enabled": "thumbtack",
+ "banner.disabled": "thumbtack unpinned",
+ "visible.enabled": "far-eye",
+ "visible.disabled": "far-eye-slash",
+ split_topic: "right-from-bracket",
+ invited_user: "circle-plus",
+ invited_group: "circle-plus",
+ user_left: "circle-minus",
+ removed_user: "circle-minus",
+ removed_group: "circle-minus",
+ public_topic: "comment",
+ open_topic: "comment",
+ private_topic: "envelope",
+ autobumped: "hand-point-right",
+};
+
+export function addGroupPostSmallActionCode(actionCode) {
+ customGroupActionCodes.push(actionCode);
+}
+
+// only for testing purposes
+export function resetGroupPostSmallActionCodes() {
+ customGroupActionCodes.length = 0;
+}
+
+export default class PostSmallAction extends Component {
+ @cached
+ get CustomComponent() {
+ return applyValueTransformer("post-small-action-custom-component", null, {
+ actionCode: this.code,
+ post: this.post,
+ });
+ }
+
+ get additionalClasses() {
+ return applyValueTransformer("post-small-action-class", [], {
+ post: this.args.post,
+ });
+ }
+
+ get code() {
+ return this.args.post.action_code;
+ }
+
+ @cached
+ get createdAt() {
+ return new Date(this.args.post.created_at);
+ }
+
+ get description() {
+ const when = this.createdAt
+ ? autoUpdatingRelativeAge(this.createdAt, {
+ format: "medium-with-ago-and-on",
+ })
+ : "";
+
+ let who = "";
+ if (this.username) {
+ if (this.isGroupAction) {
+ who = `<a class="mention-group" href="/g/${this.username}">@${this.username}</a>`;
+ } else {
+ who = `<a class="mention" href="${userPath(this.username)}">@${
+ this.username
+ }</a>`;
+ }
+ }
+
+ return htmlSafe(
+ i18n(`action_codes.${this.code}`, { who, when, path: this.path })
+ );
+ }
+
+ @cached
+ get icon() {
+ return applyValueTransformer(
+ "post-small-action-icon",
+ ICONS[this.code] || "exclamation",
+ { code: this.code, post: this.args.post }
+ );
+ }
+
+ get isGroupAction() {
+ return (
+ GROUP_ACTION_CODES.includes(this.code) ||
+ customGroupActionCodes.includes(this.code)
+ );
+ }
+
+ get path() {
+ if (!this.args.post.action_code_path || this.args.post.topic?.id) {
+ return;
+ }
+
+ return getURL(
+ this.args.post.action_code_path || `/t/${this.args.post.topic.id}`
+ );
+ }
+
+ get username() {
+ return this.args.post.action_code_who;
+ }
+
+ <template>
+ <article
+ id={{concat "post_" @post.post_number}}
+ class={{concatClass
+ "small-action"
+ "onscreen-post"
+ (if @post.deleted "deleted")
+ this.additionalClasses
+ }}
+ aria-label={{i18n
+ "share.post"
+ }}
+ role="region"
+ >
+ <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}}
+ </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>
+ </article>
+ </template>
+}
diff --git a/app/assets/javascripts/discourse/app/components/time-gap.gjs b/app/assets/javascripts/discourse/app/components/post/time-gap.gjs
similarity index 92%
rename from app/assets/javascripts/discourse/app/components/time-gap.gjs
rename to app/assets/javascripts/discourse/app/components/post/time-gap.gjs
index 5d0231696e4..0551bca4eaf 100644
--- a/app/assets/javascripts/discourse/app/components/time-gap.gjs
+++ b/app/assets/javascripts/discourse/app/components/post/time-gap.gjs
@@ -1,7 +1,7 @@
import Component from "@glimmer/component";
import { i18n } from "discourse-i18n";
-export default class TimeGap extends Component {
+export default class PostTimeGap extends Component {
get description() {
const daysSince = this.args.daysSince;
diff --git a/app/assets/javascripts/discourse/app/components/post/visited-line.gjs b/app/assets/javascripts/discourse/app/components/post/visited-line.gjs
new file mode 100644
index 00000000000..b0e2246f139
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/post/visited-line.gjs
@@ -0,0 +1,20 @@
+import { concat } from "@ember/helper";
+import concatClass from "discourse/helpers/concat-class";
+import { i18n } from "discourse-i18n";
+
+const PostVisitedLine = <template>
+ <div class="small-action topic-post-visited">
+ <div
+ class={{concatClass
+ "topic-post-visited-line"
+ (concat "post-" @post.post_number)
+ }}
+ >
+ <span class="topic-post-visited-message">
+ {{i18n "topics.new_messages_marker"}}
+ </span>
+ </div>
+ </div>
+</template>;
+
+export default PostVisitedLine;
diff --git a/app/assets/javascripts/discourse/app/components/reviewable-post-edits.gjs b/app/assets/javascripts/discourse/app/components/reviewable-post-edits.gjs
index 657d34cbf73..5152882409a 100644
--- a/app/assets/javascripts/discourse/app/components/reviewable-post-edits.gjs
+++ b/app/assets/javascripts/discourse/app/components/reviewable-post-edits.gjs
@@ -4,10 +4,10 @@ import { action } from "@ember/object";
import { gt } from "@ember/object/computed";
import { service } from "@ember/service";
import HistoryModal from "discourse/components/modal/history";
+import { historyHeat } from "discourse/components/post/meta-data/edits-indicator";
import icon from "discourse/helpers/d-icon";
import discourseComputed from "discourse/lib/decorators";
import { longDate } from "discourse/lib/formatter";
-import { historyHeat } from "discourse/widgets/post-edits-indicator";
import { i18n } from "discourse-i18n";
export default class ReviewablePostEdits extends Component {
diff --git a/app/assets/javascripts/discourse/app/components/scrolling-post-stream.js b/app/assets/javascripts/discourse/app/components/scrolling-post-stream.js
index cb9572fbd78..7992c214814 100644
--- a/app/assets/javascripts/discourse/app/components/scrolling-post-stream.js
+++ b/app/assets/javascripts/discourse/app/components/scrolling-post-stream.js
@@ -1,4 +1,4 @@
-import { schedule, scheduleOnce } from "@ember/runloop";
+import { next, schedule, scheduleOnce } from "@ember/runloop";
import { service } from "@ember/service";
import MountWidget from "discourse/components/mount-widget";
import discourseDebounce from "discourse/lib/debounce";
@@ -33,6 +33,7 @@ function findTopView(posts, viewportTop, postsWrapperTop, min, max) {
export default class ScrollingPostStream extends MountWidget {
@service screenTrack;
+ @service site;
widget = "post-stream";
_topVisible = null;
@@ -46,6 +47,7 @@ export default class ScrollingPostStream extends MountWidget {
"posts",
"canCreatePost",
"filteredPostsCount",
+ "filteringRepliesToPostNumber",
"multiSelect",
"gaps",
"selectedQuery",
@@ -319,7 +321,12 @@ export default class ScrollingPostStream extends MountWidget {
};
document.addEventListener("touchmove", this._debouncedScroll, opts);
window.addEventListener("scroll", this._debouncedScroll, opts);
- this._scrollTriggered();
+
+ if (this.site.useGlimmerPostStream) {
+ next(() => this._scrollTriggered());
+ } else {
+ this._scrollTriggered();
+ }
this.appEvents.on("post-stream:posted", this, "_posted");
diff --git a/app/assets/javascripts/discourse/app/components/user-avatar-flair.gjs b/app/assets/javascripts/discourse/app/components/user-avatar-flair.gjs
index b182eca5eb6..38be1564eb2 100644
--- a/app/assets/javascripts/discourse/app/components/user-avatar-flair.gjs
+++ b/app/assets/javascripts/discourse/app/components/user-avatar-flair.gjs
@@ -1,13 +1,14 @@
-import Component from "@ember/component";
-import { tagName } from "@ember-decorators/component";
+import Component from "@glimmer/component";
+import { service } from "@ember/service";
import AvatarFlair from "discourse/components/avatar-flair";
import autoGroupFlairForUser from "discourse/lib/avatar-flair";
-import discourseComputed from "discourse/lib/decorators";
-@tagName("")
export default class UserAvatarFlair extends Component {
- @discourseComputed("user")
- flair(user) {
+ @service site;
+
+ get flair() {
+ const user = this.args.user;
+
if (!user || !user.flair_group_id) {
return;
}
diff --git a/app/assets/javascripts/discourse/app/components/user-avatar.gjs b/app/assets/javascripts/discourse/app/components/user-avatar.gjs
new file mode 100644
index 00000000000..b444e815a19
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/user-avatar.gjs
@@ -0,0 +1,51 @@
+import Component from "@glimmer/component";
+import { service } from "@ember/service";
+import UserLink from "discourse/components/user-link";
+import avatar from "discourse/helpers/avatar";
+import concatClass from "discourse/helpers/concat-class";
+
+// TODO (saquetim) the pattern <a>{{avatar ...}}</a> is used a lot. Should we replace it with this component to ensure consistency???
+export default class UserAvatar extends Component {
+ @service currentUser;
+ @service siteSettings;
+
+ get ariaHidden() {
+ if (this.args.ariaHidden !== null) {
+ return this.args.ariaHidden;
+ }
+
+ if (this.args.ariaLabel) {
+ return false;
+ }
+
+ // often avatars are paired with usernames, making them redundant for screen readers so we hide the avatar from
+ // screen readers by default
+ return this.args.ariaHidden ?? true;
+ }
+
+ get hideFromAnonUser() {
+ return (
+ this.siteSettings.hide_user_profiles_from_public && !this.currentUser
+ );
+ }
+
+ <template>
+ <UserLink
+ ...attributes
+ @ariaHidden={{@ariaHidden}}
+ @ariaLabel={{@ariaLabel}}
+ @href={{@href}}
+ @user={{@user}}
+ >
+ {{avatar
+ @user
+ extraClasses=(concatClass
+ @avatarClasses (if this.hideFromAnonUser "non-clickable")
+ )
+ imageSize=@size
+ hideTitle=@hideTitle
+ loading=(if @lazy "lazy")
+ }}
+ </UserLink>
+ </template>
+}
diff --git a/app/assets/javascripts/discourse/app/components/user-link.gjs b/app/assets/javascripts/discourse/app/components/user-link.gjs
new file mode 100644
index 00000000000..39494894934
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/user-link.gjs
@@ -0,0 +1,63 @@
+import Component from "@glimmer/component";
+import { service } from "@ember/service";
+import { userPath } from "discourse/lib/url";
+import { i18n } from "discourse-i18n";
+
+export default class UserLink extends Component {
+ @service currentUser;
+ @service siteSettings;
+
+ get username() {
+ return this.args.username || this.args.user?.username;
+ }
+
+ get hideFromAnonUser() {
+ return (
+ this.siteSettings.hide_user_profiles_from_public && !this.currentUser
+ );
+ }
+
+ get href() {
+ const url = this.args.href || this.args.user?.path;
+ if (url) {
+ return url;
+ }
+
+ if (this.username) {
+ return userPath(this.username.toLowerCase());
+ }
+ }
+
+ get ariaHidden() {
+ return this.args.ariaHidden ?? !!this.args.ariaLabel;
+ }
+
+ get ariaLabel() {
+ if (this.args.ariaHidden) {
+ return;
+ }
+
+ if (this.args.ariaLabel) {
+ return this.args.ariaLabel;
+ }
+
+ if (this.username) {
+ return i18n("user.profile_possessive", {
+ username: this.username,
+ });
+ }
+ }
+
+ <template>
+ <a
+ class={{if this.hideFromAnonUser "non-clickable"}}
+ ...attributes
+ href={{this.href}}
+ data-user-card={{this.username}}
+ aria-hidden={{this.ariaHidden}}
+ aria-label={{this.ariaLabel}}
+ >
+ {{yield}}
+ </a>
+ </template>
+}
diff --git a/app/assets/javascripts/discourse/app/components/user-link.js b/app/assets/javascripts/discourse/app/components/user-link.js
deleted file mode 100644
index 4b4df2f5393..00000000000
--- a/app/assets/javascripts/discourse/app/components/user-link.js
+++ /dev/null
@@ -1,10 +0,0 @@
-import Component from "@ember/component";
-import { alias } from "@ember/object/computed";
-import { attributeBindings, tagName } from "@ember-decorators/component";
-
-@tagName("a")
-@attributeBindings("href", "dataUserCard:data-user-card")
-export default class UserLink extends Component {
- @alias("user.path") href;
- @alias("user.username") dataUserCard;
-}
diff --git a/app/assets/javascripts/discourse/app/controllers/topic.js b/app/assets/javascripts/discourse/app/controllers/topic.js
index 32f97db5c29..fe2220758b0 100644
--- a/app/assets/javascripts/discourse/app/controllers/topic.js
+++ b/app/assets/javascripts/discourse/app/controllers/topic.js
@@ -1294,6 +1294,11 @@ export default class TopicController extends Controller {
.catch((error) => popupAjaxError(error));
}
+ @action
+ updateTopicPageQueryParams() {
+ this.updateQueryParams();
+ }
+
_jumpToIndex(index) {
const postStream = this.get("model.postStream");
diff --git a/app/assets/javascripts/discourse/app/deprecation-workflow.js b/app/assets/javascripts/discourse/app/deprecation-workflow.js
index f80c3690057..b0140f6932b 100644
--- a/app/assets/javascripts/discourse/app/deprecation-workflow.js
+++ b/app/assets/javascripts/discourse/app/deprecation-workflow.js
@@ -6,6 +6,11 @@ const DEPRECATION_WORKFLOW = [
handler: "silence",
matchId: "discourse.decorate-widget.hamburger-widget-links",
},
+ // TODO (glimmer-post-stream): remove the silence once upgrade notes are ready and we start rolling out the new version
+ {
+ handler: "silence",
+ matchId: "discourse.post-stream-widget-overrides",
+ },
];
export default DEPRECATION_WORKFLOW;
diff --git a/app/assets/javascripts/discourse/app/helpers/avatar.js b/app/assets/javascripts/discourse/app/helpers/avatar.js
index 30a0a9f055b..4ce4831ee1f 100644
--- a/app/assets/javascripts/discourse/app/helpers/avatar.js
+++ b/app/assets/javascripts/discourse/app/helpers/avatar.js
@@ -72,7 +72,8 @@ export function renderAvatar(user, options) {
return avatarImg({
size: options.imageSize,
extraClasses: get(user, "extras") || options.extraClasses,
- title: title || displayName,
+ loading: options.loading,
+ title: options.hideTitle ? null : title || displayName,
avatarTemplate,
});
} else {
diff --git a/app/assets/javascripts/discourse/app/helpers/user-prioritized-name.js b/app/assets/javascripts/discourse/app/helpers/user-prioritized-name.js
new file mode 100644
index 00000000000..e29c134bac3
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/helpers/user-prioritized-name.js
@@ -0,0 +1,6 @@
+import { prioritizeNameFallback } from "discourse/lib/settings";
+import { formatUsername } from "discourse/lib/utilities";
+
+export default function userPrioritizedName(user) {
+ return prioritizeNameFallback(user.name, formatUsername(user.username));
+}
diff --git a/app/assets/javascripts/discourse/app/instance-initializers/post-decorations.js b/app/assets/javascripts/discourse/app/instance-initializers/post-decorations.js
index 0313daa9b79..9fced0d766a 100644
--- a/app/assets/javascripts/discourse/app/instance-initializers/post-decorations.js
+++ b/app/assets/javascripts/discourse/app/instance-initializers/post-decorations.js
@@ -133,6 +133,8 @@ export default {
}
function generateFullScreenTableModal(event) {
+ const { postId } = this;
+
const table = event.currentTarget.parentElement.nextElementSibling;
const tempTable = table.cloneNode(true);
const cookedWrapper = document.createElement("div");
@@ -140,35 +142,35 @@ export default {
if (siteSettings.display_footnotes_inline) {
cookedWrapper.classList.add("inline-footnotes");
}
- cookedWrapper.dataset.refPostId = this.id;
+ cookedWrapper.dataset.refPostId = postId;
cookedWrapper.appendChild(tempTable);
modal.show(FullscreenTableModal, {
model: { tableHtml: cookedWrapper },
});
}
- function generateSpreadsheetModal() {
- const tableIndex = this.tableIndex;
-
- return ajax(`/posts/${this.id}`, { type: "GET" })
- .then((post) => {
- parseAsync(post.raw).then((tokens) => {
- const allTables = tokenRange(tokens, "table_open", "table_close");
- const tableTokens = allTables[tableIndex];
-
- modal.show(SpreadsheetEditor, {
- model: {
- post,
- tableIndex,
- tableTokens,
- },
- });
- });
- })
- .catch(popupAjaxError);
+ async function generateSpreadsheetModal() {
+ const { postId, tableIndex } = this;
+
+ try {
+ const post = await ajax(`/posts/${postId}`, { type: "GET" });
+ const tokens = await parseAsync(post.raw);
+ const allTables = tokenRange(tokens, "table_open", "table_close");
+ const tableTokens = allTables[tableIndex];
+
+ modal.show(SpreadsheetEditor, {
+ model: {
+ post,
+ tableIndex,
+ tableTokens,
+ },
+ });
+ } catch (error) {
+ popupAjaxError(error);
+ }
}
- function generatePopups(tables, attrs) {
+ function generatePopups(tables, post) {
tables.forEach((table, index) => {
const buttonWrapper = document.createElement("div");
buttonWrapper.classList.add("fullscreen-table-wrapper__buttons");
@@ -185,14 +187,15 @@ export default {
table.parentNode.setAttribute("data-table-index", index);
table.parentNode.classList.add("fullscreen-table-wrapper");
- if (attrs.canEdit) {
+ // TODO (glimmer-post-stream) in the Glimmer post stream we can check for post.can_edit instead
+ if (post.canEdit) {
table.parentNode.classList.add("--editable");
buttonWrapper.append(tableEditorBtn);
tableEditorBtn.addEventListener(
"click",
generateSpreadsheetModal.bind({
+ postId: post.id,
tableIndex: index,
- ...attrs,
}),
false
);
@@ -218,7 +221,7 @@ export default {
buttonWrapper.append(expandTableBtn);
expandTableBtn.addEventListener(
"click",
- generateFullScreenTableModal.bind(attrs),
+ generateFullScreenTableModal.bind({ postId: post.id }),
false
);
table.parentNode.insertBefore(buttonWrapper, table);
@@ -241,10 +244,10 @@ export default {
}
api.decorateCookedElement(
- (post, helper) => {
+ (element, helper) => {
schedule("afterRender", () => {
- const tables = post.querySelectorAll(".md-table table");
- generatePopups(tables, helper.widget.attrs);
+ const tables = element.querySelectorAll(".md-table table");
+ generatePopups(tables, helper.model);
});
},
{
diff --git a/app/assets/javascripts/discourse/app/lib/avatar-utils.js b/app/assets/javascripts/discourse/app/lib/avatar-utils.js
index b779000eadc..c64e9ce4081 100644
--- a/app/assets/javascripts/discourse/app/lib/avatar-utils.js
+++ b/app/assets/javascripts/discourse/app/lib/avatar-utils.js
@@ -78,7 +78,13 @@ export function avatarImg(options, customGetURL) {
title = ` title='${escaped}'`;
}
- return `<img alt='' width='${size}' height='${size}' src='${url}' class='${classes}'${title}>`;
+ let loading = "";
+ if (options.loading) {
+ const escaped = escape(options.loading || "");
+ loading = ` loading='${escaped}'`;
+ }
+
+ return `<img alt='' width='${size}' height='${size}' src='${url}' class='${classes}'${title}${loading}>`;
}
export function tinyAvatar(avatarTemplate, options) {
diff --git a/app/assets/javascripts/discourse/app/lib/plugin-api.gjs b/app/assets/javascripts/discourse/app/lib/plugin-api.gjs
index 8da2cd0086b..82d1b92585c 100644
--- a/app/assets/javascripts/discourse/app/lib/plugin-api.gjs
+++ b/app/assets/javascripts/discourse/app/lib/plugin-api.gjs
@@ -5,6 +5,7 @@
export const PLUGIN_API_VERSION = "2.1.1";
+import Component from "@glimmer/component";
import $ from "jquery";
import { h } from "virtual-dom";
import { addAboutPageActivity } from "discourse/components/about-page";
@@ -26,6 +27,8 @@ import { headerIconsDAG } from "discourse/components/header/icons";
import { registeredTabs } from "discourse/components/more-topics";
import { addWidgetCleanCallback } from "discourse/components/mount-widget";
import { addPluginOutletDecorator } from "discourse/components/plugin-connector";
+import PostMetaDataPosterNameIcon from "discourse/components/post/meta-data/poster-name/icon";
+import { addGroupPostSmallActionCode } from "discourse/components/post/small-action";
import {
addPluginReviewableParam,
registerReviewableActionModal,
@@ -63,12 +66,13 @@ import classPrepend, {
} from "discourse/lib/class-prepend";
import { addPopupMenuOption } from "discourse/lib/composer/custom-popup-menu-options";
import { registerRichEditorExtension } from "discourse/lib/composer/rich-editor-extensions";
-import deprecated from "discourse/lib/deprecated";
+import deprecated, { withSilencedDeprecations } from "discourse/lib/deprecated";
import { registerDesktopNotificationHandler } from "discourse/lib/desktop-notifications";
import { downloadCalendar } from "discourse/lib/download-calendar";
import { isTesting } from "discourse/lib/environment";
import { getOwnerWithFallback } from "discourse/lib/get-owner";
import { registerHashtagType } from "discourse/lib/hashtag-type-registry";
+import { makeArray } from "discourse/lib/helpers";
import {
registerHighlightJSLanguage,
registerHighlightJSPlugin,
@@ -142,7 +146,6 @@ import {
replaceButton,
} from "discourse/widgets/post-menu";
import {
- addGroupPostSmallActionCode,
addPostSmallActionClassesCallback,
addPostSmallActionIcon,
} from "discourse/widgets/post-small-action";
@@ -162,12 +165,52 @@ import { addImageWrapperButton } from "discourse-markdown-it/features/image-cont
import { CUSTOM_USER_SEARCH_OPTIONS } from "select-kit/components/user-chooser";
import { modifySelectKit } from "select-kit/mixins/plugin-api";
+const DEPRECATED_POST_STREAM_WIDGETS = [
+ "actions-summary",
+ "avatar-flair",
+ "embedded-post",
+ "expand-hidden",
+ "expand-post-button",
+ "filter-jump-to-post",
+ "filter-show-all",
+ "post-article",
+ "post-article",
+ "post-avatar-user-info",
+ "post-avatar",
+ "post-body",
+ "post-contents",
+ "post-date",
+ "post-edits-indicator",
+ "post-email-indicator",
+ "post-gap",
+ "post-group-request",
+ "post-links",
+ "post-locked-indicator",
+ "post-meta-data",
+ "post-notice",
+ "post-placeholder",
+ "post-stream",
+ "post",
+ "poster-name",
+ "poster-name-title",
+ "posts-filtered-notice",
+ "reply-to-tab",
+ "select-post",
+ "topic-post-visited-line",
+];
+
const DEPRECATED_POST_MENU_WIDGETS = [
"post-menu",
"post-user-tip-shim",
"small-user-list",
];
+const POST_STREAM_DEPRECATION_OPTIONS = {
+ since: "v3.5.0.beta1-dev",
+ id: "discourse.post-stream-widget-overrides",
+ // url: "", // TODO (glimmer-post-stream) uncomment when the topic is created on meta
+};
+
const POST_MENU_DEPRECATION_OPTIONS = {
since: "v3.4.0.beta3-dev",
id: "discourse.post-menu-widget-overrides",
@@ -620,6 +663,14 @@ class PluginApi {
addDecorator(callback, { afterAdopt: !!opts.afterAdopt });
+ this.onAppEvent(
+ opts.afterAdopt
+ ? "decorate-post-cooked-element:after-adopt"
+ : "decorate-post-cooked-element:before-adopt",
+ callback
+ );
+
+ // TODO (glimmer-post-stream) should we also handle afterAdopt for non-stream renderings?
if (!opts.onlyStream) {
this.onAppEvent("decorate-non-stream-cooked-element", callback);
}
@@ -701,52 +752,92 @@ class PluginApi {
const site = this._lookupContainer("service:site");
const loc = site && site.mobileView ? "before" : "after";
- decorateWidget(`poster-name:${loc}`, (dec) => {
- const attrs = dec.attrs;
- let results = cb(attrs.userCustomFields || {}, attrs);
+ const IconsComponent = class extends Component {
+ get definitions() {
+ return makeArray(
+ cb(
+ this.args.outletArgs.post.user_custom_fields || {},
+ this.args.outletArgs.post
+ )
+ );
+ }
- if (results) {
- if (!Array.isArray(results)) {
- results = [results];
- }
+ <template>
+ {{#each this.definitions as |definition|}}
+ <PostMetaDataPosterNameIcon
+ @className={{definition.className}}
+ @emoji={{definition.emoji}}
+ @emojiTitle={{definition.emojiTitle}}
+ @icon={{definition.icon}}
+ @text={{definition.text}}
+ @title={{definition.title}}
+ @url={{definition.url}}
+ />
+ {{/each}}
+ </template>
+ };
+
+ if (loc === "after") {
+ this.renderAfterWrapperOutlet(
+ "post-meta-data-poster-name",
+ IconsComponent
+ );
+ } else {
+ this.renderBeforeWrapperOutlet(
+ "post-meta-data-poster-name",
+ IconsComponent
+ );
+ }
- return results.map((result) => {
- let iconBody;
-
- if (result.icon) {
- iconBody = iconNode(result.icon);
- } else if (result.emoji) {
- iconBody = result.emoji.split("|").map((name) => {
- let widgetAttrs = { name };
- if (result.emojiTitle) {
- widgetAttrs.title = true;
- }
- return dec.attach("emoji", widgetAttrs);
- });
- }
+ // TODO (glimmer-post-stream): remove the fallback when removing the legacy post stream code
+ withSilencedDeprecations("discourse.post-stream-widget-overrides", () => {
+ decorateWidget(`poster-name:${loc}`, (dec) => {
+ const attrs = dec.attrs;
+ let results = cb(attrs.userCustomFields || {}, attrs);
- if (result.text) {
- iconBody = [iconBody, result.text];
+ if (results) {
+ if (!Array.isArray(results)) {
+ results = [results];
}
- if (result.url) {
- iconBody = dec.h(
- "a",
- { attributes: { href: result.url } },
+ return results.map((result) => {
+ let iconBody;
+
+ if (result.icon) {
+ iconBody = iconNode(result.icon);
+ } else if (result.emoji) {
+ iconBody = result.emoji.split("|").map((name) => {
+ let widgetAttrs = { name };
+ if (result.emojiTitle) {
+ widgetAttrs.title = true;
+ }
+ return dec.attach("emoji", widgetAttrs);
+ });
+ }
+
+ if (result.text) {
+ iconBody = [iconBody, result.text];
+ }
+
+ if (result.url) {
+ iconBody = dec.h(
+ "a",
+ { attributes: { href: result.url } },
+ iconBody
+ );
+ }
+
+ return dec.h(
+ "span.poster-icon",
+ {
+ className: result.className,
+ attributes: { title: result.title },
+ },
iconBody
);
- }
-
- return dec.h(
- "span.poster-icon",
- {
- className: result.className,
- attributes: { title: result.title },
- },
- iconBody
- );
- });
- }
+ });
+ }
+ });
});
}
@@ -1142,6 +1233,10 @@ class PluginApi {
**/
disableNameSuppressionOnPosts() {
disableNameSuppression();
+ this.registerValueTransformer(
+ "post-meta-data-poster-name-suppress-similar-name",
+ () => true
+ );
}
/**
@@ -1445,6 +1540,12 @@ class PluginApi {
* ```
**/
addPostSmallActionIcon(key, icon) {
+ this.registerValueTransformer(
+ "post-small-action-icon",
+ ({ value, context: { code } }) => (key === code ? icon : value)
+ );
+
+ // TODO (glimmer-post-stream): remove the fallback when removing the legacy post stream code
addPostSmallActionIcon(key, icon);
}
@@ -1472,6 +1573,15 @@ class PluginApi {
* ```
**/
addPostSmallActionClassesCallback(callback) {
+ this.registerValueTransformer(
+ "post-small-action-class",
+ ({ value, context: { post } }) => [
+ ...makeArray(value),
+ ...makeArray(callback(post)),
+ ]
+ );
+
+ // TODO (glimmer-post-stream): remove the fallback when removing the legacy post stream code
addPostSmallActionClassesCallback(callback);
}
@@ -1533,6 +1643,15 @@ class PluginApi {
* addPostClassesCallback((attrs) => {if (attrs.post_number == 1) return ["first"];})
**/
addPostClassesCallback(callback) {
+ this.registerValueTransformer(
+ "post-class",
+ ({ value, context: { post } }) => [
+ ...makeArray(value),
+ ...makeArray(callback(post)),
+ ]
+ );
+
+ // TODO (glimmer-post-stream): remove the fallback when removing the legacy post stream code
addPostClassesCallback(callback);
}
@@ -1590,6 +1709,11 @@ class PluginApi {
* })
*/
addPostTransformCallback(callback) {
+ deprecated(
+ "`api.addPostTransformCallback` has been deprecated.",
+ POST_STREAM_DEPRECATION_OPTIONS
+ );
+
addPostTransformCallback(callback);
}
@@ -3409,6 +3533,14 @@ class PluginApi {
// );
// }
+ if (DEPRECATED_POST_STREAM_WIDGETS.includes(widgetName)) {
+ deprecated(
+ `The \`${widgetName}\` widget has been deprecated and \`api.${override}\` is no longer a supported override.`,
+ POST_STREAM_DEPRECATION_OPTIONS
+ );
+ return;
+ }
+
if (DEPRECATED_POST_MENU_WIDGETS.includes(widgetName)) {
deprecated(
`The ${widgetName} widget has been deprecated and ${override} is no longer a supported override.`,
diff --git a/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/link-counts.js b/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/link-counts.js
new file mode 100644
index 00000000000..8df8b5ba923
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/link-counts.js
@@ -0,0 +1,73 @@
+import { isValidLink } from "discourse/lib/click-track";
+import { number } from "discourse/lib/formatter";
+import { i18n } from "discourse-i18n";
+
+export default function (element, context) {
+ const { data } = context;
+
+ const linkCounts = data.post.link_counts;
+ if (!linkCounts?.length) {
+ return;
+ }
+
+ // find the best <a> element in each onebox and display link counts only
+ // for that one (the best element is the most significant one to the
+ // viewer)
+ const bestElements = new Map();
+ element.querySelectorAll("aside.onebox").forEach((onebox) => {
+ // look in headings first
+ for (let i = 1; i <= 6; ++i) {
+ const hLinks = onebox.querySelectorAll(`h${i} a[href]`);
+ if (hLinks.length > 0) {
+ bestElements.set(onebox, hLinks[0]);
+ return;
+ }
+ }
+
+ // use the header otherwise
+ const hLinks = onebox.querySelectorAll("header a[href]");
+ if (hLinks.length > 0) {
+ bestElements.set(onebox, hLinks[0]);
+ }
+ });
+
+ linkCounts.forEach((lc) => {
+ if (!lc.clicks || lc.clicks < 1) {
+ return;
+ }
+
+ element.querySelectorAll("a[href]").forEach((link) => {
+ const href = link.getAttribute("href");
+ let valid = href === lc.url;
+
+ // this might be an attachment
+ if (lc.internal && /^\/uploads\//.test(lc.url)) {
+ valid = href.includes(lc.url);
+ }
+
+ // match server-side behavior for internal links with query params
+ if (lc.internal && /\?/.test(href)) {
+ valid = href.split("?")[0] === lc.url;
+ }
+
+ // don't display badge counts on category badge & oneboxes (unless when explicitly stated)
+ if (valid && isValidLink(link)) {
+ const onebox = link.closest(".onebox");
+
+ if (
+ !onebox ||
+ !bestElements.has(onebox) ||
+ bestElements.get(onebox) === link
+ ) {
+ link.setAttribute("data-clicks", number(lc.clicks));
+
+ const countText = i18n("post.link_clicked", {
+ count: lc.clicks,
+ });
+ const ariaLabel = `${link.textContent.trim()} ${countText}`;
+ link.setAttribute("aria-label", ariaLabel);
+ }
+ }
+ });
+ });
+}
diff --git a/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/mentions.gjs b/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/mentions.gjs
new file mode 100644
index 00000000000..0536c2c7c90
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/mentions.gjs
@@ -0,0 +1,86 @@
+import UserStatusMessage from "discourse/components/user-status-message";
+import getURL from "discourse/lib/get-url";
+import { applyValueTransformer } from "discourse/lib/transformer";
+
+const CookedUserStatusMessage = <template>
+ {{#in-element @data.wrapper}}
+ <UserStatusMessage @status={{@data.status}} />
+ {{/in-element}}
+</template>;
+
+export default function (element, context) {
+ const {
+ data: { post },
+ state,
+ owner,
+ helper,
+ } = context;
+
+ state.extractedMentions = _extractMentions(element, post);
+
+ const userStatusService = owner.lookup("service:user-status");
+
+ const _updateUserStatus = (updatedUser) => {
+ state.extractedMentions
+ .filter(({ user }) => updatedUser.id === user?.id)
+ .forEach(({ mentions, user }) => {
+ _renderUserStatusOnMentions(mentions, user, helper);
+ });
+ };
+
+ state.extractedMentions.forEach(({ mentions, user }) => {
+ if (userStatusService.isEnabled) {
+ user.statusManager?.trackStatus?.();
+ user.on?.("status-changed", element, _updateUserStatus);
+
+ _renderUserStatusOnMentions(mentions, user, helper);
+ }
+
+ const classes = applyValueTransformer("mentions-class", [], {
+ user,
+ });
+
+ mentions.forEach((mention) => {
+ mention.classList.add(...classes);
+ });
+ });
+
+ // cleanup code
+ return () => {
+ state.extractedMentions = [];
+
+ if (userStatusService.isEnabled) {
+ post?.mentioned_users?.forEach((user) => {
+ user.statusManager?.stopTrackingStatus?.();
+ user.off?.("status-changed", element, _updateUserStatus);
+ });
+ }
+ };
+}
+
+function _renderUserStatusOnMentions(mentions, user, helper) {
+ mentions.forEach((mention) => {
+ let wrapper = mention.querySelector(".user-status-message-wrapper");
+ if (!wrapper) {
+ wrapper = document.createElement("span");
+ wrapper.classList.add("user-status-message-wrapper");
+ mention.appendChild(wrapper);
+ }
+
+ helper.renderGlimmer(mention, CookedUserStatusMessage, {
+ wrapper,
+ status: user.status,
+ });
+ });
+}
+
+function _extractMentions(element, post) {
+ return (
+ post?.mentioned_users?.map((user) => {
+ const href = getURL(`/u/${user.username.toLowerCase()}`);
+ const mentions = element.querySelectorAll(`a.mention[href="${href}"]`);
+
+ return { user, mentions };
+ }) || []
+ );
+}
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.js
new file mode 100644
index 00000000000..1a1bf1c633c
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/quote-controls.js
@@ -0,0 +1,190 @@
+import { spinnerHTML } from "discourse/helpers/loading-spinner";
+import { ajax } from "discourse/lib/ajax";
+import escape from "discourse/lib/escape";
+import highlightHTML from "discourse/lib/highlight-html";
+import { iconHTML } from "discourse/lib/icon-library";
+import { postUrl } from "discourse/lib/utilities";
+import { i18n } from "discourse-i18n";
+
+export default function (element, context) {
+ const { state } = context;
+
+ const quotes = element.querySelectorAll("aside.quote");
+ if (quotes.length === 0) {
+ return;
+ }
+
+ state.originalQuoteContents = new Map();
+
+ quotes.forEach((aside, index) => {
+ if (aside.dataset.post) {
+ const quoteId = `quote-id-${aside.dataset.topic}-${aside.dataset.post}-${index}`;
+
+ const blockquote = aside.querySelector("blockquote");
+ if (blockquote) {
+ blockquote.id = quoteId;
+ }
+
+ _updateQuoteElements(aside, "chevron-down", context);
+ const title = aside.querySelector(".title");
+
+ if (!title) {
+ return;
+ }
+
+ // If post/topic is not found then display username, skip controls
+ if (aside.classList.contains("quote-post-not-found")) {
+ if (aside.dataset.username) {
+ title.innerHTML = escape(aside.dataset.username);
+ } else {
+ title.remove();
+ }
+
+ return;
+ }
+
+ // Unless it's a full quote, allow click to expand
+ if (!aside.dataset.full && !title.dataset.hasQuoteControls) {
+ title.addEventListener("click", (e) => {
+ if (e.target.closest("a")) {
+ return true;
+ }
+
+ _toggleQuote(aside, context);
+ });
+
+ title.dataset.hasQuoteControls = true;
+ }
+ }
+ });
+}
+
+function _updateQuoteElements(aside, desc, context) {
+ const { data } = context;
+
+ const quoteTitle = i18n("post.follow_quote");
+ const postNumber = aside.dataset.post;
+ const topicNumber = aside.dataset.topic;
+
+ // If we have a post reference
+ let navLink = "";
+ if (
+ topicNumber &&
+ postNumber &&
+ topicNumber === data.post.topic_id?.toString()
+ ) {
+ const topicId = data.post.topic_id;
+ const slug = data.post.topic.slug;
+
+ const url = postUrl(slug, topicId, postNumber);
+ const icon = iconHTML("arrow-up");
+
+ navLink = `<a href='${url}' title='${quoteTitle}' class='btn-flat back'>${icon}</a>`;
+ }
+
+ // Only add the expand/contract control if it's not a full post
+ const titleElement = aside.querySelector(".title");
+ let expandContract = "";
+
+ if (!aside.dataset.full) {
+ const icon = iconHTML(desc, { title: "post.expand_collapse" });
+ const quoteId = aside.querySelector("blockquote")?.id;
+
+ if (quoteId) {
+ const isExpanded = aside.dataset.expanded === "true";
+ expandContract = `<button aria-controls="${quoteId}" aria-expanded="${isExpanded}" class="quote-toggle btn-flat">${icon}</button>`;
+
+ if (titleElement) {
+ titleElement.style.cursor = "pointer";
+ }
+ }
+ }
+
+ if (data.ignoredUsers?.length && titleElement) {
+ const username = titleElement.innerText.trim().slice(0, -1);
+
+ if (username.length > 0 && data.ignoredUsers.includes(username)) {
+ aside.querySelectorAll("p").forEach((el) => el.remove());
+ aside.classList.add("ignored-user");
+ }
+ }
+
+ const quoteControls = aside.querySelector(".quote-controls");
+ if (quoteControls) {
+ quoteControls.innerHTML = expandContract + navLink;
+ }
+}
+
+async function _toggleQuote(aside, context) {
+ const { createDetachedElement, data, renderNestedCookedContent, state } =
+ context;
+
+ if (state.expanding) {
+ return;
+ }
+
+ state.expanding = true;
+ const blockQuote = aside.querySelector("blockquote");
+
+ if (!blockQuote) {
+ return;
+ }
+
+ if (aside.dataset.expanded) {
+ delete aside.dataset.expanded;
+ } else {
+ aside.dataset.expanded = true;
+ }
+
+ const quoteId = blockQuote.id;
+
+ if (aside.dataset.expanded) {
+ _updateQuoteElements(aside, "chevron-up", context);
+
+ // Show expanded quote
+ state.originalQuoteContents.set(quoteId, blockQuote.innerHTML);
+
+ const originalText =
+ blockQuote.textContent.trim() ||
+ data.post.cooked.querySelector("blockquote").textContent.trim();
+
+ blockQuote.innerHTML = spinnerHTML;
+
+ const topicId = parseInt(aside.dataset.topic || data.post.topic_id, 10);
+ const postId = parseInt(aside.dataset.post, 10);
+
+ try {
+ const result = await ajax(`/posts/by_number/${topicId}/${postId}`);
+
+ const post = data.post;
+ const quotedPosts = post.quoted || {};
+ quotedPosts[result.id] = result;
+ post.set("quoted", quotedPosts);
+
+ const div = createDetachedElement("div");
+ div.classList.add("expanded-quote");
+ div.dataset.postId = result.id;
+
+ // inception
+ renderNestedCookedContent(div, result.cooked, (element) =>
+ highlightHTML(element, originalText, {
+ matchCase: true,
+ })
+ );
+
+ blockQuote.innerHTML = "";
+ blockQuote.appendChild(div);
+ } catch (e) {
+ if ([403, 404].includes(e.jqXHR.status)) {
+ const icon = iconHTML(e.jqXHR.status === 403 ? "lock" : "trash-can");
+ blockQuote.innerHTML = `<div class='expanded-quote icon-only'>${icon}</div>`;
+ }
+ }
+ } else {
+ // Hide expanded quote
+ _updateQuoteElements(aside, "chevron-down", context);
+ blockQuote.innerHTML = state.originalQuoteContents.get(blockQuote.id);
+ }
+
+ state.expanding = false;
+}
diff --git a/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/search-highlight.js b/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/search-highlight.js
new file mode 100644
index 00000000000..57c3249bea7
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/search-highlight.js
@@ -0,0 +1,19 @@
+import { unhighlightHTML } from "discourse/lib/highlight-html";
+import highlightSearch from "discourse/lib/highlight-search";
+
+export default function (element, context) {
+ const { data, state } = context;
+ const highlight = data.highlightTerm;
+
+ if (highlight && highlight.length > 2) {
+ if (state.highlighted) {
+ unhighlightHTML(element);
+ }
+
+ highlightSearch(element, highlight, { defaultClassName: true });
+ state.highlighted = true;
+ } else if (state.highlighted) {
+ unhighlightHTML(element);
+ state.highlighted = false;
+ }
+}
diff --git a/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/selection-barrier.js b/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/selection-barrier.js
new file mode 100644
index 00000000000..6511f98c149
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/selection-barrier.js
@@ -0,0 +1,14 @@
+// On WebKit-based browsers, triple clicking on the last paragraph of a post won't stop at the end of the paragraph.
+// It looks like the browser is selecting EOL characters, and that causes the selection to leak into the following
+// nodes until it finds a non-empty node. This is a workaround to prevent that from happening.
+// We insert a div after the last paragraph at the end of the cooked content, containing a <br> element.
+// The line break works as a barrier, causing the selection to stop at the correct place.
+// To prevent layout shifts this div is styled to be invisible with height 0 and overflow hidden and set aria-hidden
+// to true to prevent screen readers from reading it.
+export default function (element) {
+ const selectionBarrier = document.createElement("div");
+ selectionBarrier.classList.add("cooked-selection-barrier");
+ selectionBarrier.ariaHidden = "true";
+ selectionBarrier.appendChild(document.createElement("br"));
+ element.appendChild(selectionBarrier);
+}
diff --git a/app/assets/javascripts/discourse/app/lib/transform-post.js b/app/assets/javascripts/discourse/app/lib/transform-post.js
index 219082d05dc..dbc58c3487f 100644
--- a/app/assets/javascripts/discourse/app/lib/transform-post.js
+++ b/app/assets/javascripts/discourse/app/lib/transform-post.js
@@ -180,10 +180,8 @@ export default function transformPost(
}
if (postAtts.isDeleted) {
- postAtts.deletedByAvatarTemplate = post.get(
- "postDeletedBy.avatar_template"
- );
- postAtts.deletedByUsername = post.get("postDeletedBy.username");
+ postAtts.deletedByAvatarTemplate = post.get("deletedBy.avatar_template");
+ postAtts.deletedByUsername = post.get("deletedBy.username");
}
const replyToUser = post.get("reply_to_user");
diff --git a/app/assets/javascripts/discourse/app/lib/transformer/registry.js b/app/assets/javascripts/discourse/app/lib/transformer/registry.js
index 21803799820..050ad601837 100644
--- a/app/assets/javascripts/discourse/app/lib/transformer/registry.js
+++ b/app/assets/javascripts/discourse/app/lib/transformer/registry.js
@@ -30,9 +30,18 @@ export const VALUE_TRANSFORMERS = Object.freeze([
"navigation-bar-dropdown-mode",
"parent-category-row-class",
"parent-category-row-class-mobile",
+ "post-class",
"post-menu-buttons",
"post-menu-collapsed",
+ "post-meta-data-poster-name-suppress-similar-name",
+ "post-notice-component",
+ "post-show-topic-map",
+ "post-small-action-class",
+ "post-small-action-custom-component",
+ "post-small-action-icon",
"post-text-selection-prevent-close",
+ "site-setting-enable-welcome-banner",
+ "site-setting-search-experience",
"small-user-attrs",
"tag-separator",
"topic-list-class",
@@ -42,6 +51,4 @@ export const VALUE_TRANSFORMERS = Object.freeze([
"topic-list-item-expand-pinned",
"topic-list-item-mobile-layout",
"topic-list-item-style",
- "site-setting-enable-welcome-banner",
- "site-setting-search-experience",
]);
diff --git a/app/assets/javascripts/discourse/app/models/action-summary.js b/app/assets/javascripts/discourse/app/models/action-summary.js
index 3b8ce55cbb6..21904ac115d 100644
--- a/app/assets/javascripts/discourse/app/models/action-summary.js
+++ b/app/assets/javascripts/discourse/app/models/action-summary.js
@@ -3,6 +3,7 @@ import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import RestModel from "discourse/models/rest";
+// TODO (glimmer-post-stream) is this model still used?
export default class ActionSummary extends RestModel {
@or("can_undo", "can_act") canToggle;
diff --git a/app/assets/javascripts/discourse/app/models/post.js b/app/assets/javascripts/discourse/app/models/post.js
index 1dd3db9fa40..386bca0465b 100644
--- a/app/assets/javascripts/discourse/app/models/post.js
+++ b/app/assets/javascripts/discourse/app/models/post.js
@@ -1,4 +1,4 @@
-import { tracked } from "@glimmer/tracking";
+import { cached, tracked } from "@glimmer/tracking";
import EmberObject, { get } from "@ember/object";
import { alias, and, equal, not, or } from "@ember/object/computed";
import { service } from "@ember/service";
@@ -15,6 +15,7 @@ import { defineTrackedProperty } from "discourse/lib/tracked-tools";
import { userPath } from "discourse/lib/url";
import { postUrl } from "discourse/lib/utilities";
import ActionSummary from "discourse/models/action-summary";
+import Badge from "discourse/models/badge";
import Composer from "discourse/models/composer";
import RestModel from "discourse/models/rest";
import Site from "discourse/models/site";
@@ -149,26 +150,65 @@ export default class Post extends RestModel {
@service currentUser;
@service site;
+ @tracked customShare = null;
+
// Use @trackedPostProperty here instead of Glimmer's @tracked because we need to know which properties are tracked
// in order to correctly update the post in the updateFromPost method. Currently this is not possible using only
// the standard tracked method because these properties are added to the class prototype and are not enumarated by
// object.keys().
// See https://github.com/emberjs/ember.js/issues/18220
+ @trackedPostProperty action_code;
+ @trackedPostProperty action_code_path;
+ @trackedPostProperty action_code_who;
+ @trackedPostProperty actions_summary;
+ @trackedPostProperty admin;
+ @trackedPostProperty badges_granted;
@trackedPostProperty bookmarked;
@trackedPostProperty can_delete;
@trackedPostProperty can_edit;
@trackedPostProperty can_permanently_delete;
@trackedPostProperty can_recover;
+ @trackedPostProperty can_see_hidden_post;
+ @trackedPostProperty can_view_edit_history;
+ @trackedPostProperty cooked;
+ @trackedPostProperty cooked_hidden;
+ @trackedPostProperty created_at;
@trackedPostProperty deleted_at;
+ @trackedPostProperty deleted_by;
+ @trackedPostProperty excerpt;
+ @trackedPostProperty expandedExcerpt;
+ @trackedPostProperty group_moderator;
+ @trackedPostProperty hidden;
+ @trackedPostProperty is_auto_generated;
+ @trackedPostProperty last_wiki_edit;
@trackedPostProperty likeAction;
+ @trackedPostProperty link_counts;
+ @trackedPostProperty locked;
+ @trackedPostProperty moderator;
+ @trackedPostProperty name;
+ @trackedPostProperty notice;
+ @trackedPostProperty notice_created_by_user;
+ @trackedPostProperty post_number;
@trackedPostProperty post_type;
+ @trackedPostProperty primary_group_name;
+ @trackedPostProperty read;
+ @trackedPostProperty reply_count;
+ @trackedPostProperty reply_to_user;
+ @trackedPostProperty staff;
+ @trackedPostProperty title_is_group;
+ @trackedPostProperty trust_level;
+ @trackedPostProperty updated_at;
+ @trackedPostProperty user;
@trackedPostProperty user_deleted;
@trackedPostProperty user_id;
+ @trackedPostProperty user_suspended;
+ @trackedPostProperty user_title;
+ @trackedPostProperty username;
+ @trackedPostProperty version;
+ @trackedPostProperty via_email;
+ @trackedPostProperty wiki;
@trackedPostProperty yours;
- @trackedPostProperty expandedExcerpt;
- @trackedPostProperty excerpt;
-
- customShare = null;
+ @trackedPostProperty user_custom_fields;
@alias("can_edit") canEdit; // for compatibility with existing code
@equal("trust_level", 0) new_user;
@@ -179,6 +219,8 @@ export default class Post extends RestModel {
@or("deleted_at", "user_deleted") recoverable; // post or content still can be recovered
@propertyEqual("topic.details.created_by.id", "user_id") topicOwner;
@alias("topic.details.created_by.id") topicCreatedById;
+ @alias("deletedBy") postDeletedBy; // TODO (glimmer-post-stream): check if this alias can be removed after removing the widget code
+ @alias("deletedAt") postDeletedAt; // TODO (glimmer-post-stream): check if this alias can be removed after removing the widget code
constructor() {
super(...arguments);
@@ -189,9 +231,8 @@ export default class Post extends RestModel {
});
}
- @discourseComputed("url", "customShare")
- shareUrl(url) {
- return this.customShare || resolveShareUrl(url, this.currentUser);
+ get shareUrl() {
+ return this.customShare || resolveShareUrl(this.url, this.currentUser);
}
@discourseComputed("name", "username")
@@ -199,14 +240,12 @@ export default class Post extends RestModel {
return name && name !== username && this.siteSettings.display_name_on_posts;
}
- @discourseComputed("firstPost", "deleted_by", "topic.deleted_by")
- postDeletedBy(firstPost, deletedBy, topicDeletedBy) {
- return firstPost ? topicDeletedBy : deletedBy;
+ get deletedBy() {
+ return this.firstPost ? this.topic?.deleted_by : this.deleted_by;
}
- @discourseComputed("firstPost", "deleted_at", "topic.deleted_at")
- postDeletedAt(firstPost, deletedAt, topicDeletedAt) {
- return firstPost ? topicDeletedAt : deletedAt;
+ get deletedAt() {
+ return this.firstPost ? this.topic?.deleted_at : this.deleted_at;
}
@discourseComputed("post_number", "topic_id", "topic.slug")
@@ -241,13 +280,12 @@ export default class Post extends RestModel {
.catch(popupAjaxError);
}
- @discourseComputed("[email protected]")
- internalLinks() {
+ get internalLinks() {
if (isEmpty(this.link_counts)) {
return null;
}
- return this.link_counts.filterBy("internal").filterBy("title");
+ return this.link_counts.filter((link) => link.internal && link.title);
}
@discourseComputed("[email protected]_act")
@@ -334,6 +372,10 @@ export default class Post extends RestModel {
return !this.isRecoveringTopic && !this.recoverable && this.can_recover;
}
+ get canSplitMergeTopic() {
+ return !!this.topic?.details?.can_split_merge_topic;
+ }
+
get canToggleLike() {
return !!this.likeAction?.get("canToggle");
}
@@ -342,6 +384,10 @@ export default class Post extends RestModel {
return this.topic.get("postStream.filterRepliesToPostNumber");
}
+ get hasReplies() {
+ return this.reply_count > 0;
+ }
+
get isWhisper() {
return this.post_type === this.site.post_types.whisper;
}
@@ -415,13 +461,9 @@ export default class Post extends RestModel {
}
// Expands the first post's content, if embedded and shortened.
- expand() {
- return ajax(`/posts/${this.id}/expand-embed`).then((post) => {
- this.set(
- "cooked",
- `<section class="expanded-embed">${post.cooked}</section>`
- );
- });
+ async expand() {
+ const post = await ajax(`/posts/${this.id}/expand-embed`);
+ this.cooked = `<section class="expanded-embed">${post.cooked}</section>`;
}
// Recover a deleted post
@@ -674,4 +716,47 @@ export default class Post extends RestModel {
return badgeIds.map((badgeId) => this.topic.user_badges.badges[badgeId]);
}
}
+
+ @cached
+ get badgesGranted() {
+ return this.badges_granted?.map((json) => {
+ const badges = Badge.createFromJson(json);
+ return Array.isArray(badges) ? badges[0] : badges;
+ });
+ }
+
+ get requestedGroupName() {
+ return this.post_number === 1 ? this.topic?.requested_group_name : null;
+ }
+
+ get expandablePost() {
+ return this.post_number === 1 && !!this.topic?.expandable_first_post;
+ }
+
+ get topicUrl() {
+ return this.topic?.url;
+ }
+
+ @cached
+ get actionsSummary() {
+ return this.actions_summary
+ ?.filter((postAction) => {
+ return postAction.actionType.name_key !== "like" && postAction.acted;
+ })
+ ?.map((postAction) => {
+ const action = postAction.actionType.name_key;
+
+ return {
+ id: postAction.id,
+ postId: this.id,
+ action,
+ canUndo: postAction.can_undo,
+ description: i18n(`post.actions.by_you.${action}`, {
+ defaultValue: i18n(`post.actions.by_you.custom`, {
+ custom: postAction.actionType.name,
+ }),
+ }),
+ };
+ });
+ }
}
diff --git a/app/assets/javascripts/discourse/app/models/site.js b/app/assets/javascripts/discourse/app/models/site.js
index a83d90cd274..50b5670f26c 100644
--- a/app/assets/javascripts/discourse/app/models/site.js
+++ b/app/assets/javascripts/discourse/app/models/site.js
@@ -15,6 +15,7 @@ import Category from "discourse/models/category";
import PostActionType from "discourse/models/post-action-type";
import RestModel from "discourse/models/rest";
import TrustLevel from "discourse/models/trust-level";
+import { havePostStreamWidgetExtensions } from "discourse/widgets/post-stream";
@singleton
export default class Site extends RestModel {
@@ -79,6 +80,7 @@ export default class Site extends RestModel {
}
@service siteSettings;
+ @service currentUser;
@tracked categories;
@@ -86,6 +88,7 @@ export default class Site extends RestModel {
@sort("categories", "topicCountDesc") categoriesByCount;
+ #glimmerPostStreamEnabled;
#glimmerTopicDecision;
init() {
@@ -95,6 +98,69 @@ export default class Site extends RestModel {
this.categories = this.categories || [];
}
+ get useGlimmerPostStream() {
+ if (this.#glimmerPostStreamEnabled !== undefined) {
+ // Use cached value after the first call to prevent duplicate messages in the console
+ return this.#glimmerPostStreamEnabled;
+ }
+
+ let enabled;
+
+ /* eslint-disable no-console */
+ let settingValue = this.siteSettings.glimmer_post_stream_mode;
+ if (
+ settingValue === "disabled" &&
+ this.currentUser?.use_glimmer_post_stream_mode_auto_mode
+ ) {
+ settingValue = "auto";
+ }
+
+ if (settingValue === "disabled") {
+ enabled = false;
+ } else {
+ if (settingValue === "enabled") {
+ if (havePostStreamWidgetExtensions) {
+ console.log(
+ [
+ "⚠️ Using the new 'glimmer' post stream, even though some themes/plugins are not ready.\n" +
+ "The following plugins and/or themes are using deprecated APIs and may have broken customizations: \n",
+ ...Array.from(havePostStreamWidgetExtensions).sort(),
+ ].join("\n- ")
+ );
+ } else {
+ if (!isTesting() && !isRailsTesting()) {
+ console.log("✅ Using the new 'glimmer' post stream!");
+ }
+ }
+
+ enabled = true;
+ } else {
+ // auto
+ if (havePostStreamWidgetExtensions) {
+ console.warn(
+ [
+ "⚠️ Detected themes/plugins which are incompatible with the new 'glimmer' post stream. Falling back to the old implementation.\n" +
+ "The following plugins and/or themes are using deprecated APIs: \n",
+ ...Array.from(havePostStreamWidgetExtensions).sort(),
+ ].join("\n- ")
+ );
+ enabled = false;
+ } else {
+ if (!isTesting() && !isRailsTesting()) {
+ console.log("✅ Using the new 'glimmer' post stream!");
+ }
+
+ enabled = true;
+ }
+ }
+ }
+ /* eslint-enable no-console */
+
+ this.#glimmerPostStreamEnabled = enabled;
+
+ return enabled;
+ }
+
get useGlimmerTopicList() {
if (this.#glimmerTopicDecision !== undefined) {
// Caches the decision after the first call, and avoids re-printing the same message
diff --git a/app/assets/javascripts/discourse/app/models/topic-details.js b/app/assets/javascripts/discourse/app/models/topic-details.js
index ec841a55e9b..2b3bc126ba4 100644
--- a/app/assets/javascripts/discourse/app/models/topic-details.js
+++ b/app/assets/javascripts/discourse/app/models/topic-details.js
@@ -16,6 +16,7 @@ export default class TopicDetails extends RestModel {
@tracked can_edit_staff_notes;
@tracked can_permanently_delete;
@tracked can_publish_page;
+ @tracked can_split_merge_topic;
@tracked created_by;
@tracked notification_level;
diff --git a/app/assets/javascripts/discourse/app/models/topic.js b/app/assets/javascripts/discourse/app/models/topic.js
index d8b9d5d1eec..d396188becd 100644
--- a/app/assets/javascripts/discourse/app/models/topic.js
+++ b/app/assets/javascripts/discourse/app/models/topic.js
@@ -1,4 +1,4 @@
-import { cached } from "@glimmer/tracking";
+import { cached, tracked } from "@glimmer/tracking";
import EmberObject, { computed } from "@ember/object";
import { dependentKeyCompat } from "@ember/object/compat";
import { alias, and, equal, notEmpty, or } from "@ember/object/computed";
@@ -178,11 +178,11 @@ export default class Topic extends RestModel {
return promise;
}
- static bulkOperation(topics, operation, options, tracked) {
+ static bulkOperation(topics, operation, options, isTracked) {
const data = {
topic_ids: topics.mapBy("id"),
operation,
- tracked,
+ tracked: isTracked,
};
if (options) {
@@ -197,8 +197,8 @@ export default class Topic extends RestModel {
});
}
- static bulkOperationByFilter(filter, operation, options, tracked) {
- const data = { filter, operation, tracked };
+ static bulkOperationByFilter(filter, operation, options, isTracked) {
+ const data = { filter, operation, tracked: isTracked };
if (options) {
if (options.categoryId) {
@@ -227,14 +227,18 @@ export default class Topic extends RestModel {
}
static resetNew(category, include_subcategories, opts = {}) {
- let { tracked, tag, topicIds } = {
+ let {
+ tracked: isTracked,
+ tag,
+ topicIds,
+ } = {
tracked: false,
tag: null,
topicIds: null,
...opts,
};
- const data = { tracked };
+ const data = { tracked: isTracked };
if (category) {
data.category_id = category.id;
data.include_subcategories = include_subcategories;
@@ -297,6 +301,9 @@ export default class Topic extends RestModel {
@service currentUser;
@service siteSettings;
+ @tracked deleted_by;
+ @tracked deleted_at;
+
message = null;
errorLoading = false;
@@ -314,6 +321,11 @@ export default class Topic extends RestModel {
@and("pinned", "readLastPost") canClearPin;
@or("details.can_edit", "details.can_edit_tags") canEditTags;
+ @tracked _details = this.store.createRecord("topicDetails", {
+ id: this.id,
+ topic: this,
+ });
+
@discourseComputed("last_read_post_number", "highest_post_number")
visited(lastReadPostNumber, highestPostNumber) {
// >= to handle case where there are deleted posts at the end of the topic
@@ -455,10 +467,7 @@ export default class Topic extends RestModel {
}
get details() {
- return (this._details ??= this.store.createRecord("topicDetails", {
- id: this.id,
- topic: this,
- }));
+ return this._details;
}
set details(value) {
diff --git a/app/assets/javascripts/discourse/app/models/user.js b/app/assets/javascripts/discourse/app/models/user.js
index 487ba070f57..d46ec8053ea 100644
--- a/app/assets/javascripts/discourse/app/models/user.js
+++ b/app/assets/javascripts/discourse/app/models/user.js
@@ -1446,7 +1446,7 @@ class UserStatusManager {
}
_statusChanged() {
- this.user.trigger("status-changed");
+ this.user.trigger("status-changed", this.user);
const status = this.user.status;
if (status && status.ends_at) {
@@ -1480,12 +1480,12 @@ class UserStatusManager {
}
_autoClearStatus() {
- this.user.set("status", null);
+ this.user.status = null;
}
_updateStatus(statuses) {
if (statuses.hasOwnProperty(this.user.id)) {
- this.user.set("status", statuses[this.user.id]);
+ this.user.status = statuses[this.user.id];
}
}
}
diff --git a/app/assets/javascripts/discourse/app/services/user-status.js b/app/assets/javascripts/discourse/app/services/user-status.js
index 768db81008d..4de2d9e76c6 100644
--- a/app/assets/javascripts/discourse/app/services/user-status.js
+++ b/app/assets/javascripts/discourse/app/services/user-status.js
@@ -6,6 +6,11 @@ import { disableImplicitInjections } from "discourse/lib/implicit-injections";
@disableImplicitInjections
export default class UserStatusService extends Service {
@service currentUser;
+ @service siteSettings;
+
+ get isEnabled() {
+ return this.siteSettings.enable_user_status;
+ }
async set(status, pauseNotifications) {
await ajax({
diff --git a/app/assets/javascripts/discourse/app/templates/topic.gjs b/app/assets/javascripts/discourse/app/templates/topic.gjs
index f5e8faa8f58..544417a7a03 100644
--- a/app/assets/javascripts/discourse/app/templates/topic.gjs
+++ b/app/assets/javascripts/discourse/app/templates/topic.gjs
@@ -480,6 +480,8 @@ export default RouteTemplate(
@fillGapAfter={{@controller.fillGapAfter}}
@showInvite={{routeAction "showInvite"}}
@showPagePublish={{routeAction "showPagePublish"}}
+ @filteringRepliesToPostNumber={{@controller.replies_to_post_number}}
+ @updateTopicPageQueryParams={{@controller.updateTopicPageQueryParams}}
/>
{{/unless}}
@@ -517,9 +519,9 @@ export default RouteTemplate(
<ReviewableCreatedByName
@user={{@controller.currentUser}}
/>
- <div class="post-body"><CookText
- @rawText={{pending.raw}}
- /></div>
+ <div class="post-body">
+ <CookText @rawText={{pending.raw}} />
+ </div>
</div>
</div>
<div class="reviewable-actions">
diff --git a/app/assets/javascripts/discourse/app/widgets/actions-summary.js b/app/assets/javascripts/discourse/app/widgets/actions-summary.js
index 50e15241435..fe5d934fdea 100644
--- a/app/assets/javascripts/discourse/app/widgets/actions-summary.js
+++ b/app/assets/javascripts/discourse/app/widgets/actions-summary.js
@@ -19,6 +19,5 @@ registerWidgetShim(
registerWidgetShim(
"actions-summary",
"section.post-actions",
- hbs`
- <ActionsSummary @data={{@data}} /> `
+ hbs`<Post::ActionsSummary @post={{@data}} />`
);
diff --git a/app/assets/javascripts/discourse/app/widgets/decorator-helper.js b/app/assets/javascripts/discourse/app/widgets/decorator-helper.js
index e8059feead1..b57409d7018 100644
--- a/app/assets/javascripts/discourse/app/widgets/decorator-helper.js
+++ b/app/assets/javascripts/discourse/app/widgets/decorator-helper.js
@@ -42,6 +42,10 @@ class DecoratorHelper {
return this.widget.attach(name, attrs, state);
}
+ get model() {
+ return this.widget.findAncestorModel();
+ }
+
/**
* Returns the model associated with this widget. When decorating
* posts this will normally be the post.
@@ -54,7 +58,7 @@ class DecoratorHelper {
* ```
**/
getModel() {
- return this.widget.findAncestorModel();
+ return this.model;
}
/**
diff --git a/app/assets/javascripts/discourse/app/widgets/embedded-post.js b/app/assets/javascripts/discourse/app/widgets/embedded-post.js
index 757e9408f93..9fb3c1a233b 100644
--- a/app/assets/javascripts/discourse/app/widgets/embedded-post.js
+++ b/app/assets/javascripts/discourse/app/widgets/embedded-post.js
@@ -4,23 +4,25 @@ import hbs from "discourse/widgets/hbs-compiler";
import PostCooked from "discourse/widgets/post-cooked";
import { createWidget } from "discourse/widgets/widget";
+// glimmer-post-stream: has glimmer version
createWidget("post-link-arrow", {
tagName: "div.post-link-arrow",
template: hbs`
- <a href={{attrs.shareUrl}} class="post-info arrow" title={{i18n "topic.jump_reply"}} aria-label={{i18n
- "topic.jump_reply_aria" username=attrs.name
- }}>
+ <a href={{attrs.shareUrl}} class="post-info arrow" title={{i18n "topic.jump_reply"}} aria-label={{i18n
+ "topic.jump_reply_aria" username=attrs.name
+ }}>
{{#if attrs.above}}
{{d-icon "arrow-up"}}
{{else}}
{{d-icon "arrow-down"}}
{{/if}}
{{i18n "topic.jump_reply_button"}}
- </a>
+ </a>
`,
});
+// glimmer-post-stream: has glimmer version
export default createWidget("embedded-post", {
tagName: "div.reply",
buildKey: (attrs) => `embedded-post-${attrs.id}`,
@@ -57,6 +59,7 @@ export default createWidget("embedded-post", {
},
init() {
+ // TODO (glimmer-post-stream): How does this fit into the Glimmer lifecycle?
this.postContentsDestroyCallbacks = [];
},
diff --git a/app/assets/javascripts/discourse/app/widgets/post-edits-indicator.js b/app/assets/javascripts/discourse/app/widgets/post-edits-indicator.js
index b50ded2ba11..34ab7054656 100644
--- a/app/assets/javascripts/discourse/app/widgets/post-edits-indicator.js
+++ b/app/assets/javascripts/discourse/app/widgets/post-edits-indicator.js
@@ -1,33 +1,9 @@
+import { historyHeat } from "discourse/components/post/meta-data/edits-indicator";
import { longDate } from "discourse/lib/formatter";
import { createWidget } from "discourse/widgets/widget";
import { i18n } from "discourse-i18n";
-function mult(val) {
- return 60 * 50 * 1000 * val;
-}
-
-export function historyHeat(siteSettings, updatedAt) {
- if (!updatedAt) {
- return;
- }
-
- // Show heat on age
- const rightNow = Date.now();
- const updatedAtTime = updatedAt.getTime();
-
- if (updatedAtTime > rightNow - mult(siteSettings.history_hours_low)) {
- return "heatmap-high";
- }
-
- if (updatedAtTime > rightNow - mult(siteSettings.history_hours_medium)) {
- return "heatmap-med";
- }
-
- if (updatedAtTime > rightNow - mult(siteSettings.history_hours_high)) {
- return "heatmap-low";
- }
-}
-
+// glimmer-post-stream: has glimmer version
export default createWidget("post-edits-indicator", {
tagName: "div.post-info.edits",
diff --git a/app/assets/javascripts/discourse/app/widgets/post-placeholder.js b/app/assets/javascripts/discourse/app/widgets/post-placeholder.js
index aa0cdcca190..f66e097ec16 100644
--- a/app/assets/javascripts/discourse/app/widgets/post-placeholder.js
+++ b/app/assets/javascripts/discourse/app/widgets/post-placeholder.js
@@ -1,6 +1,7 @@
import hbs from "discourse/widgets/hbs-compiler";
import { createWidget } from "discourse/widgets/widget";
+// glimmer-post-stream: has glimmer version
export default createWidget("post-placeholder", {
tagName: "article.placeholder",
template: hbs`
diff --git a/app/assets/javascripts/discourse/app/widgets/post-small-action.js b/app/assets/javascripts/discourse/app/widgets/post-small-action.js
index 5e6053fffc5..908adb7c016 100644
--- a/app/assets/javascripts/discourse/app/widgets/post-small-action.js
+++ b/app/assets/javascripts/discourse/app/widgets/post-small-action.js
@@ -1,6 +1,10 @@
import { computed } from "@ember/object";
import { htmlSafe } from "@ember/template";
import { h } from "virtual-dom";
+import {
+ GROUP_ACTION_CODES,
+ ICONS,
+} from "discourse/components/post/small-action";
import { autoUpdatingRelativeAge } from "discourse/lib/formatter";
import { iconNode } from "discourse/lib/icon-library";
import { userPath } from "discourse/lib/url";
@@ -20,7 +24,7 @@ export function actionDescriptionHtml(actionCode, createdAt, username, path) {
let who = "";
if (username) {
- if (groupActionCodes.includes(actionCode)) {
+ if (GROUP_ACTION_CODES.includes(actionCode)) {
who = `<a class="mention-group" href="/g/${username}">@${username}</a>`;
} else {
who = `<a class="mention" href="${userPath(username)}">@${username}</a>`;
@@ -50,41 +54,8 @@ export function actionDescription(
const addPostSmallActionClassesCallbacks = [];
-const groupActionCodes = ["invited_group", "removed_group"];
-
-const icons = {
- "closed.enabled": "lock",
- "closed.disabled": "unlock-keyhole",
- "autoclosed.enabled": "lock",
- "autoclosed.disabled": "unlock-keyhole",
- "archived.enabled": "folder",
- "archived.disabled": "folder-open",
- "pinned.enabled": "thumbtack",
- "pinned.disabled": "thumbtack unpinned",
- "pinned_globally.enabled": "thumbtack",
- "pinned_globally.disabled": "thumbtack unpinned",
- "banner.enabled": "thumbtack",
- "banner.disabled": "thumbtack unpinned",
- "visible.enabled": "far-eye",
- "visible.disabled": "far-eye-slash",
- split_topic: "right-from-bracket",
- invited_user: "circle-plus",
- invited_group: "circle-plus",
- user_left: "circle-minus",
- removed_user: "circle-minus",
- removed_group: "circle-minus",
- public_topic: "comment",
- open_topic: "comment",
- private_topic: "envelope",
- autobumped: "hand-point-right",
-};
-
export function addPostSmallActionIcon(key, icon) {
- icons[key] = icon;
-}
-
-export function addGroupPostSmallActionCode(actionCode) {
- groupActionCodes.push(actionCode);
+ ICONS[key] = icon;
}
export function addPostSmallActionClassesCallback(callback) {
@@ -95,6 +66,7 @@ export function resetPostSmallActionClassesCallbacks() {
addPostSmallActionClassesCallbacks.length = 0;
}
+// glimmer-post-stream: has glimmer version
export default createWidget("post-small-action", {
buildKey: (attrs) => `post-small-act-${attrs.id}`,
tagName: "article.small-action.onscreen-post",
@@ -192,7 +164,7 @@ export default createWidget("post-small-action", {
}
return [
- h("div.topic-avatar", iconNode(icons[attrs.actionCode] || "exclamation")),
+ h("div.topic-avatar", iconNode(ICONS[attrs.actionCode] || "exclamation")),
h("div.small-action-desc", [
h("div.small-action-contents", contents),
h("div.small-action-buttons", buttons),
diff --git a/app/assets/javascripts/discourse/app/widgets/post-stream.js b/app/assets/javascripts/discourse/app/widgets/post-stream.js
index 45101df8143..c8f7ec89fff 100644
--- a/app/assets/javascripts/discourse/app/widgets/post-stream.js
+++ b/app/assets/javascripts/discourse/app/widgets/post-stream.js
@@ -1,10 +1,14 @@
+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";
import { 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 { avatarFor } from "discourse/widgets/post";
@@ -12,6 +16,18 @@ import RenderGlimmer from "discourse/widgets/render-glimmer";
import { createWidget } from "discourse/widgets/widget";
import { i18n } from "discourse-i18n";
+export let havePostStreamWidgetExtensions = null;
+
+registerDeprecationHandler((_, opts) => {
+ if (opts?.id === "discourse.post-stream-widget-overrides") {
+ if (!havePostStreamWidgetExtensions) {
+ havePostStreamWidgetExtensions = new Set();
+ }
+
+ havePostStreamWidgetExtensions.add(consolePrefix().slice(1, -1));
+ }
+});
+
let transformCallbacks = null;
export function postTransformCallbacks(transformed) {
@@ -71,6 +87,7 @@ addWidgetCleanCallback("post-stream", () => {
_heights = {};
});
+// glimmer-post-stream: has glimmer version
createWidget("posts-filtered-notice", {
buildKey: (attrs) => `posts-filtered-notice-${attrs.id}`,
@@ -153,6 +170,7 @@ createWidget("posts-filtered-notice", {
},
});
+// glimmer-post-stream: has glimmer version
createWidget("filter-jump-to-post", {
tagName: "a.filtered-jump-to-post",
buildKey: (attrs) => `jump-to-post-${attrs.id}`,
@@ -169,6 +187,7 @@ createWidget("filter-jump-to-post", {
},
});
+// glimmer-post-stream: has glimmer version
createWidget("filter-show-all", {
tagName: "button.filtered-replies-show-all",
buildKey: (attrs) => `filtered-show-all-${attrs.id}`,
@@ -194,6 +213,8 @@ export default createWidget("post-stream", {
tagName: "div.post-stream",
html(attrs) {
+ getOwner(this).lookup("service:site").useGlimmerPostStream;
+
const posts = attrs.posts || [];
const postArray = posts.toArray();
const postArrayLength = postArray.length;
@@ -211,7 +232,13 @@ export default createWidget("post-stream", {
const post = postArray[i];
if (post instanceof Placeholder) {
- result.push(this.attach("post-placeholder"));
+ this.site.useGlimmerPostStream
+ ? new RenderGlimmer(
+ this,
+ "div.post-placeholder-shim",
+ PostPlaceholder
+ )
+ : result.push(this.attach("post-placeholder"));
continue;
}
@@ -245,11 +272,26 @@ export default createWidget("post-stream", {
const beforeGap = before[post.id];
if (beforeGap) {
result.push(
- this.attach(
- "post-gap",
- { pos: "before", postId: post.id, gap: beforeGap },
- { model: post }
- )
+ 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 }
+ )
);
}
@@ -262,8 +304,7 @@ export default createWidget("post-stream", {
new RenderGlimmer(
this,
"div.time-gap.small-action",
- hbs`
- <TimeGap @daysSince={{@data.daysSince}} />`,
+ hbs`<Post::TimeGap @daysSince={{@data.daysSince}} />`,
{ daysSince }
)
);
@@ -278,25 +319,115 @@ export default createWidget("post-stream", {
if (transformed.isSmallAction) {
result.push(
- this.attach("post-small-action", transformed, { model: post })
+ 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 })
);
} else {
- transformed.showReadIndicator = attrs.showReadIndicator;
- // The following properties will have to be untangled from the transformed model when
- // converting this widget to a Glimmer component:
- // canCreatePost, showReadIndicator, prevPost, nextPost
- result.push(this.attach("post", transformed, { model: post }));
+ 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),
+ 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 }));
+ }
}
// Post gap - after
const afterGap = after[post.id];
if (afterGap) {
result.push(
- this.attach(
- "post-gap",
- { pos: "after", postId: post.id, gap: afterGap },
- { model: post }
- )
+ 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 }
+ )
);
}
@@ -306,9 +437,18 @@ export default createWidget("post-stream", {
attrs.lastReadPostNumber === post.post_number
) {
result.push(
- this.attach("topic-post-visited-line", {
- post_number: post.post_number,
- })
+ 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,
+ })
);
}
@@ -321,11 +461,26 @@ export default createWidget("post-stream", {
(Object.keys(before).length > 0 || Object.keys(after).length > 0)
) {
result.push(
- this.attach("posts-filtered-notice", {
- posts: postArray,
- streamFilters: attrs.streamFilters,
- filteredPostsCount: attrs.filteredPostsCount,
- })
+ 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,
+ })
);
}
diff --git a/app/assets/javascripts/discourse/app/widgets/post.js b/app/assets/javascripts/discourse/app/widgets/post.js
index 23813903507..8339a56db9d 100644
--- a/app/assets/javascripts/discourse/app/widgets/post.js
+++ b/app/assets/javascripts/discourse/app/widgets/post.js
@@ -30,7 +30,9 @@ import widgetHbs from "discourse/widgets/hbs-compiler";
import PostCooked from "discourse/widgets/post-cooked";
import { postTransformCallbacks } from "discourse/widgets/post-stream";
import RawHtml from "discourse/widgets/raw-html";
-import RenderGlimmer from "discourse/widgets/render-glimmer";
+import RenderGlimmer, {
+ registerWidgetShim,
+} from "discourse/widgets/render-glimmer";
import { applyDecorators, createWidget } from "discourse/widgets/widget";
import { i18n } from "discourse-i18n";
@@ -96,6 +98,7 @@ export function avatarImg(wanted, attrs) {
return h("img", properties);
}
+// glimmer-post-stream: has glimmer version
export function avatarFor(wanted, attrs, linkAttrs) {
const attributes = {
href: attrs.url,
@@ -126,6 +129,7 @@ export function avatarFor(wanted, attrs, linkAttrs) {
);
}
+// glimmer-post-stream: has glimmer version
createWidget("select-post", {
tagName: "div.select-posts",
@@ -169,6 +173,7 @@ createWidget("select-post", {
},
});
+// glimmer-post-stream: has glimmer version
createWidget("reply-to-tab", {
tagName: "a.reply-to-tab",
buildKey: (attrs) => `reply-to-tab-${attrs.id}`,
@@ -282,12 +287,14 @@ createWidget("post-avatar", {
},
});
+// glimmer-post-stream: has glimmer version
createWidget("post-locked-indicator", {
tagName: "div.post-info.post-locked",
template: widgetHbs`{{d-icon "lock"}}`,
title: () => i18n("post.locked"),
});
+// glimmer-post-stream: has glimmer version
createWidget("post-email-indicator", {
tagName: "div.post-info.via-email",
@@ -321,6 +328,7 @@ function showReplyTab(attrs, siteSettings) {
);
}
+// glimmer-post-stream: has glimmer version
createWidget("post-meta-data", {
tagName: "div.topic-meta-data",
@@ -406,6 +414,7 @@ createWidget("post-meta-data", {
},
});
+// glimmer-post-stream: has glimmer version
createWidget("expand-hidden", {
tagName: "a.expand-hidden",
@@ -418,6 +427,7 @@ createWidget("expand-hidden", {
},
});
+// glimmer-post-stream: has glimmer version
createWidget("post-date", {
tagName: "div.post-info.post-date",
@@ -452,6 +462,7 @@ createWidget("post-date", {
},
});
+// glimmer-post-stream: has glimmer version
createWidget("expand-post-button", {
tagName: "button.btn.expand-post",
buildKey: (attrs) => `expand-post-button-${attrs.id}`,
@@ -474,6 +485,7 @@ createWidget("expand-post-button", {
},
});
+// glimmer-post-stream: has glimmer version
createWidget("post-group-request", {
buildKey: (attrs) => `post-group-request-${attrs.id}`,
@@ -490,6 +502,7 @@ createWidget("post-group-request", {
},
});
+// glimmer-post-stream: has glimmer version
createWidget("post-contents", {
buildKey: (attrs) => `post-contents-${attrs.id}`,
@@ -593,6 +606,7 @@ createWidget("post-contents", {
copyLink: () => this.sendWidgetAction("copyLink"),
deletePost: () => this.sendWidgetAction("deletePost"), // this action comes from the post stream
editPost: () => this.sendWidgetAction("editPost"), // this action comes from the post stream
+ expandHidden: () => this.sendWidgetAction("editPost"), // this action comes from the post stream
grantBadge: () => this.sendWidgetAction("grantBadge"), // this action comes from the post stream
lockPost: () => this.sendWidgetAction("lockPost"), // this action comes from the post stream
permanentlyDeletePost: () =>
@@ -786,6 +800,7 @@ createWidget("post-contents", {
},
init() {
+ // TODO (glimmer-post-stream): How does this fit into the Glimmer lifecycle?
this.postContentsDestroyCallbacks = [];
},
@@ -794,6 +809,7 @@ createWidget("post-contents", {
},
});
+// glimmer-post-stream: has glimmer version
createWidget("post-notice", {
tagName: "div.post-notice",
@@ -860,6 +876,7 @@ createWidget("post-notice", {
},
});
+// glimmer-post-stream: has glimmer version
createWidget("post-body", {
tagName: "div.topic-body.clearfix",
@@ -877,6 +894,7 @@ createWidget("post-body", {
},
});
+// glimmer-post-stream: has glimmer version
createWidget("post-article", {
tagName: "article.boxed.onscreen-post",
buildKey: (attrs) => `post-article-${attrs.id}`,
@@ -1061,13 +1079,18 @@ createWidget("post-article", {
},
});
-let addPostClassesCallbacks = null;
+const addPostClassesCallbacks = [];
export function addPostClassesCallback(callback) {
- addPostClassesCallbacks = addPostClassesCallbacks || [];
addPostClassesCallbacks.push(callback);
}
+// only for testing purposes
+export function resetPostClassesCallback() {
+ addPostClassesCallbacks.length = 0;
+}
+
+// glimmer-post-stream: has glimmer version
export default createWidget("post", {
buildKey: (attrs) => `post-${attrs.id}`,
services: ["dialog", "user-tips"],
@@ -1180,3 +1203,48 @@ export default createWidget("post", {
}
},
});
+
+// TODO (glimmer-post-menu): Once this widget is removed the `<section>...</section>` tag needs to be added to the PostMenu component
+registerWidgetShim(
+ "glimmer-post",
+ "div",
+ hbs`
+ <Post
+ @canCreatePost={{@data.canCreatePost}}
+ @cancelFilter={{@data.cancelFilter}}
+ @changeNotice={{@data.changeNotice}}
+ @changePostOwner={{@data.changePostOwner}}
+ @deletePost={{@data.deletePost}}
+ @editPost={{@data.editPost}}
+ @expandHidden={{@expandHidden}}
+ @filteringRepliesToPostNumber={{@data.filteringRepliesToPostNumber}}
+ @grantBadge={{@data.grantBadge}}
+ @lockPost={{@data.lockPost}}
+ @multiSelect={{@data.multiSelect}}
+ @nextPost={{@data.nextPost}}
+ @permanentlyDeletePost={{@data.permanentlyDeletePost}}
+ @post={{@data.post}}
+ @prevPost={{@data.prevPost}}
+ @rebakePost={{@data.rebakePost}}
+ @recoverPost={{@data.recoverPost}}
+ @replyToPost={{@data.replyToPost}}
+ @selectBelow={{@data.selectBelow}}
+ @selectReplies={{@data.selectReplies}}
+ @selected={{@data.selected}}
+ @showFlags={{@data.showFlags}}
+ @showHistory={{@data.showHistory}}
+ @showInvite={{@data.showInvite}}
+ @showLogin={{@data.showLogin}}
+ @showPagePublish={{@data.showPagePublish}}
+ @showRawEmail={{@data.showRawEmail}}
+ @showReadIndicator={{@data.showReadIndicator}}
+ @togglePostSelection={{@data.togglePostSelection}}
+ @togglePostType={{@data.togglePostType}}
+ @toggleReplies={{@toggleReplies}}
+ @toggleReplyAbove={{@data.toggleReplyAbove}}
+ @toggleWiki={{@data.toggleWiki}}
+ @unhidePost={{@data.unhidePost}}
+ @unlockPost={{@data.unlockPost}}
+ @updateTopicPageQueryParams={{@data.updateTopicPageQueryParams}}
+ />`
+);
diff --git a/app/assets/javascripts/discourse/app/widgets/poster-name.js b/app/assets/javascripts/discourse/app/widgets/poster-name.js
index 99e4cd7eaf6..16ab4076f37 100644
--- a/app/assets/javascripts/discourse/app/widgets/poster-name.js
+++ b/app/assets/javascripts/discourse/app/widgets/poster-name.js
@@ -16,6 +16,7 @@ export function disableNameSuppression() {
sanitizeName = (name) => name;
}
+// glimmer-post-stream: has glimmer version
createWidget("poster-name-title", {
tagName: "span.user-title",
@@ -53,6 +54,7 @@ createWidget("poster-name-title", {
},
});
+// glimmer-post-stream: has glimmer version
export default createWidget("poster-name", {
tagName: "div.names.trigger-user-card",
diff --git a/app/assets/javascripts/discourse/app/widgets/widget.js b/app/assets/javascripts/discourse/app/widgets/widget.js
index 26f4ea04af4..0860f11451b 100644
--- a/app/assets/javascripts/discourse/app/widgets/widget.js
+++ b/app/assets/javascripts/discourse/app/widgets/widget.js
@@ -85,6 +85,7 @@ export function resetDecorators() {
}
const _customSettings = {};
+
export function changeSetting(widgetName, settingName, newValue) {
_customSettings[widgetName] = _customSettings[widgetName] || {};
_customSettings[widgetName][settingName] = newValue;
@@ -186,6 +187,7 @@ export default class Widget {
}
init() {}
+
transform() {
return {};
}
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.js
index 2ddde147ce8..0812f40812a 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
@@ -3,45 +3,55 @@ import { test } from "qunit";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
import { i18n } from "discourse-i18n";
-acceptance("Composer - Draft saving", function (needs) {
- needs.user();
-
- const draftThatWillBeSaved = "This_will_be_saved_successfully";
-
- needs.pretender((server, helper) => {
- server.post("/drafts.json", (request) => {
- const success = request.requestBody.includes(draftThatWillBeSaved);
- return success
- ? helper.response({ success: true })
- : helper.response(500, {});
- });
- });
-
- 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 fillIn(".d-editor-input", draftThatWillBeSaved);
-
- assert
- .dom("div#draft-status span")
- .doesNotExist("the draft was saved, there's no warning");
-
- await fillIn(".d-editor-input", "This won't be saved because of error");
- assert
- .dom("div#draft-status span")
- .hasText(
- i18n("composer.drafts_offline"),
- "the draft wasn't saved, a warning is rendered"
- );
- assert
- .dom("div#draft-status svg.d-icon-triangle-exclamation")
- .exists("an exclamation icon is rendered");
-
- await fillIn(".d-editor-input", draftThatWillBeSaved);
- assert
- .dom("div#draft-status span")
- .doesNotExist("the draft was saved again, the warning has disappeared");
- });
+["enabled", "disabled"].forEach((postStreamMode) => {
+ acceptance(
+ `Composer - Draft saving (glimmer_post_stream_mode = ${postStreamMode})`,
+ function (needs) {
+ needs.settings({
+ glimmer_post_stream_mode: postStreamMode,
+ });
+ needs.user();
+
+ const draftThatWillBeSaved = "This_will_be_saved_successfully";
+
+ needs.pretender((server, helper) => {
+ server.post("/drafts.json", (request) => {
+ const success = request.requestBody.includes(draftThatWillBeSaved);
+ return success
+ ? helper.response({ success: true })
+ : helper.response(500, {});
+ });
+ });
+
+ 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 fillIn(".d-editor-input", draftThatWillBeSaved);
+
+ assert
+ .dom("div#draft-status span")
+ .doesNotExist("the draft was saved, there's no warning");
+
+ await fillIn(".d-editor-input", "This won't be saved because of error");
+ assert
+ .dom("div#draft-status span")
+ .hasText(
+ i18n("composer.drafts_offline"),
+ "the draft wasn't saved, a warning is rendered"
+ );
+ assert
+ .dom("div#draft-status svg.d-icon-triangle-exclamation")
+ .exists("an exclamation icon is rendered");
+
+ await fillIn(".d-editor-input", draftThatWillBeSaved);
+ assert
+ .dom("div#draft-status span")
+ .doesNotExist(
+ "the draft was saved again, the warning has disappeared"
+ );
+ });
+ }
+ );
});
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.js
index 25da810b54f..72fcfd63d7d 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
@@ -2,35 +2,44 @@ import { click, fillIn, visit } from "@ember/test-helpers";
import { test } from "qunit";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
-acceptance("Composer - Edit conflict", function (needs) {
- needs.user();
+["enabled", "disabled"].forEach((postStreamMode) => {
+ acceptance(
+ `Composer - Edit conflict (glimmer_post_stream_mode = ${postStreamMode})`,
+ function (needs) {
+ needs.settings({
+ glimmer_post_stream_mode: postStreamMode,
+ });
- let lastBody;
- needs.pretender((server, helper) => {
- server.post("/drafts.json", (request) => {
- lastBody = request.requestBody;
- return helper.response({ success: true });
- });
- });
+ needs.user();
- 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 fillIn(
- ".d-editor-input",
- "hello world hello world hello world hello world hello world"
- );
- assert.false(lastBody.includes("original_text"));
- });
+ let lastBody;
+ needs.pretender((server, helper) => {
+ server.post("/drafts.json", (request) => {
+ lastBody = request.requestBody;
+ return helper.response({ success: true });
+ });
+ });
- 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 fillIn(
- ".d-editor-input",
- "hello world hello world hello world hello world hello world"
- );
- assert.true(lastBody.includes("original_text"));
- });
+ 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 fillIn(
+ ".d-editor-input",
+ "hello world hello world hello world hello world hello world"
+ );
+ assert.false(lastBody.includes("original_text"));
+ });
+
+ 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 fillIn(
+ ".d-editor-input",
+ "hello world hello world hello world hello world hello world"
+ );
+ assert.true(lastBody.includes("original_text"));
+ });
+ }
+ );
});
diff --git a/app/assets/javascripts/discourse/tests/acceptance/composer-hyperlink-test.js b/app/assets/javascripts/discourse/tests/acceptance/composer-hyperlink-test.js
index aff9f21b8c9..6c629d23b0a 100644
--- a/app/assets/javascripts/discourse/tests/acceptance/composer-hyperlink-test.js
+++ b/app/assets/javascripts/discourse/tests/acceptance/composer-hyperlink-test.js
@@ -2,105 +2,119 @@ import { click, fillIn, triggerKeyEvent, visit } from "@ember/test-helpers";
import { test } from "qunit";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
-acceptance("Composer - Hyperlink", function (needs) {
- needs.user();
-
- 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 fillIn(".d-editor-input", "This is a link to ");
-
- assert
- .dom(".insert-link.d-modal__body")
- .doesNotExist("no hyperlink modal by default");
-
- await click(".d-editor button.link");
- assert.dom(".insert-link.d-modal__body").exists("hyperlink modal visible");
-
- await fillIn(".d-modal__body .link-url", "google.com");
- await fillIn(".d-modal__body .link-text", "Google");
- await click(".d-modal__footer button.btn-primary");
-
- assert
- .dom(".d-editor-input")
- .hasValue(
- "This is a link to [Google](https://google.com)",
- "adds link with url and text, prepends 'https://'"
- );
-
- assert
- .dom(".insert-link.d-modal__body")
- .doesNotExist("modal dismissed after submitting link");
-
- await fillIn(".d-editor-input", "Reset textarea contents.");
-
- await click(".d-editor button.link");
- await fillIn(".d-modal__body .link-url", "google.com");
- await fillIn(".d-modal__body .link-text", "Google");
- await click(".d-modal__footer button.btn-danger");
-
- assert
- .dom(".d-editor-input")
- .hasValue(
- "Reset textarea contents.",
- "doesn’t insert anything after cancelling"
- );
-
- assert
- .dom(".insert-link.d-modal__body")
- .doesNotExist("modal dismissed after cancelling");
-
- const textarea = document.querySelector("#reply-control .d-editor-input");
- textarea.selectionStart = 0;
- textarea.selectionEnd = 6;
- await click(".d-editor button.link");
-
- await fillIn(".d-modal__body .link-url", "somelink.com");
- await click(".d-modal__footer button.btn-primary");
-
- assert
- .dom(".d-editor-input")
- .hasValue(
- "[Reset](https://somelink.com) textarea contents.",
- "adds link to a selected text"
- );
-
- await fillIn(".d-editor-input", "");
-
- await click(".d-editor button.link");
- await fillIn(".d-modal__body .link-url", "http://google.com");
- await triggerKeyEvent(".d-modal__body .link-url", "keyup", "Space");
- assert
- .dom(".internal-link-results")
- .doesNotExist(
- "does not show internal links search dropdown when inputting a url"
- );
-
- await fillIn(".d-modal__body .link-url", "local");
- await triggerKeyEvent(".d-modal__body .link-url", "keyup", "Space");
- assert
- .dom(".internal-link-results")
- .exists("shows internal links search dropdown when entering keywords");
-
- await triggerKeyEvent(".insert-link", "keydown", "ArrowDown");
- await triggerKeyEvent(".insert-link", "keydown", "Enter");
-
- assert
- .dom(".internal-link-results")
- .doesNotExist(
- "search dropdown dismissed after selecting an internal link"
- );
-
- assert
- .dom(".link-url")
- .hasValue(/http/, "replaces link url field with internal link");
-
- await triggerKeyEvent(".insert-link", "keydown", "Escape");
-
- assert
- .dom(".d-editor-input")
- .isFocused(
- "focus stays on composer after dismissing modal using Esc key"
- );
- });
+["enabled", "disabled"].forEach((postStreamMode) => {
+ acceptance(
+ `Composer - Hyperlink (glimmer_post_stream_mode = ${postStreamMode})`,
+ function (needs) {
+ needs.settings({
+ glimmer_post_stream_mode: postStreamMode,
+ });
+ needs.user();
+
+ 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 fillIn(".d-editor-input", "This is a link to ");
+
+ assert
+ .dom(".insert-link.d-modal__body")
+ .doesNotExist("no hyperlink modal by default");
+
+ await click(".d-editor button.link");
+ assert
+ .dom(".insert-link.d-modal__body")
+ .exists("hyperlink modal visible");
+
+ await fillIn(".d-modal__body .link-url", "google.com");
+ await fillIn(".d-modal__body .link-text", "Google");
+ await click(".d-modal__footer button.btn-primary");
+
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ "This is a link to [Google](https://google.com)",
+ "adds link with url and text, prepends 'https://'"
+ );
+
+ assert
+ .dom(".insert-link.d-modal__body")
+ .doesNotExist("modal dismissed after submitting link");
+
+ await fillIn(".d-editor-input", "Reset textarea contents.");
+
+ await click(".d-editor button.link");
+ await fillIn(".d-modal__body .link-url", "google.com");
+ await fillIn(".d-modal__body .link-text", "Google");
+ await click(".d-modal__footer button.btn-danger");
+
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ "Reset textarea contents.",
+ "doesn’t insert anything after cancelling"
+ );
+
+ assert
+ .dom(".insert-link.d-modal__body")
+ .doesNotExist("modal dismissed after cancelling");
+
+ const textarea = document.querySelector(
+ "#reply-control .d-editor-input"
+ );
+ textarea.selectionStart = 0;
+ textarea.selectionEnd = 6;
+ await click(".d-editor button.link");
+
+ await fillIn(".d-modal__body .link-url", "somelink.com");
+ await click(".d-modal__footer button.btn-primary");
+
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ "[Reset](https://somelink.com) textarea contents.",
+ "adds link to a selected text"
+ );
+
+ await fillIn(".d-editor-input", "");
+
+ await click(".d-editor button.link");
+ await fillIn(".d-modal__body .link-url", "http://google.com");
+ await triggerKeyEvent(".d-modal__body .link-url", "keyup", "Space");
+ assert
+ .dom(".internal-link-results")
+ .doesNotExist(
+ "does not show internal links search dropdown when inputting a url"
+ );
+
+ await fillIn(".d-modal__body .link-url", "local");
+ await triggerKeyEvent(".d-modal__body .link-url", "keyup", "Space");
+ assert
+ .dom(".internal-link-results")
+ .exists(
+ "shows internal links search dropdown when entering keywords"
+ );
+
+ await triggerKeyEvent(".insert-link", "keydown", "ArrowDown");
+ await triggerKeyEvent(".insert-link", "keydown", "Enter");
+
+ assert
+ .dom(".internal-link-results")
+ .doesNotExist(
+ "search dropdown dismissed after selecting an internal link"
+ );
+
+ assert
+ .dom(".link-url")
+ .hasValue(/http/, "replaces link url field with internal link");
+
+ await triggerKeyEvent(".insert-link", "keydown", "Escape");
+
+ assert
+ .dom(".d-editor-input")
+ .isFocused(
+ "focus stays on composer after dismissing modal using Esc key"
+ );
+ });
+ }
+ );
});
diff --git a/app/assets/javascripts/discourse/tests/acceptance/composer-test.js b/app/assets/javascripts/discourse/tests/acceptance/composer-test.js
index e17128adcbd..c036e67c974 100644
--- a/app/assets/javascripts/discourse/tests/acceptance/composer-test.js
+++ b/app/assets/javascripts/discourse/tests/acceptance/composer-test.js
@@ -27,1402 +27,1489 @@ import {
import selectKit from "discourse/tests/helpers/select-kit-helper";
import { i18n } from "discourse-i18n";
-acceptance("Composer", function (needs) {
- needs.user({
- id: 5,
- username: "kris",
- whisperer: true,
- });
- needs.settings({
- general_category_id: 1,
- default_composer_category: 1,
- });
- needs.site({
- can_tag_topics: true,
- categories: [
- {
- id: 1,
- name: "General",
- slug: "general",
- permission: 1,
- topic_template: null,
- },
- {
- id: 2,
- name: "test too",
- slug: "test-too",
- permission: 1,
- topic_template: "",
- },
- ],
- });
- needs.pretender((server, helper) => {
- server.put("/u/kris.json", () => helper.response({ user: {} }));
- server.post("/uploads/lookup-urls", () => {
- return helper.response([]);
- });
- server.get("/posts/419", () => {
- return helper.response({ id: 419 });
- });
- server.get("/composer/mentions", () => {
- return helper.response({
- users: [],
- user_reasons: {},
- groups: { staff: { user_count: 30 } },
- group_reasons: {},
- max_users_notified_per_group_mention: 100,
- });
- });
- server.get("/t/960.json", () => {
- const topicList = cloneJSON(TopicFixtures["/t/9/1.json"]);
- topicList.post_stream.posts[2].post_type = 4;
- return helper.response(topicList);
- });
- });
-
- test("Composer is opened", async function (assert) {
- await visit("/");
- await click("#create-topic");
- // Check that the default category is selected
- assert.strictEqual(selectKit(".category-chooser").header().value(), "1");
-
- assert.strictEqual(
- document.documentElement.style.getPropertyValue("--composer-height"),
- "var(--new-topic-composer-height, 400px)",
- "sets --composer-height to 400px when creating topic"
- );
-
- await fillIn(
- ".d-editor-input",
- "this is the *content* of a new topic post"
- );
- await click(".toggle-minimize");
- assert.strictEqual(
- document.documentElement.style.getPropertyValue("--composer-height"),
- "40px",
- "sets --composer-height to 40px when composer is minimized to draft mode"
- );
-
- await click(".toggle-fullscreen");
- assert.strictEqual(
- document.documentElement.style.getPropertyValue("--composer-height"),
- "var(--new-topic-composer-height, 400px)",
- "sets --composer-height back to 400px when composer is opened from draft mode"
- );
-
- await fillIn(".d-editor-input", "");
- await click(".toggle-minimize");
- assert.strictEqual(
- document.documentElement.style.getPropertyValue("--composer-height"),
- "",
- "removes --composer-height property when composer is closed"
- );
- });
-
- test("Composer height adjustment", async function (assert) {
- await visit("/");
- await click("#create-topic");
- await triggerEvent(".grippie", "mousedown");
- await triggerEvent(".grippie", "mousemove");
- await triggerEvent(".grippie", "mouseup");
- await visit("/"); // reload page
- await click("#create-topic");
-
- const expectedHeight = localStorage.getItem(
- "__test_discourse_composerHeight"
- );
- const actualHeight =
- document.documentElement.style.getPropertyValue("--composer-height");
-
- assert.strictEqual(
- expectedHeight,
- actualHeight,
- "Updated height is persistent"
- );
- });
-
- test("composer controls", async function (assert) {
- await visit("/");
- assert.dom("#create-topic").exists("the create button is visible");
-
- await click("#create-topic");
- assert.dom(".d-editor-input").exists("the composer input is visible");
- await focus(".title-input input");
- assert
- .dom(".title-input .popup-tip.good.hide")
- .exists("title errors are hidden by default");
- assert
- .dom(".d-editor-textarea-wrapper .popup-tip.bad.hide")
- .exists("body errors are hidden by default");
-
- await click(".toggle-preview");
- assert
- .dom(".d-editor-preview")
- .isNotVisible("clicking the toggle hides the preview");
-
- await click(".toggle-preview");
- assert
- .dom(".d-editor-preview")
- .isVisible("clicking the toggle shows the preview again");
-
- await click("#reply-control button.create");
- assert
- .dom(".title-input .popup-tip.bad")
- .exists("shows the empty title error");
- assert
- .dom(".d-editor-textarea-wrapper .popup-tip.bad")
- .exists("shows the empty body error");
-
- await fillIn("#reply-title", "this is my new topic title");
- assert
- .dom(".title-input .popup-tip.good.hide")
- .exists("the title is now good");
-
- await triggerKeyEvent(
- ".d-editor-textarea-wrapper .popup-tip.bad",
- "keydown",
- "Enter"
- );
- assert
- .dom(".d-editor-textarea-wrapper .popup-tip.bad.hide")
- .exists("body error is dismissed via keyboard");
-
- await fillIn(".d-editor-input", "this is the *content* of a post");
- assert
- .dom(".d-editor-preview")
- .hasHtml(
- "<p>this is the <em>content</em> of a post</p>",
- "previews content"
- );
- assert
- .dom(".d-editor-textarea-wrapper .popup-tip.good")
- .exists("the body is now good");
-
- const textarea = find("#reply-control .d-editor-input");
- textarea.selectionStart = textarea.value.length;
- textarea.selectionEnd = textarea.value.length;
-
- await triggerKeyEvent(textarea, "keydown", "B", metaModifier);
-
- assert
- .dom("#reply-control .d-editor-input")
- .hasValue(
- `this is the *content* of a post**${i18n("composer.bold_text")}**`,
- "supports keyboard shortcuts"
- );
-
- await click("#reply-control button.cancel");
- assert.dom(".d-modal").exists("pops up a confirmation dialog");
-
- await click(".d-modal__footer .discard-draft");
- assert
- .dom(".d-modal__body")
- .doesNotExist("the confirmation can be cancelled");
- });
-
- test("Create a topic with server side errors", async function (assert) {
- pretender.post("/posts", function () {
- return response(422, { errors: ["That title has already been taken"] });
- });
-
- await visit("/");
- await click("#create-topic");
- await fillIn("#reply-title", "this title triggers an error");
- await fillIn(".d-editor-input", "this is the *content* of a post");
- await click("#reply-control button.create");
- assert.dom(".dialog-body").exists("pops up an error message");
-
- await click(".dialog-footer .btn-primary");
- assert.dom(".dialog-body").doesNotExist("dismisses the error");
- assert.dom(".d-editor-input").exists("the composer input is visible");
- });
-
- test("Create a Topic", async function (assert) {
- await visit("/");
- await click("#create-topic");
- await fillIn("#reply-title", "Internationalization Localization");
- await fillIn(
- ".d-editor-input",
- "this is the *content* of a new topic post"
- );
- await click("#reply-control button.create");
- assert.strictEqual(
- currentURL(),
- "/t/internationalization-localization/280",
- "transitions to the newly created topic URL"
- );
- });
-
- test("Create an enqueued Topic", async function (assert) {
- pretender.post("/posts", function () {
- return response(200, {
- success: true,
- action: "enqueued",
- pending_post: {
- id: 1234,
- raw: "enqueue this content please",
- },
- });
- });
-
- await visit("/");
- await click("#create-topic");
- await fillIn("#reply-title", "Internationalization Localization");
- await fillIn(".d-editor-input", "enqueue this content please");
- await click("#reply-control button.create");
- assert.dom(".d-modal").exists("pops up a modal");
- assert.strictEqual(currentURL(), "/", "doesn't change routes");
-
- await click(".d-modal__footer button");
- assert.dom(".d-modal").doesNotExist("the modal can be dismissed");
- });
-
- test("Can display a message and route to a URL", async function (assert) {
- await visit("/");
- await click("#create-topic");
- await fillIn("#reply-title", "This title doesn't matter");
- await fillIn(".d-editor-input", "custom message that is a good length");
- await click("#reply-control button.create");
-
- assert
- .dom("#dialog-holder .dialog-body")
- .hasText("This is a custom response");
- assert.strictEqual(currentURL(), "/", "doesn't change routes");
-
- await click(".dialog-footer .btn-primary");
- assert.strictEqual(
- currentURL(),
- "/faq",
- "can navigate to a `route_to` destination"
- );
- });
-
- test("Create a Reply", async function (assert) {
- await visit("/t/internationalization-localization/280");
-
- assert
- .dom('article[data-post-id="12345"]')
- .doesNotExist("the post is not in the DOM");
-
- await click("#topic-footer-buttons .btn.create");
- assert.dom(".d-editor-input").exists("the composer input is visible");
- assert
- .dom("#reply-title")
- .doesNotExist("there is no title since this is a reply");
-
- 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")
- .hasText("this is the content of my reply");
- });
-
- test("Replying to the first post in a topic is a topic reply", async function (assert) {
- await visit("/t/internationalization-localization/280");
-
- await click("#post_1 .reply.create");
- assert
- .dom(".reply-details a.topic-link")
- .hasText("Internationalization / localization");
-
- await click("#post_1 .reply.create");
- assert
- .dom(".reply-details a.topic-link")
- .hasText("Internationalization / localization");
- });
-
- test("Can edit a post after starting a reply", async function (assert) {
- await visit("/t/internationalization-localization/280");
-
- 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(".d-modal__footer button.keep-editing");
- assert.dom(".discard-draft-modal.modal").doesNotExist();
- assert
- .dom(".d-editor-input")
- .hasValue(
- "this is the content of my reply",
- "composer does not switch when using Keep Editing button"
- );
-
- await click(".topic-post:nth-of-type(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();
-
- assert
- .dom(".d-editor-input")
- .hasValue(
- find(".topic-post:nth-of-type(1) .cooked > p").innerText,
- "composer has contents of post to be edited"
- );
- });
-
- test("Can Keep Editing when replying on a different topic", async function (assert) {
- await visit("/t/internationalization-localization/280");
-
- await click("#topic-footer-buttons .create");
- await fillIn(".d-editor-input", "this is the content of my reply");
-
- await visit("/t/this-is-a-test-topic/9");
- await click("#topic-footer-buttons .create");
- assert.dom(".discard-draft-modal.modal").exists();
-
- await click(".d-modal__footer button.keep-editing");
- assert.dom(".discard-draft-modal.modal").doesNotExist();
-
- assert
- .dom(".d-editor-input")
- .hasValue(
- "this is the content of my reply",
- "composer does not switch when using Keep Editing button"
- );
- });
-
- test("Posting on a different topic", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click("#topic-footer-buttons .btn.create");
- await fillIn(
- ".d-editor-input",
- "this is the content for a different topic"
- );
- await visit("/t/1-3-0beta9-no-rate-limit-popups/28830");
-
- assert.strictEqual(
- currentURL(),
- "/t/1-3-0beta9-no-rate-limit-popups/28830"
- );
-
- await click("#reply-control button.create");
-
- assert.dom(".reply-where-modal").exists("pops up a modal");
- assert
- .dom(".topic-title")
- .exists({ count: 2 }, "it renders the two topics");
- assert
- .dom(".btn-reply-where:nth-of-type(1) .badge-category__name")
- .hasText("test too", "it renders the category name");
- assert
- .dom(".btn-reply-where:nth-of-type(2) .discourse-tags")
- .hasText("foo", "it renders the tags");
-
- await click(".btn-reply-here");
-
- assert
- .dom(".topic-post:last-of-type .cooked p")
- .hasText(
- "If you use gettext format you could leverage Launchpad translations and the community behind it."
- );
- });
-
- test("Discard draft modal works when switching topics", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click("#topic-footer-buttons .btn.create");
- await fillIn(".d-editor-input", "this is the content of the first reply");
-
- await visit("/t/this-is-a-test-topic/9");
- assert.true(
- currentURL().startsWith("/t/this-is-a-test-topic/9"),
- "moves to second topic"
- );
- await click("#topic-footer-buttons .btn.create");
- assert
- .dom(".discard-draft-modal.modal")
- .exists("pops up the discard drafts modal");
-
- await click(".d-modal__footer button.keep-editing");
-
- assert.dom(".discard-draft-modal.modal").doesNotExist("hides modal");
- await click("#topic-footer-buttons .btn.create");
- assert.dom(".discard-draft-modal.modal").exists("pops up the modal again");
-
- await click(".d-modal__footer button.discard-draft");
-
- assert
- .dom(".d-editor-input")
- .hasNoValue("discards draft and reset composer textarea");
- });
-
- test("Create an enqueued Reply", async function (assert) {
- pretender.post("/posts", function () {
- return response(200, {
- success: true,
- action: "enqueued",
- pending_post: {
- id: 1234,
- raw: "enqueue this content please",
- },
- });
- });
-
- await visit("/t/internationalization-localization/280");
- assert.dom(".pending-posts .reviewable-item").doesNotExist();
-
- await click("#topic-footer-buttons .btn.create");
- assert.dom(".d-editor-input").exists("the composer input is visible");
- assert
- .dom("#reply-title")
- .doesNotExist("there is no title since this is a reply");
-
- await fillIn(".d-editor-input", "enqueue this content please");
- await click("#reply-control button.create");
- assert
- .dom(".topic-post:last-of-type .cooked p")
- .doesNotIncludeText(
- "enqueue this content please",
- "doesn't insert the post"
- );
- assert.dom(".d-modal").exists("pops up a modal");
-
- await click(".d-modal__footer button");
- assert.dom(".d-modal").doesNotExist("the modal can be dismissed");
- assert.dom(".pending-posts .reviewable-item").exists();
- });
-
- test("Edit the first post", async function (assert) {
- await visit("/t/internationalization-localization/280");
-
- assert
- .dom(".topic-post:nth-of-type(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");
- assert
- .dom(".d-editor-input")
- .hasValue(
- /^Any plans to support/,
- "populates the input with the post text"
- );
-
- await fillIn(".d-editor-input", "This is the new text for the post");
- await fillIn("#reply-title", "This is the new text for the title");
- 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")
- .exists("has the edits icon");
- assert
- .dom("#topic-title h1")
- .includesText(
- "This is the new text for the title",
- "shows the new title"
- );
- assert
- .dom(".topic-post:nth-of-type(1) .cooked")
- .includesText("This is the new text for the post", "updates the post");
- });
-
- test("Editing a post stages new content", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click(".topic-post button.show-more-actions");
- await click(".topic-post button.edit");
-
- await fillIn(".d-editor-input", "will return empty json");
- await fillIn("#reply-title", "This is the new text for the title");
-
- 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");
- assert
- .dom(".topic-post.staged .cooked")
- .hasText("will return empty json");
-
- return response(200, {});
- });
-
- await click("#reply-control button.create");
-
- await visit("/t/internationalization-localization/280");
- assert.dom(".topic-post.staged").doesNotExist();
- });
-
- 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");
- 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");
- assert
- .dom(".d-editor-input")
- .hasValue(
- /^This is the second post\./,
- "populates the input with the post text"
- );
- });
-
- 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 fillIn(".d-editor-input", "This is a dirty reply");
- await click(".topic-post:nth-of-type(2) button.edit");
- assert
- .dom(".discard-draft-modal.modal")
- .exists("pops up a confirmation dialog");
-
- await click(".d-modal__footer button.discard-draft");
- assert
- .dom(".d-editor-input")
- .hasValue(
- /^This is the second post\./,
- "populates the input with the post text"
- );
- });
-
- 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");
- 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(1) button.reply");
- assert.dom(".d-editor-input").hasNoValue("clears the composer input");
-
- await click(".topic-post:nth-of-type(1) button.edit");
- assert
- .dom(".d-editor-input")
- .hasValue(
- /^This is the first post\./,
- "populates the input with the post text"
- );
- });
-
- 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");
- assert
- .dom(".d-editor-input")
- .hasValue(
- /^This is the second post\./,
- "populates the input with the post text"
- );
-
- await click(".topic-post:nth-of-type(2) button.reply");
- assert.dom(".d-editor-input").hasNoValue("clears the composer input");
-
- await click(".topic-post:nth-of-type(2) button.edit");
- assert
- .dom(".d-editor-input")
- .hasValue(
- /^This is the second post\./,
- "populates the input with the post text"
- );
- });
-
- test("Composer can toggle whispers when whisperer user", async function (assert) {
- 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 menu.expand();
- await menu.selectRowByName("toggle-whisper");
-
- assert
- .dom(".composer-actions svg.d-icon-far-eye-slash")
- .exists("sets the post type to whisper");
-
- await menu.expand();
- await menu.selectRowByName("toggle-whisper");
-
- assert
- .dom(".composer-actions svg.d-icon-far-eye-slash")
- .doesNotExist("removes the whisper mode");
-
- await menu.expand();
- await menu.selectRowByName("toggle-whisper");
-
- await click(".toggle-fullscreen");
-
- await menu.expand();
-
- assert.true(
- menu.rowByName("toggle-whisper").exists(),
- "whisper toggling is still present when going fullscreen"
- );
- });
+["enabled", "disabled"].forEach((postStreamMode) => {
+ acceptance(
+ `Composer (glimmer_post_stream_mode = ${postStreamMode})`,
+ function (needs) {
+ needs.user({
+ id: 5,
+ username: "kris",
+ whisperer: true,
+ });
+ needs.settings({
+ glimmer_post_stream_mode: postStreamMode,
+ general_category_id: 1,
+ default_composer_category: 1,
+ });
+ needs.site({
+ can_tag_topics: true,
+ categories: [
+ {
+ id: 1,
+ name: "General",
+ slug: "general",
+ permission: 1,
+ topic_template: null,
+ },
+ {
+ id: 2,
+ name: "test too",
+ slug: "test-too",
+ permission: 1,
+ topic_template: "",
+ },
+ ],
+ });
+ needs.pretender((server, helper) => {
+ server.put("/u/kris.json", () => helper.response({ user: {} }));
+ server.post("/uploads/lookup-urls", () => {
+ return helper.response([]);
+ });
+ server.get("/posts/419", () => {
+ return helper.response({ id: 419 });
+ });
+ server.get("/composer/mentions", () => {
+ return helper.response({
+ users: [],
+ user_reasons: {},
+ groups: { staff: { user_count: 30 } },
+ group_reasons: {},
+ max_users_notified_per_group_mention: 100,
+ });
+ });
+ server.get("/t/960.json", () => {
+ const topicList = cloneJSON(TopicFixtures["/t/9/1.json"]);
+ topicList.post_stream.posts[2].post_type = 4;
+ return helper.response(topicList);
+ });
+ });
- 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");
-
- assert.dom("#reply-control.open").exists("starts in open state by default");
-
- await click(".toggle-fullscreen");
-
- assert
- .dom("#reply-control.fullscreen")
- .exists("expands composer to full screen");
-
- assert
- .dom(".composer-fullscreen-prompt")
- .exists("the exit fullscreen prompt is visible");
-
- await click(".toggle-fullscreen");
-
- assert
- .dom("#reply-control.open")
- .exists("collapses composer to regular size");
-
- await fillIn(".d-editor-input", "This is a dirty reply");
- await click(".toggler");
-
- assert
- .dom("#reply-control.draft")
- .exists("collapses composer to draft bar");
-
- await click(".toggle-fullscreen");
-
- assert
- .dom("#reply-control.open")
- .exists("from draft, it expands composer back to open state");
- });
-
- 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");
-
- assert.dom("#reply-control.open").exists("starts in open state by default");
-
- await click(".toggle-fullscreen");
-
- assert
- .dom("#reply-control button.create")
- .exists("shows composer submit button in fullscreen");
-
- await fillIn(".d-editor-input", "too short");
- await click("#reply-control button.create");
-
- assert
- .dom("#reply-control.open")
- .exists("goes back to open state if there's errors");
- });
-
- 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 selectKit(".toolbar-popup-menu-options").expand();
-
- await selectKit(".toolbar-popup-menu-options").selectRowByName(
- "toggle-whisper"
- );
-
- assert
- .dom(".composer-actions svg.d-icon-far-eye-slash")
- .exists("sets the post type to whisper");
-
- await visit("/");
- assert.dom("#create-topic").exists("the create topic button is visible");
-
- await click("#create-topic");
- assert
- .dom(".reply-details .whisper .d-icon-far-eye-slash")
- .doesNotExist("should reset the state of the composer's model");
-
- await selectKit(".toolbar-popup-menu-options").expand();
- await selectKit(".toolbar-popup-menu-options").selectRowByName(
- "toggle-invisible"
- );
-
- assert
- .dom(".reply-details .unlist")
- .includesText(i18n("composer.unlist"), "sets the topic to unlisted");
-
- await visit("/t/this-is-a-test-topic/9");
-
- await click(".topic-post:nth-of-type(1) button.reply");
- assert
- .dom(".reply-details .whisper")
- .doesNotExist("should reset the state of the composer's model");
- });
-
- 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(".reply-details summary div");
- assert
- .dom('.reply-details li[data-value="toggle_whisper"]')
- .doesNotExist("toggle whisper is not available when reply to whisper");
- await click('.reply-details li[data-value="reply_to_topic"]');
- await click(".reply-details summary div");
- assert
- .dom('.reply-details li[data-value="toggle_whisper"]')
- .exists("toggle whisper is available when reply to topic");
- });
-
- 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("#reply-control .save-or-cancel button.cancel");
- await click(".topic-footer-main-buttons button.create");
- await click(".reply-details summary div");
- assert
- .dom('.reply-details li[data-value="toggle_whisper"]')
- .exists("toggle whisper is available when reply to topic");
- });
-
- 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 fillIn(".d-editor-input", "This is a dirty reply");
- await click(".toggler");
- await click(".topic-post:nth-of-type(2) button.edit");
- assert
- .dom(".discard-draft-modal.modal")
- .exists("pops up a confirmation dialog");
- assert.dom(".d-modal__footer button.save-draft").doesNotExist();
- assert
- .dom(".d-modal__footer button.keep-editing")
- .hasText(
- i18n("post.cancel_composer.keep_editing"),
- "has keep editing button"
- );
- await click(".d-modal__footer button.discard-draft");
- assert
- .dom(".d-editor-input")
- .hasValue(
- /^This is the second post\./,
- "populates the input with the post text"
- );
- });
-
- 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 fillIn(".d-editor-input", "This is a dirty reply");
-
- await click("#site-logo");
- await click("#create-topic");
-
- assert
- .dom(".discard-draft-modal.modal")
- .exists("pops up a confirmation dialog");
- assert
- .dom(".d-modal__footer button.save-draft")
- .hasText(
- i18n("post.cancel_composer.save_draft"),
- "has save draft button"
- );
- assert
- .dom(".d-modal__footer button.keep-editing")
- .hasText(
- i18n("post.cancel_composer.keep_editing"),
- "has keep editing button"
- );
-
- await click(".d-modal__footer button.save-draft");
- assert.dom(".d-editor-input").hasNoValue("clears the composer input");
- });
-
- 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");
-
- assert.dom(".dialog-body").doesNotExist("does not open the dialog");
- assert.dom(".d-editor-input").exists("the composer input is visible");
- assert.dom(".d-editor-input").hasValue(/^Any plans to support/);
- });
-
- test("Can switch states without abandon popup", async function (assert) {
- await visit("/t/internationalization-localization/280");
-
- const longText = "a".repeat(256);
-
- sinon.stub(Draft, "get").resolves({
- draft: null,
- draft_sequence: 0,
- });
-
- await click(".btn-primary.create.btn");
-
- await fillIn(".d-editor-input", longText);
-
- assert
- .dom('.action-title a[href="/t/internationalization-localization/280"]')
- .exists("the mode should be: reply to post");
-
- await click("article#post_3 button.reply");
-
- const composerActions = selectKit(".composer-actions");
- await composerActions.expand();
- await composerActions.selectRowByValue("reply_as_new_topic");
-
- assert.dom(".d-modal__body").doesNotExist("abandon popup shouldn't come");
-
- assert
- .dom(".d-editor-input")
- .includesValue(longText, "entered text should still be there");
-
- assert
- .dom('.action-title a[href="/t/internationalization-localization/280"]')
- .doesNotExist("mode should have changed");
- });
-
- test("Does not replace recipient when another draft exists", async function (assert) {
- sinon.stub(Draft, "get").resolves({
- draft:
- '{"reply":"hello","action":"privateMessage","title":"hello","categoryId":null,"archetypeId":"private_message","metaData":null,"recipients":"codinghorror","composerTime":9159,"typingTime":2500}',
- draft_sequence: 0,
- });
-
- await visit("/u/charlie");
- await click("button.compose-pm");
-
- const privateMessageUsers = selectKit("#private-message-users");
- assert.strictEqual(privateMessageUsers.header().value(), "charlie");
-
- await click(".submit-panel .cancel");
- assert.dom(".d-editor-input").doesNotExist();
- });
-
- test("Deleting the text content of the first post in a private message", async function (assert) {
- await visit("/t/34");
-
- await click("#post_1 .d-icon-ellipsis");
- await click("#post_1 .d-icon-pencil");
- await fillIn(".d-editor-input", "");
-
- assert
- .dom(".d-editor-container textarea")
- .hasAttribute(
- "placeholder",
- i18n("composer.reply_placeholder"),
- "should not block because of missing category"
- );
- });
-
- test("reply button has envelope icon when replying to private message", async function (assert) {
- await visit("/t/34");
- await click("article#post_3 button.reply");
- assert
- .dom(".save-or-cancel button.create")
- .hasText(i18n("composer.create_pm"), "reply button says Message");
- assert
- .dom(".save-or-cancel button.create svg.d-icon-envelope")
- .exists("reply button has envelope icon");
- });
-
- test("edit button when editing a post in a PM", async function (assert) {
- await visit("/t/34");
- await click("article#post_3 button.show-more-actions");
- await click("article#post_3 button.edit");
-
- assert
- .dom(".save-or-cancel button.create")
- .hasText(i18n("composer.save_edit"), "save button says Save Edit");
- assert
- .dom(".save-or-cancel button.create svg.d-icon-pencil")
- .exists("save button has pencil icon");
- });
-
- test("Shows duplicate_link notice", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click("#topic-footer-buttons .create");
-
- this.container.lookup("service:composer").set(
- "linkLookup",
- new LinkLookup({
- "github.com": {
- domain: "github.com",
- username: "system",
- posted_at: "2021-01-01T12:00:00.000Z",
- post_number: 1,
- },
- })
- );
-
- await fillIn(".d-editor-input", "[](https://discourse.org)");
- assert.dom(".composer-popup").doesNotExist();
-
- await fillIn(".d-editor-input", "[quote][](https://github.com)[/quote]");
- assert.dom(".composer-popup").doesNotExist();
-
- await fillIn(".d-editor-input", "[](https://github.com)");
- assert.dom(".composer-popup").exists();
- });
-
- test("Shows the 'group_mentioned' notice", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click("#topic-footer-buttons .create");
-
- await fillIn(".d-editor-input", "[quote]\n@staff\n[/quote]");
- assert
- .dom(".composer-popup")
- .doesNotExist("Doesn't show the 'group_mentioned' notice in a quote");
-
- await fillIn(".d-editor-input", "@staff");
- assert.dom(".composer-popup").exists("shows the 'group_mentioned' notice");
- });
-
- test("Does not save invalid draft", async function (assert) {
- this.siteSettings.min_first_post_length = 20;
-
- await visit("/");
- await click("#create-topic");
- await fillIn("#reply-title", "Something");
- await fillIn(".d-editor-input", "Something");
- await click(".save-or-cancel .cancel");
- assert.dom(".discard-draft-modal .save-draft").doesNotExist();
- });
-
- test("Saves drafts that only contain quotes", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click("#topic-footer-buttons .create");
-
- await fillIn(".d-editor-input", "[quote]some quote[/quote]");
-
- await click(".save-or-cancel .cancel");
- assert.dom(".discard-draft-modal .save-draft").exists();
- });
-
- test("Discard drafts modal can be dismissed via keyboard", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click("#topic-footer-buttons .create");
-
- await fillIn(".d-editor-input", "[quote]some quote[/quote]");
-
- await click(".save-or-cancel .cancel");
- assert.dom(".discard-draft-modal .save-draft").exists();
-
- await triggerKeyEvent(
- ".discard-draft-modal .save-draft",
- "keydown",
- "Escape"
- );
-
- assert.dom(".discard-draft-modal").doesNotExist();
-
- assert
- .dom(".d-editor-input")
- .hasValue(
- "[quote]some quote[/quote]",
- "composer textarea is not cleared"
- );
- });
-});
+ test("Composer is opened", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+ // Check that the default category is selected
+ assert.strictEqual(
+ selectKit(".category-chooser").header().value(),
+ "1"
+ );
+
+ assert.strictEqual(
+ document.documentElement.style.getPropertyValue("--composer-height"),
+ "var(--new-topic-composer-height, 400px)",
+ "sets --composer-height to 400px when creating topic"
+ );
+
+ await fillIn(
+ ".d-editor-input",
+ "this is the *content* of a new topic post"
+ );
+ await click(".toggle-minimize");
+ assert.strictEqual(
+ document.documentElement.style.getPropertyValue("--composer-height"),
+ "40px",
+ "sets --composer-height to 40px when composer is minimized to draft mode"
+ );
+
+ await click(".toggle-fullscreen");
+ assert.strictEqual(
+ document.documentElement.style.getPropertyValue("--composer-height"),
+ "var(--new-topic-composer-height, 400px)",
+ "sets --composer-height back to 400px when composer is opened from draft mode"
+ );
+
+ await fillIn(".d-editor-input", "");
+ await click(".toggle-minimize");
+ assert.strictEqual(
+ document.documentElement.style.getPropertyValue("--composer-height"),
+ "",
+ "removes --composer-height property when composer is closed"
+ );
+ });
-acceptance("Composer - Customizations", function (needs) {
- needs.user();
- needs.site({ can_tag_topics: true });
-
- function customComposerAction(composer) {
- return (
- (composer.tags || []).includes("monkey") &&
- composer.action === CREATE_TOPIC
- );
- }
-
- needs.hooks.beforeEach(() => {
- withPluginApi("0.8.14", (api) => {
- api.customizeComposerText({
- actionTitle(model) {
- if (customComposerAction(model)) {
- return "custom text";
- }
- },
-
- saveLabel(model) {
- if (customComposerAction(model)) {
- return "composer.emoji";
- }
- },
- });
- });
- });
-
- test("Supports text customization", async function (assert) {
- await visit("/");
- await click("#create-topic");
- assert.dom(".action-title").hasText(i18n("topic.create_long"));
- assert.dom(".save-or-cancel button").hasText(i18n("composer.create_topic"));
- const tags = selectKit(".mini-tag-chooser");
- await tags.expand();
- await tags.selectRowByValue("monkey");
- assert.dom(".action-title").hasText("custom text");
- assert.dom(".save-or-cancel button").hasText(i18n("composer.emoji"));
- });
-});
+ test("Composer height adjustment", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+ await triggerEvent(".grippie", "mousedown");
+ await triggerEvent(".grippie", "mousemove");
+ await triggerEvent(".grippie", "mouseup");
+ await visit("/"); // reload page
+ await click("#create-topic");
+
+ const expectedHeight = localStorage.getItem(
+ "__test_discourse_composerHeight"
+ );
+ const actualHeight =
+ document.documentElement.style.getPropertyValue("--composer-height");
+
+ assert.strictEqual(
+ expectedHeight,
+ actualHeight,
+ "Updated height is persistent"
+ );
+ });
-acceptance("Composer - Error Extensibility", function (needs) {
- needs.user();
- needs.settings({
- general_category_id: 1,
- default_composer_category: 1,
- });
-
- needs.hooks.beforeEach(() => {
- withPluginApi("1.5.0", (api) => {
- api.addComposerSaveErrorCallback((error) => {
- if (error.match(/PLUGIN_XYZ ERROR/)) {
- // handle error
- return true;
- }
- return false;
- });
- });
- });
-
- test("Create a topic with server side errors handled by a plugin", async function (assert) {
- pretender.post("/posts", function () {
- return response(422, { errors: ["PLUGIN_XYZ ERROR"] });
- });
-
- await visit("/");
- await click("#create-topic");
- await fillIn("#reply-title", "this title triggers an error");
- await fillIn(".d-editor-input", "this is the *content* of a post");
- await click("#reply-control button.create");
- assert.dom(".dialog-body").doesNotExist("does not pop up an error message");
- });
-
- test("Create a topic with server side errors not handled by a plugin", async function (assert) {
- pretender.post("/posts", function () {
- return response(422, { errors: ["PLUGIN_ABC ERROR"] });
- });
-
- await visit("/");
- await click("#create-topic");
- await fillIn("#reply-title", "this title triggers an error");
- await fillIn(".d-editor-input", "this is the *content* of a post");
- await click("#reply-control button.create");
- assert.dom(".dialog-body").exists("pops up an error message");
- assert
- .dom(".dialog-body")
- .hasText(/PLUGIN_ABC ERROR/, "contains the server side error text");
- await click(".dialog-footer .btn-primary");
- assert.dom(".dialog-body").doesNotExist("dismisses the error");
- assert.dom(".d-editor-input").exists("the composer input is visible");
- });
-});
+ test("composer controls", async function (assert) {
+ await visit("/");
+ assert.dom("#create-topic").exists("the create button is visible");
+
+ await click("#create-topic");
+ assert.dom(".d-editor-input").exists("the composer input is visible");
+ await focus(".title-input input");
+ assert
+ .dom(".title-input .popup-tip.good.hide")
+ .exists("title errors are hidden by default");
+ assert
+ .dom(".d-editor-textarea-wrapper .popup-tip.bad.hide")
+ .exists("body errors are hidden by default");
+
+ await click(".toggle-preview");
+ assert
+ .dom(".d-editor-preview")
+ .isNotVisible("clicking the toggle hides the preview");
+
+ await click(".toggle-preview");
+ assert
+ .dom(".d-editor-preview")
+ .isVisible("clicking the toggle shows the preview again");
+
+ await click("#reply-control button.create");
+ assert
+ .dom(".title-input .popup-tip.bad")
+ .exists("shows the empty title error");
+ assert
+ .dom(".d-editor-textarea-wrapper .popup-tip.bad")
+ .exists("shows the empty body error");
+
+ await fillIn("#reply-title", "this is my new topic title");
+ assert
+ .dom(".title-input .popup-tip.good.hide")
+ .exists("the title is now good");
+
+ await triggerKeyEvent(
+ ".d-editor-textarea-wrapper .popup-tip.bad",
+ "keydown",
+ "Enter"
+ );
+ assert
+ .dom(".d-editor-textarea-wrapper .popup-tip.bad.hide")
+ .exists("body error is dismissed via keyboard");
+
+ await fillIn(".d-editor-input", "this is the *content* of a post");
+ assert
+ .dom(".d-editor-preview")
+ .hasHtml(
+ "<p>this is the <em>content</em> of a post</p>",
+ "previews content"
+ );
+ assert
+ .dom(".d-editor-textarea-wrapper .popup-tip.good")
+ .exists("the body is now good");
+
+ const textarea = find("#reply-control .d-editor-input");
+ textarea.selectionStart = textarea.value.length;
+ textarea.selectionEnd = textarea.value.length;
+
+ await triggerKeyEvent(textarea, "keydown", "B", metaModifier);
+
+ assert
+ .dom("#reply-control .d-editor-input")
+ .hasValue(
+ `this is the *content* of a post**${i18n("composer.bold_text")}**`,
+ "supports keyboard shortcuts"
+ );
+
+ await click("#reply-control button.cancel");
+ assert.dom(".d-modal").exists("pops up a confirmation dialog");
+
+ await click(".d-modal__footer .discard-draft");
+ assert
+ .dom(".d-modal__body")
+ .doesNotExist("the confirmation can be cancelled");
+ });
-acceptance("Composer - Focus Open and Closed", function (needs) {
- needs.user();
- needs.settings({ allow_uncategorized_topics: true });
+ test("Create a topic with server side errors", async function (assert) {
+ pretender.post("/posts", function () {
+ return response(422, {
+ errors: ["That title has already been taken"],
+ });
+ });
- test("Focusing a composer which is not open with create topic", async function (assert) {
- await visit("/t/internationalization-localization/280");
+ await visit("/");
+ await click("#create-topic");
+ await fillIn("#reply-title", "this title triggers an error");
+ await fillIn(".d-editor-input", "this is the *content* of a post");
+ await click("#reply-control button.create");
+ assert.dom(".dialog-body").exists("pops up an error message");
- const composer = this.container.lookup("service:composer");
- await composer.focusComposer({ fallbackToNewTopic: true });
+ await click(".dialog-footer .btn-primary");
+ assert.dom(".dialog-body").doesNotExist("dismisses the error");
+ assert.dom(".d-editor-input").exists("the composer input is visible");
+ });
- await settled();
- assert.dom(".d-editor-input").isFocused("composer is open and focused");
- assert.strictEqual(composer.model.action, Composer.CREATE_TOPIC);
- });
+ test("Create a Topic", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+ await fillIn("#reply-title", "Internationalization Localization");
+ await fillIn(
+ ".d-editor-input",
+ "this is the *content* of a new topic post"
+ );
+ await click("#reply-control button.create");
+ assert.strictEqual(
+ currentURL(),
+ "/t/internationalization-localization/280",
+ "transitions to the newly created topic URL"
+ );
+ });
- test("Focusing a composer which is not open with create topic and append text", async function (assert) {
- await visit("/t/internationalization-localization/280");
+ test("Create an enqueued Topic", async function (assert) {
+ pretender.post("/posts", function () {
+ return response(200, {
+ success: true,
+ action: "enqueued",
+ pending_post: {
+ id: 1234,
+ raw: "enqueue this content please",
+ },
+ });
+ });
- const composer = this.container.lookup("service:composer");
- await composer.focusComposer({
- fallbackToNewTopic: true,
- insertText: "this is appended",
- });
+ await visit("/");
+ await click("#create-topic");
+ await fillIn("#reply-title", "Internationalization Localization");
+ await fillIn(".d-editor-input", "enqueue this content please");
+ await click("#reply-control button.create");
+ assert.dom(".d-modal").exists("pops up a modal");
+ assert.strictEqual(currentURL(), "/", "doesn't change routes");
- await settled();
- assert.dom(".d-editor-input").isFocused("composer is open and focused");
- assert.dom("textarea.d-editor-input").hasValue("this is appended");
- });
+ await click(".d-modal__footer button");
+ assert.dom(".d-modal").doesNotExist("the modal can be dismissed");
+ });
- test("Focusing a composer which is already open", async function (assert) {
- await visit("/");
- await click("#create-topic");
+ test("Can display a message and route to a URL", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+ await fillIn("#reply-title", "This title doesn't matter");
+ await fillIn(".d-editor-input", "custom message that is a good length");
+ await click("#reply-control button.create");
+
+ assert
+ .dom("#dialog-holder .dialog-body")
+ .hasText("This is a custom response");
+ assert.strictEqual(currentURL(), "/", "doesn't change routes");
+
+ await click(".dialog-footer .btn-primary");
+ assert.strictEqual(
+ currentURL(),
+ "/faq",
+ "can navigate to a `route_to` destination"
+ );
+ });
- const composer = this.container.lookup("service:composer");
- await composer.focusComposer();
+ test("Create a Reply", async function (assert) {
+ await visit("/t/internationalization-localization/280");
- await settled();
- assert.dom(".d-editor-input").isFocused("composer is open and focused");
- });
+ assert
+ .dom('article[data-post-id="12345"]')
+ .doesNotExist("the post is not in the DOM");
- test("Focusing a composer which is already open and append text", async function (assert) {
- await visit("/");
- await click("#create-topic");
+ await click("#topic-footer-buttons .btn.create");
+ assert.dom(".d-editor-input").exists("the composer input is visible");
+ assert
+ .dom("#reply-title")
+ .doesNotExist("there is no title since this is a reply");
- const composer = this.container.lookup("service:composer");
- await composer.focusComposer({ insertText: "this is some appended text" });
+ 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")
+ .hasText("this is the content of my reply");
+ });
- await settled();
- assert.dom(".d-editor-input").isFocused("composer is open and focused");
- assert
- .dom("textarea.d-editor-input")
- .hasValue("this is some appended text");
- });
+ test("Replying to the first post in a topic is a topic reply", async function (assert) {
+ await visit("/t/internationalization-localization/280");
- 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("#post_1 .reply.create");
+ assert
+ .dom(".reply-details a.topic-link")
+ .hasText("Internationalization / localization");
- await click(".topic-post:nth-of-type(1) button.edit");
- await fillIn(".d-editor-input", "This is a dirty reply");
- await click(".toggle-minimize");
+ await click("#post_1 .reply.create");
+ assert
+ .dom(".reply-details a.topic-link")
+ .hasText("Internationalization / localization");
+ });
- const composer = this.container.lookup("service:composer");
- await composer.focusComposer({ insertText: "this is some appended text" });
+ test("Can edit a post after starting a reply", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+
+ 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(".d-modal__footer button.keep-editing");
+ assert.dom(".discard-draft-modal.modal").doesNotExist();
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ "this is the content of my reply",
+ "composer does not switch when using Keep Editing button"
+ );
+
+ await click(".topic-post:nth-of-type(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();
+
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ find(".topic-post:nth-of-type(1) .cooked > p").innerText,
+ "composer has contents of post to be edited"
+ );
+ });
- await settled();
- assert.dom(".d-editor-input").isFocused("composer is open and focused");
- assert
- .dom("textarea.d-editor-input")
- .hasValue("This is a dirty reply\n\nthis is some appended text");
- });
-});
+ test("Can Keep Editing when replying on a different topic", async function (assert) {
+ await visit("/t/internationalization-localization/280");
-// Default Composer Category tests
-acceptance("Composer - Default category", function (needs) {
- needs.user();
- needs.settings({
- general_category_id: 1,
- default_composer_category: 2,
- });
- needs.site({
- categories: [
- {
- id: 1,
- name: "General",
- slug: "general",
- permission: 1,
- topic_template: null,
- },
- {
- id: 2,
- name: "test too",
- slug: "test-too",
- permission: 1,
- topic_template: null,
- },
- ],
- });
-
- test("Default category is selected over general category", async function (assert) {
- await visit("/");
- await click("#create-topic");
- assert.strictEqual(selectKit(".category-chooser").header().value(), "2");
- assert.strictEqual(
- selectKit(".category-chooser").header().name(),
- "test too"
- );
- });
-});
+ await click("#topic-footer-buttons .create");
+ await fillIn(".d-editor-input", "this is the content of my reply");
-acceptance("Composer - Uncategorized category", function (needs) {
- needs.user();
- needs.settings({
- general_category_id: -1, // For sites that never had this seeded
- default_composer_category: -1, // For sites that never had this seeded
- allow_uncategorized_topics: true,
- });
- needs.site({
- categories: [
- {
- id: 1,
- name: "General",
- slug: "general",
- permission: 1,
- topic_template: null,
- },
- {
- id: 2,
- name: "test too",
- slug: "test-too",
- permission: 1,
- topic_template: null,
- },
- ],
- });
-
- test("Uncategorized category is selected", async function (assert) {
- await visit("/");
- await click("#create-topic");
- assert.strictEqual(selectKit(".category-chooser").header().value(), null);
- });
-});
+ await visit("/t/this-is-a-test-topic/9");
+ await click("#topic-footer-buttons .create");
+ assert.dom(".discard-draft-modal.modal").exists();
-acceptance("Composer - default category not set", function (needs) {
- needs.user();
- needs.settings({
- default_composer_category: "",
- });
- needs.site({
- categories: [
- {
- id: 1,
- name: "General",
- slug: "general",
- permission: 1,
- topic_template: null,
- },
- {
- id: 2,
- name: "test too",
- slug: "test-too",
- permission: 1,
- topic_template: null,
- },
- ],
- });
-
- test("Nothing is selected", async function (assert) {
- await visit("/");
- await click("#create-topic");
- assert.strictEqual(selectKit(".category-chooser").header().value(), null);
- assert.strictEqual(
- selectKit(".category-chooser").header().name(),
- "category&hellip;"
- );
- });
-});
-// END: Default Composer Category tests
-
-acceptance("composer buttons API", function (needs) {
- needs.user();
- needs.settings({
- allow_uncategorized_topics: true,
- });
-
- test("buttons can support a shortcut", async function (assert) {
- withPluginApi("0", (api) => {
- api.addComposerToolbarPopupMenuOption({
- action: (toolbarEvent) => {
- toolbarEvent.applySurround("**", "**");
- },
- shortcut: "alt+b",
- icon: "far-bold",
- name: "bold",
- title: "some_title",
- label: "some_label",
-
- condition: () => {
- return true;
- },
- });
- });
-
- await visit("/t/internationalization-localization/280");
- await click(".post-controls button.reply");
- await fillIn(".d-editor-input", "hello the world");
-
- const editor = find(".d-editor-input");
- editor.setSelectionRange(6, 9); // select the text input in the composer
-
- await triggerKeyEvent(".d-editor-input", "keydown", "B", {
- altKey: true,
- ...metaModifier,
- });
-
- assert
- .dom(".d-editor-input")
- .hasValue("hello **the** world", "adds the bold");
-
- const dropdown = selectKit(".toolbar-popup-menu-options");
- await dropdown.expand();
-
- const row = dropdown.rowByName("bold").el();
- assert
- .dom(row)
- .hasAttribute(
- "title",
- i18n("some_title") +
- ` (${translateModKey(PLATFORM_KEY_MODIFIER + "+alt+b")})`,
- "shows the title with shortcut"
- );
- assert
- .dom(row)
- .hasText(
- i18n("some_label") +
- ` ${translateModKey(PLATFORM_KEY_MODIFIER + "+alt+b")}`,
- "shows the label with shortcut"
- );
- });
-
- test("buttons can support a shortcut that triggers a custom action", async function (assert) {
- withPluginApi("1.37.1", (api) => {
- api.onToolbarCreate((toolbar) => {
- toolbar.addButton({
- id: "smile",
- group: "extras",
- icon: "far-face-smile",
- shortcut: "ALT+S",
- shortcutAction: (toolbarEvent) => {
- toolbarEvent.addText(":smile: from keyboard");
+ await click(".d-modal__footer button.keep-editing");
+ assert.dom(".discard-draft-modal.modal").doesNotExist();
+
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ "this is the content of my reply",
+ "composer does not switch when using Keep Editing button"
+ );
+ });
+
+ test("Posting on a different topic", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click("#topic-footer-buttons .btn.create");
+ await fillIn(
+ ".d-editor-input",
+ "this is the content for a different topic"
+ );
+ await visit("/t/1-3-0beta9-no-rate-limit-popups/28830");
+
+ assert.strictEqual(
+ currentURL(),
+ "/t/1-3-0beta9-no-rate-limit-popups/28830"
+ );
+
+ await click("#reply-control button.create");
+
+ assert.dom(".reply-where-modal").exists("pops up a modal");
+ assert
+ .dom(".topic-title")
+ .exists({ count: 2 }, "it renders the two topics");
+ assert
+ .dom(".btn-reply-where:nth-of-type(1) .badge-category__name")
+ .hasText("test too", "it renders the category name");
+ assert
+ .dom(".btn-reply-where:nth-of-type(2) .discourse-tags")
+ .hasText("foo", "it renders the tags");
+
+ await click(".btn-reply-here");
+
+ assert
+ .dom(".topic-post:last-of-type .cooked p")
+ .hasText(
+ "If you use gettext format you could leverage Launchpad translations and the community behind it."
+ );
+ });
+
+ test("Discard draft modal works when switching topics", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click("#topic-footer-buttons .btn.create");
+ await fillIn(
+ ".d-editor-input",
+ "this is the content of the first reply"
+ );
+
+ await visit("/t/this-is-a-test-topic/9");
+ assert.true(
+ currentURL().startsWith("/t/this-is-a-test-topic/9"),
+ "moves to second topic"
+ );
+ await click("#topic-footer-buttons .btn.create");
+ assert
+ .dom(".discard-draft-modal.modal")
+ .exists("pops up the discard drafts modal");
+
+ await click(".d-modal__footer button.keep-editing");
+
+ assert.dom(".discard-draft-modal.modal").doesNotExist("hides modal");
+ await click("#topic-footer-buttons .btn.create");
+ assert
+ .dom(".discard-draft-modal.modal")
+ .exists("pops up the modal again");
+
+ await click(".d-modal__footer button.discard-draft");
+
+ assert
+ .dom(".d-editor-input")
+ .hasNoValue("discards draft and reset composer textarea");
+ });
+
+ test("Create an enqueued Reply", async function (assert) {
+ pretender.post("/posts", function () {
+ return response(200, {
+ success: true,
+ action: "enqueued",
+ pending_post: {
+ id: 1234,
+ raw: "enqueue this content please",
+ },
+ });
+ });
+
+ await visit("/t/internationalization-localization/280");
+ assert.dom(".pending-posts .reviewable-item").doesNotExist();
+
+ await click("#topic-footer-buttons .btn.create");
+ assert.dom(".d-editor-input").exists("the composer input is visible");
+ assert
+ .dom("#reply-title")
+ .doesNotExist("there is no title since this is a reply");
+
+ await fillIn(".d-editor-input", "enqueue this content please");
+ await click("#reply-control button.create");
+ assert
+ .dom(".topic-post:last-of-type .cooked p")
+ .doesNotIncludeText(
+ "enqueue this content please",
+ "doesn't insert the post"
+ );
+ assert.dom(".d-modal").exists("pops up a modal");
+
+ await click(".d-modal__footer button");
+ assert.dom(".d-modal").doesNotExist("the modal can be dismissed");
+ assert.dom(".pending-posts .reviewable-item").exists();
+ });
+
+ test("Edit the first post", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+
+ assert
+ .dom(".topic-post:nth-of-type(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");
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ /^Any plans to support/,
+ "populates the input with the post text"
+ );
+
+ await fillIn(".d-editor-input", "This is the new text for the post");
+ await fillIn("#reply-title", "This is the new text for the title");
+ 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")
+ .exists("has the edits icon");
+ assert
+ .dom("#topic-title h1")
+ .includesText(
+ "This is the new text for the title",
+ "shows the new title"
+ );
+ assert
+ .dom(".topic-post:nth-of-type(1) .cooked")
+ .includesText(
+ "This is the new text for the post",
+ "updates the post"
+ );
+ });
+
+ test("Editing a post stages new content", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click(".topic-post button.show-more-actions");
+ await click(".topic-post button.edit");
+
+ await fillIn(".d-editor-input", "will return empty json");
+ await fillIn("#reply-title", "This is the new text for the title");
+
+ 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");
+ assert
+ .dom(".topic-post.staged .cooked")
+ .hasText("will return empty json");
+
+ return response(200, {});
+ });
+
+ await click("#reply-control button.create");
+
+ await visit("/t/internationalization-localization/280");
+ assert.dom(".topic-post.staged").doesNotExist();
+ });
+
+ 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");
+ 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");
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ /^This is the second post\./,
+ "populates the input with the post text"
+ );
+ });
+
+ 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 fillIn(".d-editor-input", "This is a dirty reply");
+ await click(".topic-post:nth-of-type(2) button.edit");
+ assert
+ .dom(".discard-draft-modal.modal")
+ .exists("pops up a confirmation dialog");
+
+ await click(".d-modal__footer button.discard-draft");
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ /^This is the second post\./,
+ "populates the input with the post text"
+ );
+ });
+
+ 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");
+ 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(1) button.reply");
+ assert.dom(".d-editor-input").hasNoValue("clears the composer input");
+
+ await click(".topic-post:nth-of-type(1) button.edit");
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ /^This is the first post\./,
+ "populates the input with the post text"
+ );
+ });
+
+ 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");
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ /^This is the second post\./,
+ "populates the input with the post text"
+ );
+
+ await click(".topic-post:nth-of-type(2) button.reply");
+ assert.dom(".d-editor-input").hasNoValue("clears the composer input");
+
+ await click(".topic-post:nth-of-type(2) button.edit");
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ /^This is the second post\./,
+ "populates the input with the post text"
+ );
+ });
+
+ test("Composer can toggle whispers when whisperer user", async function (assert) {
+ 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 menu.expand();
+ await menu.selectRowByName("toggle-whisper");
+
+ assert
+ .dom(".composer-actions svg.d-icon-far-eye-slash")
+ .exists("sets the post type to whisper");
+
+ await menu.expand();
+ await menu.selectRowByName("toggle-whisper");
+
+ assert
+ .dom(".composer-actions svg.d-icon-far-eye-slash")
+ .doesNotExist("removes the whisper mode");
+
+ await menu.expand();
+ await menu.selectRowByName("toggle-whisper");
+
+ await click(".toggle-fullscreen");
+
+ await menu.expand();
+
+ assert.true(
+ menu.rowByName("toggle-whisper").exists(),
+ "whisper toggling is still present when going fullscreen"
+ );
+ });
+
+ 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");
+
+ assert
+ .dom("#reply-control.open")
+ .exists("starts in open state by default");
+
+ await click(".toggle-fullscreen");
+
+ assert
+ .dom("#reply-control.fullscreen")
+ .exists("expands composer to full screen");
+
+ assert
+ .dom(".composer-fullscreen-prompt")
+ .exists("the exit fullscreen prompt is visible");
+
+ await click(".toggle-fullscreen");
+
+ assert
+ .dom("#reply-control.open")
+ .exists("collapses composer to regular size");
+
+ await fillIn(".d-editor-input", "This is a dirty reply");
+ await click(".toggler");
+
+ assert
+ .dom("#reply-control.draft")
+ .exists("collapses composer to draft bar");
+
+ await click(".toggle-fullscreen");
+
+ assert
+ .dom("#reply-control.open")
+ .exists("from draft, it expands composer back to open state");
+ });
+
+ 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");
+
+ assert
+ .dom("#reply-control.open")
+ .exists("starts in open state by default");
+
+ await click(".toggle-fullscreen");
+
+ assert
+ .dom("#reply-control button.create")
+ .exists("shows composer submit button in fullscreen");
+
+ await fillIn(".d-editor-input", "too short");
+ await click("#reply-control button.create");
+
+ assert
+ .dom("#reply-control.open")
+ .exists("goes back to open state if there's errors");
+ });
+
+ 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 selectKit(".toolbar-popup-menu-options").expand();
+
+ await selectKit(".toolbar-popup-menu-options").selectRowByName(
+ "toggle-whisper"
+ );
+
+ assert
+ .dom(".composer-actions svg.d-icon-far-eye-slash")
+ .exists("sets the post type to whisper");
+
+ await visit("/");
+ assert
+ .dom("#create-topic")
+ .exists("the create topic button is visible");
+
+ await click("#create-topic");
+ assert
+ .dom(".reply-details .whisper .d-icon-far-eye-slash")
+ .doesNotExist("should reset the state of the composer's model");
+
+ await selectKit(".toolbar-popup-menu-options").expand();
+ await selectKit(".toolbar-popup-menu-options").selectRowByName(
+ "toggle-invisible"
+ );
+
+ assert
+ .dom(".reply-details .unlist")
+ .includesText(i18n("composer.unlist"), "sets the topic to unlisted");
+
+ await visit("/t/this-is-a-test-topic/9");
+
+ await click(".topic-post:nth-of-type(1) button.reply");
+ assert
+ .dom(".reply-details .whisper")
+ .doesNotExist("should reset the state of the composer's model");
+ });
+
+ 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(".reply-details summary div");
+ assert
+ .dom('.reply-details li[data-value="toggle_whisper"]')
+ .doesNotExist(
+ "toggle whisper is not available when reply to whisper"
+ );
+ await click('.reply-details li[data-value="reply_to_topic"]');
+ await click(".reply-details summary div");
+ assert
+ .dom('.reply-details li[data-value="toggle_whisper"]')
+ .exists("toggle whisper is available when reply to topic");
+ });
+
+ 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("#reply-control .save-or-cancel button.cancel");
+ await click(".topic-footer-main-buttons button.create");
+ await click(".reply-details summary div");
+ assert
+ .dom('.reply-details li[data-value="toggle_whisper"]')
+ .exists("toggle whisper is available when reply to topic");
+ });
+
+ 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 fillIn(".d-editor-input", "This is a dirty reply");
+ await click(".toggler");
+ await click(".topic-post:nth-of-type(2) button.edit");
+ assert
+ .dom(".discard-draft-modal.modal")
+ .exists("pops up a confirmation dialog");
+ assert.dom(".d-modal__footer button.save-draft").doesNotExist();
+ assert
+ .dom(".d-modal__footer button.keep-editing")
+ .hasText(
+ i18n("post.cancel_composer.keep_editing"),
+ "has keep editing button"
+ );
+ await click(".d-modal__footer button.discard-draft");
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ /^This is the second post\./,
+ "populates the input with the post text"
+ );
+ });
+
+ 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 fillIn(".d-editor-input", "This is a dirty reply");
+
+ await click("#site-logo");
+ await click("#create-topic");
+
+ assert
+ .dom(".discard-draft-modal.modal")
+ .exists("pops up a confirmation dialog");
+ assert
+ .dom(".d-modal__footer button.save-draft")
+ .hasText(
+ i18n("post.cancel_composer.save_draft"),
+ "has save draft button"
+ );
+ assert
+ .dom(".d-modal__footer button.keep-editing")
+ .hasText(
+ i18n("post.cancel_composer.keep_editing"),
+ "has keep editing button"
+ );
+
+ await click(".d-modal__footer button.save-draft");
+ assert.dom(".d-editor-input").hasNoValue("clears the composer input");
+ });
+
+ 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");
+
+ assert.dom(".dialog-body").doesNotExist("does not open the dialog");
+ assert.dom(".d-editor-input").exists("the composer input is visible");
+ assert.dom(".d-editor-input").hasValue(/^Any plans to support/);
+ });
+
+ test("Can switch states without abandon popup", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+
+ const longText = "a".repeat(256);
+
+ sinon.stub(Draft, "get").resolves({
+ draft: null,
+ draft_sequence: 0,
+ });
+
+ await click(".btn-primary.create.btn");
+
+ await fillIn(".d-editor-input", longText);
+
+ assert
+ .dom(
+ '.action-title a[href="/t/internationalization-localization/280"]'
+ )
+ .exists("the mode should be: reply to post");
+
+ await click("article#post_3 button.reply");
+
+ const composerActions = selectKit(".composer-actions");
+ await composerActions.expand();
+ await composerActions.selectRowByValue("reply_as_new_topic");
+
+ assert
+ .dom(".d-modal__body")
+ .doesNotExist("abandon popup shouldn't come");
+
+ assert
+ .dom(".d-editor-input")
+ .includesValue(longText, "entered text should still be there");
+
+ assert
+ .dom(
+ '.action-title a[href="/t/internationalization-localization/280"]'
+ )
+ .doesNotExist("mode should have changed");
+ });
+
+ test("Does not replace recipient when another draft exists", async function (assert) {
+ sinon.stub(Draft, "get").resolves({
+ draft:
+ '{"reply":"hello","action":"privateMessage","title":"hello","categoryId":null,"archetypeId":"private_message","metaData":null,"recipients":"codinghorror","composerTime":9159,"typingTime":2500}',
+ draft_sequence: 0,
+ });
+
+ await visit("/u/charlie");
+ await click("button.compose-pm");
+
+ const privateMessageUsers = selectKit("#private-message-users");
+ assert.strictEqual(privateMessageUsers.header().value(), "charlie");
+
+ await click(".submit-panel .cancel");
+ assert.dom(".d-editor-input").doesNotExist();
+ });
+
+ test("Deleting the text content of the first post in a private message", async function (assert) {
+ await visit("/t/34");
+
+ await click("#post_1 .d-icon-ellipsis");
+ await click("#post_1 .d-icon-pencil");
+ await fillIn(".d-editor-input", "");
+
+ assert
+ .dom(".d-editor-container textarea")
+ .hasAttribute(
+ "placeholder",
+ i18n("composer.reply_placeholder"),
+ "should not block because of missing category"
+ );
+ });
+
+ test("reply button has envelope icon when replying to private message", async function (assert) {
+ await visit("/t/34");
+ await click("article#post_3 button.reply");
+ assert
+ .dom(".save-or-cancel button.create")
+ .hasText(i18n("composer.create_pm"), "reply button says Message");
+ assert
+ .dom(".save-or-cancel button.create svg.d-icon-envelope")
+ .exists("reply button has envelope icon");
+ });
+
+ test("edit button when editing a post in a PM", async function (assert) {
+ await visit("/t/34");
+ await click("article#post_3 button.show-more-actions");
+ await click("article#post_3 button.edit");
+
+ assert
+ .dom(".save-or-cancel button.create")
+ .hasText(i18n("composer.save_edit"), "save button says Save Edit");
+ assert
+ .dom(".save-or-cancel button.create svg.d-icon-pencil")
+ .exists("save button has pencil icon");
+ });
+
+ test("Shows duplicate_link notice", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click("#topic-footer-buttons .create");
+
+ this.container.lookup("service:composer").set(
+ "linkLookup",
+ new LinkLookup({
+ "github.com": {
+ domain: "github.com",
+ username: "system",
+ posted_at: "2021-01-01T12:00:00.000Z",
+ post_number: 1,
+ },
+ })
+ );
+
+ await fillIn(".d-editor-input", "[](https://discourse.org)");
+ assert.dom(".composer-popup").doesNotExist();
+
+ await fillIn(
+ ".d-editor-input",
+ "[quote][](https://github.com)[/quote]"
+ );
+ assert.dom(".composer-popup").doesNotExist();
+
+ await fillIn(".d-editor-input", "[](https://github.com)");
+ assert.dom(".composer-popup").exists();
+ });
+
+ test("Shows the 'group_mentioned' notice", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click("#topic-footer-buttons .create");
+
+ await fillIn(".d-editor-input", "[quote]\n@staff\n[/quote]");
+ assert
+ .dom(".composer-popup")
+ .doesNotExist("Doesn't show the 'group_mentioned' notice in a quote");
+
+ await fillIn(".d-editor-input", "@staff");
+ assert
+ .dom(".composer-popup")
+ .exists("shows the 'group_mentioned' notice");
+ });
+
+ test("Does not save invalid draft", async function (assert) {
+ this.siteSettings.min_first_post_length = 20;
+
+ await visit("/");
+ await click("#create-topic");
+ await fillIn("#reply-title", "Something");
+ await fillIn(".d-editor-input", "Something");
+ await click(".save-or-cancel .cancel");
+ assert.dom(".discard-draft-modal .save-draft").doesNotExist();
+ });
+
+ test("Saves drafts that only contain quotes", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click("#topic-footer-buttons .create");
+
+ await fillIn(".d-editor-input", "[quote]some quote[/quote]");
+
+ await click(".save-or-cancel .cancel");
+ assert.dom(".discard-draft-modal .save-draft").exists();
+ });
+
+ test("Discard drafts modal can be dismissed via keyboard", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click("#topic-footer-buttons .create");
+
+ await fillIn(".d-editor-input", "[quote]some quote[/quote]");
+
+ await click(".save-or-cancel .cancel");
+ assert.dom(".discard-draft-modal .save-draft").exists();
+
+ await triggerKeyEvent(
+ ".discard-draft-modal .save-draft",
+ "keydown",
+ "Escape"
+ );
+
+ assert.dom(".discard-draft-modal").doesNotExist();
+
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ "[quote]some quote[/quote]",
+ "composer textarea is not cleared"
+ );
+ });
+ }
+ );
+
+ acceptance(
+ `Composer - Customizations (glimmer_post_stream_mode = ${postStreamMode})`,
+ function (needs) {
+ needs.settings({
+ glimmer_post_stream_mode: postStreamMode,
+ });
+ needs.user();
+ needs.site({ can_tag_topics: true });
+
+ function customComposerAction(composer) {
+ return (
+ (composer.tags || []).includes("monkey") &&
+ composer.action === CREATE_TOPIC
+ );
+ }
+
+ needs.hooks.beforeEach(() => {
+ withPluginApi("0.8.14", (api) => {
+ api.customizeComposerText({
+ actionTitle(model) {
+ if (customComposerAction(model)) {
+ return "custom text";
+ }
+ },
+
+ saveLabel(model) {
+ if (customComposerAction(model)) {
+ return "composer.emoji";
+ }
+ },
+ });
+ });
+ });
+
+ test("Supports text customization", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+ assert.dom(".action-title").hasText(i18n("topic.create_long"));
+ assert
+ .dom(".save-or-cancel button")
+ .hasText(i18n("composer.create_topic"));
+ const tags = selectKit(".mini-tag-chooser");
+ await tags.expand();
+ await tags.selectRowByValue("monkey");
+ assert.dom(".action-title").hasText("custom text");
+ assert.dom(".save-or-cancel button").hasText(i18n("composer.emoji"));
+ });
+ }
+ );
+
+ acceptance(
+ `Composer - Error Extensibility (glimmer_post_stream_mode = ${postStreamMode})`,
+ function (needs) {
+ needs.user();
+ needs.settings({
+ glimmer_post_stream_mode: postStreamMode,
+ general_category_id: 1,
+ default_composer_category: 1,
+ });
+
+ needs.hooks.beforeEach(() => {
+ withPluginApi("1.5.0", (api) => {
+ api.addComposerSaveErrorCallback((error) => {
+ if (error.match(/PLUGIN_XYZ ERROR/)) {
+ // handle error
+ return true;
+ }
+ return false;
+ });
+ });
+ });
+
+ test("Create a topic with server side errors handled by a plugin", async function (assert) {
+ pretender.post("/posts", function () {
+ return response(422, { errors: ["PLUGIN_XYZ ERROR"] });
+ });
+
+ await visit("/");
+ await click("#create-topic");
+ await fillIn("#reply-title", "this title triggers an error");
+ await fillIn(".d-editor-input", "this is the *content* of a post");
+ await click("#reply-control button.create");
+ assert
+ .dom(".dialog-body")
+ .doesNotExist("does not pop up an error message");
+ });
+
+ test("Create a topic with server side errors not handled by a plugin", async function (assert) {
+ pretender.post("/posts", function () {
+ return response(422, { errors: ["PLUGIN_ABC ERROR"] });
+ });
+
+ await visit("/");
+ await click("#create-topic");
+ await fillIn("#reply-title", "this title triggers an error");
+ await fillIn(".d-editor-input", "this is the *content* of a post");
+ await click("#reply-control button.create");
+ assert.dom(".dialog-body").exists("pops up an error message");
+ assert
+ .dom(".dialog-body")
+ .hasText(/PLUGIN_ABC ERROR/, "contains the server side error text");
+ await click(".dialog-footer .btn-primary");
+ assert.dom(".dialog-body").doesNotExist("dismisses the error");
+ assert.dom(".d-editor-input").exists("the composer input is visible");
+ });
+ }
+ );
+
+ acceptance(
+ `Composer - Focus Open and Closed (glimmer_post_stream_mode = ${postStreamMode})`,
+ function (needs) {
+ needs.user();
+ needs.settings({
+ glimmer_post_stream_mode: postStreamMode,
+ allow_uncategorized_topics: true,
+ });
+
+ test("Focusing a composer which is not open with create topic", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+
+ const composer = this.container.lookup("service:composer");
+ await composer.focusComposer({ fallbackToNewTopic: true });
+
+ await settled();
+ assert.dom(".d-editor-input").isFocused("composer is open and focused");
+ assert.strictEqual(composer.model.action, Composer.CREATE_TOPIC);
+ });
+
+ test("Focusing a composer which is not open with create topic and append text", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+
+ const composer = this.container.lookup("service:composer");
+ await composer.focusComposer({
+ fallbackToNewTopic: true,
+ insertText: "this is appended",
+ });
+
+ await settled();
+ assert.dom(".d-editor-input").isFocused("composer is open and focused");
+ assert.dom("textarea.d-editor-input").hasValue("this is appended");
+ });
+
+ test("Focusing a composer which is already open", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+
+ const composer = this.container.lookup("service:composer");
+ await composer.focusComposer();
+
+ await settled();
+ assert.dom(".d-editor-input").isFocused("composer is open and focused");
+ });
+
+ test("Focusing a composer which is already open and append text", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+
+ const composer = this.container.lookup("service:composer");
+ await composer.focusComposer({
+ insertText: "this is some appended text",
+ });
+
+ await settled();
+ assert.dom(".d-editor-input").isFocused("composer is open and focused");
+ assert
+ .dom("textarea.d-editor-input")
+ .hasValue("this is some appended text");
+ });
+
+ 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 fillIn(".d-editor-input", "This is a dirty reply");
+ await click(".toggle-minimize");
+
+ const composer = this.container.lookup("service:composer");
+ await composer.focusComposer({
+ insertText: "this is some appended text",
+ });
+
+ await settled();
+ assert.dom(".d-editor-input").isFocused("composer is open and focused");
+ assert
+ .dom("textarea.d-editor-input")
+ .hasValue("This is a dirty reply\n\nthis is some appended text");
+ });
+ }
+ );
+
+ // Default Composer Category tests
+ acceptance(
+ `Composer - Default category (glimmer_post_stream_mode = ${postStreamMode})`,
+ function (needs) {
+ needs.user();
+ needs.settings({
+ glimmer_post_stream_mode: postStreamMode,
+ general_category_id: 1,
+ default_composer_category: 2,
+ });
+ needs.site({
+ categories: [
+ {
+ id: 1,
+ name: "General",
+ slug: "general",
+ permission: 1,
+ topic_template: null,
},
- sendAction: (event) => {
- event.addText(":smile: from click");
+ {
+ id: 2,
+ name: "test too",
+ slug: "test-too",
+ permission: 1,
+ topic_template: null,
},
+ ],
+ });
+
+ test("Default category is selected over general category", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+ assert.strictEqual(
+ selectKit(".category-chooser").header().value(),
+ "2"
+ );
+ assert.strictEqual(
+ selectKit(".category-chooser").header().name(),
+ "test too"
+ );
+ });
+ }
+ );
+
+ acceptance(
+ `Composer - Uncategorized category (glimmer_post_stream_mode = ${postStreamMode})`,
+ function (needs) {
+ needs.user();
+ needs.settings({
+ glimmer_post_stream_mode: postStreamMode,
+ general_category_id: -1, // For sites that never had this seeded
+ default_composer_category: -1, // For sites that never had this seeded
+ allow_uncategorized_topics: true,
+ });
+ needs.site({
+ categories: [
+ {
+ id: 1,
+ name: "General",
+ slug: "general",
+ permission: 1,
+ topic_template: null,
+ },
+ {
+ id: 2,
+ name: "test too",
+ slug: "test-too",
+ permission: 1,
+ topic_template: null,
+ },
+ ],
+ });
+
+ test("Uncategorized category is selected", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+ assert.strictEqual(
+ selectKit(".category-chooser").header().value(),
+ null
+ );
+ });
+ }
+ );
+
+ acceptance(
+ `Composer - default category not set (glimmer_post_stream_mode = ${postStreamMode})`,
+ function (needs) {
+ needs.user();
+ needs.settings({
+ glimmer_post_stream_mode: postStreamMode,
+ default_composer_category: "",
+ });
+ needs.site({
+ categories: [
+ {
+ id: 1,
+ name: "General",
+ slug: "general",
+ permission: 1,
+ topic_template: null,
+ },
+ {
+ id: 2,
+ name: "test too",
+ slug: "test-too",
+ permission: 1,
+ topic_template: null,
+ },
+ ],
+ });
+
+ test("Nothing is selected", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+ assert.strictEqual(
+ selectKit(".category-chooser").header().value(),
+ null
+ );
+ assert.strictEqual(
+ selectKit(".category-chooser").header().name(),
+ "category&hellip;"
+ );
+ });
+ }
+ );
+ // END: Default Composer Category tests
+
+ acceptance(
+ `composer buttons API (glimmer_post_stream_mode = ${postStreamMode})`,
+ function (needs) {
+ needs.user();
+ needs.settings({
+ glimmer_post_stream_mode: postStreamMode,
+ allow_uncategorized_topics: true,
+ });
+
+ test("buttons can support a shortcut", async function (assert) {
+ withPluginApi("0", (api) => {
+ api.addComposerToolbarPopupMenuOption({
+ action: (toolbarEvent) => {
+ toolbarEvent.applySurround("**", "**");
+ },
+ shortcut: "alt+b",
+ icon: "far-bold",
+ name: "bold",
+ title: "some_title",
+ label: "some_label",
+
+ condition: () => {
+ return true;
+ },
+ });
});
+
+ await visit("/t/internationalization-localization/280");
+ await click(".post-controls button.reply");
+ await fillIn(".d-editor-input", "hello the world");
+
+ const editor = find(".d-editor-input");
+ editor.setSelectionRange(6, 9); // select the text input in the composer
+
+ await triggerKeyEvent(".d-editor-input", "keydown", "B", {
+ altKey: true,
+ ...metaModifier,
+ });
+
+ assert
+ .dom(".d-editor-input")
+ .hasValue("hello **the** world", "adds the bold");
+
+ const dropdown = selectKit(".toolbar-popup-menu-options");
+ await dropdown.expand();
+
+ const row = dropdown.rowByName("bold").el();
+ assert
+ .dom(row)
+ .hasAttribute(
+ "title",
+ i18n("some_title") +
+ ` (${translateModKey(PLATFORM_KEY_MODIFIER + "+alt+b")})`,
+ "shows the title with shortcut"
+ );
+ assert
+ .dom(row)
+ .hasText(
+ i18n("some_label") +
+ ` ${translateModKey(PLATFORM_KEY_MODIFIER + "+alt+b")}`,
+ "shows the label with shortcut"
+ );
+ });
+
+ test("buttons can support a shortcut that triggers a custom action", async function (assert) {
+ withPluginApi("1.37.1", (api) => {
+ api.onToolbarCreate((toolbar) => {
+ toolbar.addButton({
+ id: "smile",
+ group: "extras",
+ icon: "far-face-smile",
+ shortcut: "ALT+S",
+ shortcutAction: (toolbarEvent) => {
+ toolbarEvent.addText(":smile: from keyboard");
+ },
+ sendAction: (event) => {
+ event.addText(":smile: from click");
+ },
+ });
+ });
+ });
+
+ await visit("/t/internationalization-localization/280");
+ await click(".post-controls button.reply");
+
+ const editor = find(".d-editor-input");
+ await triggerKeyEvent(".d-editor-input", "keydown", "S", {
+ altKey: true,
+ ...metaModifier,
+ });
+
+ assert.dom(editor).hasValue(":smile: from keyboard");
+ });
+
+ test("buttons can be added conditionally", async function (assert) {
+ withPluginApi("0", (api) => {
+ api.addComposerToolbarPopupMenuOption({
+ action: (toolbarEvent) => {
+ toolbarEvent.applySurround("**", "**");
+ },
+ icon: "far-bold",
+ label: "some_label",
+ condition: (composer) => {
+ return composer.model.creatingTopic;
+ },
+ });
+ });
+
+ await visit("/t/internationalization-localization/280");
+
+ await click(".post-controls button.reply");
+ assert.dom(".d-editor-input").exists("the composer input is visible");
+
+ const expectedName = "[en.some_label]";
+ const dropdown = selectKit(".toolbar-popup-menu-options");
+ await dropdown.expand();
+
+ assert.false(
+ dropdown.rowByName(expectedName).exists(),
+ "custom button is not displayed for reply"
+ );
+
+ await visit("/latest");
+ await click("#create-topic");
+
+ await dropdown.expand();
+ assert.true(
+ dropdown.rowByName(expectedName).exists(),
+ "custom button is displayed for new topic"
+ );
});
- });
-
- await visit("/t/internationalization-localization/280");
- await click(".post-controls button.reply");
-
- const editor = find(".d-editor-input");
- await triggerKeyEvent(".d-editor-input", "keydown", "S", {
- altKey: true,
- ...metaModifier,
- });
-
- assert.dom(editor).hasValue(":smile: from keyboard");
- });
-
- test("buttons can be added conditionally", async function (assert) {
- withPluginApi("0", (api) => {
- api.addComposerToolbarPopupMenuOption({
- action: (toolbarEvent) => {
- toolbarEvent.applySurround("**", "**");
- },
- icon: "far-bold",
- label: "some_label",
- condition: (composer) => {
- return composer.model.creatingTopic;
- },
- });
- });
-
- await visit("/t/internationalization-localization/280");
-
- await click(".post-controls button.reply");
- assert.dom(".d-editor-input").exists("the composer input is visible");
-
- const expectedName = "[en.some_label]";
- const dropdown = selectKit(".toolbar-popup-menu-options");
- await dropdown.expand();
-
- assert.false(
- dropdown.rowByName(expectedName).exists(),
- "custom button is not displayed for reply"
- );
-
- await visit("/latest");
- await click("#create-topic");
-
- await dropdown.expand();
- assert.true(
- dropdown.rowByName(expectedName).exists(),
- "custom button is displayed for new topic"
- );
- });
+ }
+ );
});
diff --git a/app/assets/javascripts/discourse/tests/acceptance/flag-post-test.js b/app/assets/javascripts/discourse/tests/acceptance/flag-post-test.js
index ffca7f7ce6c..0c7f6805951 100644
--- a/app/assets/javascripts/discourse/tests/acceptance/flag-post-test.js
+++ b/app/assets/javascripts/discourse/tests/acceptance/flag-post-test.js
@@ -23,189 +23,201 @@ async function pressEnter(selector, modifier) {
});
}
-acceptance("flagging", function (needs) {
- needs.user({ admin: true });
- needs.pretender((server, helper) => {
- server.get("/u/uwe_keim.json", () => {
- return helper.response(userFixtures["/u/charlie.json"]);
- });
- server.get("/admin/users/255.json", () => {
- return helper.response({
- id: 255,
- automatic: false,
- name: "admin",
- username: "admin",
- user_count: 0,
- alias_level: 99,
- visible: true,
- automatic_membership_email_domains: "",
- primary_group: false,
- title: null,
- grant_trust_level: null,
- has_messages: false,
- flair_url: null,
- flair_bg_color: null,
- flair_color: null,
- bio_raw: null,
- bio_cooked: null,
- public_admission: false,
- allow_membership_requests: true,
- membership_request_template: "Please add me",
- can_be_deleted: true,
- can_delete_all_posts: true,
+["enabled", "disabled"].forEach((postStreamMode) => {
+ acceptance(
+ `flagging (glimmer_post_stream_mode = ${postStreamMode})`,
+ function (needs) {
+ needs.settings({
+ glimmer_post_stream_mode: postStreamMode,
});
- });
- server.get("/admin/users/5.json", () => {
- return helper.response({
- id: 5,
- automatic: false,
- name: "user",
- username: "user",
- user_count: 0,
- alias_level: 99,
- visible: true,
- automatic_membership_email_domains: "",
- primary_group: false,
- title: null,
- grant_trust_level: null,
- has_messages: false,
- flair_url: null,
- flair_bg_color: null,
- flair_color: null,
- bio_raw: null,
- bio_cooked: null,
- public_admission: false,
- allow_membership_requests: true,
- membership_request_template: "Please add me",
- full_name: null,
+ needs.user({ admin: true });
+ needs.pretender((server, helper) => {
+ server.get("/u/uwe_keim.json", () => {
+ return helper.response(userFixtures["/u/charlie.json"]);
+ });
+ server.get("/admin/users/255.json", () => {
+ return helper.response({
+ id: 255,
+ automatic: false,
+ name: "admin",
+ username: "admin",
+ user_count: 0,
+ alias_level: 99,
+ visible: true,
+ automatic_membership_email_domains: "",
+ primary_group: false,
+ title: null,
+ grant_trust_level: null,
+ has_messages: false,
+ flair_url: null,
+ flair_bg_color: null,
+ flair_color: null,
+ bio_raw: null,
+ bio_cooked: null,
+ public_admission: false,
+ allow_membership_requests: true,
+ membership_request_template: "Please add me",
+ can_be_deleted: true,
+ can_delete_all_posts: true,
+ });
+ });
+ server.get("/admin/users/5.json", () => {
+ return helper.response({
+ id: 5,
+ automatic: false,
+ name: "user",
+ username: "user",
+ user_count: 0,
+ alias_level: 99,
+ visible: true,
+ automatic_membership_email_domains: "",
+ primary_group: false,
+ title: null,
+ grant_trust_level: null,
+ has_messages: false,
+ flair_url: null,
+ flair_bg_color: null,
+ flair_color: null,
+ bio_raw: null,
+ bio_cooked: null,
+ public_admission: false,
+ allow_membership_requests: true,
+ membership_request_template: "Please add me",
+ full_name: null,
+ });
+ });
+ server.put("/admin/users/5/silence", () => {
+ return helper.response({
+ silenced: true,
+ });
+ });
+ server.post("/post_actions", () => {
+ return helper.response({
+ response: true,
+ });
+ });
});
- });
- server.put("/admin/users/5/silence", () => {
- return helper.response({
- silenced: true,
- });
- });
- server.post("/post_actions", () => {
- return helper.response({
- response: true,
- });
- });
- });
- test("Flag modal opening", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await openFlagModal();
- assert.dom(".flag-modal-body").exists("shows the flag modal");
- });
+ test("Flag modal opening", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await openFlagModal();
+ assert.dom(".flag-modal-body").exists("shows the flag modal");
+ });
- test("Flag take action dropdown exists", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await openFlagModal();
- await click("#radio_inappropriate");
- await selectKit(".reviewable-action-dropdown").expand();
- assert
- .dom("[data-value='agree_and_silence']")
- .exists("it shows the silence action option");
- assert
- .dom("[data-value='agree_and_suspend']")
- .exists("it shows the suspend action option");
- assert
- .dom("[data-value='agree_and_hide']")
- .exists("it shows the hide action option");
- });
+ test("Flag take action dropdown exists", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await openFlagModal();
+ await click("#radio_inappropriate");
+ await selectKit(".reviewable-action-dropdown").expand();
+ assert
+ .dom("[data-value='agree_and_silence']")
+ .exists("it shows the silence action option");
+ assert
+ .dom("[data-value='agree_and_suspend']")
+ .exists("it shows the suspend action option");
+ assert
+ .dom("[data-value='agree_and_hide']")
+ .exists("it shows the hide action option");
+ });
- test("Can silence from take action", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await openFlagModal();
- await click("#radio_inappropriate");
- await selectKit(".reviewable-action-dropdown").expand();
- await click("[data-value='agree_and_silence']");
- assert.dom(".silence-user-modal").exists("shows the silence modal");
- assert.dom(".suspend-message").hasValue("", "penalty message is empty");
- const silenceUntilCombobox = selectKit(".silence-until .combobox");
- await silenceUntilCombobox.expand();
- await silenceUntilCombobox.selectRowByValue("tomorrow");
- assert.dom(".d-modal__body").exists();
- await fillIn("input.silence-reason", "for breaking the rules");
-
- await click(".perform-penalize");
- assert.dom(".d-modal__body").doesNotExist();
- });
+ test("Can silence from take action", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await openFlagModal();
+ await click("#radio_inappropriate");
+ await selectKit(".reviewable-action-dropdown").expand();
+ await click("[data-value='agree_and_silence']");
+ assert.dom(".silence-user-modal").exists("shows the silence modal");
+ assert.dom(".suspend-message").hasValue("", "penalty message is empty");
+ const silenceUntilCombobox = selectKit(".silence-until .combobox");
+ await silenceUntilCombobox.expand();
+ await silenceUntilCombobox.selectRowByValue("tomorrow");
+ assert.dom(".d-modal__body").exists();
+ await fillIn("input.silence-reason", "for breaking the rules");
+
+ await click(".perform-penalize");
+ assert.dom(".d-modal__body").doesNotExist();
+ });
- test("Message appears in penalty modal", async function (assert) {
- this.siteSettings.penalty_include_post_message = true;
- await visit("/t/internationalization-localization/280");
- await openFlagModal();
- await click("#radio_inappropriate");
- await selectKit(".reviewable-action-dropdown").expand();
- await click("[data-value='agree_and_silence']");
- assert.dom(".silence-user-modal").exists("shows the silence modal");
- assert
- .dom(".suspend-message")
- .hasValue(
- "-------------------\n<p>Any plans to support localization of UI elements, so that I (for example) could set up a completely German speaking forum?</p>\n-------------------",
- "penalty message is prefilled with post text"
- );
- });
+ test("Message appears in penalty modal", async function (assert) {
+ this.siteSettings.penalty_include_post_message = true;
+ await visit("/t/internationalization-localization/280");
+ await openFlagModal();
+ await click("#radio_inappropriate");
+ await selectKit(".reviewable-action-dropdown").expand();
+ await click("[data-value='agree_and_silence']");
+ assert.dom(".silence-user-modal").exists("shows the silence modal");
+ assert
+ .dom(".suspend-message")
+ .hasValue(
+ "-------------------\n<p>Any plans to support localization of UI elements, so that I (for example) could set up a completely German speaking forum?</p>\n-------------------",
+ "penalty message is prefilled with post text"
+ );
+ });
- test("Can delete spammer from spam", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await openFlagModal();
- await click("#radio_spam");
+ test("Can delete spammer from spam", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await openFlagModal();
+ await click("#radio_spam");
- assert.dom(".delete-spammer").exists();
- });
+ assert.dom(".delete-spammer").exists();
+ });
- test("Gets dismissable warning from canceling incomplete silence from take action", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await openFlagModal();
- await click("#radio_inappropriate");
- await selectKit(".reviewable-action-dropdown").expand();
- await click("[data-value='agree_and_silence']");
-
- const silenceUntilCombobox = selectKit(".silence-until .combobox");
- await silenceUntilCombobox.expand();
- await silenceUntilCombobox.selectRowByValue("tomorrow");
- await fillIn("input.silence-reason", "for breaking the rules");
- await click(".d-modal-cancel");
- assert.dom(".dialog-body").exists();
-
- await click(".dialog-footer .btn-default");
- assert.dom(".dialog-body").doesNotExist();
- assert.dom(".silence-user-modal").exists("shows the silence modal");
-
- await click(".d-modal-cancel");
- assert.dom(".dialog-body").exists();
-
- await click(".dialog-footer .btn-primary");
- assert.dom(".dialog-body").doesNotExist();
- });
+ test("Gets dismissable warning from canceling incomplete silence from take action", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await openFlagModal();
+ await click("#radio_inappropriate");
+ await selectKit(".reviewable-action-dropdown").expand();
+ await click("[data-value='agree_and_silence']");
+
+ const silenceUntilCombobox = selectKit(".silence-until .combobox");
+ await silenceUntilCombobox.expand();
+ await silenceUntilCombobox.selectRowByValue("tomorrow");
+ await fillIn("input.silence-reason", "for breaking the rules");
+ await click(".d-modal-cancel");
+ assert.dom(".dialog-body").exists();
+
+ await click(".dialog-footer .btn-default");
+ assert.dom(".dialog-body").doesNotExist();
+ assert.dom(".silence-user-modal").exists("shows the silence modal");
+
+ await click(".d-modal-cancel");
+ assert.dom(".dialog-body").exists();
+
+ await click(".dialog-footer .btn-primary");
+ assert.dom(".dialog-body").doesNotExist();
+ });
- test("CTRL + ENTER accepts the modal", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await openFlagModal();
+ test("CTRL + ENTER accepts the modal", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await openFlagModal();
- await pressEnter(".d-modal", "ctrlKey");
- assert
- .dom(".d-modal")
- .exists("The modal wasn't closed because the accept button was disabled");
+ await pressEnter(".d-modal", "ctrlKey");
+ assert
+ .dom(".d-modal")
+ .exists(
+ "The modal wasn't closed because the accept button was disabled"
+ );
- await click("#radio_inappropriate"); // this enables the accept button
- await pressEnter(".d-modal", "ctrlKey");
- assert.dom(".d-modal").doesNotExist("The modal was closed");
- });
+ await click("#radio_inappropriate"); // this enables the accept button
+ await pressEnter(".d-modal", "ctrlKey");
+ assert.dom(".d-modal").doesNotExist("The modal was closed");
+ });
- test("CMD or WINDOWS-KEY + ENTER accepts the modal", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await openFlagModal();
+ test("CMD or WINDOWS-KEY + ENTER accepts the modal", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await openFlagModal();
- await pressEnter(".d-modal", "metaKey");
- assert
- .dom(".d-modal")
- .exists("The modal wasn't closed because the accept button was disabled");
+ await pressEnter(".d-modal", "metaKey");
+ assert
+ .dom(".d-modal")
+ .exists(
+ "The modal wasn't closed because the accept button was disabled"
+ );
- await click("#radio_inappropriate"); // this enables the accept button
- await pressEnter(".d-modal", "ctrlKey");
- assert.dom(".d-modal").doesNotExist("The modal was closed");
- });
+ await click("#radio_inappropriate"); // this enables the accept button
+ await pressEnter(".d-modal", "ctrlKey");
+ assert.dom(".d-modal").doesNotExist("The modal was closed");
+ });
+ }
+ );
});
diff --git a/app/assets/javascripts/discourse/tests/acceptance/page-publishing-test.js b/app/assets/javascripts/discourse/tests/acceptance/page-publishing-test.js
index c162a210ac1..9817a3a2a50 100644
--- a/app/assets/javascripts/discourse/tests/acceptance/page-publishing-test.js
+++ b/app/assets/javascripts/discourse/tests/acceptance/page-publishing-test.js
@@ -2,42 +2,51 @@ import { click, fillIn, visit } from "@ember/test-helpers";
import { test } from "qunit";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
-acceptance("Page Publishing", function (needs) {
- needs.user();
- needs.pretender((server, helper) => {
- const validSlug = helper.response({ valid_slug: true });
+["enabled", "disabled"].forEach((postStreamMode) => {
+ acceptance(
+ `Page Publishing (glimmer_post_stream_mode = ${postStreamMode})`,
+ function (needs) {
+ needs.settings({
+ glimmer_post_stream_mode: postStreamMode,
+ });
+
+ needs.user();
+ needs.pretender((server, helper) => {
+ const validSlug = helper.response({ valid_slug: true });
- server.put("/pub/by-topic/280", () => {
- return helper.response({});
- });
- server.get("/pub/by-topic/280", () => {
- return helper.response({});
- });
- server.get("/pub/check-slug", (req) => {
- if (req.queryParams.slug === "internationalization-localization") {
- return validSlug;
- }
- return helper.response({
- valid_slug: false,
- reason: "i don't need a reason",
+ server.put("/pub/by-topic/280", () => {
+ return helper.response({});
+ });
+ server.get("/pub/by-topic/280", () => {
+ return helper.response({});
+ });
+ server.get("/pub/check-slug", (req) => {
+ if (req.queryParams.slug === "internationalization-localization") {
+ return validSlug;
+ }
+ return helper.response({
+ valid_slug: false,
+ reason: "i don't need a reason",
+ });
+ });
});
- });
- });
- 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(".publish-page");
+ 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(".publish-page");
- await fillIn(".publish-slug", "bad-slug");
- assert.dom(".valid-slug").doesNotExist();
- assert.dom(".invalid-slug").exists();
- await fillIn(".publish-slug", "internationalization-localization");
- assert.dom(".valid-slug").exists();
- assert.dom(".invalid-slug").doesNotExist();
+ await fillIn(".publish-slug", "bad-slug");
+ assert.dom(".valid-slug").doesNotExist();
+ assert.dom(".invalid-slug").exists();
+ await fillIn(".publish-slug", "internationalization-localization");
+ assert.dom(".valid-slug").exists();
+ assert.dom(".invalid-slug").doesNotExist();
- await click(".publish-page");
- assert.dom(".current-url").exists();
- });
+ await click(".publish-page");
+ assert.dom(".current-url").exists();
+ });
+ }
+ );
});
diff --git a/app/assets/javascripts/discourse/tests/acceptance/post-inline-mentions-test.js b/app/assets/javascripts/discourse/tests/acceptance/post-inline-mentions-test.js
index be45048c9cb..891ef1caff7 100644
--- a/app/assets/javascripts/discourse/tests/acceptance/post-inline-mentions-test.js
+++ b/app/assets/javascripts/discourse/tests/acceptance/post-inline-mentions-test.js
@@ -32,6 +32,7 @@ function topicWithUserStatus(topicId, mentionedUserId, status) {
acceptance("Post inline mentions", function (needs) {
needs.user();
+ needs.settings({ enable_user_status: true });
const topicId = 130;
const mentionedUserId = 1;
@@ -132,6 +133,7 @@ acceptance("Post inline mentions", function (needs) {
acceptance("Post inline mentions – user status tooltip", function (needs) {
needs.user();
+ needs.settings({ enable_user_status: true });
const topicId = 130;
const mentionedUserId = 1;
@@ -155,7 +157,7 @@ acceptance("Post inline mentions – user status tooltip", function (needs) {
.dom(".topic-post .cooked .mention .user-status-message")
.exists("user status is shown");
- await mouseMove(".user-status-message");
+ await mouseMove(".topic-post .cooked .mention .user-status-message");
assert
.dom(".user-status-message-tooltip")
@@ -172,7 +174,9 @@ acceptance("Post inline mentions – user status tooltip", function (needs) {
});
});
-acceptance("Post inline mentions as an anonymous user", function () {
+acceptance("Post inline mentions as an anonymous user", function (needs) {
+ needs.settings({ enable_user_status: true });
+
const topicId = 130;
const mentionedUserId = 1;
const status = {
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.js
index b93aeb4bd36..81f9f88a5a3 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
@@ -2,50 +2,60 @@ import { click, find, visit } from "@ember/test-helpers";
import { test } from "qunit";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
-acceptance("Post Table Wrapper Test", function () {
- 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";
- assert
- .dom(`${postWithLargeTable} .fullscreen-table-wrapper`)
- .exists("The wrapper is present on the post with the large table");
-
- assert
- .dom(
- `${postWithLargeTable} .fullscreen-table-wrapper .fullscreen-table-wrapper__buttons .open-popup-link`
- )
- .exists("buttons for the table wrapper appear inside a separate div");
-
- const fullscreenButtonWrapper = find(
- `${postWithLargeTable} .fullscreen-table-wrapper .fullscreen-table-wrapper__buttons`
- );
-
- assert.strictEqual(
- window
- .getComputedStyle(fullscreenButtonWrapper)
- .getPropertyValue("position"),
- "absolute",
- "the wrapper buttons should not be in the cooked post's flow"
- );
-
- await click(
- `${postWithLargeTable} .fullscreen-table-wrapper .btn-expand-table`
- );
-
- assert
- .dom(".fullscreen-table-modal")
- .exists("The fullscreen table modal appears");
- assert
- .dom(".fullscreen-table-modal table")
- .exists("The table is present inside the modal");
-
- await click(".fullscreen-table-modal .modal-close");
- await click(
- `${postWithLargeTable} .fullscreen-table-wrapper .btn-expand-table svg`
- );
-
- assert
- .dom(".fullscreen-table-modal")
- .exists("Fullscreen table modal appears on clicking svg icon");
- });
+["enabled", "disabled"].forEach((postStreamMode) => {
+ acceptance(
+ `Post Table Wrapper Test (glimmer_post_stream_mode = ${postStreamMode})`,
+
+ function (needs) {
+ needs.settings({
+ glimmer_post_stream_mode: postStreamMode,
+ });
+
+ 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";
+ assert
+ .dom(`${postWithLargeTable} .fullscreen-table-wrapper`)
+ .exists("The wrapper is present on the post with the large table");
+
+ assert
+ .dom(
+ `${postWithLargeTable} .fullscreen-table-wrapper .fullscreen-table-wrapper__buttons .open-popup-link`
+ )
+ .exists("buttons for the table wrapper appear inside a separate div");
+
+ const fullscreenButtonWrapper = find(
+ `${postWithLargeTable} .fullscreen-table-wrapper .fullscreen-table-wrapper__buttons`
+ );
+
+ assert.strictEqual(
+ window
+ .getComputedStyle(fullscreenButtonWrapper)
+ .getPropertyValue("position"),
+ "absolute",
+ "the wrapper buttons should not be in the cooked post's flow"
+ );
+
+ await click(
+ `${postWithLargeTable} .fullscreen-table-wrapper .btn-expand-table`
+ );
+
+ assert
+ .dom(".fullscreen-table-modal")
+ .exists("The fullscreen table modal appears");
+ assert
+ .dom(".fullscreen-table-modal table")
+ .exists("The table is present inside the modal");
+
+ await click(".fullscreen-table-modal .modal-close");
+ await click(
+ `${postWithLargeTable} .fullscreen-table-wrapper .btn-expand-table svg`
+ );
+
+ assert
+ .dom(".fullscreen-table-modal")
+ .exists("Fullscreen table modal appears on clicking svg icon");
+ });
+ }
+ );
});
diff --git a/app/assets/javascripts/discourse/tests/acceptance/table-builder-test.js b/app/assets/javascripts/discourse/tests/acceptance/table-builder-test.js
index 5bb9b19c451..bcec9ba7ec8 100644
--- a/app/assets/javascripts/discourse/tests/acceptance/table-builder-test.js
+++ b/app/assets/javascripts/discourse/tests/acceptance/table-builder-test.js
@@ -3,30 +3,38 @@ import { test } from "qunit";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
import selectKit from "discourse/tests/helpers/select-kit-helper";
-acceptance("Table Builder", function (needs) {
- needs.user();
+["enabled", "disabled"].forEach((postStreamMode) => {
+ acceptance(
+ `Table Builder (glimmer_post_stream_mode = ${postStreamMode})`,
+ function (needs) {
+ needs.settings({
+ glimmer_post_stream_mode: postStreamMode,
+ });
+ needs.user();
- test("Can see table builder button when creating a topic", async function (assert) {
- await visit("/");
- await click("#create-topic");
- await click(".d-editor-button-bar .options");
- await selectKit(".toolbar-popup-menu-options").expand();
+ test("Can see table builder button when creating a topic", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+ await click(".d-editor-button-bar .options");
+ await selectKit(".toolbar-popup-menu-options").expand();
- assert
- .dom(`.select-kit-row[data-name='toggle-spreadsheet']`)
- .exists("it shows the builder button");
- });
+ assert
+ .dom(`.select-kit-row[data-name='toggle-spreadsheet']`)
+ .exists("it shows the builder button");
+ });
- test("Can see table builder button when editing post", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click("#post_1 .show-more-actions");
- await click("#post_1 .edit");
- assert.dom("#reply-control").exists();
- await click(".d-editor-button-bar .options");
- await selectKit(".toolbar-popup-menu-options").expand();
+ test("Can see table builder button when editing post", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click("#post_1 .show-more-actions");
+ await click("#post_1 .edit");
+ assert.dom("#reply-control").exists();
+ await click(".d-editor-button-bar .options");
+ await selectKit(".toolbar-popup-menu-options").expand();
- assert
- .dom(`.select-kit-row[data-name='toggle-spreadsheet']`)
- .exists("it shows the builder button");
- });
+ assert
+ .dom(`.select-kit-row[data-name='toggle-spreadsheet']`)
+ .exists("it shows the builder button");
+ });
+ }
+ );
});
diff --git a/app/assets/javascripts/discourse/tests/acceptance/topic-post-decorate-cooked-test.gjs b/app/assets/javascripts/discourse/tests/acceptance/topic-post-decorate-cooked-test.gjs
new file mode 100644
index 00000000000..6b0b4002e12
--- /dev/null
+++ b/app/assets/javascripts/discourse/tests/acceptance/topic-post-decorate-cooked-test.gjs
@@ -0,0 +1,84 @@
+import Component from "@glimmer/component";
+import { setComponentTemplate } from "@ember/component";
+import { visit } from "@ember/test-helpers";
+import { hbs } from "ember-cli-htmlbars";
+import { test } from "qunit";
+import { withPluginApi } from "discourse/lib/plugin-api";
+import { acceptance } from "discourse/tests/helpers/qunit-helpers";
+
+["enabled", "disabled"].forEach((postStreamMode) => {
+ acceptance(
+ `Acceptance | decorateCookedElement (glimmer_post_stream_mode = ${postStreamMode})`,
+ function (needs) {
+ needs.settings({
+ glimmer_post_stream_mode: postStreamMode,
+ });
+
+ test("decorator with renderGlimmer works", async function (assert) {
+ class DemoComponent extends Component {
+ static eventLog = [];
+
+ constructor() {
+ DemoComponent.eventLog.push("created");
+ super(...arguments);
+ }
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ DemoComponent.eventLog.push("willDestroy");
+ }
+ }
+
+ setComponentTemplate(
+ hbs`<span class='glimmer-component-content'>Hello world</span>`,
+ DemoComponent
+ );
+
+ withPluginApi(0, (api) => {
+ api.decorateCookedElement(
+ (cooked, helper) => {
+ if (helper.getModel().post_number !== 1) {
+ return;
+ }
+
+ cooked.innerHTML =
+ "<div class='existing-wrapper'>Some existing content</div>";
+
+ helper.renderGlimmer(
+ cooked,
+ <template><@data.component /></template>,
+ {
+ component: DemoComponent,
+ }
+ );
+
+ // Append to existing element
+ helper.renderGlimmer(
+ cooked.querySelector(".existing-wrapper"),
+ <template>
+ <span>with more content from glimmer</span>
+ </template>
+ );
+ },
+ { onlyStream: true }
+ );
+ });
+
+ await visit("/t/internationalization-localization/280");
+
+ assert.dom("span.glimmer-component-content").exists();
+
+ assert.dom("div.existing-wrapper").exists();
+ assert
+ .dom("div.existing-wrapper span")
+ .hasText("with more content from glimmer");
+
+ assert.deepEqual(DemoComponent.eventLog, ["created"]);
+
+ await visit("/");
+
+ assert.deepEqual(DemoComponent.eventLog, ["created", "willDestroy"]);
+ });
+ }
+ );
+});
diff --git a/app/assets/javascripts/discourse/tests/acceptance/topic-post-decorate-cooked-test.js b/app/assets/javascripts/discourse/tests/acceptance/topic-post-decorate-cooked-test.js
deleted file mode 100644
index d88e58abc3c..00000000000
--- a/app/assets/javascripts/discourse/tests/acceptance/topic-post-decorate-cooked-test.js
+++ /dev/null
@@ -1,73 +0,0 @@
-import Component from "@glimmer/component";
-import { setComponentTemplate } from "@ember/component";
-import { visit } from "@ember/test-helpers";
-import { hbs } from "ember-cli-htmlbars";
-import { test } from "qunit";
-import { withPluginApi } from "discourse/lib/plugin-api";
-import { acceptance } from "discourse/tests/helpers/qunit-helpers";
-
-acceptance("Acceptance | decorateCookedElement", function () {
- test("decorator with renderGlimmer works", async function (assert) {
- class DemoComponent extends Component {
- static eventLog = [];
-
- constructor() {
- DemoComponent.eventLog.push("created");
- super(...arguments);
- }
-
- willDestroy() {
- super.willDestroy(...arguments);
- DemoComponent.eventLog.push("willDestroy");
- }
- }
- setComponentTemplate(
- hbs`<span class='glimmer-component-content'>Hello world</span>`,
- DemoComponent
- );
-
- withPluginApi(0, (api) => {
- api.decorateCookedElement(
- (cooked, helper) => {
- if (helper.getModel().post_number !== 1) {
- return;
- }
- cooked.innerHTML =
- "<div class='existing-wrapper'>Some existing content</div>";
-
- // Create new wrapper element and append
- cooked.appendChild(
- helper.renderGlimmer(
- "div.glimmer-wrapper",
- hbs`<@data.component />`,
- { component: DemoComponent }
- )
- );
-
- // Append to existing element
- helper.renderGlimmer(
- cooked.querySelector(".existing-wrapper"),
- hbs` with more content from glimmer`
- );
- },
- { onlyStream: true }
- );
- });
-
- await visit("/t/internationalization-localization/280");
-
- assert.dom("div.glimmer-wrapper").exists();
- assert.dom("span.glimmer-component-content").exists();
-
- assert.dom("div.existing-wrapper").exists();
- assert
- .dom("div.existing-wrapper")
- .hasText("Some existing content with more content from glimmer");
-
- assert.deepEqual(DemoComponent.eventLog, ["created"]);
-
- await visit("/");
-
- assert.deepEqual(DemoComponent.eventLog, ["created", "willDestroy"]);
- });
-});
diff --git a/app/assets/javascripts/discourse/tests/acceptance/topic-test.js b/app/assets/javascripts/discourse/tests/acceptance/topic-test.js
index 7a9789258f0..07f925c97ce 100644
--- a/app/assets/javascripts/discourse/tests/acceptance/topic-test.js
+++ b/app/assets/javascripts/discourse/tests/acceptance/topic-test.js
@@ -18,604 +18,670 @@ import {
import selectKit from "discourse/tests/helpers/select-kit-helper";
import { i18n } from "discourse-i18n";
-["enabled", "disabled"].forEach((postMenuMode) => {
- acceptance(
- `Topic (glimmer_post_menu_mode = ${postMenuMode})`,
- function (needs) {
- needs.user();
- needs.settings({
- post_menu:
- "read|like|share|flag|edit|bookmark|delete|admin|reply|copyLink",
- glimmer_post_menu_mode: postMenuMode,
- });
- needs.pretender((server, helper) => {
- server.get("/c/2/visible_groups.json", () =>
- helper.response(200, {
- groups: [],
- })
- );
-
- server.get("/c/feature/find_by_slug.json", () => {
- return helper.response(200, CategoryFixtures["/c/1/show.json"]);
- });
- server.put("/posts/398/wiki", () => {
- return helper.response({});
+["enabled", "disabled"].forEach((postStreamMode) => {
+ ["enabled", "disabled"].forEach((postMenuMode) => {
+ acceptance(
+ `Topic (glimmer_post_stream_mode = ${postStreamMode}) (glimmer_post_menu_mode = ${postMenuMode})`,
+ function (needs) {
+ needs.user();
+ needs.settings({
+ post_menu:
+ "read|like|share|flag|edit|bookmark|delete|admin|reply|copyLink",
+ glimmer_post_menu_mode: postMenuMode,
+ glimmer_post_stream_mode: postStreamMode,
});
- });
+ needs.pretender((server, helper) => {
+ server.get("/c/2/visible_groups.json", () =>
+ helper.response(200, {
+ groups: [],
+ })
+ );
- test("Reply as new topic", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click("button.share:nth-of-type(1)");
- await click("button.new-topic");
+ server.get("/c/feature/find_by_slug.json", () => {
+ return helper.response(200, CategoryFixtures["/c/1/show.json"]);
+ });
+ server.put("/posts/398/wiki", () => {
+ return helper.response({});
+ });
+ });
- assert.dom(".d-editor-input").exists("the composer input is visible");
+ test("Reply as new topic", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click("button.share:nth-of-type(1)");
+ await click("button.new-topic");
+
+ assert.dom(".d-editor-input").exists("the composer input is visible");
+
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ `Continuing the discussion from [Internationalization / localization](${window.location.origin}/t/internationalization-localization/280):\n\n`,
+ "fills composer with the ring string"
+ );
+ assert.strictEqual(
+ selectKit(".category-chooser").header().value(),
+ "2",
+ "fills category selector with the right category"
+ );
+ });
- assert
- .dom(".d-editor-input")
- .hasValue(
- `Continuing the discussion from [Internationalization / localization](${window.location.origin}/t/internationalization-localization/280):\n\n`,
- "fills composer with the ring string"
+ test("Reply as new message", async function (assert) {
+ await visit("/t/pm-for-testing/12");
+ await click("button.share:nth-of-type(1)");
+ await click("button.new-topic");
+
+ assert.dom(".d-editor-input").exists("the composer input is visible");
+
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ `Continuing the discussion from [PM for testing](${window.location.origin}/t/pm-for-testing/12):\n\n`,
+ "fills composer with the ring string"
+ );
+
+ const privateMessageUsers = selectKit("#private-message-users");
+ assert.strictEqual(
+ privateMessageUsers.header().value(),
+ "someguy,test,Group",
+ "fills up the composer correctly"
);
- assert.strictEqual(
- selectKit(".category-chooser").header().value(),
- "2",
- "fills category selector with the right category"
- );
- });
+ });
- test("Reply as new message", async function (assert) {
- await visit("/t/pm-for-testing/12");
- await click("button.share:nth-of-type(1)");
- await click("button.new-topic");
+ test("Share Modal", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click(".topic-post:first-child button.share");
- assert.dom(".d-editor-input").exists("the composer input is visible");
+ assert.dom(".share-topic-modal").exists("shows the share modal");
+ });
- assert
- .dom(".d-editor-input")
- .hasValue(
- `Continuing the discussion from [PM for testing](${window.location.origin}/t/pm-for-testing/12):\n\n`,
- "fills composer with the ring string"
+ 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"
);
- const privateMessageUsers = selectKit("#private-message-users");
- assert.strictEqual(
- privateMessageUsers.header().value(),
- "someguy,test,Group",
- "fills up the composer correctly"
- );
- });
+ assert
+ .dom(".post-action-menu__copy-link-checkmark")
+ .exists("shows the Link Copied! message");
+ });
- test("Share Modal", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click(".topic-post:first-child button.share");
+ test("Showing and hiding the edit controls", async function (assert) {
+ await visit("/t/internationalization-localization/280");
- assert.dom(".share-topic-modal").exists("shows the share modal");
- });
+ await click("#topic-title .d-icon-pencil");
- 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"
- );
+ assert.dom("#edit-title").exists("shows the editing controls");
+ assert
+ .dom(".title-wrapper .remove-featured-link")
+ .doesNotExist("link to remove featured link is not shown");
- assert
- .dom(".post-action-menu__copy-link-checkmark")
- .exists("shows the Link Copied! message");
- });
+ await fillIn("#edit-title", "this is the new title");
+ await click("#topic-title .cancel-edit");
+ assert.dom("#edit-title").doesNotExist("hides the editing controls");
+ });
- test("Showing and hiding the edit controls", async function (assert) {
- await visit("/t/internationalization-localization/280");
+ test("Updating the topic title and category", async function (assert) {
+ const categoryChooser = selectKit(".title-wrapper .category-chooser");
- await click("#topic-title .d-icon-pencil");
+ await visit("/t/internationalization-localization/280");
- assert.dom("#edit-title").exists("shows the editing controls");
- assert
- .dom(".title-wrapper .remove-featured-link")
- .doesNotExist("link to remove featured link is not shown");
+ await click("#topic-title .d-icon-pencil");
+ await fillIn("#edit-title", "this is the new title");
+ await categoryChooser.expand();
+ await categoryChooser.selectRowByValue(4);
+ await click("#topic-title .submit-edit");
- await fillIn("#edit-title", "this is the new title");
- await click("#topic-title .cancel-edit");
- assert.dom("#edit-title").doesNotExist("hides the editing controls");
- });
+ assert
+ .dom("#topic-title .badge-category")
+ .hasText("faq", "displays the new category");
+ assert
+ .dom(".fancy-title")
+ .hasText("this is the new title", "displays the new title");
+ });
- test("Updating the topic title and category", async function (assert) {
- const categoryChooser = selectKit(".title-wrapper .category-chooser");
+ test("Marking a topic as wiki", async function (assert) {
+ await visit("/t/internationalization-localization/280");
- await visit("/t/internationalization-localization/280");
+ assert.dom("a.wiki").doesNotExist("does not show the wiki icon");
- await click("#topic-title .d-icon-pencil");
- await fillIn("#edit-title", "this is the new title");
- await categoryChooser.expand();
- await categoryChooser.selectRowByValue(4);
- await click("#topic-title .submit-edit");
+ 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(".btn.wiki");
- assert
- .dom("#topic-title .badge-category")
- .hasText("faq", "displays the new category");
- assert
- .dom(".fancy-title")
- .hasText("this is the new title", "displays the new title");
- });
+ assert.dom("button.wiki").exists("shows the wiki icon");
+ });
- test("Marking a topic as wiki", async function (assert) {
- await visit("/t/internationalization-localization/280");
+ test("Visit topic routes", async function (assert) {
+ await visit("/t/12");
- assert.dom("a.wiki").doesNotExist("does not show the wiki icon");
+ assert
+ .dom(".fancy-title")
+ .hasText("PM for testing", "routes to the right topic");
- 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(".btn.wiki");
+ await visit("/t/280/20");
- assert.dom("button.wiki").exists("shows the wiki icon");
- });
+ assert
+ .dom(".fancy-title")
+ .hasText(
+ "Internationalization / localization",
+ "routes to the right topic"
+ );
+ });
- test("Visit topic routes", async function (assert) {
- await visit("/t/12");
+ test("Updating the topic title with emojis", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click("#topic-title .d-icon-pencil");
- assert
- .dom(".fancy-title")
- .hasText("PM for testing", "routes to the right topic");
+ await fillIn("#edit-title", "emojis title :bike: :blonde_woman:t6:");
- await visit("/t/280/20");
+ await click("#topic-title .submit-edit");
- assert
- .dom(".fancy-title")
- .hasText(
- "Internationalization / localization",
- "routes to the right topic"
- );
- });
+ assert
+ .dom(".fancy-title")
+ .includesHtml("bike.png", "displays the new title with emojis");
+ });
- test("Updating the topic title with emojis", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click("#topic-title .d-icon-pencil");
+ test("Updating the topic title with unicode emojis", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click("#topic-title .d-icon-pencil");
- await fillIn("#edit-title", "emojis title :bike: :blonde_woman:t6:");
+ await fillIn("#edit-title", "emojis title 👨‍🌾🙏");
- await click("#topic-title .submit-edit");
+ await click("#topic-title .submit-edit");
- assert
- .dom(".fancy-title")
- .includesHtml("bike.png", "displays the new title with emojis");
- });
+ assert
+ .dom(".fancy-title")
+ .includesHtml(
+ "man_farmer.png",
+ "displays the new title with emojis"
+ );
+ });
- test("Updating the topic title with unicode emojis", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click("#topic-title .d-icon-pencil");
+ test("Updating the topic title with unicode emojis without whitespace", async function (assert) {
+ this.siteSettings.enable_inline_emoji_translation = true;
+ await visit("/t/internationalization-localization/280");
+ await click("#topic-title .d-icon-pencil");
- await fillIn("#edit-title", "emojis title 👨‍🌾🙏");
+ await fillIn("#edit-title", "Test🙂Title");
- await click("#topic-title .submit-edit");
+ await click("#topic-title .submit-edit");
- assert
- .dom(".fancy-title")
- .includesHtml("man_farmer.png", "displays the new title with emojis");
- });
+ assert
+ .dom(".fancy-title")
+ .includesHtml(
+ "slightly_smiling_face.png",
+ "displays the new title with emojis"
+ );
+ });
- test("Updating the topic title with unicode emojis without whitespace", async function (assert) {
- this.siteSettings.enable_inline_emoji_translation = true;
- await visit("/t/internationalization-localization/280");
- await click("#topic-title .d-icon-pencil");
+ test("Suggested topics", async function (assert) {
+ await visit("/t/internationalization-localization/280");
- await fillIn("#edit-title", "Test🙂Title");
+ assert
+ .dom("#suggested-topics-title")
+ .hasText(i18n("suggested_topics.title"));
+ });
- await click("#topic-title .submit-edit");
+ 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(".toggle-admin-menu");
+ assert.dom(".topic-admin-recover").exists("shows the recover button");
+ });
- assert
- .dom(".fancy-title")
- .includesHtml(
- "slightly_smiling_face.png",
- "displays the new title with emojis"
- );
- });
+ 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");
+ assert
+ .dom(".delete-topic-confirm-modal")
+ .exists("shows the delete confirmation modal");
+
+ await click(".delete-topic-confirm-modal .btn-primary");
+ assert
+ .dom(".delete-topic-confirm-modal")
+ .doesNotExist("hides the delete confirmation modal");
+ await click(".topic-post:nth-of-type(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");
+ });
- test("Suggested topics", async function (assert) {
- await visit("/t/internationalization-localization/280");
+ test("Group category moderator posts", async function (assert) {
+ await visit("/t/topic-for-group-moderators/2480");
- assert
- .dom("#suggested-topics-title")
- .hasText(i18n("suggested_topics.title"));
- });
+ assert.dom(".category-moderator").exists("has a class applied");
+ assert.dom(".d-icon-shield-halved").exists("shows an icon");
+ });
- 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(".toggle-admin-menu");
- assert.dom(".topic-admin-recover").exists("shows the recover button");
- });
+ test("Suspended user posts", async function (assert) {
+ await visit("/t/topic-from-suspended-user/54077");
- 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");
- assert
- .dom(".delete-topic-confirm-modal")
- .exists("shows the delete confirmation modal");
+ assert
+ .dom(".topic-post.user-suspended > #post_1")
+ .exists("has a class applied");
+ });
+ }
+ );
+ });
- await click(".delete-topic-confirm-modal .btn-primary");
- assert
- .dom(".delete-topic-confirm-modal")
- .doesNotExist("hides the delete confirmation modal");
- await click(".topic-post:nth-of-type(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");
+ acceptance(
+ `Topic featured links (glimmer_post_stream_mode = ${postStreamMode})`,
+ function (needs) {
+ needs.user();
+ needs.settings({
+ topic_featured_link_enabled: true,
+ max_topic_title_length: 80,
+ exclude_rel_nofollow_domains: "example.com",
+ display_name_on_posts: false,
+ prioritize_username_in_ux: true,
+ glimmer_post_stream_mode: postStreamMode,
+ });
+ needs.pretender((server, helper) => {
+ server.get("/inline-onebox", () => {
+ return helper.response({ "inline-oneboxes": [] });
+ });
});
- test("Group category moderator posts", async function (assert) {
- await visit("/t/topic-for-group-moderators/2480");
+ test("remove nofollow attribute", async function (assert) {
+ await visit("/t/-/299/1");
- assert.dom(".category-moderator").exists("has a class applied");
- assert.dom(".d-icon-shield-halved").exists("shows an icon");
+ assert
+ .dom(".title-wrapper .topic-featured-link")
+ .hasText("example.com");
+ assert
+ .dom(".title-wrapper .topic-featured-link")
+ .hasAttribute("rel", "ugc");
});
- test("Suspended user posts", async function (assert) {
- await visit("/t/topic-from-suspended-user/54077");
+ test("remove featured link", async function (assert) {
+ await visit("/t/-/299/1");
+ assert
+ .dom(".title-wrapper .topic-featured-link")
+ .exists("link is shown with topic title");
+ await click(".title-wrapper .edit-topic");
assert
- .dom(".topic-post.user-suspended > #post_1")
- .exists("has a class applied");
+ .dom(".title-wrapper .remove-featured-link")
+ .exists("link to remove featured link");
});
- }
- );
-});
-
-acceptance("Topic featured links", function (needs) {
- needs.user();
- needs.settings({
- topic_featured_link_enabled: true,
- max_topic_title_length: 80,
- exclude_rel_nofollow_domains: "example.com",
- display_name_on_posts: false,
- prioritize_username_in_ux: true,
- });
- needs.pretender((server, helper) => {
- server.get("/inline-onebox", () => {
- return helper.response({ "inline-oneboxes": [] });
- });
- });
- test("remove nofollow attribute", async function (assert) {
- await visit("/t/-/299/1");
+ test("Converting to a public topic", async function (assert) {
+ await visit("/t/test-pm/34");
+ assert.dom(".private_message").exists();
+ await click(".toggle-admin-menu");
+ await click(".topic-admin-convert button");
- assert.dom(".title-wrapper .topic-featured-link").hasText("example.com");
- assert
- .dom(".title-wrapper .topic-featured-link")
- .hasAttribute("rel", "ugc");
- });
+ let categoryChooser = selectKit(
+ ".convert-to-public-topic .category-chooser"
+ );
+ await categoryChooser.expand();
+ await categoryChooser.selectRowByValue(21);
- test("remove featured link", async function (assert) {
- await visit("/t/-/299/1");
- assert
- .dom(".title-wrapper .topic-featured-link")
- .exists("link is shown with topic title");
+ await click(".convert-to-public-topic .btn-primary");
+ assert.dom(".private_message").doesNotExist();
+ });
- await click(".title-wrapper .edit-topic");
- assert
- .dom(".title-wrapper .remove-featured-link")
- .exists("link to remove featured link");
- });
+ test("Unpinning unlisted topic", async function (assert) {
+ await visit("/t/internationalization-localization/280");
- test("Converting to a public topic", async function (assert) {
- await visit("/t/test-pm/34");
- assert.dom(".private_message").exists();
- await click(".toggle-admin-menu");
- await click(".topic-admin-convert button");
+ await click(".toggle-admin-menu");
+ await click(".topic-admin-pin .btn");
+ await click(".make-banner");
- let categoryChooser = selectKit(
- ".convert-to-public-topic .category-chooser"
- );
- await categoryChooser.expand();
- await categoryChooser.selectRowByValue(21);
+ await click(".toggle-admin-menu");
+ await click(".topic-admin-visible .btn");
- await click(".convert-to-public-topic .btn-primary");
- assert.dom(".private_message").doesNotExist();
- });
+ await click(".toggle-admin-menu");
+ assert
+ .dom(".topic-admin-pin")
+ .exists("should show the multi select menu");
+ });
- test("Unpinning unlisted topic", async function (assert) {
- await visit("/t/internationalization-localization/280");
+ test("selecting posts", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click(".toggle-admin-menu");
+ await click(".topic-admin-multi-select .btn");
- await click(".toggle-admin-menu");
- await click(".topic-admin-pin .btn");
- await click(".make-banner");
+ assert
+ .dom(".selected-posts:not(.hidden)")
+ .exists("should show the multi select menu");
- await click(".toggle-admin-menu");
- await click(".topic-admin-visible .btn");
+ assert
+ .dom(".select-all")
+ .exists("should allow users to select all the posts");
+ });
- await click(".toggle-admin-menu");
- assert.dom(".topic-admin-pin").exists("should show the multi select menu");
- });
+ test("select below", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click(".toggle-admin-menu");
+ await click(".topic-admin-multi-select .btn");
+ await click("#post_3 .select-below");
- test("selecting posts", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click(".toggle-admin-menu");
- await click(".topic-admin-multi-select .btn");
+ assert
+ .dom(".selected-posts")
+ .includesHtml(
+ i18n("topic.multi_select.description", { count: 18 }),
+ "selects the right number of posts"
+ );
- assert
- .dom(".selected-posts:not(.hidden)")
- .exists("should show the multi select menu");
+ await click("#post_2 .select-below");
- assert
- .dom(".select-all")
- .exists("should allow users to select all the posts");
- });
+ assert
+ .dom(".selected-posts")
+ .includesHtml(
+ i18n("topic.multi_select.description", { count: 19 }),
+ "selects the right number of posts"
+ );
+ });
- test("select below", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click(".toggle-admin-menu");
- await click(".topic-admin-multi-select .btn");
- await click("#post_3 .select-below");
-
- assert
- .dom(".selected-posts")
- .includesHtml(
- i18n("topic.multi_select.description", { count: 18 }),
- "selects the right number of posts"
- );
+ test("View Hidden Replies", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click(".gap");
- await click("#post_2 .select-below");
+ assert.dom(".gap").doesNotExist("hides gap");
+ });
- assert
- .dom(".selected-posts")
- .includesHtml(
- i18n("topic.multi_select.description", { count: 19 }),
- "selects the right number of posts"
- );
- });
+ test("Quoting a quote keeps the original poster name", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await selectText("#post_5 blockquote");
+ await click(".quote-button .insert-quote");
- test("View Hidden Replies", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click(".gap");
+ assert
+ .dom(".d-editor-input")
+ .includesValue('quote="codinghorror said, post:3, topic:280"');
+ });
- assert.dom(".gap").doesNotExist("hides gap");
- });
+ test("Quoting a quote of a different topic keeps the original topic title", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await selectText("#post_9 blockquote");
+ await click(".quote-button .insert-quote");
- test("Quoting a quote keeps the original poster name", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await selectText("#post_5 blockquote");
- await click(".quote-button .insert-quote");
+ assert
+ .dom(".d-editor-input")
+ .includesValue(
+ 'quote="A new topic with a link to another topic, post:3, topic:62"'
+ );
+ });
- assert
- .dom(".d-editor-input")
- .includesValue('quote="codinghorror said, post:3, topic:280"');
- });
+ test("Quoting a quote with the Reply button keeps the original poster name", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await selectText("#post_5 blockquote");
+ await click(".reply");
- test("Quoting a quote of a different topic keeps the original topic title", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await selectText("#post_9 blockquote");
- await click(".quote-button .insert-quote");
+ assert
+ .dom(".d-editor-input")
+ .includesValue('quote="codinghorror said, post:3, topic:280"');
+ });
- assert
- .dom(".d-editor-input")
- .includesValue(
- 'quote="A new topic with a link to another topic, post:3, topic:62"'
+ // Using J/K on Firefox clean the text selection, so this won't work there
+ chromeTest(
+ "Quoting a quote with replyAsNewTopic keeps the original poster name",
+ async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await selectText("#post_5 blockquote");
+ await triggerKeyEvent(document, "keypress", "J");
+ await triggerKeyEvent(document, "keypress", "T");
+
+ assert
+ .dom(".d-editor-input")
+ .includesValue('quote="codinghorror said, post:3, topic:280"');
+ }
);
- });
- test("Quoting a quote with the Reply button keeps the original poster name", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await selectText("#post_5 blockquote");
- await click(".reply");
+ test("Quoting by selecting text can mark the quote as full", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await selectText("#post_5 .cooked");
+ await click(".quote-button .insert-quote");
+ assert
+ .dom(".d-editor-input")
+ .includesValue('quote="pekka, post:5, topic:280, full:true"');
+ });
+ }
+ );
+
+ acceptance(
+ `Topic featured links (glimmer_post_stream_mode = ${postStreamMode})`,
+ function (needs) {
+ needs.user();
+ needs.settings({
+ topic_featured_link_enabled: true,
+ max_topic_title_length: 80,
+ glimmer_post_stream_mode: postStreamMode,
+ });
- assert
- .dom(".d-editor-input")
- .includesValue('quote="codinghorror said, post:3, topic:280"');
- });
+ test("remove featured link", async function (assert) {
+ await visit("/t/-/299/1");
+ assert
+ .dom(".title-wrapper .topic-featured-link")
+ .exists("link is shown with topic title");
- // Using J/K on Firefox clean the text selection, so this won't work there
- chromeTest(
- "Quoting a quote with replyAsNewTopic keeps the original poster name",
- async function (assert) {
- await visit("/t/internationalization-localization/280");
- await selectText("#post_5 blockquote");
- await triggerKeyEvent(document, "keypress", "J");
- await triggerKeyEvent(document, "keypress", "T");
-
- assert
- .dom(".d-editor-input")
- .includesValue('quote="codinghorror said, post:3, topic:280"');
+ await click(".title-wrapper .edit-topic");
+ assert
+ .dom(".title-wrapper .remove-featured-link")
+ .exists("link to remove featured link");
+ });
}
);
- test("Quoting by selecting text can mark the quote as full", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await selectText("#post_5 .cooked");
- await click(".quote-button .insert-quote");
- assert
- .dom(".d-editor-input")
- .includesValue('quote="pekka, post:5, topic:280, full:true"');
- });
-});
+ acceptance(
+ `Topic pinning/unpinning as an admin (glimmer_post_stream_mode = ${postStreamMode})`,
+ function (needs) {
+ needs.user({ admin: true });
+ needs.settings({
+ glimmer_post_stream_mode: postStreamMode,
+ });
-acceptance("Topic featured links", function (needs) {
- needs.user();
- needs.settings({
- topic_featured_link_enabled: true,
- max_topic_title_length: 80,
- });
+ test("Admin pinning topic", async function (assert) {
+ await visit("/t/topic-for-group-moderators/2480");
- test("remove featured link", async function (assert) {
- await visit("/t/-/299/1");
- assert
- .dom(".title-wrapper .topic-featured-link")
- .exists("link is shown with topic title");
+ await click(".toggle-admin-menu");
+ await click(".topic-admin-pin .btn");
- await click(".title-wrapper .edit-topic");
- assert
- .dom(".title-wrapper .remove-featured-link")
- .exists("link to remove featured link");
- });
-});
+ assert
+ .dom(".feature-topic .btn-primary")
+ .exists("should show the 'Pin Topic' button");
-acceptance("Topic pinning/unpinning as an admin", function (needs) {
- needs.user({ admin: true });
+ assert
+ .dom(".make-banner")
+ .exists("should show the 'Banner Topic' button");
+ });
+ }
+ );
- test("Admin pinning topic", async function (assert) {
- await visit("/t/topic-for-group-moderators/2480");
+ acceptance(
+ `Topic pinning/unpinning as a staff member (glimmer_post_stream_mode = ${postStreamMode})`,
+ function (needs) {
+ needs.user({ moderator: true, admin: false, trust_level: 2 });
+ needs.settings({
+ glimmer_post_stream_mode: postStreamMode,
+ });
- await click(".toggle-admin-menu");
- await click(".topic-admin-pin .btn");
+ test("Staff pinning topic", async function (assert) {
+ await visit("/t/topic-for-group-moderators/2480");
- assert
- .dom(".feature-topic .btn-primary")
- .exists("should show the 'Pin Topic' button");
+ await click(".toggle-admin-menu");
+ await click(".topic-admin-pin .btn");
- assert.dom(".make-banner").exists("should show the 'Banner Topic' button");
- });
-});
+ assert
+ .dom(".feature-topic .btn-primary")
+ .exists("should show the 'Pin Topic' button");
-acceptance("Topic pinning/unpinning as a staff member", function (needs) {
- needs.user({ moderator: true, admin: false, trust_level: 2 });
+ assert
+ .dom(".make-banner")
+ .exists("should show the 'Banner Topic' button");
+ });
+ }
+ );
- test("Staff pinning topic", async function (assert) {
- await visit("/t/topic-for-group-moderators/2480");
+ acceptance(
+ `Topic pinning/unpinning as a group moderator (glimmer_post_stream_mode = ${postStreamMode})`,
+ function (needs) {
+ needs.user({ moderator: false, admin: false, trust_level: 1 });
+ needs.settings({
+ glimmer_post_stream_mode: postStreamMode,
+ });
- await click(".toggle-admin-menu");
- await click(".topic-admin-pin .btn");
+ test("Group category moderator pinning topic", async function (assert) {
+ await visit("/t/topic-for-group-moderators/2480");
- assert
- .dom(".feature-topic .btn-primary")
- .exists("should show the 'Pin Topic' button");
+ await click(".toggle-admin-menu");
+ await click(".topic-admin-pin .btn");
- assert.dom(".make-banner").exists("should show the 'Banner Topic' button");
- });
-});
+ assert
+ .dom(".feature-topic .btn-primary")
+ .exists("should show the 'Pin Topic' button");
-acceptance("Topic pinning/unpinning as a group moderator", function (needs) {
- needs.user({ moderator: false, admin: false, trust_level: 1 });
+ assert
+ .dom(".make-banner")
+ .doesNotExist("should not show the 'Banner Topic' button");
+ });
+ }
+ );
- test("Group category moderator pinning topic", async function (assert) {
- await visit("/t/topic-for-group-moderators/2480");
+ acceptance(
+ `Topic last visit line (glimmer_post_stream_mode = ${postStreamMode})`,
+ function (needs) {
+ needs.user({ moderator: false, admin: false, trust_level: 1 });
+ needs.settings({
+ glimmer_post_stream_mode: postStreamMode,
+ });
- await click(".toggle-admin-menu");
- await click(".topic-admin-pin .btn");
+ test("visit topic", async function (assert) {
+ await visit("/t/-/280");
- assert
- .dom(".feature-topic .btn-primary")
- .exists("should show the 'Pin Topic' button");
+ assert
+ .dom(".topic-post-visited-line.post-10")
+ .exists("shows the last visited line on the right post");
- assert
- .dom(".make-banner")
- .doesNotExist("should not show the 'Banner Topic' button");
- });
-});
+ await visit("/t/-/9");
-acceptance("Topic last visit line", function (needs) {
- needs.user({ moderator: false, admin: false, trust_level: 1 });
+ assert
+ .dom(".topic-post-visited-line")
+ .doesNotExist(
+ "does not show last visited line if post is the last post"
+ );
+ });
+ }
+ );
- test("visit topic", async function (assert) {
- await visit("/t/-/280");
+ acceptance(
+ `Topic filter replies to post number (glimmer_post_stream_mode = ${postStreamMode})`,
+ function (needs) {
+ needs.settings({
+ enable_filtered_replies_view: true,
+ glimmer_post_stream_mode: postStreamMode,
+ });
- assert
- .dom(".topic-post-visited-line.post-10")
- .exists("shows the last visited line on the right post");
+ test("visit topic", async function (assert) {
+ await visit("/t/-/280");
- await visit("/t/-/9");
+ assert
+ .dom("#post_3 .show-replies")
+ .hasAttribute(
+ "title",
+ i18n("post.filtered_replies_hint", { count: 3 }),
+ "displays the right title for filtering by replies"
+ );
- assert
- .dom(".topic-post-visited-line")
- .doesNotExist("does not show last visited line if post is the last post");
- });
-});
+ await visit("/");
+ await visit("/t/-/280?replies_to_post_number=3");
-acceptance("Topic filter replies to post number", function (needs) {
- needs.settings({
- enable_filtered_replies_view: true,
- });
+ assert
+ .dom("#post_3 .show-replies")
+ .hasAttribute(
+ "title",
+ i18n("post.view_all_posts"),
+ "displays the right title when filtered by replies"
+ );
+ });
+ }
+ );
- test("visit topic", async function (assert) {
- await visit("/t/-/280");
+ acceptance(
+ `Navigating between topics (glimmer_post_stream_mode = ${postStreamMode})`,
+ function (needs) {
+ needs.settings({
+ glimmer_post_stream_mode: postStreamMode,
+ });
- assert
- .dom("#post_3 .show-replies")
- .hasAttribute(
- "title",
- i18n("post.filtered_replies_hint", { count: 3 }),
- "displays the right title for filtering by replies"
- );
+ needs.pretender((server, helper) => {
+ const topicResponse = cloneJSON(topicFixtures["/t/280/1.json"]);
+ const firstPost = topicResponse.post_stream.posts[0];
+ firstPost.cooked += `\n<a class='same-topic-slugless' href='/t/280'>Link 1</a>`;
+ firstPost.cooked += `\n<a class='same-topic-slugless-post' href='/t/280/3'>Link 2</a>`;
+ firstPost.cooked += `\n<a class='diff-topic-slugless' href='/t/28830'>Link 3</a>`;
+ firstPost.cooked += `\n<a class='diff-topic-slugless-post' href='/t/28830/1'>Link 4</a>`;
+ firstPost.cooked += `\n<a class='by-post-id' href='/p/${firstPost.id}'>Link to Post</a>`;
+
+ server.get("/t/280.json", () => helper.response(topicResponse));
+ server.get("/t/280/:post_number.json", () =>
+ helper.response(topicResponse)
+ );
+ });
- await visit("/");
- await visit("/t/-/280?replies_to_post_number=3");
+ test("clicking slug-less URLs within the same topic", async function (assert) {
+ await visit("/t/-/280");
+ await click("a.same-topic-slugless");
+ assert.true(currentURL().includes("/280"));
- assert
- .dom("#post_3 .show-replies")
- .hasAttribute(
- "title",
- i18n("post.view_all_posts"),
- "displays the right title when filtered by replies"
- );
- });
-});
+ await click("a.same-topic-slugless-post");
+ assert.true(currentURL().includes("/280"));
+ });
-acceptance("Navigating between topics", function (needs) {
- needs.pretender((server, helper) => {
- const topicResponse = cloneJSON(topicFixtures["/t/280/1.json"]);
- const firstPost = topicResponse.post_stream.posts[0];
- firstPost.cooked += `\n<a class='same-topic-slugless' href='/t/280'>Link 1</a>`;
- firstPost.cooked += `\n<a class='same-topic-slugless-post' href='/t/280/3'>Link 2</a>`;
- firstPost.cooked += `\n<a class='diff-topic-slugless' href='/t/28830'>Link 3</a>`;
- firstPost.cooked += `\n<a class='diff-topic-slugless-post' href='/t/28830/1'>Link 4</a>`;
- firstPost.cooked += `\n<a class='by-post-id' href='/p/${firstPost.id}'>Link to Post</a>`;
-
- server.get("/t/280.json", () => helper.response(topicResponse));
- server.get("/t/280/:post_number.json", () =>
- helper.response(topicResponse)
- );
- });
+ test("clicking slug-less URLs to a different topic", async function (assert) {
+ await visit("/t/-/280");
+ await click("a.diff-topic-slugless");
+ assert.true(currentURL().includes("/28830"));
- test("clicking slug-less URLs within the same topic", async function (assert) {
- await visit("/t/-/280");
- await click("a.same-topic-slugless");
- assert.true(currentURL().includes("/280"));
+ await visit("/t/-/280");
+ await click("a.diff-topic-slugless-post");
+ assert.true(currentURL().includes("/28830"));
+ });
- await click("a.same-topic-slugless-post");
- assert.true(currentURL().includes("/280"));
- });
+ test("clicking post URLs", async function (assert) {
+ await visit("/t/-/280");
+ await click("a.by-post-id");
+ assert.true(currentURL().includes("/280"));
+ });
+ }
+ );
- test("clicking slug-less URLs to a different topic", async function (assert) {
- await visit("/t/-/280");
- await click("a.diff-topic-slugless");
- assert.true(currentURL().includes("/28830"));
+ acceptance(
+ `Topic stats update automatically (glimmer_post_stream_mode = ${postStreamMode})`,
+ function (needs) {
+ needs.settings({
+ glimmer_post_stream_mode: postStreamMode,
+ });
- await visit("/t/-/280");
- await click("a.diff-topic-slugless-post");
- assert.true(currentURL().includes("/28830"));
- });
+ test("Likes count updates automatically", async function (assert) {
+ await visit("/t/internationalization-localization/280");
- test("clicking post URLs", async function (assert) {
- await visit("/t/-/280");
- await click("a.by-post-id");
- assert.true(currentURL().includes("/280"));
- });
-});
+ const oldLikesCount = document.querySelector(
+ "#post_1 .topic-map .topic-map__likes-trigger .number"
+ ).textContent;
+ const likesChangedFixture = {
+ id: 280,
+ type: "stats",
+ like_count: parseInt(oldLikesCount, 10) + 42,
+ };
+ const expectedLikesCount = likesChangedFixture.like_count.toString();
-acceptance("Topic stats update automatically", function () {
- test("Likes count updates automatically", async function (assert) {
- await visit("/t/internationalization-localization/280");
-
- const oldLikesCount = document.querySelector(
- "#post_1 .topic-map .topic-map__likes-trigger .number"
- ).textContent;
- const likesChangedFixture = {
- id: 280,
- type: "stats",
- like_count: parseInt(oldLikesCount, 10) + 42,
- };
- const expectedLikesCount = likesChangedFixture.like_count.toString();
-
- // simulate the topic like_count being changed
- await publishToMessageBus("/topic/280", likesChangedFixture);
-
- assert
- .dom("#post_1 .topic-map .topic-map__likes-trigger .number")
- .hasText(expectedLikesCount);
- assert.notStrictEqual(
- oldLikesCount,
- expectedLikesCount,
- "updates the likes count on the topic stats"
- );
- });
+ // simulate the topic like_count being changed
+ await publishToMessageBus("/topic/280", likesChangedFixture);
+
+ assert
+ .dom("#post_1 .topic-map .topic-map__likes-trigger .number")
+ .hasText(expectedLikesCount);
+ assert.notStrictEqual(
+ oldLikesCount,
+ expectedLikesCount,
+ "updates the likes count on the topic stats"
+ );
+ });
+ }
+ );
});
diff --git a/app/assets/javascripts/discourse/tests/helpers/qunit-helpers.js b/app/assets/javascripts/discourse/tests/helpers/qunit-helpers.js
index 31b8ae47f71..1dc60f98dd7 100644
--- a/app/assets/javascripts/discourse/tests/helpers/qunit-helpers.js
+++ b/app/assets/javascripts/discourse/tests/helpers/qunit-helpers.js
@@ -26,6 +26,7 @@ import { clearExtraHeaderIcons as clearExtraGlimmerHeaderIcons } from "discourse
import { clearRegisteredTabs } from "discourse/components/more-topics";
import { resetWidgetCleanCallbacks } from "discourse/components/mount-widget";
import { resetDecorators as resetPluginOutletDecorators } from "discourse/components/plugin-connector";
+import { resetGroupPostSmallActionCodes } from "discourse/components/post/small-action";
import { resetItemSelectCallbacks } from "discourse/components/search-menu/results/assistant-item";
import { resetQuickSearchRandomTips } from "discourse/components/search-menu/results/random-quick-tip";
import { resetOnKeyUpCallbacks } from "discourse/components/search-menu/search-term";
@@ -99,8 +100,10 @@ import {
currentSettings,
mergeSettings,
} from "discourse/tests/helpers/site-settings";
+import { resetPostClassesCallback } from "discourse/widgets/post";
import { resetDecorators as resetPostCookedDecorators } from "discourse/widgets/post-cooked";
import { resetPostMenuExtraButtons } from "discourse/widgets/post-menu";
+import { resetPostSmallActionClassesCallbacks } from "discourse/widgets/post-small-action";
import { resetDecorators } from "discourse/widgets/widget";
import I18n from "discourse-i18n";
import { _clearSnapshots } from "select-kit/components/composer-actions";
@@ -269,6 +272,9 @@ export function testCleanup(container, app) {
clearRegisteredTabs();
resetNeedsHbrTopicList();
clearAddedTrackedPostProperties();
+ resetGroupPostSmallActionCodes();
+ resetPostSmallActionClassesCallbacks();
+ resetPostClassesCallback();
}
function cleanupCssGeneratorTags() {
diff --git a/app/assets/javascripts/discourse/tests/integration/components/post/actions-summary-test.gjs b/app/assets/javascripts/discourse/tests/integration/components/post/actions-summary-test.gjs
new file mode 100644
index 00000000000..039bbca9587
--- /dev/null
+++ b/app/assets/javascripts/discourse/tests/integration/components/post/actions-summary-test.gjs
@@ -0,0 +1,56 @@
+import { getOwner } from "@ember/owner";
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import PostActionsSummary from "discourse/components/post/actions-summary";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+
+function renderComponent(post) {
+ return render(<template><PostActionsSummary @post={{post}} /></template>);
+}
+
+module("Integration | Component | Post | PostActionsSummary", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.siteSettings.glimmer_post_stream_mode = "enabled";
+
+ const store = getOwner(this).lookup("service:store");
+ const topic = store.createRecord("topic", { id: 1 });
+ const post = store.createRecord("post", {
+ id: 123,
+ post_number: 1,
+ topic,
+ like_count: 3,
+ actions_summary: [{ id: 2, count: 1, hidden: false, can_act: true }],
+ });
+
+ this.post = post;
+ });
+
+ test("post deleted (first post)", async function (assert) {
+ this.post.topic.deleted_at = "2016-01-01";
+ this.post.topic.deleted_by = {
+ username: "eviltrout",
+ avatar_template: "/images/avatar.png",
+ };
+
+ await renderComponent(this.post);
+
+ assert.dom(".post-action .d-icon-trash-can").exists("has the deleted icon");
+ assert.dom(".avatar[title=eviltrout]").exists("has the deleted by avatar");
+ });
+
+ test("post deleted (other posts)", async function (assert) {
+ this.post.post_number = 2;
+ this.post.deleted_at = "2016-01-01";
+ this.post.deleted_by = {
+ username: "eviltrout",
+ avatar_template: "/images/avatar.png",
+ };
+
+ await renderComponent(this.post);
+
+ assert.dom(".post-action .d-icon-trash-can").exists("has the deleted icon");
+ assert.dom(".avatar[title=eviltrout]").exists("has the deleted by avatar");
+ });
+});
diff --git a/app/assets/javascripts/discourse/tests/integration/components/post/cooked-html-test.gjs b/app/assets/javascripts/discourse/tests/integration/components/post/cooked-html-test.gjs
new file mode 100644
index 00000000000..38289a33959
--- /dev/null
+++ b/app/assets/javascripts/discourse/tests/integration/components/post/cooked-html-test.gjs
@@ -0,0 +1,41 @@
+import { getOwner } from "@ember/owner";
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import PostCookedHtml from "discourse/components/post/cooked-html";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+
+function renderComponent(post, { highlightTerm } = {}) {
+ return render(
+ <template>
+ <PostCookedHtml @post={{post}} @highlightTerm={{highlightTerm}} />
+ </template>
+ );
+}
+
+module("Integration | Component | Post | PostCookedHtml", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.siteSettings.glimmer_post_stream_mode = "enabled";
+
+ const store = getOwner(this).lookup("service:store");
+ const topic = store.createRecord("topic", { id: 1 });
+ const post = store.createRecord("post", {
+ id: 123,
+ post_number: 1,
+ topic,
+ like_count: 3,
+ actions_summary: [{ id: 2, count: 1, hidden: false, can_act: true }],
+ });
+
+ this.post = post;
+ });
+
+ test("quotes with no username and no valid topic", async function (assert) {
+ this.post.cooked = `<aside class=\"quote no-group quote-post-not-found\" data-post=\"1\" data-topic=\"123456\">\n<blockquote>\n<p>abcd</p>\n</blockquote>\n</aside>\n<p>Testing the issue</p>`;
+
+ await renderComponent(this.post);
+
+ assert.dom("blockquote").hasText("abcd");
+ });
+});
diff --git a/app/assets/javascripts/discourse/tests/integration/components/post/meta-data/poster-name-test.gjs b/app/assets/javascripts/discourse/tests/integration/components/post/meta-data/poster-name-test.gjs
new file mode 100644
index 00000000000..175a56e82df
--- /dev/null
+++ b/app/assets/javascripts/discourse/tests/integration/components/post/meta-data/poster-name-test.gjs
@@ -0,0 +1,191 @@
+import { getOwner } from "@ember/owner";
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import PostMetaDataPosterName from "discourse/components/post/meta-data/poster-name";
+import { withPluginApi } from "discourse/lib/plugin-api";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+
+function renderComponent(post) {
+ return render(<template><PostMetaDataPosterName @post={{post}} /></template>);
+}
+
+module(
+ "Integration | Component | Post | PostMetaDataPosterName",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.siteSettings.glimmer_post_stream_mode = "enabled";
+
+ this.store = getOwner(this).lookup("service:store");
+ const topic = this.store.createRecord("topic", { id: 1 });
+ const post = this.store.createRecord("post", {
+ id: 123,
+ post_number: 1,
+ topic,
+ like_count: 3,
+ actions_summary: [{ id: 2, count: 1, hidden: false, can_act: true }],
+ });
+
+ this.post = post;
+ });
+
+ test("basic rendering", async function (assert) {
+ this.post.username = "eviltrout";
+ this.post.name = "Robin Ward";
+ this.post.user_title = "Trout Master";
+
+ await renderComponent(this.post);
+
+ assert.dom(".names").exists();
+ assert.dom("span.username").exists();
+ assert
+ .dom('a[data-user-card="eviltrout"]')
+ .exists()
+ .hasAttribute("href", "/u/eviltrout");
+ assert.dom(".username a").hasText("eviltrout");
+ assert.dom(".user-title").hasText("Trout Master");
+ });
+
+ test("extra classes and glyphs", async function (assert) {
+ this.post.username = "eviltrout";
+ this.post.staff = true;
+ this.post.admin = true;
+ this.post.moderator = true;
+ this.post.trust_level = 0;
+ this.post.primary_group_name = "fish";
+
+ await renderComponent(this.post);
+
+ assert.dom("span.staff").exists();
+ assert.dom("span.admin").exists();
+ assert.dom("span.moderator").exists();
+ assert.dom(".d-icon-shield-halved").exists();
+ assert.dom("span.new-user").exists();
+ assert.dom("span.group--fish").exists();
+ });
+
+ test("disable display name on posts", async function (assert) {
+ this.siteSettings.display_name_on_posts = false;
+ this.post.username = "eviltrout";
+ this.post.name = "Robin Ward";
+
+ await renderComponent(this.post);
+
+ assert.dom(".full-name").doesNotExist();
+ });
+
+ test("doesn't render a name if it's similar to the username", async function (assert) {
+ this.siteSettings.prioritize_username_in_ux = true;
+ this.siteSettings.display_name_on_posts = true;
+ this.post.username = "eviltrout";
+ this.post.name = "evil-trout";
+
+ await renderComponent(this.post);
+
+ assert
+ .dom(".second")
+ .doesNotExist("similar names are suppressed by default");
+
+ // the transformer can change this behavior
+ withPluginApi((api) => {
+ api.registerValueTransformer(
+ "post-meta-data-poster-name-suppress-similar-name",
+ () => false
+ );
+ });
+
+ await renderComponent(this.post);
+
+ assert
+ .dom(".second")
+ .exists(
+ "suppresing similar names can changed using the post-meta-data-poster-name-suppress-similar-name transformer"
+ );
+ });
+
+ test("renders badges that are passed in", async function (assert) {
+ this.post.username = "eviltrout";
+ this.post.user = this.store.createRecord("user", {
+ username: "eviltrout",
+ });
+ this.post.badges_granted = [
+ { badge: { id: 1, icon: "heart", slug: "badge1", name: "Badge One" } },
+ { badge: { id: 2, icon: "target", slug: "badge2", name: "Badge Two" } },
+ ];
+
+ await renderComponent(this.post);
+
+ // Check that the custom CSS classes are set
+ assert.dom("span.user-badge-button-badge1").exists();
+ assert.dom("span.user-badge-button-badge2").exists();
+
+ // Check that the custom titles are set
+ assert.dom("span.user-badge[title*='Badge One']").exists();
+ assert.dom("span.user-badge[title*='Badge Two']").exists();
+
+ // Check that the badges link to the correct badge page
+ assert
+ .dom(
+ "a.user-card-badge-link[href='/badges/1/badge1?username=eviltrout']"
+ )
+ .exists();
+ assert
+ .dom(
+ "a.user-card-badge-link[href='/badges/2/badge2?username=eviltrout']"
+ )
+ .exists();
+ });
+
+ test("api.addPosterIcons", async function (assert) {
+ this.post.username = "eviltrout";
+ this.post.user = this.store.createRecord("user", {
+ username: "eviltrout",
+ });
+
+ withPluginApi((api) => {
+ api.addPosterIcons((_, { username }) => {
+ return [
+ {
+ className: "test-icon",
+ icon: "cake-candles",
+ title: `${username}`,
+ text: "Test icon",
+ },
+ {
+ className: "test-smile",
+ emoji: "heart|smile",
+ emojiTitle: "test emojis",
+ url: "/u/eviltrout",
+ title: `${username}`,
+ },
+ ];
+ });
+ });
+
+ await renderComponent(this.post);
+
+ assert
+ .dom("span.poster-icon.test-icon")
+ .exists()
+ .hasAttribute("title", this.post.username)
+ .hasText("Test icon");
+ assert.dom("span.poster-icon.test-icon > .d-icon-cake-candles").exists();
+
+ assert
+ .dom("span.poster-icon.test-smile")
+ .exists()
+ .hasAttribute("title", this.post.username);
+ assert
+ .dom("span.poster-icon.test-smile > a")
+ .exists()
+ .hasAttribute("href", "/u/eviltrout");
+ assert
+ .dom("span.poster-icon.test-smile > a > .emoji[alt='heart']")
+ .exists();
+ assert
+ .dom("span.poster-icon.test-smile > a > .emoji[alt='smile']")
+ .exists();
+ });
+ }
+);
diff --git a/app/assets/javascripts/discourse/tests/integration/components/post/post-links-test.gjs b/app/assets/javascripts/discourse/tests/integration/components/post/post-links-test.gjs
new file mode 100644
index 00000000000..24b2b0484b9
--- /dev/null
+++ b/app/assets/javascripts/discourse/tests/integration/components/post/post-links-test.gjs
@@ -0,0 +1,129 @@
+import { getOwner } from "@ember/owner";
+import { click, render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import PostLinks from "discourse/components/post/links";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+
+function renderComponent(post) {
+ return render(<template><PostLinks @post={{post}} /></template>);
+}
+
+module("Integration | Component | Post | PostLinks", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.siteSettings.glimmer_post_stream_mode = "enabled";
+
+ const store = getOwner(this).lookup("service:store");
+ const topic = store.createRecord("topic", { id: 1 });
+ const post = store.createRecord("post", {
+ id: 123,
+ post_number: 1,
+ topic,
+ like_count: 3,
+ actions_summary: [{ id: 2, count: 1, hidden: false, can_act: true }],
+ });
+
+ this.post = post;
+ });
+
+ test("duplicate links", async function (assert) {
+ this.post.link_counts = [
+ {
+ title: "Link 1",
+ url: "/t/1",
+ internal: true,
+ reflection: true,
+ clicks: 2,
+ },
+ {
+ title: "Link 1",
+ url: "/t/1?dupe",
+ internal: true,
+ reflection: true,
+ },
+ {
+ url: "/groups/test",
+ internal: true,
+ reflection: false,
+ },
+ {
+ title: "Evil Trout Link",
+ url: "http://eviltrout.com",
+ internal: false,
+ reflection: false,
+ },
+ {
+ title: "Evil Trout Link",
+ url: "http://dupe.eviltrout.com",
+ internal: false,
+ reflection: false,
+ },
+ ];
+
+ await renderComponent(this.post);
+
+ assert.dom(".expand-links").doesNotExist("there is no expand button");
+
+ assert
+ .dom(".post-links a.track-link")
+ .exists({ count: 1 }, "hides the dupe link")
+ .hasAttribute("data-clicks", "2", "has the correct click count");
+ });
+
+ test("collapsed links", async function (assert) {
+ this.post.link_counts = [
+ {
+ title: "Link 1",
+ url: "/t/1",
+ internal: true,
+ reflection: true,
+ },
+ {
+ title: "Link 2",
+ url: "/t/2",
+ internal: true,
+ reflection: true,
+ },
+ {
+ title: "Link 3",
+ url: "/t/3",
+ internal: true,
+ reflection: true,
+ },
+ {
+ title: "Link 4",
+ url: "/t/4",
+ internal: true,
+ reflection: true,
+ },
+ {
+ title: "Link 5",
+ url: "/t/5",
+ internal: true,
+ reflection: true,
+ },
+ {
+ title: "Link 6",
+ url: "/t/6",
+ internal: true,
+ reflection: true,
+ },
+ {
+ title: "Link 7",
+ url: "/t/7",
+ internal: true,
+ reflection: true,
+ },
+ ];
+
+ await renderComponent(this.post);
+
+ assert.dom(".expand-links").exists({ count: 1 }, "collapsed by default");
+
+ await click(".expand-links");
+
+ assert.dom(".post-links a.track-link").exists({ count: 7 });
+ assert.dom(".expand-links").doesNotExist("there is no expand 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.gjs
new file mode 100644
index 00000000000..c73080b40b4
--- /dev/null
+++ b/app/assets/javascripts/discourse/tests/integration/components/post/post-test.gjs
@@ -0,0 +1,730 @@
+import { getOwner } from "@ember/owner";
+import { click, render, triggerEvent } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import Post from "discourse/components/post";
+import { withPluginApi } from "discourse/lib/plugin-api";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import { count, queryAll } from "discourse/tests/helpers/qunit-helpers";
+import { i18n } from "discourse-i18n";
+import DMenus from "float-kit/components/d-menus";
+
+function renderComponent(
+ post,
+ {
+ prevPost,
+ changePostOwner,
+ editPost,
+ expandHidden,
+ permanentlyDeletePost,
+ rebakePost,
+ showHistory,
+ showRawEmail,
+ togglePostType,
+ unhidePost,
+ } = {}
+) {
+ // TODO (glimmer-post-stream) remove the outer div when the post-stream widget is converted to a Glimmer component
+ return render(
+ <template>
+ <div class="topic-post glimmer-post-stream">
+ <Post
+ @post={{post}}
+ @prevPost={{prevPost}}
+ @changePostOwner={{changePostOwner}}
+ @editPost={{editPost}}
+ @expandHidden={{expandHidden}}
+ @permanentlyDeletePost={{permanentlyDeletePost}}
+ @rebakePost={{rebakePost}}
+ @showHistory={{showHistory}}
+ @showRawEmail={{showRawEmail}}
+ @togglePostType={{togglePostType}}
+ @unhidePost={{unhidePost}}
+ />
+ </div>
+ <DMenus />
+ </template>
+ );
+}
+
+module("Integration | Component | Post", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.siteSettings.glimmer_post_stream_mode = "enabled";
+ this.siteSettings.glimmer_post_menu_mode = "enabled";
+ this.siteSettings.post_menu_hidden_items = "";
+
+ this.store = getOwner(this).lookup("service:store");
+ const topic = this.store.createRecord("topic", { id: 123 });
+ const post = this.store.createRecord("post", {
+ id: 123,
+ post_number: 1,
+ topic,
+ like_count: 3,
+ actions_summary: [{ id: 2, count: 1, hidden: false, can_act: true }],
+ });
+
+ this.post = post;
+ });
+
+ test("basic elements", async function (assert) {
+ await renderComponent(this.post);
+
+ assert.dom(".names").exists("includes poster name");
+ assert.dom("a.post-date").exists("includes post date");
+ });
+
+ test("can add classes to the component", async function (assert) {
+ withPluginApi((api) => {
+ api.registerValueTransformer("post-class", ({ value }) => {
+ value.push("custom-class");
+ return value;
+ });
+
+ api.addPostClassesCallback((post) => `api-custom-class-${post.id}`);
+ });
+
+ await renderComponent(this.post);
+
+ assert
+ .dom(".topic-post.custom-class.api-custom-class-123")
+ .exists("applies the custom classes to the component");
+ });
+
+ test("links", async function (assert) {
+ this.post.link_counts = [
+ {
+ title: "Link 1",
+ url: "/t/1",
+ internal: true,
+ reflection: true,
+ clicks: 2,
+ },
+ ];
+
+ await renderComponent(this.post);
+
+ assert.dom(".post-links-container").exists("links are displayed");
+ assert
+ .dom(".post-links a.track-link")
+ .exists({ count: 1 }, "hides the dupe link")
+ .hasAttribute("data-clicks", "2", "has the correct click count");
+ });
+
+ test("post - cooked links", async function (assert) {
+ this.post.cooked =
+ "<a href='http://link1.example.com/'>first link</a> and <a href='http://link2.example.com/?some=query'>second link</a>";
+ this.post.link_counts = [
+ { url: "http://link1.example.com/", clicks: 1, internal: true },
+ { url: "http://link2.example.com/", clicks: 2, internal: true },
+ ];
+
+ await renderComponent(this.post);
+
+ assert.strictEqual(
+ queryAll("a[data-clicks='1']")[0].getAttribute("data-clicks"),
+ "1"
+ );
+ assert.strictEqual(
+ queryAll("a[data-clicks='2']")[0].getAttribute("data-clicks"),
+ "2"
+ );
+ });
+
+ test("post - cooked onebox links", async function (assert) {
+ this.post.cooked = `
+ <p><a href="https://example.com">Other URL</a></p>
+
+ <aside class="onebox twitterstatus" data-onebox-src="https://twitter.com/codinghorror">
+ <header class="source">
+ <a href="https://twitter.com/codinghorror" target="_blank" rel="noopener">twitter.com</a>
+ </header>
+ <article class="onebox-body">
+ <h4><a href="https://twitter.com/codinghorror" target="_blank" rel="noopener">Jeff Atwood</a></h4>
+ <div class="twitter-screen-name"><a href="https://twitter.com/codinghorror" target="_blank" rel="noopener">@codinghorror</a></div>
+ </article>
+ </aside>`;
+ this.post.link_counts = [
+ { url: "https://example.com", clicks: 1 },
+ { url: "https://twitter.com/codinghorror", clicks: 2 },
+ ];
+
+ await renderComponent(this.post);
+
+ assert.strictEqual(
+ queryAll("a[data-clicks='1']")[0].getAttribute("data-clicks"),
+ "1",
+ "First link has correct data attribute and content"
+ );
+ assert.strictEqual(
+ queryAll("a[data-clicks='2']")[0].getAttribute("data-clicks"),
+ "2",
+ "Second link has correct data attribute and content"
+ );
+ });
+
+ test("wiki", async function (assert) {
+ this.post.wiki = true;
+ this.post.version = 2;
+ this.post.can_view_edit_history = true;
+
+ await renderComponent(this.post, {
+ showHistory: () => assert.step("show history called"),
+ });
+
+ await click(".post-info .wiki");
+ assert.verifySteps(
+ ["show history called"],
+ "clicking the wiki icon displays the post history"
+ );
+ });
+
+ test("wiki without revision", async function (assert) {
+ this.post.wiki = true;
+ this.post.version = 1;
+ this.post.can_view_edit_history = true;
+
+ await renderComponent(this.post, {
+ editPost: () => assert.step("edit post called"),
+ });
+
+ await click(".post-info .wiki");
+ assert.verifySteps(
+ ["edit post called"],
+ "clicking wiki icon edits the post"
+ );
+ });
+
+ test("via-email", async function (assert) {
+ this.currentUser.can_view_raw_email = true;
+ this.post.via_email = true;
+
+ await renderComponent(this.post, {
+ showRawEmail: () => assert.step("show raw email called"),
+ });
+
+ await click(".post-info.via-email");
+ assert.verifySteps(
+ ["show raw email called"],
+ "clicking the envelope shows the raw email"
+ );
+ });
+
+ test("via-email without permission", async function (assert) {
+ this.currentUser.can_view_raw_email = false;
+ this.post.via_email = true;
+
+ await renderComponent(this.post, {
+ showRawEmail: () => assert.step("show raw email called"),
+ });
+
+ await click(".post-info.via-email");
+ assert.verifySteps([], "clicking the envelope doesn't show the raw email");
+ });
+
+ test("history", async function (assert) {
+ this.post.version = 3;
+ this.post.can_view_edit_history = true;
+
+ await renderComponent(this.post, {
+ showHistory: () => assert.step("show history called"),
+ });
+
+ await click(".post-info.edits button");
+ assert.verifySteps(
+ ["show history called"],
+ "clicking the pencil shows the history"
+ );
+ });
+
+ test("history without view permission", async function (assert) {
+ this.post.version = 3;
+ this.post.can_view_edit_history = false;
+
+ await renderComponent(this.post, {
+ showHistory: () => assert.step("show history called"),
+ });
+
+ await click(".post-info.edits button");
+ assert.verifySteps([], "clicking the pencil doesn't show the history");
+ });
+
+ test("whisper", async function (assert) {
+ this.post.post_type = this.site.post_types.whisper;
+
+ await renderComponent(this.post);
+
+ assert.strictEqual(count(".topic-post.whisper"), 1);
+ assert.strictEqual(count(".post-info.whisper"), 1);
+ });
+
+ test("read indicator", async function (assert) {
+ this.post.read = true;
+
+ await renderComponent(this.post);
+
+ assert.dom(".read-state.read").exists();
+ });
+
+ test("unread indicator", async function (assert) {
+ this.post.read = false;
+
+ await renderComponent(this.post);
+
+ assert.dom(".read-state").exists();
+ });
+
+ test("reply directly above (suppressed)", async function (assert) {
+ this.post.reply_to_user = {
+ username: "eviltrout",
+ avatar_template: "/images/avatar.png",
+ };
+ this.post.post_number = 2;
+ this.post.reply_to_post_number = 1;
+
+ const prevPost = this.store.createRecord("post", {
+ id: 122,
+ post_number: 1,
+ topic: this.post.topic,
+ });
+
+ await renderComponent(this.post, { prevPost });
+
+ assert.dom("a.reply-to-tab").doesNotExist("hides the tab");
+ assert.dom(".avoid-tab").doesNotExist("doesn't have the avoid tab class");
+ });
+
+ test("reply a few posts above", async function (assert) {
+ this.post.reply_to_user = {
+ username: "eviltrout",
+ avatar_template: "/images/avatar.png",
+ };
+ this.post.post_number = 5;
+ this.post.reply_to_post_number = 1;
+
+ const prevPost = this.store.createRecord("post", {
+ id: 122,
+ post_number: 4,
+ topic: this.post.topic,
+ });
+
+ await renderComponent(this.post, { prevPost });
+
+ assert.dom("a.reply-to-tab").exists("shows the tab");
+ assert.strictEqual(count(".avoid-tab"), 1, "has the avoid tab class");
+ });
+
+ test("reply directly above", async function (assert) {
+ this.siteSettings.suppress_reply_directly_above = false;
+ this.post.reply_to_user = {
+ username: "eviltrout",
+ avatar_template: "/images/avatar.png",
+ };
+ this.post.post_number = 2;
+ this.post.reply_to_post_number = 1;
+
+ const prevPost = this.store.createRecord("post", {
+ id: 122,
+ post_number: 1,
+ topic: this.post.topic,
+ });
+
+ await renderComponent(this.post, { prevPost });
+
+ assert.strictEqual(count(".avoid-tab"), 1, "has the avoid tab class");
+ await click("a.reply-to-tab");
+ assert.strictEqual(count("section.embedded-posts.top .cooked"), 1);
+ assert.strictEqual(count("section.embedded-posts .d-icon-arrow-up"), 1);
+ });
+
+ test("cooked content hidden", async function (assert) {
+ this.post.cooked_hidden = true;
+ this.post.can_see_hidden_post = true;
+
+ await renderComponent(this.post, {
+ expandHidden: () => assert.step("expand hidden called"),
+ });
+
+ await click(".topic-body .expand-hidden");
+ assert.verifySteps(["expand hidden called"], "expand the cooked content");
+ });
+
+ test(`cooked content hidden - can't view hidden post`, async function (assert) {
+ this.post.cooked_hidden = true;
+ this.post.can_see_hidden_post = false;
+
+ await renderComponent(this.post);
+
+ assert
+ .dom(".topic-body .expand-hidden")
+ .doesNotExist("button is not displayed");
+ });
+
+ test("expand first post", async function (assert) {
+ this.post.post_number = 1;
+ this.post.topic.expandable_first_post = true;
+
+ await renderComponent(this.post);
+
+ await click(".topic-body .expand-post");
+ assert.dom(".expand-post").doesNotExist("button is gone");
+ });
+
+ test("can't show admin menu when you can't manage", async function (assert) {
+ this.currentUser.admin = false;
+
+ await renderComponent(this.post);
+
+ assert.dom(".post-menu-area .show-post-admin-menu").doesNotExist();
+ });
+
+ test("show admin menu", async function (assert) {
+ this.currentUser.admin = true;
+
+ await renderComponent(this.post);
+
+ assert
+ .dom("[data-content][data-identifier='admin-post-menu']")
+ .doesNotExist();
+
+ await click(".post-menu-area .show-post-admin-menu");
+ assert.dom("[data-content][data-identifier='admin-post-menu']").exists();
+
+ await triggerEvent(".post-menu-area", "pointerdown");
+ assert
+ .dom("[data-content][data-identifier='admin-post-menu']")
+ .doesNotExist("clicking outside clears the popup");
+ });
+
+ test("permanently delete topic", async function (assert) {
+ this.currentUser.admin = true;
+
+ this.post.topic.details.can_permanently_delete = true;
+ this.post.deleted_at = new Date().toISOString();
+
+ await renderComponent(this.post, {
+ permanentlyDeletePost: () =>
+ assert.step("permanently delete post called"),
+ });
+
+ await click(".post-menu-area .show-post-admin-menu");
+ await click(
+ "[data-content][data-identifier='admin-post-menu'] .permanently-delete"
+ );
+ assert.verifySteps(
+ ["permanently delete post called"],
+ "clicked on permanently delete"
+ );
+ assert
+ .dom("[data-content][data-identifier='admin-post-menu']")
+ .doesNotExist("also hides the menu");
+ });
+
+ test("permanently delete post", async function (assert) {
+ this.currentUser.admin = true;
+
+ this.post.post_number = 2;
+ this.post.can_permanently_delete = true;
+ this.post.deleted_at = new Date().toISOString();
+
+ await renderComponent(this.post, {
+ permanentlyDeletePost: () =>
+ assert.step("permanently delete post called"),
+ });
+
+ await click(".post-menu-area .show-post-admin-menu");
+
+ await click(
+ "[data-content][data-identifier='admin-post-menu'] .permanently-delete"
+ );
+ assert.verifySteps(
+ ["permanently delete post called"],
+ "clicked on permanently delete"
+ );
+ assert
+ .dom("[data-content][data-identifier='admin-post-menu']")
+ .doesNotExist("also hides the menu");
+ });
+
+ test("toggle moderator post", async function (assert) {
+ this.currentUser.moderator = true;
+
+ await renderComponent(this.post, {
+ togglePostType: () => assert.step("toggle post type called"),
+ });
+
+ await click(".post-menu-area .show-post-admin-menu");
+ await click(
+ "[data-content][data-identifier='admin-post-menu'] .toggle-post-type"
+ );
+ assert.verifySteps(
+ ["toggle post type called"],
+ "clicked on toggle moderator post (add staff color)"
+ );
+ assert
+ .dom("[data-content][data-identifier='admin-post-menu']")
+ .doesNotExist("also hides the menu");
+ });
+
+ test("rebake post", async function (assert) {
+ this.currentUser.moderator = true;
+
+ await renderComponent(this.post, {
+ rebakePost: () => assert.step("rebake post called"),
+ });
+
+ await click(".post-menu-area .show-post-admin-menu");
+ await click(
+ "[data-content][data-identifier='admin-post-menu'] .rebuild-html"
+ );
+ assert.verifySteps(
+ ["rebake post called"],
+ "clicked on rebake post (rebuild html)"
+ );
+ assert
+ .dom("[data-content][data-identifier='admin-post-menu']")
+ .doesNotExist("also hides the menu");
+ });
+
+ test("unhide post", async function (assert) {
+ this.currentUser.admin = true;
+ this.post.hidden = true;
+
+ await renderComponent(this.post, {
+ unhidePost: () => assert.step("unhide post called"),
+ });
+
+ await click(".post-menu-area .show-post-admin-menu");
+
+ await click(
+ "[data-content][data-identifier='admin-post-menu'] .unhide-post"
+ );
+ assert.verifySteps(["unhide post called"], "clicked on unhide post");
+ assert
+ .dom("[data-content][data-identifier='admin-post-menu']")
+ .doesNotExist("also hides the menu");
+ });
+
+ test("change owner", async function (assert) {
+ this.currentUser.admin = true;
+
+ await renderComponent(this.post, {
+ changePostOwner: () => assert.step("change post owner called"),
+ });
+
+ await click(".post-menu-area .show-post-admin-menu");
+ await click(
+ "[data-content][data-identifier='admin-post-menu'] .change-owner"
+ );
+ assert.verifySteps(
+ ["change post owner called"],
+ "clicked on change post owner"
+ );
+ assert
+ .dom("[data-content][data-identifier='admin-post-menu']")
+ .doesNotExist("also hides the menu");
+ });
+
+ test("the topic map visibility can be changed using the `post-show-topic-map` transformer", async function (assert) {
+ this.siteSettings.show_topic_map_in_topics_without_replies = false;
+
+ this.post.post_number = 1;
+
+ await renderComponent(this.post);
+ assert.dom(".topic-map").doesNotExist();
+
+ withPluginApi((api) => {
+ api.registerValueTransformer("post-show-topic-map", () => true);
+ });
+
+ await renderComponent(this.post);
+
+ assert.dom(".topic-map").exists();
+ });
+
+ test("shows the topic map when there are no replies", async function (assert) {
+ this.siteSettings.show_topic_map_in_topics_without_replies = true;
+
+ this.post.topic.archetype = "regular";
+ this.post.post_number = 1;
+
+ await renderComponent(this.post);
+
+ assert.dom(".topic-map").exists();
+ });
+
+ test("topic map - few participants", async function (assert) {
+ this.post.topic.posts_count = 10;
+ this.post.topic.participant_count = 2;
+ this.post.topic.archetype = "regular";
+ this.post.topic.details.set("participants", [
+ { username: "eviltrout" },
+ { username: "codinghorror" },
+ ]);
+ this.post.post_number = 1;
+
+ await renderComponent(this.post);
+
+ assert.dom(".topic-map__users-trigger").doesNotExist();
+ assert.dom(".topic-map__users-list a.poster").exists({ count: 2 });
+ });
+
+ test("topic map - participants", async function (assert) {
+ this.post.topic.posts_count = 10;
+ this.post.topic.participant_count = 6;
+ this.post.topic.archetype = "regular";
+ this.post.topic.postStream.setProperties({
+ userFilters: ["sam", "codinghorror"],
+ });
+ this.post.topic.details.set("participants", [
+ { username: "eviltrout" },
+ { username: "codinghorror" },
+ { username: "sam" },
+ { username: "zogstrip" },
+ { username: "joffreyjaffeux" },
+ { username: "david" },
+ ]);
+ this.post.post_number = 1;
+
+ await renderComponent(this.post);
+
+ assert.dom(".topic-map__users-list a.poster").exists({ count: 5 });
+
+ await click(".topic-map__users-trigger");
+ assert
+ .dom(".topic-map__users-content .topic-map__users-list a.poster")
+ .exists({ count: 6 });
+ });
+
+ test("topic map - no top reply summary", async function (assert) {
+ this.post.topic.posts_count = 2;
+ this.post.topic.archetype = "regular";
+ this.post.post_number = 1;
+
+ await renderComponent(this.post);
+
+ assert.dom(".topic-map").exists();
+ assert.dom(".summarization-button .top-replies").doesNotExist();
+ });
+
+ test("topic map - has top replies summary", async function (assert) {
+ this.post.topic.posts_count = 2;
+ this.post.topic.archetype = "regular";
+ this.post.topic.has_summary = true;
+ this.post.post_number = 1;
+
+ await renderComponent(this.post);
+
+ assert.dom(".summarization-button .top-replies").exists({ count: 1 });
+ });
+
+ test("pm map", async function (assert) {
+ this.post.topic.posts_count = 2;
+ this.post.topic.archetype = "private_message";
+ this.post.topic.details.allowed_users = [{ username: "eviltrout" }];
+ this.post.post_number = 1;
+
+ await renderComponent(this.post);
+
+ assert.dom(".topic-map__private-message-map").exists({ count: 1 });
+ assert.dom(".topic-map__private-message-map .user").exists({ count: 1 });
+ });
+
+ test("post notice - with username", async function (assert) {
+ const twoDaysAgo = new Date();
+ twoDaysAgo.setDate(twoDaysAgo.getDate() - 2);
+ this.siteSettings.display_name_on_posts = false;
+ this.siteSettings.prioritize_username_in_ux = true;
+ this.siteSettings.old_post_notice_days = 14;
+
+ this.post.username = "codinghorror";
+ this.post.name = "Jeff";
+ this.post.created_at = new Date();
+ this.post.notice = {
+ type: "returning_user",
+ lastPostedAt: twoDaysAgo,
+ };
+
+ await renderComponent(this.post);
+
+ assert.dom(".post-notice.returning-user:not(.old)").hasText(
+ i18n("post.notice.returning_user", {
+ user: "codinghorror",
+ time: "2 days ago",
+ })
+ );
+ });
+
+ test("post notice - with name", async function (assert) {
+ this.siteSettings.display_name_on_posts = true;
+ this.siteSettings.prioritize_username_in_ux = false;
+ this.siteSettings.old_post_notice_days = 14;
+
+ this.post.username = "codinghorror";
+ this.post.name = "Jeff";
+ this.post.created_at = new Date(2019, 0, 1);
+ this.post.notice = { type: "new_user" };
+
+ await renderComponent(this.post);
+
+ assert
+ .dom(".post-notice.old.new-user")
+ .hasText(i18n("post.notice.new_user", { user: "Jeff", time: "Jan '10" }));
+ });
+
+ test("show group request in post", async function (assert) {
+ this.post.username = "foo";
+ this.post.topic.requested_group_name = "testGroup";
+ this.post.post_number = 1;
+
+ await renderComponent(this.post);
+
+ assert.dom(".group-request a").hasText(i18n("groups.requests.handle"));
+ assert
+ .dom(".group-request a")
+ .hasAttribute("href", "/g/testGroup/requests?filter=foo");
+ });
+
+ test("shows user status if enabled in site settings", async function (assert) {
+ this.siteSettings.enable_user_status = true;
+ const status = {
+ emoji: "tooth",
+ description: "off to dentist",
+ };
+
+ this.post.user = this.store.createRecord("user", { status });
+
+ await renderComponent(this.post);
+
+ assert.dom(".user-status-message").exists();
+ });
+
+ test("doesn't show user status if disabled in site settings", async function (assert) {
+ this.siteSettings.enable_user_status = false;
+ const status = {
+ emoji: "tooth",
+ description: "off to dentist",
+ };
+
+ this.post.user = this.store.createRecord("user", { status });
+
+ await renderComponent(this.post);
+
+ assert.dom(".user-status-message").doesNotExist();
+ });
+
+ test("more actions button is displayed when multiple hidden items are configured", async function (assert) {
+ this.siteSettings.post_menu_hidden_items = "bookmark|edit|copyLink";
+
+ await renderComponent(this.post);
+ assert.dom(".show-more-actions").exists();
+ });
+
+ test("hidden menu expands automatically when only one hidden item is configured", async function (assert) {
+ this.siteSettings.post_menu_hidden_items = "bookmark";
+
+ await renderComponent(this.post);
+
+ assert.dom(".show-more-actions").doesNotExist();
+ });
+});
diff --git a/app/assets/javascripts/discourse/tests/integration/components/post/small-action-test.gjs b/app/assets/javascripts/discourse/tests/integration/components/post/small-action-test.gjs
new file mode 100644
index 00000000000..2c45bb69549
--- /dev/null
+++ b/app/assets/javascripts/discourse/tests/integration/components/post/small-action-test.gjs
@@ -0,0 +1,152 @@
+import { getOwner } from "@ember/owner";
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import PostSmallAction from "discourse/components/post/small-action";
+import { withPluginApi } from "discourse/lib/plugin-api";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+
+function renderComponent(post) {
+ return render(<template><PostSmallAction @post={{post}} /></template>);
+}
+
+module("Integration | Component | Post | PostSmallAction", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.siteSettings.glimmer_post_stream_mode = "enabled";
+
+ const store = getOwner(this).lookup("service:store");
+ const topic = store.createRecord("topic", { id: 1 });
+ const post = store.createRecord("post", {
+ id: 123,
+ post_number: 1,
+ topic,
+ like_count: 3,
+ action_code: "open_topic",
+ actions_summary: [{ id: 2, count: 1, hidden: false, can_act: true }],
+ });
+
+ this.post = post;
+ });
+
+ test("does not have delete/edit/recover buttons by default", async function (assert) {
+ await renderComponent(this.post);
+
+ assert.dom(".small-action-desc .small-action-delete").doesNotExist();
+ assert.dom(".small-action-desc .small-action-recover").doesNotExist();
+ assert.dom(".small-action-desc .small-action-edit").doesNotExist();
+ });
+
+ test("shows edit button if canEdit", async function (assert) {
+ this.post.can_edit = true;
+
+ await renderComponent(this.post);
+
+ assert
+ .dom(".small-action-desc .small-action-edit")
+ .exists("adds the edit small action button");
+ });
+
+ test("can add classes to the component", async function (assert) {
+ withPluginApi((api) => {
+ api.registerValueTransformer("post-small-action-class", ({ value }) => {
+ value.push("custom-class");
+ return value;
+ });
+
+ api.addPostSmallActionClassesCallback(
+ (post) => `api-custom-class-${post.id}`
+ );
+ });
+
+ await renderComponent(this.post);
+
+ assert
+ .dom(".small-action.custom-class.api-custom-class-123")
+ .exists("applies the custom classes to the component");
+ });
+
+ test("can use a custom component", async function (assert) {
+ withPluginApi((api) => {
+ api.registerValueTransformer("post-small-action-custom-component", () => {
+ return <template>
+ <div class="custom-component">CUSTOM COMPONENT</div>
+ </template>;
+ });
+ });
+
+ await renderComponent(this.post);
+
+ assert
+ .dom(".small-action .custom-component")
+ .exists("uses the custom component");
+ assert
+ .dom(".small-action .small-action-custom-message")
+ .doesNotExist("won't render the cooked test");
+ });
+
+ test("can customize the icon of the component", async function (assert) {
+ withPluginApi((api) => {
+ api.registerValueTransformer(
+ "post-small-action-icon",
+ () => "far-circle-check"
+ );
+ });
+
+ await renderComponent(this.post);
+
+ assert
+ .dom(".small-action .d-icon-far-circle-check")
+ .exists("the custom icon was rendered");
+ });
+
+ test("api.addPostSmallActionIcon", async function (assert) {
+ withPluginApi((api) => {
+ api.addPostSmallActionIcon("open_topic", "far-circle-check");
+ api.addPostSmallActionIcon("private_topic", "heart");
+ });
+
+ await renderComponent(this.post);
+
+ assert
+ .dom(".small-action .d-icon-far-circle-check")
+ .exists("the correct custom icon was rendered");
+ });
+
+ test("does not show edit button if canRecover even if canEdit", async function (assert) {
+ this.post.can_edit = true;
+ this.post.deleted_at = new Date().toISOString();
+ this.post.can_recover = true;
+
+ await renderComponent(this.post);
+
+ assert
+ .dom(".small-action-desc .small-action-edit")
+ .doesNotExist("does not add the edit small action button");
+ assert
+ .dom(".small-action-desc .small-action-recover")
+ .exists("adds the recover small action button");
+ });
+
+ test("shows delete button if canDelete", async function (assert) {
+ this.post.can_delete = true;
+ this.currentUser.staff = true;
+
+ await renderComponent(this.post);
+
+ assert
+ .dom(".small-action-desc .small-action-delete")
+ .exists("adds the delete small action button");
+ });
+
+ test("shows undo button if canRecover", async function (assert) {
+ this.post.deleted_at = new Date().toISOString();
+ this.post.can_recover = true;
+
+ await renderComponent(this.post);
+
+ assert
+ .dom(".small-action-desc .small-action-recover")
+ .exists("adds the recover small action button");
+ });
+});
diff --git a/app/assets/javascripts/discourse/tests/integration/components/time-gap-test.gjs b/app/assets/javascripts/discourse/tests/integration/components/post/time-gap-test.gjs
similarity index 64%
rename from app/assets/javascripts/discourse/tests/integration/components/time-gap-test.gjs
rename to app/assets/javascripts/discourse/tests/integration/components/post/time-gap-test.gjs
index 282520457a9..6e8b72c24d9 100644
--- a/app/assets/javascripts/discourse/tests/integration/components/time-gap-test.gjs
+++ b/app/assets/javascripts/discourse/tests/integration/components/post/time-gap-test.gjs
@@ -1,55 +1,43 @@
import { render } from "@ember/test-helpers";
import { module, test } from "qunit";
-import TimeGap from "discourse/components/time-gap";
+import TimeGap from "discourse/components/post/time-gap";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
import { i18n } from "discourse-i18n";
-module("Integration | Component | time-gap", function (hooks) {
+function renderComponent(daysSince) {
+ return render(<template><TimeGap @daysSince={{daysSince}} /></template>);
+}
+
+module("Integration | Component | Post | TimeGap", function (hooks) {
setupRenderingTest(hooks);
test("it renders days correctly", async function (assert) {
- const self = this;
-
this.set("daysSince", 5);
- await render(
- <template><TimeGap @daysSince={{self.daysSince}} /></template>
- );
+ await renderComponent(this.daysSince);
assert
.dom(".small-action-desc.timegap")
.hasText(i18n("dates.later.x_days", { count: 5 }));
});
test("it renders months correctly", async function (assert) {
- const self = this;
-
this.set("daysSince", 90);
- await render(
- <template><TimeGap @daysSince={{self.daysSince}} /></template>
- );
+ await renderComponent(this.daysSince);
assert
.dom(".small-action-desc.timegap")
.hasText(i18n("dates.later.x_months", { count: 3 }));
});
test("it renders years correctly", async function (assert) {
- const self = this;
-
this.set("daysSince", 730);
- await render(
- <template><TimeGap @daysSince={{self.daysSince}} /></template>
- );
+ await renderComponent(this.daysSince);
assert
.dom(".small-action-desc.timegap")
.hasText(i18n("dates.later.x_years", { count: 2 }));
});
test("it renders the correct elements", async function (assert) {
- const self = this;
-
this.set("daysSince", 10);
- await render(
- <template><TimeGap @daysSince={{self.daysSince}} /></template>
- );
+ await renderComponent(this.daysSince);
assert.dom(".topic-avatar").exists();
assert.dom(".small-action-desc.timegap").exists();
});
diff --git a/app/assets/javascripts/discourse/tests/integration/components/small-user-list-test.gjs b/app/assets/javascripts/discourse/tests/integration/components/small-user-list-test.gjs
new file mode 100644
index 00000000000..b150b32bfa2
--- /dev/null
+++ b/app/assets/javascripts/discourse/tests/integration/components/small-user-list-test.gjs
@@ -0,0 +1,22 @@
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import SmallUserList from "discourse/components/small-user-list";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+
+module("Integration | Component | SmallUserList", function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("renders avatars and support for unknown", async function (assert) {
+ const users = [
+ { id: 456, username: "eviltrout" },
+ { id: 457, username: "someone", unknown: true },
+ ];
+
+ await render(<template><SmallUserList @users={{users}} /></template>);
+
+ assert.dom(".small-user-list").exists();
+ assert.dom('[data-user-card="eviltrout"]').exists({ count: 1 });
+ assert.dom('[data-user-card="someone"]').doesNotExist();
+ assert.dom(".unknown").exists("includes unknown user");
+ });
+});
diff --git a/app/assets/javascripts/discourse/tests/integration/components/widgets/actions-summary-test.gjs b/app/assets/javascripts/discourse/tests/integration/components/widgets/actions-summary-test.gjs
index 82cea27a50d..882e86844b1 100644
--- a/app/assets/javascripts/discourse/tests/integration/components/widgets/actions-summary-test.gjs
+++ b/app/assets/javascripts/discourse/tests/integration/components/widgets/actions-summary-test.gjs
@@ -3,14 +3,17 @@ import { module, test } from "qunit";
import MountWidget from "discourse/components/mount-widget";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+// TODO (glimmer-post-stream) remove this test when removing the widget post stream code
module("Integration | Component | Widget | actions-summary", function (hooks) {
setupRenderingTest(hooks);
test("post deleted", async function (assert) {
const args = {
- deleted_at: "2016-01-01",
- deletedByUsername: "eviltrout",
- deletedByAvatarTemplate: "/images/avatar.png",
+ deletedAt: "2016-01-01",
+ deletedBy: {
+ username: "eviltrout",
+ avatar_template: "/images/avatar.png",
+ },
};
await render(
diff --git a/app/assets/javascripts/discourse/tests/integration/components/widgets/post-cooked-test.gjs b/app/assets/javascripts/discourse/tests/integration/components/widgets/post-cooked-test.gjs
index c65f65c9b74..4e62322ec35 100644
--- a/app/assets/javascripts/discourse/tests/integration/components/widgets/post-cooked-test.gjs
+++ b/app/assets/javascripts/discourse/tests/integration/components/widgets/post-cooked-test.gjs
@@ -6,6 +6,7 @@ import DecoratorHelper from "discourse/widgets/decorator-helper";
import PostCooked from "discourse/widgets/post-cooked";
import { createWidget } from "discourse/widgets/widget";
+// TODO (glimmer-post-stream) remove this test when removing the widget post stream code
module("Integration | Component | Widget | post-cooked", function (hooks) {
setupRenderingTest(hooks);
diff --git a/app/assets/javascripts/discourse/tests/integration/components/widgets/post-links-test.gjs b/app/assets/javascripts/discourse/tests/integration/components/widgets/post-links-test.gjs
index 35fddc038eb..ad4ceaba48c 100644
--- a/app/assets/javascripts/discourse/tests/integration/components/widgets/post-links-test.gjs
+++ b/app/assets/javascripts/discourse/tests/integration/components/widgets/post-links-test.gjs
@@ -3,6 +3,7 @@ import { module, test } from "qunit";
import MountWidget from "discourse/components/mount-widget";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+// TODO (glimmer-post-stream) remove this test when removing the widget post stream code
module("Integration | Component | Widget | post-links", function (hooks) {
setupRenderingTest(hooks);
diff --git a/app/assets/javascripts/discourse/tests/integration/components/widgets/post-small-action-test.gjs b/app/assets/javascripts/discourse/tests/integration/components/widgets/post-small-action-test.gjs
index a5a7293d6a0..092cccff2af 100644
--- a/app/assets/javascripts/discourse/tests/integration/components/widgets/post-small-action-test.gjs
+++ b/app/assets/javascripts/discourse/tests/integration/components/widgets/post-small-action-test.gjs
@@ -1,15 +1,20 @@
import { render } from "@ember/test-helpers";
import { module, test } from "qunit";
import MountWidget from "discourse/components/mount-widget";
+import { withSilencedDeprecations } from "discourse/lib/deprecated";
import { withPluginApi } from "discourse/lib/plugin-api";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
-import { resetPostSmallActionClassesCallbacks } from "discourse/widgets/post-small-action";
+// TODO (glimmer-post-stream) remove this test when removing the widget post stream code
module(
"Integration | Component | Widget | post-small-action",
function (hooks) {
setupRenderingTest(hooks);
+ hooks.beforeEach(function () {
+ this.siteSettings.glimmer_post_stream_mode = "disabled";
+ });
+
test("does not have delete/edit/recover buttons by default", async function (assert) {
const self = this;
@@ -110,9 +115,9 @@ module(
});
test("`addPostSmallActionClassesCallback` plugin api", async function (assert) {
- try {
- const self = this;
+ const self = this;
+ withSilencedDeprecations("discourse.post-stream-widget-overrides", () => {
withPluginApi("1.6.0", (api) => {
api.addPostSmallActionClassesCallback((postAttrs) => {
if (postAttrs.canRecover) {
@@ -120,35 +125,33 @@ module(
}
});
});
+ });
- this.set("args", { id: 123, canRecover: false });
+ this.set("args", { id: 123, canRecover: false });
- await render(
- <template>
- <MountWidget @widget="post-small-action" @args={{self.args}} />
- </template>
- );
+ await render(
+ <template>
+ <MountWidget @widget="post-small-action" @args={{self.args}} />
+ </template>
+ );
- assert
- .dom(".abcde")
- .doesNotExist(
- "custom CSS class is not added when condition is not met"
- );
+ assert
+ .dom(".abcde")
+ .doesNotExist(
+ "custom CSS class is not added when condition is not met"
+ );
- this.set("args", { id: 123, canRecover: true });
+ this.set("args", { id: 123, canRecover: true });
- await render(
- <template>
- <MountWidget @widget="post-small-action" @args={{self.args}} />
- </template>
- );
+ await render(
+ <template>
+ <MountWidget @widget="post-small-action" @args={{self.args}} />
+ </template>
+ );
- assert
- .dom(".abcde")
- .exists("adds custom CSS class as registered from the plugin API");
- } finally {
- resetPostSmallActionClassesCallbacks();
- }
+ assert
+ .dom(".abcde")
+ .exists("adds custom CSS class as registered from the plugin API");
});
}
);
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.gjs
index 81876d3dd97..488ca3090c8 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
@@ -13,223 +13,226 @@ function postStreamTest(name, attrs) {
this.set("posts", attrs.posts.call(this));
await render(
- hbs`
- <MountWidget @widget="post-stream" @args={{hash posts=this.posts}} />`
+ hbs`<MountWidget @widget="post-stream" @args={{hash posts=this.posts}} />`
);
attrs.test.call(this, assert);
});
}
-["enabled", "disabled"].forEach((postMenuMode) => {
- let lastTransformedPost = null;
-
- module(
- `Integration | Component | Widget | post-stream (glimmer_post_menu_mode = ${postMenuMode})`,
- function (hooks) {
- setupRenderingTest(hooks);
-
- hooks.beforeEach(function () {
- this.siteSettings.glimmer_post_menu_mode = postMenuMode;
- });
-
- hooks.afterEach(function () {
- resetPostMenuExtraButtons();
- });
-
- const CustomPostMenuButton = <template>
- <DButton
- class="hot-coffee"
- ...attributes
- @icon="mug-saucer"
- @title="coffee.title"
- />
- </template>;
-
- postStreamTest("extensibility", {
- posts() {
- withPluginApi("1.34.0", (api) => {
- api.registerValueTransformer(
- "post-menu-buttons",
- ({ value: dag, context: { post, firstButtonKey } }) => {
- dag.add("coffee", CustomPostMenuButton, {
- before: firstButtonKey,
- });
-
- // value transformers shouldn't have side effects
- // we are only doing it below for testing purposes. Do not use strategies like this in the app code
- lastTransformedPost = post;
- }
+["enabled", "disabled"].forEach((postStreamMode) => {
+ ["enabled", "disabled"].forEach((postMenuMode) => {
+ let lastTransformedPost = null;
+
+ module(
+ `Integration | Component | Widget | post-stream (glimmer_post_stream_mode = ${postStreamMode}) (glimmer_post_menu_mode = ${postMenuMode})`,
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.siteSettings.glimmer_post_menu_mode = postMenuMode;
+ this.siteSettings.glimmer_post_stream_mode = postStreamMode;
+ });
+
+ hooks.afterEach(function () {
+ resetPostMenuExtraButtons();
+ });
+
+ const CustomPostMenuButton = <template>
+ <DButton
+ class="hot-coffee"
+ ...attributes
+ @icon="mug-saucer"
+ @title="coffee.title"
+ />
+ </template>;
+
+ postStreamTest("extensibility", {
+ posts() {
+ withPluginApi("1.34.0", (api) => {
+ api.registerValueTransformer(
+ "post-menu-buttons",
+ ({ value: dag, context: { post, firstButtonKey } }) => {
+ dag.add("coffee", CustomPostMenuButton, {
+ before: firstButtonKey,
+ });
+
+ // value transformers shouldn't have side effects
+ // we are only doing it below for testing purposes. Do not use strategies like this in the app code
+ lastTransformedPost = post;
+ }
+ );
+
+ withSilencedDeprecations(
+ "discourse.post-menu-widget-overrides",
+ () => {
+ api.addPostMenuButton("coffee", (transformedPost) => {
+ lastTransformedPost = transformedPost;
+
+ return {
+ action: "drinkCoffee",
+ icon: "mug-saucer",
+ className: "hot-coffee",
+ title: "coffee.title",
+ position: "first",
+ };
+ });
+ }
+ );
+ });
+
+ const store = getOwner(this).lookup("service:store");
+ const topic = store.createRecord("topic");
+ topic.set("details.created_by", { id: 123 });
+ topic.set("id", 1234);
+
+ return [
+ store.createRecord("post", {
+ topic,
+ id: 1,
+ post_number: 1,
+ user_id: 123,
+ primary_group_name: "trout",
+ avatar_template: "/images/avatar.png",
+ }),
+ ];
+ },
+
+ test(assert) {
+ 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")
+ .exists("it transforms posts");
+ assert.strictEqual(
+ lastTransformedPost.topic.id,
+ 1234,
+ "it also transforms the topic"
);
-
- withSilencedDeprecations(
- "discourse.post-menu-widget-overrides",
- () => {
- api.addPostMenuButton("coffee", (transformedPost) => {
- lastTransformedPost = transformedPost;
-
- return {
- action: "drinkCoffee",
- icon: "mug-saucer",
- className: "hot-coffee",
- title: "coffee.title",
- position: "first",
- };
- });
- }
- );
- });
-
- const store = getOwner(this).lookup("service:store");
- const topic = store.createRecord("topic");
- topic.set("details.created_by", { id: 123 });
- topic.set("id", 1234);
-
- return [
- store.createRecord("post", {
- topic,
- id: 1,
- post_number: 1,
- user_id: 123,
- primary_group_name: "trout",
- avatar_template: "/images/avatar.png",
- }),
- ];
- },
-
- test(assert) {
- 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")
- .exists("it transforms posts");
- assert.strictEqual(
- lastTransformedPost.topic.id,
- 1234,
- "it also transforms the topic"
- );
- assert
- .dom(".actions .hot-coffee")
- .exists({ count: 1 }, "has the extended button");
- },
- });
-
- postStreamTest("basics", {
- posts() {
- const site = getOwner(this).lookup("service:site");
- const store = getOwner(this).lookup("service:store");
- const topic = store.createRecord("topic");
- topic.set("details.created_by", { id: 123 });
-
- return [
- store.createRecord("post", {
- topic,
- id: 1,
- post_number: 1,
- user_id: 123,
- primary_group_name: "trout",
- avatar_template: "/images/avatar.png",
- }),
- store.createRecord("post", {
- topic,
- id: 2,
- post_number: 2,
- post_type: site.get("post_types.moderator_action"),
- }),
- store.createRecord("post", {
- topic,
- id: 3,
- post_number: 3,
- hidden: true,
- }),
- store.createRecord("post", {
- topic,
- id: 4,
- post_number: 4,
- post_type: site.get("post_types.whisper"),
- }),
- store.createRecord("post", {
- topic,
- id: 5,
- post_number: 5,
- wiki: true,
- via_email: true,
- }),
- store.createRecord("post", {
- topic,
- id: 6,
- post_number: 6,
- via_email: true,
- is_auto_generated: true,
- }),
- ];
- },
-
- test(assert) {
- assert.dom(".post-stream").exists({ count: 1 });
- assert.dom(".topic-post").exists({ count: 6 }, "renders all posts");
-
- // look for special class bindings
- assert
- .dom(".topic-post:nth-of-type(1).topic-owner")
- .exists({ count: 1 }, "applies the topic owner class");
- assert
- .dom(".topic-post:nth-of-type(1).group-trout")
- .exists({ count: 1 }, "applies the primary group class");
- assert
- .dom(".topic-post:nth-of-type(1).regular")
- .exists({ count: 1 }, "applies the regular class");
- assert
- .dom(".topic-post:nth-of-type(2).moderator")
- .exists({ count: 1 }, "applies the moderator class");
- assert
- .dom(".topic-post:nth-of-type(3).post-hidden")
- .exists({ count: 1 }, "applies the hidden class");
- assert
- .dom(".topic-post:nth-of-type(4).whisper")
- .exists({ count: 1 }, "applies the whisper class");
- assert
- .dom(".topic-post:nth-of-type(5).wiki")
- .exists({ count: 1 }, "applies the wiki class");
-
- // it renders an article for the body with appropriate attributes
- assert.dom("article#post_2").exists({ count: 1 });
- assert.dom('article[data-user-id="123"]').exists({ count: 1 });
- assert.dom('article[data-post-id="3"]').exists({ count: 1 });
- assert.dom("article#post_5.via-email").exists({ count: 1 });
- assert.dom("article#post_6.is-auto-generated").exists({ count: 1 });
-
- assert
- .dom("article:nth-of-type(1) .main-avatar")
- .exists({ count: 1 }, "renders the main avatar");
- },
- });
-
- postStreamTest("deleted posts", {
- posts() {
- const store = getOwner(this).lookup("service:store");
- const topic = store.createRecord("topic");
- topic.set("details.created_by", { id: 123 });
-
- return [
- store.createRecord("post", {
- topic,
- id: 1,
- post_number: 1,
- deleted_at: new Date().toString(),
- }),
- ];
- },
-
- test(assert) {
- assert
- .dom(".topic-post.deleted")
- .exists({ count: 1 }, "applies the deleted class");
- assert
- .dom(".deleted-user-avatar")
- .exists({ count: 1 }, "has the trash avatar");
- },
- });
- }
- );
+ assert
+ .dom(".actions .hot-coffee")
+ .exists({ count: 1 }, "has the extended button");
+ },
+ });
+
+ postStreamTest("basics", {
+ posts() {
+ const site = getOwner(this).lookup("service:site");
+ const store = getOwner(this).lookup("service:store");
+ const topic = store.createRecord("topic");
+ topic.set("details.created_by", { id: 123 });
+
+ return [
+ store.createRecord("post", {
+ topic,
+ id: 1,
+ post_number: 1,
+ username: "eviltrout",
+ user_id: 123,
+ primary_group_name: "trout",
+ avatar_template: "/images/avatar.png",
+ }),
+ store.createRecord("post", {
+ topic,
+ id: 2,
+ post_number: 2,
+ post_type: site.get("post_types.moderator_action"),
+ }),
+ store.createRecord("post", {
+ topic,
+ id: 3,
+ post_number: 3,
+ hidden: true,
+ }),
+ store.createRecord("post", {
+ topic,
+ id: 4,
+ post_number: 4,
+ post_type: site.get("post_types.whisper"),
+ }),
+ store.createRecord("post", {
+ topic,
+ id: 5,
+ post_number: 5,
+ wiki: true,
+ via_email: true,
+ }),
+ store.createRecord("post", {
+ topic,
+ id: 6,
+ post_number: 6,
+ via_email: true,
+ is_auto_generated: true,
+ }),
+ ];
+ },
+
+ async test(assert) {
+ assert.dom(".post-stream").exists({ count: 1 });
+ assert.dom(".topic-post").exists({ count: 6 }, "renders all posts");
+
+ // look for special class bindings
+ assert
+ .dom(".topic-post:nth-of-type(1).topic-owner")
+ .exists({ count: 1 }, "applies the topic owner class");
+ assert
+ .dom(".topic-post:nth-of-type(1).group-trout")
+ .exists({ count: 1 }, "applies the primary group class");
+ assert
+ .dom(".topic-post:nth-of-type(1).regular")
+ .exists({ count: 1 }, "applies the regular class");
+ assert
+ .dom(".topic-post:nth-of-type(2).moderator")
+ .exists({ count: 1 }, "applies the moderator class");
+ assert
+ .dom(".topic-post:nth-of-type(3).post-hidden")
+ .exists({ count: 1 }, "applies the hidden class");
+ assert
+ .dom(".topic-post:nth-of-type(4).whisper")
+ .exists({ count: 1 }, "applies the whisper class");
+ assert
+ .dom(".topic-post:nth-of-type(5).wiki")
+ .exists({ count: 1 }, "applies the wiki class");
+
+ // it renders an article for the body with appropriate attributes
+ assert.dom("article#post_2").exists({ count: 1 });
+ assert.dom('article[data-user-id="123"]').exists({ count: 1 });
+ assert.dom('article[data-post-id="3"]').exists({ count: 1 });
+ assert.dom("article#post_5.via-email").exists({ count: 1 });
+ assert.dom("article#post_6.is-auto-generated").exists({ count: 1 });
+
+ assert
+ .dom("article:nth-of-type(1) .main-avatar")
+ .exists({ count: 1 }, "renders the main avatar");
+ },
+ });
+
+ postStreamTest("deleted posts", {
+ posts() {
+ const store = getOwner(this).lookup("service:store");
+ const topic = store.createRecord("topic");
+ topic.set("details.created_by", { id: 123 });
+
+ return [
+ store.createRecord("post", {
+ topic,
+ id: 1,
+ post_number: 1,
+ deleted_at: new Date().toString(),
+ }),
+ ];
+ },
+
+ test(assert) {
+ assert
+ .dom(".topic-post.deleted")
+ .exists({ count: 1 }, "applies the deleted class");
+ assert
+ .dom(".deleted-user-avatar")
+ .exists({ count: 1 }, "has the trash avatar");
+ },
+ });
+ }
+ );
+ });
});
diff --git a/app/assets/javascripts/discourse/tests/integration/components/widgets/post-test.gjs b/app/assets/javascripts/discourse/tests/integration/components/widgets/post-test.gjs
index 133d0a4daa2..61e8f7df25f 100644
--- a/app/assets/javascripts/discourse/tests/integration/components/widgets/post-test.gjs
+++ b/app/assets/javascripts/discourse/tests/integration/components/widgets/post-test.gjs
@@ -9,6 +9,7 @@ import { setupRenderingTest } from "discourse/tests/helpers/component-test";
import { i18n } from "discourse-i18n";
import DMenus from "float-kit/components/d-menus";
+// TODO (glimmer-post-stream) remove this test when removing the widget post stream code
module("Integration | Component | Widget | post", function (hooks) {
setupRenderingTest(hooks);
diff --git a/app/assets/javascripts/discourse/tests/integration/components/widgets/poster-name-test.gjs b/app/assets/javascripts/discourse/tests/integration/components/widgets/poster-name-test.gjs
index 2630b14a319..d825a3817e8 100644
--- a/app/assets/javascripts/discourse/tests/integration/components/widgets/poster-name-test.gjs
+++ b/app/assets/javascripts/discourse/tests/integration/components/widgets/poster-name-test.gjs
@@ -5,9 +5,14 @@ import Badge from "discourse/models/badge";
import User from "discourse/models/user";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+// TODO (glimmer-post-stream) remove this test when removing the widget post stream code
module("Integration | Component | Widget | poster-name", function (hooks) {
setupRenderingTest(hooks);
+ hooks.beforeEach(function () {
+ this.siteSettings.glimmer_post_stream_mode = "disabled";
+ });
+
test("basic rendering", async function (assert) {
const args = {
username: "eviltrout",
diff --git a/app/assets/javascripts/discourse/tests/integration/components/widgets/small-user-list-test.gjs b/app/assets/javascripts/discourse/tests/integration/components/widgets/small-user-list-test.gjs
index 3a6ccce8a99..da69d98c548 100644
--- a/app/assets/javascripts/discourse/tests/integration/components/widgets/small-user-list-test.gjs
+++ b/app/assets/javascripts/discourse/tests/integration/components/widgets/small-user-list-test.gjs
@@ -3,6 +3,7 @@ import { module, test } from "qunit";
import MountWidget from "discourse/components/mount-widget";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+// TODO (glimmer-post-stream) remove this test when removing the widget post stream code
module("Integration | Component | Widget | small-user-list", function (hooks) {
setupRenderingTest(hooks);
diff --git a/app/assets/stylesheets/common/base/topic-post.scss b/app/assets/stylesheets/common/base/topic-post.scss
index ea1182677a3..05a3c9aaf36 100644
--- a/app/assets/stylesheets/common/base/topic-post.scss
+++ b/app/assets/stylesheets/common/base/topic-post.scss
@@ -567,7 +567,8 @@ nav.post-controls {
}
}
- .widget-button {
+ .widget-button, // TODO (glimmer-post-stream): Remove this when glimmer-post-stream is enabled
+ .btn {
&:hover {
color: currentcolor;
background: var(--danger-low);
@@ -978,7 +979,8 @@ aside.quote {
}
&.edits {
- .widget-button {
+ .widget-button, // TODO (glimmer-post-stream): Remove this when glimmer-post-stream is enabled
+ .btn {
display: flex;
align-items: center;
@@ -1500,8 +1502,14 @@ span.mention {
}
}
- .post-notice-message p {
- display: inline;
+ .post-notice-message {
+ p {
+ display: inline;
+ }
+
+ .custom_created_by {
+ display: inline-block;
+ }
}
p {
diff --git a/app/assets/stylesheets/desktop/topic-post.scss b/app/assets/stylesheets/desktop/topic-post.scss
index 3767626d05f..63c9e53d2bb 100644
--- a/app/assets/stylesheets/desktop/topic-post.scss
+++ b/app/assets/stylesheets/desktop/topic-post.scss
@@ -227,7 +227,7 @@ pre.codeblock-buttons:hover {
&::before {
content: "";
position: absolute;
- top: -22px;
+ top: -1.5em;
width: 1px;
height: calc(100% + 1.25em);
background: var(--primary-300);
@@ -243,7 +243,7 @@ pre.codeblock-buttons:hover {
&::before {
content: "";
position: absolute;
- top: -22px;
+ top: -1.5em;
width: 1px;
height: calc(100% + 1.5em);
background: var(--primary-300);
@@ -370,7 +370,7 @@ pre.codeblock-buttons:hover {
&::before {
content: "";
position: absolute;
- top: 16px;
+ top: 1.5em;
width: 1px;
height: calc(100% + 1.5em);
background: var(--primary-300);
diff --git a/app/serializers/current_user_serializer.rb b/app/serializers/current_user_serializer.rb
index 3f803d88548..c219fd40f8c 100644
--- a/app/serializers/current_user_serializer.rb
+++ b/app/serializers/current_user_serializer.rb
@@ -76,7 +76,8 @@ class CurrentUserSerializer < BasicUserSerializer
:can_view_raw_email,
:login_method,
:has_unseen_features,
- :can_see_emails
+ :can_see_emails,
+ :use_glimmer_post_stream_mode_auto_mode
delegate :user_stat, to: :object, private: true
delegate :any_posts, :draft_count, :pending_posts_count, :read_faq?, to: :user_stat
@@ -320,4 +321,12 @@ class CurrentUserSerializer < BasicUserSerializer
def include_can_see_emails?
object.staff?
end
+
+ def use_glimmer_post_stream_mode_auto_mode
+ true
+ end
+
+ def include_use_glimmer_post_stream_mode_auto_mode?
+ scope.user.in_any_groups?(SiteSetting.glimmer_post_stream_mode_auto_groups_map)
+ end
end
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index d2da8edb57d..a63a2013644 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -2760,6 +2760,8 @@ en:
glimmer_topic_list_mode: "Control whether the new 'glimmer' topic-list implementation is used. 'auto' will enable automatically once all your themes and plugins are ready. See <a href='https://meta.discourse.org/t/343404'>the Meta topic</a> for more information."
glimmer_post_menu_mode: "Control whether the new 'glimmer' post menu implementation is used. 'auto' will enable automatically once all your themes and plugins are ready. This implementation is under active development, and is not intended for production use. Do not develop themes/plugins against it until the implementation is finalized and announced."
glimmer_post_menu_groups: "Enable the new 'glimmer' post menu implementation in 'auto' mode for the specified user groups. This implementation is under active development, and is not intended for production use. Do not develop themes/plugins against it until the implementation is finalized and announced."
+ glimmer_post_stream_mode: "Control whether the new 'glimmer' post stream implementation is used. 'auto' will enable automatically once all your themes and plugins are ready. This implementation is under active development, and is not intended for production use. Do not develop themes/plugins against it until the implementation is finalized and announced."
+ glimmer_post_stream_mode_auto_groups: "Enable the new 'glimmer' post menu implementation in 'auto' mode for the specified user groups. This implementation is under active development, and is not intended for production use. Do not develop themes/plugins against it until the implementation is finalized and announced."
experimental_form_templates: "Enable the form templates feature. Manage the templates at <a href='%{base_path}/admin/customize/form-templates'>Customize / Templates</a>."
lazy_load_categories_groups: "Lazy load category information only for users of these groups. This improves performance on sites with many categories."
experimental_auto_grid_images: "Automatically wraps images in [grid] tags when 3 or more images are uploaded in the composer."
diff --git a/config/site_settings.yml b/config/site_settings.yml
index 4533ddfab84..21c36f4e805 100644
--- a/config/site_settings.yml
+++ b/config/site_settings.yml
@@ -3570,6 +3570,21 @@ experimental:
- auto
- enabled
default: enabled
+ glimmer_post_stream_mode_auto_groups:
+ client: true
+ type: group_list
+ list_type: compact
+ default: ""
+ allow_any: false
+ refresh: true
+ glimmer_post_stream_mode:
+ client: true
+ type: enum
+ choices:
+ - disabled
+ - auto
+ - enabled
+ default: disabled
enable_rich_text_paste:
client: true
default: true
diff --git a/spec/system/page_objects/pages/topic.rb b/spec/system/page_objects/pages/topic.rb
index b8062d2a984..d11576c3836 100644
--- a/spec/system/page_objects/pages/topic.rb
+++ b/spec/system/page_objects/pages/topic.rb
@@ -123,26 +123,32 @@ module PageObjects
def has_who_liked_on_post?(post, count: nil)
if count
- return within_post(post) { has_css?(".who-liked a.trigger-user-card", count: count) }
+ return(
+ within_post(post) do
+ has_css?(".who-liked.--expanded a.trigger-user-card", count: count)
+ end
+ )
end
- within_post(post) { has_css?(".who-liked") }
+ within_post(post) { has_css?(".who-liked.--expanded") }
end
def has_no_who_liked_on_post?(post)
- within_post(post) { has_no_css?(".who-liked") }
+ within_post(post) { has_no_css?(".who-liked.--expanded") }
end
def has_who_read_on_post?(post, count: nil)
if count
- return within_post(post) { has_css?(".who-read a.trigger-user-card", count: count) }
+ return(
+ within_post(post) { has_css?(".who-read.--expanded a.trigger-user-card", count: count) }
+ )
end
- within_post(post) { has_css?(".who-read") }
+ within_post(post) { has_css?(".who-read.--expanded") }
end
def has_no_who_read_on_post?(post)
- within_post(post) { has_no_css?(".who-read") }
+ within_post(post) { has_no_css?(".who-read.--expanded") }
end
def expand_post_admin_actions(post)
diff --git a/spec/system/table_builder_spec.rb b/spec/system/table_builder_spec.rb
index ef5ecb57559..bf7dc3701d8 100644
--- a/spec/system/table_builder_spec.rb
+++ b/spec/system/table_builder_spec.rb
@@ -7,18 +7,18 @@ describe "Table Builder", type: :system do
fab!(:topic) { Fabricate(:topic, user: user) }
fab!(:topic2) { Fabricate(:topic, user: user) }
fab!(:post1) { create_post(user: user, topic: topic, raw: <<~RAW) }
- |Make | Model | Year|
- |--- | --- | ---|
- |Toyota | Supra | 1998|
- |Nissan | Skyline | 1999|
- |Honda | S2000 | 2001|
- RAW
+ |Make | Model | Year|
+ |--- | --- | ---|
+ |Toyota | Supra | 1998|
+ |Nissan | Skyline | 1999|
+ |Honda | S2000 | 2001|
+ RAW
fab!(:post2) { create_post(user: user, topic: topic2, raw: <<~RAW) }
- | | | |
- |--- | --- | ---|
- |Some | content | here|
- |1 | 2 | 3|
- RAW
+ | | | |
+ |--- | --- | ---|
+ |Some | content | here|
+ |1 | 2 | 3|
+ RAW
let(:topic_page) { PageObjects::Pages::Topic.new }
@@ -28,157 +28,165 @@ describe "Table Builder", type: :system do
content.strip.gsub(/\s+/, " ").gsub(/\r\n/, "\n")
end
- context "when creating a new table" do
- it "should add table items created in spreadsheet to composer input" do
- visit("/latest")
- page.find("#create-topic").click
- page.find(".toolbar-popup-menu-options").click
- page.find(".select-kit-row[data-name='toggle-spreadsheet']").click
- insert_table_modal.type_in_cell(0, 0, "Item 1")
- insert_table_modal.type_in_cell(0, 1, "Item 2")
- insert_table_modal.type_in_cell(0, 2, "Item 3")
- insert_table_modal.type_in_cell(0, 3, "Item 4")
- insert_table_modal.click_insert_table
-
- created_table = <<~TABLE
- |Column 1 | Column 2 | Column 3 | Column 4|
- |--- | --- | --- | ---|
- |Item 1 | Item 2 | Item 3 | Item 4|
- | | | | |
- | | | | |
- | | | | |
- | | | | |
- | | | | |
- TABLE
-
- expect(normalize_value(composer.composer_input.value)).to eq(normalize_value(created_table))
- end
+ %w[enabled disabled].each do |value|
+ before { SiteSetting.glimmer_post_stream_mode = value }
+
+ context "when glimmer_post_stream_mode=#{value}" do
+ context "when creating a new table" do
+ it "should add table items created in spreadsheet to composer input" do
+ visit("/latest")
+ page.find("#create-topic").click
+ page.find(".toolbar-popup-menu-options").click
+ page.find(".select-kit-row[data-name='toggle-spreadsheet']").click
+ insert_table_modal.type_in_cell(0, 0, "Item 1")
+ insert_table_modal.type_in_cell(0, 1, "Item 2")
+ insert_table_modal.type_in_cell(0, 2, "Item 3")
+ insert_table_modal.type_in_cell(0, 3, "Item 4")
+ insert_table_modal.click_insert_table
+
+ created_table = <<~TABLE
+ |Column 1 | Column 2 | Column 3 | Column 4|
+ |--- | --- | --- | ---|
+ |Item 1 | Item 2 | Item 3 | Item 4|
+ | | | | |
+ | | | | |
+ | | | | |
+ | | | | |
+ | | | | |
+ TABLE
+
+ expect(normalize_value(composer.composer_input.value)).to eq(
+ normalize_value(created_table),
+ )
+ end
- context "when cancelling table creation" do
- it "should close the modal if there are no changes made" do
- visit("/latest")
- page.find("#create-topic").click
- page.find(".toolbar-popup-menu-options").click
- page.find(".select-kit-row[data-name='toggle-spreadsheet']").click
- insert_table_modal.cancel
- expect(page).to have_no_css(".insert-table-modal")
+ context "when cancelling table creation" do
+ it "should close the modal if there are no changes made" do
+ visit("/latest")
+ page.find("#create-topic").click
+ page.find(".toolbar-popup-menu-options").click
+ page.find(".select-kit-row[data-name='toggle-spreadsheet']").click
+ insert_table_modal.cancel
+ expect(page).to have_no_css(".insert-table-modal")
+ end
+
+ it "should show a warning popup if there are unsaved changes" do
+ visit("/latest")
+ page.find("#create-topic").click
+ page.find(".toolbar-popup-menu-options").click
+ page.find(".select-kit-row[data-name='toggle-spreadsheet']").click
+ insert_table_modal.type_in_cell(0, 0, "Item 1")
+ insert_table_modal.cancel
+ expect(page).to have_css(".dialog-container .dialog-content")
+ end
+ end
end
- it "should show a warning popup if there are unsaved changes" do
- visit("/latest")
- page.find("#create-topic").click
- page.find(".toolbar-popup-menu-options").click
- page.find(".select-kit-row[data-name='toggle-spreadsheet']").click
- insert_table_modal.type_in_cell(0, 0, "Item 1")
- insert_table_modal.cancel
- expect(page).to have_css(".dialog-container .dialog-content")
- end
- end
- end
+ context "when editing a table" do
+ it "should prefill the spreadsheet with the markdown table items from the post" do
+ topic_page.visit_topic(topic)
+ topic_page.find(".btn-edit-table", visible: :all).click
+ expect(page).to have_selector(".insert-table-modal")
+
+ expected_table_content = [
+ %w[Toyota Supra 1998],
+ %w[Nissan Skyline 1999],
+ %w[Honda S2000 2001],
+ ]
+
+ expected_table_content.each_with_index do |row, row_index|
+ row.each_with_index do |content, col_index|
+ expect(insert_table_modal).to have_content_in_cell(row_index, col_index, content)
+ end
+ end
+ end
- context "when editing a table" do
- it "should prefill the spreadsheet with the markdown table items from the post" do
- topic_page.visit_topic(topic)
- topic_page.find(".btn-edit-table", visible: :all).click
- expect(page).to have_selector(".insert-table-modal")
-
- expected_table_content = [
- %w[Toyota Supra 1998],
- %w[Nissan Skyline 1999],
- %w[Honda S2000 2001],
- ]
-
- expected_table_content.each_with_index do |row, row_index|
- row.each_with_index do |content, col_index|
- expect(insert_table_modal).to have_content_in_cell(row_index, col_index, content)
+ it "should update the post with the new table content" do
+ topic_page.visit_topic(topic)
+ topic_page.find(".btn-edit-table", visible: :all).click
+ expect(page).to have_selector(".insert-table-modal")
+ insert_table_modal.type_in_cell(1, 1, " GTR")
+ insert_table_modal.click_insert_table
+
+ updated_post = <<~RAW
+ |Make | Model | Year|
+ |--- | --- | ---|
+ |Toyota | Supra | 1998|
+ |Nissan | Skyline GTR | 1999|
+ |Honda | S2000 | 2001|
+ RAW
+
+ try_until_success do
+ expect(normalize_value(post1.reload.raw)).to eq(normalize_value(updated_post))
+ end
end
- end
- end
- it "should update the post with the new table content" do
- topic_page.visit_topic(topic)
- topic_page.find(".btn-edit-table", visible: :all).click
- expect(page).to have_selector(".insert-table-modal")
- insert_table_modal.type_in_cell(1, 1, " GTR")
- insert_table_modal.click_insert_table
-
- updated_post = <<~RAW
- |Make | Model | Year|
- |--- | --- | ---|
- |Toyota | Supra | 1998|
- |Nissan | Skyline GTR | 1999|
- |Honda | S2000 | 2001|
- RAW
-
- try_until_success do
- expect(normalize_value(post1.reload.raw)).to eq(normalize_value(updated_post))
- end
- end
+ it "should respect the original empty header" do
+ topic_page.visit_topic(topic2)
+ topic_page.find(".btn-edit-table", visible: :all).click
+ expect(page).to have_selector(".insert-table-modal")
+ insert_table_modal.type_in_cell(0, 0, " updated")
+ insert_table_modal.click_insert_table
+
+ updated_post = <<~RAW
+ | | | |
+ |--- | --- | ---|
+ |Some updated | content | here|
+ |1 | 2 | 3|
+ RAW
+
+ try_until_success do
+ expect(normalize_value(post2.reload.raw)).to eq(normalize_value(updated_post))
+ end
+ end
- it "should respect the original empty header" do
- topic_page.visit_topic(topic2)
- topic_page.find(".btn-edit-table", visible: :all).click
- expect(page).to have_selector(".insert-table-modal")
- insert_table_modal.type_in_cell(0, 0, " updated")
- insert_table_modal.click_insert_table
-
- updated_post = <<~RAW
- | | | |
- |--- | --- | ---|
- |Some updated | content | here|
- |1 | 2 | 3|
- RAW
-
- try_until_success do
- expect(normalize_value(post2.reload.raw)).to eq(normalize_value(updated_post))
- end
- end
+ context "when adding an edit reason" do
+ it "should add the edit reason to the edit history" do
+ edit_reason = "Updated Nissan model"
+
+ topic_page.visit_topic(topic)
+ topic_page.find(".btn-edit-table", visible: :all).click
+ expect(page).to have_selector(".insert-table-modal")
+ insert_table_modal.type_in_cell(1, 1, " GTR")
+ insert_table_modal.click_edit_reason
+ insert_table_modal.type_edit_reason(edit_reason)
+ insert_table_modal.click_insert_table
+ wait_for { post1.reload.edit_reason == edit_reason }
+ expect(post1.reload.edit_reason).to eq(edit_reason)
+ end
+ end
- context "when adding an edit reason" do
- it "should add the edit reason to the edit history" do
- edit_reason = "Updated Nissan model"
-
- topic_page.visit_topic(topic)
- topic_page.find(".btn-edit-table", visible: :all).click
- expect(page).to have_selector(".insert-table-modal")
- insert_table_modal.type_in_cell(1, 1, " GTR")
- insert_table_modal.click_edit_reason
- insert_table_modal.type_edit_reason(edit_reason)
- insert_table_modal.click_insert_table
- wait_for { post1.reload.edit_reason == edit_reason }
- expect(post1.reload.edit_reason).to eq(edit_reason)
- end
- end
+ context "when cancelling table creation" do
+ it "should close the modal if there are no changes made" do
+ topic_page.visit_topic(topic)
+ topic_page.find(".btn-edit-table", visible: :all).click
+ expect(page).to have_selector(".insert-table-modal")
+ insert_table_modal.cancel
+ expect(page).to have_no_css(".insert-table-modal")
+ end
+
+ it "should show a warning popup if there are unsaved changes" do
+ topic_page.visit_topic(topic)
+ topic_page.find(".btn-edit-table", visible: :all).click
+ expect(page).to have_selector(".insert-table-modal")
+ insert_table_modal.type_in_cell(1, 1, " GTR")
+ insert_table_modal.cancel
+ expect(page).to have_css(".dialog-container .dialog-content")
+ end
+ end
- context "when cancelling table creation" do
- it "should close the modal if there are no changes made" do
- topic_page.visit_topic(topic)
- topic_page.find(".btn-edit-table", visible: :all).click
- expect(page).to have_selector(".insert-table-modal")
- insert_table_modal.cancel
- expect(page).to have_no_css(".insert-table-modal")
- end
+ it "should not accept default Discourse keyboard shortcuts" do
+ # Some default keyboard shortcuts like Shift + S bring up a modal overriding
+ # the table builder modal and therefore should not be accepted
- it "should show a warning popup if there are unsaved changes" do
- topic_page.visit_topic(topic)
- topic_page.find(".btn-edit-table", visible: :all).click
- expect(page).to have_selector(".insert-table-modal")
- insert_table_modal.type_in_cell(1, 1, " GTR")
- insert_table_modal.cancel
- expect(page).to have_css(".dialog-container .dialog-content")
+ topic_page.visit_topic(topic)
+ topic_page.find(".btn-edit-table", visible: :all).click
+ insert_table_modal.find_cell(0, 0)
+ insert_table_modal.send_keys(:shift, "s")
+ expect(page).to have_css(".insert-table-modal")
+ expect(page).to have_no_css(".share-topic-modal")
+ end
end
end
-
- it "should not accept default Discourse keyboard shortcuts" do
- # Some default keyboard shortcuts like Shift + S bring up a modal overriding
- # the table builder modal and therefore should not be accepted
-
- topic_page.visit_topic(topic)
- topic_page.find(".btn-edit-table", visible: :all).click
- insert_table_modal.find_cell(0, 0)
- insert_table_modal.send_keys(:shift, "s")
- expect(page).to have_css(".insert-table-modal")
- expect(page).to have_no_css(".share-topic-modal")
- end
end
end