A platform for community discussion. Free, open, simple.
DEV: [gjs-codemod] merge js and hbs
David Taylorca2f974f38c7
diff --cc app/assets/javascripts/discourse/app/components/avatar-uploader.gjsindex cd0ad6e5348,c5ad0b52b1e..3d3740b148f--- a/app/assets/javascripts/discourse/app/components/avatar-uploader.gjs+++ b/app/assets/javascripts/discourse/app/components/avatar-uploader.gjs@@@ -1,22 -1,50 +1,73 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { getOwner } from "@ember/owner";+ import { isBlank } from "@ember/utils";+ import { tagName } from "@ember-decorators/component";+ import discourseComputed from "discourse/lib/decorators";+ import UppyUpload from "discourse/lib/uppy/uppy-upload";+ import { i18n } from "discourse-i18n";++ @tagName("span")+ export default class AvatarUploader extends Component {+ uppyUpload = new UppyUpload(getOwner(this), {+ id: "avatar-uploader",+ type: "avatar",+ validateUploadedFilesOptions: {+ imagesOnly: true,+ },+ uploadDone: (upload) => {+ this.setProperties({+ imageIsNotASquare: upload.width !== upload.height,+ uploadedAvatarTemplate: upload.url,+ uploadedAvatarId: upload.id,+ });++ this.done();+ },+ additionalParams: () => ({+ user_id: this.user_id,+ }),+ });++ imageIsNotASquare = false;++ @discourseComputed("uppyUpload.uploading", "uploadedAvatarId")+ customAvatarUploaded() {+ return !this.uppyUpload.uploading && !isBlank(this.uploadedAvatarId);+ }++ @discourseComputed("uppyUpload.uploading", "uppyUpload.uploadProgress")+ uploadLabel() {+ return this.uppyUpload.uploading+ ? `${i18n("uploading")} ${this.uppyUpload.uploadProgress}%`+ : i18n("upload");+ }++ @action+ chooseImage() {+ this.uppyUpload.openPicker();+ }+ }+++<input+ {{did-insert this.uppyUpload.setup}}+ class="hidden-upload-field"+ disabled={{this.uploading}}+ type="file"+ accept="image/*"+ aria-hidden="true"+/>+<DButton+ @translatedLabel={{this.uploadLabel}}+ @icon="far-image"+ @disabled={{this.uploading}}+ @action={{this.chooseImage}}+ @title="user.change_avatar.upload_title"+ class="btn-default avatar-uploader__button"+ data-uploaded={{this.customAvatarUploaded}}+ data-avatar-upload-id={{this.uploadedAvatarId}}+/>++{{#if this.imageIsNotASquare}}+ <div class="warning">{{i18n "user.change_avatar.image_is_not_a_square"}}</div>+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/basic-topic-list.gjsindex 57968678fb4,080a2d7f3bd..05939a03b85--- a/app/assets/javascripts/discourse/app/components/basic-topic-list.gjs+++ b/app/assets/javascripts/discourse/app/components/basic-topic-list.gjs@@@ -1,39 -1,117 +1,157 @@@+ import Component from "@ember/component";+ import { alias, not } from "@ember/object/computed";+ import { service } from "@ember/service";+ import { observes } from "@ember-decorators/object";+ import $ from "jquery";+ import discourseComputed, { bind } from "discourse/lib/decorators";++ export default class BasicTopicList extends Component {+ @service site;++ @alias("topicList.loadingMore") loadingMore;++ @not("loaded") loading;++ init() {+ super.init(...arguments);+ const topicList = this.topicList;+ if (topicList) {+ this._initFromTopicList(topicList);+ }+ }++ @discourseComputed("topicList.loaded")+ loaded() {+ let topicList = this.topicList;+ if (topicList) {+ return topicList.get("loaded");+ } else {+ return true;+ }+ }++ @observes("topicList.[]")+ _topicListChanged() {+ this._initFromTopicList(this.topicList);+ }++ _initFromTopicList(topicList) {+ if (topicList !== null) {+ this.set("topics", topicList.get("topics"));+ this.rerender();+ }+ }++ didInsertElement() {+ super.didInsertElement(...arguments);++ this.topics.forEach((topic) => {+ if (typeof topic.unread_by_group_member !== "undefined") {+ this.messageBus.subscribe(+ `/private-messages/unread-indicator/${topic.id}`,+ this.onMessage+ );+ }+ });+ }++ willDestroyElement() {+ super.willDestroyElement(...arguments);++ this.messageBus.unsubscribe(+ "/private-messages/unread-indicator/*",+ this.onMessage+ );+ }++ @bind+ onMessage(data) {+ const nodeClassList = document.querySelector(+ `.indicator-topic-${data.topic_id}`+ ).classList;++ nodeClassList.toggle("read", !data.show_indicator);+ }++ @discourseComputed("topics")+ showUnreadIndicator(topics) {+ return topics.some(+ (topic) => typeof topic.unread_by_group_member !== "undefined"+ );+ }++ click(e) {+ // Mobile basic-topic-list doesn't use the `topic-list-item` view so+ // the event for the topic entrance is never wired up.+ if (this.site.desktopView) {+ return;+ }++ let target = $(e.target);+ if (target.closest(".posts-map").length) {+ const topicId = target.closest("tr").attr("data-topic-id");+ if (topicId) {+ if (target.prop("tagName") !== "A") {+ let targetLinks = target.find("a");+ if (targetLinks.length) {+ target = targetLinks;+ } else {+ targetLinks = target.closest("a");+ if (targetLinks.length) {+ target = targetLinks;+ } else {+ return false;+ }+ }+ }++ const topic = this.topics.findBy("id", parseInt(topicId, 10));+ this.appEvents.trigger("topic-entrance:show", {+ topic,+ position: target.offset(),+ });+ }+ return false;+ }+ }+ }+++<ConditionalLoadingSpinner @condition={{this.loading}}>+ {{#if this.topics}}+ {{#if this.site.useGlimmerTopicList}}+ <TopicList::List+ @showPosters={{this.showPosters}}+ @hideCategory={{this.hideCategory}}+ @topics={{this.topics}}+ @expandExcerpts={{this.expandExcerpts}}+ @bulkSelectHelper={{this.bulkSelectHelper}}+ @canBulkSelect={{this.canBulkSelect}}+ @tagsForUser={{this.tagsForUser}}+ @changeSort={{this.changeSort}}+ @order={{this.order}}+ @ascending={{this.ascending}}+ @focusLastVisitedTopic={{this.focusLastVisitedTopic}}+ />+ {{else}}+ <TopicList+ @showPosters={{this.showPosters}}+ @hideCategory={{this.hideCategory}}+ @topics={{this.topics}}+ @expandExcerpts={{this.expandExcerpts}}+ @bulkSelectHelper={{this.bulkSelectHelper}}+ @canBulkSelect={{this.canBulkSelect}}+ @tagsForUser={{this.tagsForUser}}+ @changeSort={{this.changeSort}}+ @order={{this.order}}+ @ascending={{this.ascending}}+ @focusLastVisitedTopic={{this.focusLastVisitedTopic}}+ />+ {{/if}}+ {{else}}+ {{#unless this.loadingMore}}+ <div class="alert alert-info">+ {{i18n "choose_topic.none_found"}}+ </div>+ {{/unless}}+ {{/if}}+</ConditionalLoadingSpinner>diff --cc app/assets/javascripts/discourse/app/components/bulk-actions/notification-level.gjsindex c351a6e3747,8ac08a1ee9c..2f39b7390da--- a/app/assets/javascripts/discourse/app/components/bulk-actions/notification-level.gjs+++ b/app/assets/javascripts/discourse/app/components/bulk-actions/notification-level.gjs@@@ -1,21 -1,28 +1,50 @@@+ import Component from "@glimmer/component";+ import { action } from "@ember/object";+ import { empty } from "@ember/object/computed";+ import { topicLevels } from "discourse/lib/notification-levels";+ import { i18n } from "discourse-i18n";++ // Support for changing the notification level of various topics+ export default class NotificationLevel extends Component {+ notificationLevelId = null;++ @empty("notificationLevelId") disabled;++ get notificationLevels() {+ return topicLevels.map((level) => ({+ id: level.id.toString(),+ name: i18n(`topic.notifications.${level.key}.title`),+ description: i18n(`topic.notifications.${level.key}.description`),+ }));+ }++ @action+ changeNotificationLevel() {+ this.args.performAndRefresh({+ type: "change_notification_level",+ notification_level_id: this.notificationLevelId,+ });+ }+ }+++<div class="bulk-notification-list">+ {{#each this.notificationLevels as |level|}}+ <div class="controls">+ <label class="radio notification-level-radio checkbox-label">+ <RadioButton+ @value={{level.id}}+ @name="notification_level"+ @selection={{this.notificationLevelId}}+ />+ <strong>{{level.name}}</strong>+ <div class="description">{{html-safe level.description}}</div>+ </label>+ </div>+ {{/each}}+</div>++<DButton+ @disabled={{this.disabled}}+ @action={{this.changeNotificationLevel}}+ @label="topics.bulk.change_notification_level"+/>diff --cc app/assets/javascripts/discourse/app/components/calendar-date-time-input.gjsindex 800d5d2f2f8,42aacfe048e..fc15ad7c414--- a/app/assets/javascripts/discourse/app/components/calendar-date-time-input.gjs+++ b/app/assets/javascripts/discourse/app/components/calendar-date-time-input.gjs@@@ -1,24 -1,110 +1,135 @@@+ /* global Pikaday:true */+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { isEmpty } from "@ember/utils";+ import { Promise } from "rsvp";+ import loadScript from "discourse/lib/load-script";+ import { i18n } from "discourse-i18n";++ export default class CalendarDateTimeInput extends Component {+ _timeFormat = this.args.timeFormat || "HH:mm:ss";+ _dateFormat = this.args.dateFormat || "YYYY-MM-DD";+ _dateTimeFormat = this.args.dateTimeFormat || "YYYY-MM-DD HH:mm:ss";+ _picker = null;++ @tracked _time;+ @tracked _date;++ @action+ setupInternalDateTime() {+ this._time = this.args.time;+ this._date = this.args.date;+ }++ @action+ setupPikaday(element) {+ this.#setupPicker(element).then((picker) => {+ this._picker = picker;+ });+ }++ @action+ onChangeTime(event) {+ this._time = event.target.value;+ this.args.onChangeTime(this._time);+ }++ @action+ changeDate() {+ if (moment(this.args.date, this._dateFormat).isValid()) {+ this._date = this.args.date;+ this._picker.setDate(+ // using the format YYYY-MM-DD returns the previous day for some timezones+ moment.utc(this._date).format("YYYY/MM/DD"),+ true+ );+ } else {+ this._date = null;+ this._picker.setDate(null);+ }+ }++ @action+ changeTime() {+ if (isEmpty(this.args.time)) {+ this._time = null;+ return;+ }++ if (/^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/.test(this.args.time)) {+ this._time = this.args.time;+ }+ }++ @action+ changeMinDate() {+ if (+ this.args.minDate &&+ moment(this.args.minDate, this._dateFormat).isValid()+ ) {+ this._picker.setMinDate(+ moment(this.args.minDate, this._dateFormat).toDate()+ );+ } else {+ this._picker.setMinDate(null);+ }+ }++ #setupPicker(element) {+ return new Promise((resolve) => {+ loadScript("/javascripts/pikaday.js").then(() => {+ const options = {+ field: element.querySelector(".fake-input"),+ container: element.querySelector(+ `#picker-container-${this.args.datePickerId}`+ ),+ bound: false,+ format: "YYYY-MM-DD",+ reposition: false,+ firstDay: 1,+ setDefaultDate: true,+ keyboardInput: false,+ i18n: {+ previousMonth: i18n("dates.previous_month"),+ nextMonth: i18n("dates.next_month"),+ months: moment.months(),+ weekdays: moment.weekdays(),+ weekdaysShort: moment.weekdaysMin(),+ },+ onSelect: (date) => {+ const formattedDate = moment(date).format("YYYY-MM-DD");+ this.args.onChangeDate(formattedDate);+ },+ };++ resolve(new Pikaday(options));+ });+ });+ }+ }+++<div+ class="calendar-date-time-input"+ {{did-insert this.setupInternalDateTime}}+ {{did-insert this.setupPikaday}}+ {{did-update this.changeMinDate @minDate}}+ {{did-update this.changeDate @date}}+ {{did-update this.changeTime @time}}+>+ <Input class="fake-input" />++ <div class="date-picker" id="picker-container-{{@datePickerId}}"></div>++ <div class="time-pickers">+ {{d-icon "far-clock"}}+ <Input+ maxlength={{5}}+ placeholder="hh:mm"+ @type="time"+ @value={{this._time}}+ class="time-picker"+ {{on "input" (action this.onChangeTime)}}+ />+ </div>+</div>diff --cc app/assets/javascripts/discourse/app/components/categories-and-latest-topics.gjsindex 4a5c5167e58,25202aa1981..6352d855385--- a/app/assets/javascripts/discourse/app/components/categories-and-latest-topics.gjs+++ b/app/assets/javascripts/discourse/app/components/categories-and-latest-topics.gjs@@@ -1,13 -1,5 +1,19 @@@+ import Component from "@ember/component";+ import { classNames } from "@ember-decorators/component";++ @classNames("categories-and-latest")+ export default class CategoriesAndLatestTopics extends Component {}+++<div class="column categories">+ <CategoriesOnly @categories={{this.categories}} />+</div>++<div class="column">+ <CategoriesTopicList+ @topics={{this.topics}}+ @filter="latest"+ class="latest-topic-list"+ />+</div>++<PluginOutlet @name="extra-categories-column" @connectorTagName="div" />diff --cc app/assets/javascripts/discourse/app/components/categories-and-top-topics.gjsindex 298c5f73fdf,9d45c11eab7..4ccb917f53c--- a/app/assets/javascripts/discourse/app/components/categories-and-top-topics.gjs+++ b/app/assets/javascripts/discourse/app/components/categories-and-top-topics.gjs@@@ -1,13 -1,5 +1,19 @@@+ import Component from "@ember/component";+ import { classNames } from "@ember-decorators/component";++ @classNames("categories-and-top")+ export default class CategoriesAndTopTopics extends Component {}+++<div class="column categories">+ <CategoriesOnly @categories={{this.categories}} />+</div>++<div class="column">+ <CategoriesTopicList+ @topics={{this.topics}}+ @filter="top"+ class="top-topic-list"+ />+</div>++<PluginOutlet @name="extra-categories-column" @connectorTagName="div" />diff --cc app/assets/javascripts/discourse/app/components/categories-boxes-topic.gjsindex 94883c33cca,0eb986cb352..cbc75bf42c9--- a/app/assets/javascripts/discourse/app/components/categories-boxes-topic.gjs+++ b/app/assets/javascripts/discourse/app/components/categories-boxes-topic.gjs@@@ -1,5 -1,18 +1,24 @@@+ import Component from "@ember/component";+ import { attributeBindings, tagName } from "@ember-decorators/component";+ import discourseComputed from "discourse/lib/decorators";++ @tagName("li")+ @attributeBindings("topic.id:data-topic-id")+ export default class CategoriesBoxesTopic extends Component {+ @discourseComputed("topic.pinned", "topic.closed", "topic.archived")+ topicStatusIcon(pinned, closed, archived) {+ if (pinned) {+ return "thumbtack";+ }+ if (closed || archived) {+ return "lock";+ }+ return "far-file-lines";+ }+ }+++{{d-icon this.topicStatusIcon}}++<a href={{this.topic.lastUnreadUrl}} class="title">+ {{html-safe this.topic.fancyTitle}}+</a>diff --cc app/assets/javascripts/discourse/app/components/categories-boxes-with-topics.gjsindex 5e0c8831124,18aa465577c..82e62f0e238--- a/app/assets/javascripts/discourse/app/components/categories-boxes-with-topics.gjs+++ b/app/assets/javascripts/discourse/app/components/categories-boxes-with-topics.gjs@@@ -1,45 -1,20 +1,66 @@@+ import Component from "@ember/component";+ import { isEmpty } from "@ember/utils";+ import { classNameBindings, tagName } from "@ember-decorators/component";+ import discourseComputed from "discourse/lib/decorators";++ @tagName("section")+ @classNameBindings(+ ":category-boxes-with-topics",+ "anyLogos:with-logos:no-logos"+ )+ export default class CategoriesBoxesWithTopics extends Component {+ lockIcon = "lock";++ @discourseComputed("categories.[].uploaded_logo.url")+ anyLogos() {+ return this.categories.any((c) => {+ return !isEmpty(c.get("uploaded_logo.url"));+ });+ }+ }+++{{#each this.categories as |c|}}+ <div+ data-notification-level={{c.notificationLevelString}}+ style={{category-color-variable c.color}}+ class="category category-box category-box-{{c.slug}}+ {{if c.isMuted 'muted'}}"+ >+ <div class="category-box-inner">+ <div class="category-box-heading">+ <a class="parent-box-link" href={{c.url}}>+ {{#unless c.isMuted}}+ {{#if c.uploaded_logo.url}}+ <CategoryLogo @category={{c}} />+ {{/if}}+ {{/unless}}++ <h3>+ <CategoryTitleBefore @category={{c}} />+ {{#if c.read_restricted}}+ {{d-icon this.lockIcon}}+ {{/if}}+ {{c.displayName}}+ </h3>+ </a>+ </div>++ {{#unless c.isMuted}}+ <div class="featured-topics">+ {{#if c.topics}}+ <ul>+ {{#each c.topics as |topic|}}+ <CategoriesBoxesTopic @topic={{topic}} />+ {{/each}}+ </ul>+ {{/if}}+ </div>+ {{/unless}}++ <PluginOutlet+ @name="category-box-below-each-category"+ @outletArgs={{hash category=c}}+ />+ </div>+ </div>+{{/each}}diff --cc app/assets/javascripts/discourse/app/components/categories-boxes.gjsindex 949f0740e1a,91bb02b62f6..076e7445705--- a/app/assets/javascripts/discourse/app/components/categories-boxes.gjs+++ b/app/assets/javascripts/discourse/app/components/categories-boxes.gjs@@@ -1,112 -1,24 +1,137 @@@+ import Component from "@ember/component";+ import { isEmpty } from "@ember/utils";+ import { classNameBindings, tagName } from "@ember-decorators/component";+ import discourseComputed from "discourse/lib/decorators";++ @tagName("section")+ @classNameBindings(+ ":category-boxes",+ "anyLogos:with-logos:no-logos",+ "hasSubcategories:with-subcategories"+ )+ export default class CategoriesBoxes extends Component {+ lockIcon = "lock";++ @discourseComputed("categories.[].uploaded_logo.url")+ anyLogos() {+ return this.categories.any((c) => !isEmpty(c.get("uploaded_logo.url")));+ }++ @discourseComputed("categories.[].subcategories")+ hasSubcategories() {+ return this.categories.any((c) => !isEmpty(c.get("subcategories")));+ }+ }+++<PluginOutlet+ @name="categories-boxes-wrapper"+ @outletArgs={{hash categories=this.categories}}+>+ {{#each this.categories as |c|}}+ <PluginOutlet+ @name="category-box-before-each-box"+ @outletArgs={{hash category=c}}+ />++ <div+ style={{category-color-variable c.color}}+ data-category-id={{c.id}}+ data-notification-level={{c.notificationLevelString}}+ data-url={{c.url}}+ class="category category-box category-box-{{c.slug}}+ {{if c.isMuted 'muted'}}"+ >+ <div class="category-box-inner">+ {{#unless c.isMuted}}+ <div class="category-logo">+ {{#if c.uploaded_logo.url}}+ <CategoryLogo @category={{c}} />+ {{/if}}+ </div>+ {{/unless}}++ <div class="category-details">+ <div class="category-box-heading">+ <a class="parent-box-link" href={{c.url}}>+ <h3>+ <CategoryTitleBefore @category={{c}} />+ {{#if c.read_restricted}}+ {{d-icon this.lockIcon}}+ {{/if}}+ {{c.displayName}}+ </h3>+ </a>+ </div>++ {{#unless c.isMuted}}+ <div class="description">+ {{html-safe c.description_excerpt}}+ </div>++ {{#if c.isGrandParent}}+ {{#each c.subcategories as |subcategory|}}+ <div+ data-category-id={{subcategory.id}}+ data-notification-level={{subcategory.notificationLevelString}}+ style={{border-color subcategory.color}}+ class="subcategory with-subcategories+ {{if subcategory.uploaded_logo.url 'has-logo' 'no-logo'}}"+ >+ <div class="subcategory-box-inner">+ <CategoryTitleLink+ @tagName="h4"+ @category={{subcategory}}+ />+ {{#if subcategory.subcategories}}+ <div class="subcategories">+ {{#each subcategory.subcategories as |subsubcategory|}}+ {{#unless subsubcategory.isMuted}}+ <span class="subcategory">+ <CategoryTitleBefore+ @category={{subsubcategory}}+ />+ {{category-link subsubcategory hideParent="true"}}+ </span>+ {{/unless}}+ {{/each}}+ </div>+ {{/if}}+ </div>+ </div>+ {{/each}}+ {{else if c.subcategories}}+ <div class="subcategories">+ {{#each c.subcategories as |sc|}}+ <a class="subcategory" href={{sc.url}}>+ <span class="subcategory-image-placeholder">+ {{#if sc.uploaded_logo.url}}+ <CategoryLogo @category={{sc}} />+ {{/if}}+ </span>++ {{category-link sc hideParent="true"}}+ </a>+ {{/each}}+ </div>+ {{/if}}+ {{/unless}}+ </div>++ <PluginOutlet+ @name="category-box-below-each-category"+ @outletArgs={{hash category=c}}+ />+ </div>+ </div>++ <PluginOutlet+ @name="category-box-after-each-box"+ @outletArgs={{hash category=c}}+ />+ {{/each}}+</PluginOutlet>++<PluginOutlet+ @name="category-boxes-after-boxes"+ @outletArgs={{hash category=this.c}}+/>diff --cc app/assets/javascripts/discourse/app/components/categories-only.gjsindex f546cbbe9d3,55a8188a165..cd98eaac8a1--- a/app/assets/javascripts/discourse/app/components/categories-only.gjs+++ b/app/assets/javascripts/discourse/app/components/categories-only.gjs@@@ -1,113 -1,56 +1,170 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { tagName } from "@ember-decorators/component";+ import discourseComputed from "discourse/lib/decorators";++ @tagName("")+ export default class CategoriesOnly extends Component {+ showMuted = false;++ @discourseComputed("showMutedCategories", "filteredCategories.length")+ mutedToggleIcon(showMutedCategories, filteredCategoriesLength) {+ if (filteredCategoriesLength === 0) {+ return;+ }++ if (showMutedCategories) {+ return "minus";+ }++ return "plus";+ }++ @discourseComputed("showMuted", "filteredCategories.length")+ showMutedCategories(showMuted, filteredCategoriesLength) {+ return showMuted || filteredCategoriesLength === 0;+ }++ @discourseComputed("categories", "categories.length")+ filteredCategories(categories, categoriesLength) {+ if (!categories || categoriesLength === 0) {+ return [];+ }++ return categories.filter((cat) => !cat.isHidden);+ }++ @discourseComputed("categories", "categories.length")+ mutedCategories(categories, categoriesLength) {+ if (!categories || categoriesLength === 0) {+ return [];+ }++ // hide in single category pages+ if (categories.firstObject.parent_category_id) {+ return [];+ }++ return categories.filterBy("hasMuted");+ }++ @action+ toggleShowMuted(event) {+ event?.preventDefault();+ this.toggleProperty("showMuted");+ }+ }+++<PluginOutlet+ @name="categories-only-wrapper"+ @outletArgs={{hash categories=this.categories}}+>+ {{#if this.categories}}+ {{#if this.filteredCategories}}+ {{#if this.site.mobileView}}+ <div class="category-list {{if this.showTopics 'with-topics'}}">+ <PluginOutlet+ @name="mobile-categories"+ @outletArgs={{hash categories=this.filteredCategories}}+ >+ {{#each this.filteredCategories as |c|}}+ <ParentCategoryRow+ @category={{c}}+ @showTopics={{this.showTopics}}+ />+ {{/each}}+ </PluginOutlet>+ </div>+ {{else}}+ <table class="category-list {{if this.showTopics 'with-topics'}}">+ <thead>+ <tr>+ <th class="category"><span+ role="heading"+ aria-level="2"+ id="categories-only-category"+ >{{i18n "categories.category"}}</span></th>+ <th class="topics">{{i18n "categories.topics"}}</th>+ {{#if this.showTopics}}+ <th class="latest">{{i18n "categories.latest"}}</th>+ {{/if}}+ </tr>+ </thead>+ <tbody aria-labelledby="categories-only-category">+ {{#each this.categories as |category|}}+ <ParentCategoryRow+ @category={{category}}+ @showTopics={{this.showTopics}}+ />+ {{/each}}+ </tbody>+ </table>+ {{/if}}+ {{/if}}++ {{#if this.mutedCategories}}+ <div class="muted-categories">+ <a+ href+ class="muted-categories-link"+ {{on "click" this.toggleShowMuted}}+ >+ <h3 class="muted-categories-heading">{{i18n "categories.muted"}}</h3>+ {{#if this.mutedToggleIcon}}+ {{d-icon this.mutedToggleIcon}}+ {{/if}}+ </a>+ {{#if this.site.mobileView}}+ <div+ class="category-list+ {{if this.showTopics 'with-topics'}}+ {{unless this.showMutedCategories 'hidden'}}"+ >+ {{#each this.mutedCategories as |c|}}+ <ParentCategoryRow+ @category={{c}}+ @showTopics={{this.showTopics}}+ @listType="muted"+ />+ {{/each}}+ </div>+ {{else}}+ <table+ class="category-list+ {{if this.showTopics 'with-topics'}}+ {{unless this.showMutedCategories 'hidden'}}"+ >+ <thead>+ <tr>+ <th class="category"><span+ role="heading"+ aria-level="2"+ id="categories-only-category-muted"+ >{{i18n "categories.category"}}</span></th>+ <th class="topics">{{i18n "categories.topics"}}</th>+ {{#if this.showTopics}}+ <th class="latest">{{i18n "categories.latest"}}</th>+ {{/if}}+ </tr>+ </thead>+ <tbody aria-labelledby="categories-only-category-muted">+ {{#each this.categories as |category|}}+ <ParentCategoryRow+ @category={{category}}+ @showTopics={{this.showTopics}}+ @listType="muted"+ />+ {{/each}}+ </tbody>+ </table>+ {{/if}}+ </div>+ {{/if}}+ {{/if}}+</PluginOutlet>++<PluginOutlet+ @name="below-categories-only"+ @connectorTagName="div"+ @outletArgs={{hash categories=this.categories showTopics=this.showTopics}}+/>diff --cc app/assets/javascripts/discourse/app/components/categories-topic-list.gjsindex 89c1f2cffea,a6f761e33f9..3ded2a33a12--- a/app/assets/javascripts/discourse/app/components/categories-topic-list.gjs+++ b/app/assets/javascripts/discourse/app/components/categories-topic-list.gjs@@@ -1,40 -1,4 +1,45 @@@+ import Component from "@ember/component";++ // Exists so plugins can use it+ export default class CategoriesTopicList extends Component {}+++<div role="heading" aria-level="2" class="table-heading">+ {{i18n (concat "filters." this.filter ".title")}}+ <PluginOutlet+ @name="categories-topics-table-heading"+ @connectorTagName="div"+ />+</div>++{{#if this.topics}}+ {{#each this.topics as |t|}}+ {{#if this.site.useGlimmerTopicList}}+ <TopicList::LatestTopicListItem @topic={{t}} />+ {{else}}+ <LatestTopicListItem @topic={{t}} />+ {{/if}}+ {{/each}}++ <div class="more-topics">+ {{#if+ (eq+ this.siteSettings.desktop_category_page_style+ "categories_and_latest_topics_created_date"+ )+ }}+ <a+ href={{get-url (concat "/" this.filter "?order=created")}}+ class="btn btn-default pull-right"+ >{{i18n "more"}}</a>+ {{else}}+ <a+ href={{get-url (concat "/" this.filter)}}+ class="btn btn-default pull-right"+ >{{i18n "more"}}</a>+ {{/if}}+ </div>+{{else}}+ <div class="no-topics">+ <h3>{{i18n (concat "topics.none." this.filter)}}</h3>+ </div>+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/categories-with-featured-topics.gjsindex 30855c0a4af,f094b65746f..66df6a9641d--- a/app/assets/javascripts/discourse/app/components/categories-with-featured-topics.gjs+++ b/app/assets/javascripts/discourse/app/components/categories-with-featured-topics.gjs@@@ -1,1 -1,3 +1,5 @@@+ import Component from "@ember/component";++ export default class CategoriesWithFeaturedTopics extends Component {}+++<CategoriesOnly @categories={{this.categories}} @showTopics="true" />diff --cc app/assets/javascripts/discourse/app/components/category-name-fields.gjsindex 82784f133a1,edc8b634fd0..df10704db27--- a/app/assets/javascripts/discourse/app/components/category-name-fields.gjs+++ b/app/assets/javascripts/discourse/app/components/category-name-fields.gjs@@@ -1,26 -1,3 +1,30 @@@+ import Component from "@ember/component";++ export default class CategoryNameFields extends Component {}+++<PluginOutlet+ @name="category-name-fields-details"+ @outletArgs={{hash category=this.category}}+>+ <section class="field category-name-fields">+ {{#unless this.category.isUncategorizedCategory}}+ <section class="field-item">+ <label>{{i18n "category.name"}}</label>+ <TextField+ @value={{this.category.name}}+ @placeholderKey="category.name_placeholder"+ @maxlength="50"+ class="category-name"+ />+ </section>+ {{/unless}}+ <section class="field-item">+ <label>{{i18n "category.slug"}}</label>+ <TextField+ @value={{this.category.slug}}+ @placeholderKey="category.slug_placeholder"+ @maxlength="255"+ />+ </section>+ </section>+</PluginOutlet>diff --cc app/assets/javascripts/discourse/app/components/category-title-link.gjsindex 1284bf33c59,a5120584b6e..2d9f5298619--- a/app/assets/javascripts/discourse/app/components/category-title-link.gjs+++ b/app/assets/javascripts/discourse/app/components/category-title-link.gjs@@@ -1,12 -1,8 +1,21 @@@+ import Component from "@ember/component";+ import { tagName } from "@ember-decorators/component";++ @tagName("h3")+ export default class CategoryTitleLink extends Component {}++ // icon name defined on prototype so it can be easily overridden in theme components+ CategoryTitleLink.prototype.lockIcon = "lock";+++<a class="category-title-link" href={{this.category.url}}>+ <div class="category-text-title">+ <CategoryTitleBefore @category={{this.category}} />+ {{#if this.category.read_restricted}}+ {{d-icon this.lockIcon}}+ {{/if}}+ <span class="category-name">{{dir-span this.category.displayName}}</span>+ </div>+ {{#if this.category.uploaded_logo.url}}+ <CategoryLogo @category={{this.category}} />+ {{/if}}+</a>diff --cc app/assets/javascripts/discourse/app/components/category-unread.gjsindex 459ccc57945,33d4e31ad81..019ba8e6518--- a/app/assets/javascripts/discourse/app/components/category-unread.gjs+++ b/app/assets/javascripts/discourse/app/components/category-unread.gjs@@@ -1,17 -1,6 +1,24 @@@+ import Component from "@ember/component";+ import { classNames, tagName } from "@ember-decorators/component";++ @tagName("span")+ @classNames("category__badges")+ export default class CategoryUnread extends Component {}+++{{#if this.unreadTopicsCount}}+ <a+ href={{this.category.unreadUrl}}+ title={{i18n "topic.unread_topics" count=this.unreadTopicsCount}}+ class="badge new-posts badge-notification"+ >{{i18n+ "filters.unread.lower_title_with_count"+ count=this.unreadTopicsCount+ }}</a>+{{/if}}+{{#if this.newTopicsCount}}+ <a+ href={{this.category.newUrl}}+ title={{i18n "topic.new_topics" count=this.newTopicsCount}}+ class="badge new-posts badge-notification"+ >{{i18n "filters.new.lower_title_with_count" count=this.newTopicsCount}}</a>+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/color-picker.gjsindex f326731b149,a450bcc44cb..c23f9907c2b--- a/app/assets/javascripts/discourse/app/components/color-picker.gjs+++ b/app/assets/javascripts/discourse/app/components/color-picker.gjs@@@ -1,10 -1,23 +1,34 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { attributeBindings, classNames } from "@ember-decorators/component";+ import { i18n } from "discourse-i18n";++ @classNames("colors-container")+ @attributeBindings("role", "ariaLabel:aria-label")+ export default class ColorPicker extends Component {+ role = "group";++ @action+ selectColor(color) {+ this.set("value", color);+ }++ @action+ getColorLabel(color) {+ const isUsed = this.usedColors?.includes(color.toUpperCase())+ ? i18n("category.color_used")+ : "";+ return `#${color} ${isUsed}`;+ }+ }+++{{#each this.colors as |c|}}+ <ColorPickerChoice+ @color={{c}}+ @usedColors={{this.usedColors}}+ @selectColor={{action "selectColor"}}+ @ariaLabel={{this.getColorLabel c}}+ >+ {{d-icon "check"}}+ </ColorPickerChoice>+{{/each}}diff --cc app/assets/javascripts/discourse/app/components/composer-messages.gjsindex 8a3b2880e79,463f8fc0d7e..025ecbe6520--- a/app/assets/javascripts/discourse/app/components/composer-messages.gjs+++ b/app/assets/javascripts/discourse/app/components/composer-messages.gjs@@@ -1,14 -1,341 +1,356 @@@+ import { tracked } from "@glimmer/tracking";+ import Component from "@ember/component";+ import EmberObject, { action } from "@ember/object";+ import { not } from "@ember/object/computed";+ import { schedule } from "@ember/runloop";+ import { service } from "@ember/service";+ import { classNameBindings } from "@ember-decorators/component";+ import { ajax } from "discourse/lib/ajax";+ import { debounce } from "discourse/lib/decorators";+ import { INPUT_DELAY } from "discourse/lib/environment";+ import LinkLookup from "discourse/lib/link-lookup";+ import { i18n } from "discourse-i18n";++ let _messagesCache = {};++ @classNameBindings(":composer-popup-container", "hidden")+ export default class ComposerMessages extends Component {+ @service modal;++ @tracked showShareModal;++ checkedMessages = false;+ messages = null;+ messagesByTemplate = null;+ queuedForTyping = null;+ similarTopics = null;+ usersNotSeen = null;+ recipientNames = [];++ @not("composer.viewOpenOrFullscreen") hidden;++ _lastSimilaritySearch = null;+ _similarTopicsMessage = null;++ didInsertElement() {+ super.didInsertElement(...arguments);++ this.appEvents.on("composer:typed-reply", this, this._typedReply);+ this.appEvents.on("composer:opened", this, this._findMessages);+ this.appEvents.on("composer:find-similar", this, this._findSimilar);+ this.appEvents.on("composer-messages:close", this, this._closeTop);+ this.appEvents.on("composer-messages:create", this, this._create);+ this.reset();+ }++ willDestroyElement() {+ super.willDestroyElement(...arguments);++ this.appEvents.off("composer:typed-reply", this, this._typedReply);+ this.appEvents.off("composer:opened", this, this._findMessages);+ this.appEvents.off("composer:find-similar", this, this._findSimilar);+ this.appEvents.off("composer-messages:close", this, this._closeTop);+ this.appEvents.off("composer-messages:create", this, this._create);+ }++ _closeTop() {+ if (this.isDestroying || this.isDestroyed) {+ return;+ }++ this.messages.popObject();+ this.set("messageCount", this.messages.length);+ }++ _removeMessage(message) {+ this.messages.removeObject(message);+ this.set("messageCount", this.messages.length);+ }++ _create(info) {+ if (this.isDestroying || this.isDestroyed) {+ return;+ }++ schedule("actions", () => {+ this.reset();+ this.popup(EmberObject.create(info));+ });+ }++ // Resets all active messages.+ // For example if composing a new post.+ reset() {+ this.setProperties({+ messages: [],+ messagesByTemplate: {},+ queuedForTyping: [],+ checkedMessages: false,+ similarTopics: [],+ });+ }++ // Called after the user has typed a reply.+ // Some messages only get shown after being typed.+ @debounce(INPUT_DELAY)+ async _typedReply() {+ if (this.isDestroying || this.isDestroyed) {+ return;+ }++ for (const msg of this.queuedForTyping) {+ if (this.composer.whisper && msg.hide_if_whisper) {+ return;+ }++ this.popup(msg);+ }++ if (this.composer.privateMessage) {+ if (+ this.composer.targetRecipientsArray.length > 0 &&+ this.composer.targetRecipientsArray.every(+ (r) => r.name === this.currentUser.username+ )+ ) {+ const message = this.composer.store.createRecord("composer-message", {+ id: "yourself_confirm",+ templateName: "education",+ title: i18n("composer.yourself_confirm.title"),+ body: i18n("composer.yourself_confirm.body"),+ });++ this.popup(message);+ }++ const recipient_names = this.composer.targetRecipientsArray+ .filter((r) => r.type === "user")+ .map(({ name }) => name);++ if (+ recipient_names.length > 0 &&+ recipient_names.length !== this.recipientNames.length &&+ !recipient_names.every((v, i) => v === this.recipientNames[i])+ ) {+ this.recipientNames = recipient_names;++ const response = await ajax(+ `/composer_messages/user_not_seen_in_a_while`,+ {+ type: "GET",+ data: {+ usernames: recipient_names,+ },+ }+ );++ if (this.isDestroying || this.isDestroyed) {+ return;+ }++ if (+ response.user_count > 0 &&+ this.usersNotSeen !== response.usernames.join("-")+ ) {+ this.set("usersNotSeen", response.usernames.join("-"));+ this.messagesByTemplate["education"] = undefined;++ let usernames = [];+ response.usernames.forEach((username, index) => {+ usernames[index] =+ `<a class='mention' href='/u/${username}'>@${username}</a>`;+ });++ let body_key;+ if (response.user_count === 1) {+ body_key = "composer.user_not_seen_in_a_while.single";+ } else {+ body_key = "composer.user_not_seen_in_a_while.multiple";+ }++ const message = this.composer.store.createRecord("composer-message", {+ id: "user-not-seen",+ templateName: "education",+ body: i18n(body_key, {+ usernames: usernames.join(", "),+ time_ago: response.time_ago,+ }),+ });++ this.popup(message);+ }+ }+ }+ }++ async _findSimilar() {+ if (this.isDestroying || this.isDestroyed) {+ return;+ }++ // We don't care about similar topics unless creating a topic+ if (!this.composer.creatingTopic) {+ return;+ }++ // We don't care about similar topics when creating with a form template+ if (this.composer?.category?.form_template_ids.length > 0) {+ return;+ }++ // TODO: pass the 200 in from somewhere+ const raw = (this.composer.reply || "").slice(0, 200);+ const title = this.composer.title || "";++ // Ensure we have at least a title+ if (title.length < this.siteSettings.min_title_similar_length) {+ return;+ }++ // Don't search over and over+ const concat = title + raw;+ if (concat === this._lastSimilaritySearch) {+ return;+ }++ this._lastSimilaritySearch = concat;+ this._similarTopicsMessage ||= this.composer.store.createRecord(+ "composer-message",+ {+ id: "similar_topics",+ templateName: "similar-topics",+ extraClass: "similar-topics",+ }+ );++ const topics = await this.composer.store.find("similar-topic", {+ title,+ raw,+ });++ if (this.isDestroying || this.isDestroyed) {+ return;+ }++ this.similarTopics.clear();+ this.similarTopics.pushObjects(topics.content);++ if (this.similarTopics.length > 0) {+ this._similarTopicsMessage.set("similarTopics", this.similarTopics);+ this.popup(this._similarTopicsMessage);+ } else if (this._similarTopicsMessage) {+ this.hideMessage(this._similarTopicsMessage);+ }+ }++ // Figure out if there are any messages that should be displayed above the composer.+ async _findMessages() {+ if (this.isDestroying || this.isDestroyed) {+ return;+ }++ if (this.checkedMessages) {+ return;+ }++ const args = { composer_action: this.composer.action };+ const topicId = this.composer.topic?.id;+ const postId = this.composer.post?.id;++ if (topicId) {+ args.topic_id = topicId;+ }++ if (postId) {+ args.post_id = postId;+ }++ const cacheKey = `${args.composer_action}${args.topic_id}${args.post_id}`;++ let messages;+ if (_messagesCache.cacheKey === cacheKey) {+ messages = _messagesCache.messages;+ } else {+ messages = await this.composer.store.find("composer-message", args);+ if (this.isDestroying || this.isDestroyed) {+ return;+ }++ _messagesCache = { messages, cacheKey };+ }++ // Checking composer messages on replies can give us a list of links to check for+ // duplicates+ if (messages.extras?.duplicate_lookup) {+ this.addLinkLookup(new LinkLookup(messages.extras.duplicate_lookup));+ }++ this.set("checkedMessages", true);++ messages.forEach((msg) => {+ if (msg.wait_for_typing) {+ this.queuedForTyping.addObject(msg);+ } else {+ this.popup(msg);+ }+ });+ }++ @action+ closeMessage(message, event) {+ event?.preventDefault();+ this._removeMessage(message);+ }++ @action+ hideMessage(message) {+ this._removeMessage(message);++ // kind of hacky but the visibility depends on this+ this.messagesByTemplate[message.templateName] = undefined;+ }++ @action+ popup(message) {+ if (!this.messagesByTemplate[message.templateName]) {+ this.messages.pushObject(message);+ this.set("messageCount", this.messages.length);+ this.messagesByTemplate[message.templateName] = message;+ }+ }++ get shareModalData() {+ const { topic } = this.composer;+ return {+ topic,+ category: topic.category,+ allowInvites:+ topic.details.can_invite_to &&+ !topic.archived &&+ !topic.closed &&+ !topic.deleted,+ };+ }++ @action+ switchPM(message) {+ this.composer.set("action", "privateMessage");+ this.composer.set("targetRecipients", message.reply_username);+ this._removeMessage(message);+ }+ }+++{{#each this.messages as |message|}}+ <ComposerMessage+ @message={{message}}+ @closeMessage={{this.closeMessage}}+ @shareModal={{fn (mut this.showShareModal) true}}+ @switchPM={{this.switchPM}}+ />+ {{#if this.showShareModal}}+ <Modal::ShareTopic+ @closeModal={{fn (mut this.showShareModal) false}}+ @model={{this.shareModalData}}+ />+ {{/if}}+{{/each}}diff --cc app/assets/javascripts/discourse/app/components/composer-title.gjsindex 7be52e6e8b9,53de89fea31..66ba14ec200--- a/app/assets/javascripts/discourse/app/components/composer-title.gjs+++ b/app/assets/javascripts/discourse/app/components/composer-title.gjs@@@ -1,17 -1,237 +1,255 @@@+ import Component from "@ember/component";+ import EmberObject from "@ember/object";+ import { alias, or } from "@ember/object/computed";+ import { next, schedule } from "@ember/runloop";+ import { classNames } from "@ember-decorators/component";+ import { observes } from "@ember-decorators/object";+ import { load } from "pretty-text/oneboxer";+ import { lookupCache } from "pretty-text/oneboxer-cache";+ import { ajax } from "discourse/lib/ajax";+ import discourseDebounce from "discourse/lib/debounce";+ import discourseComputed from "discourse/lib/decorators";+ import { isTesting } from "discourse/lib/environment";+ import putCursorAtEnd from "discourse/lib/put-cursor-at-end";+ import { i18n } from "discourse-i18n";++ @classNames("title-input")+ export default class ComposerTitle extends Component {+ @alias("composer.canEditTopicFeaturedLink") watchForLink;+ @or("composer.loading", "composer.disableTitleInput") disabled;++ isTitleFocused = false;++ didInsertElement() {+ super.didInsertElement(...arguments);+ const titleInput = this.element.querySelector("input");++ this._focusHandler = () => this.set("isTitleFocused", true);+ this._blurHandler = () => this.set("isTitleFocused", false);++ titleInput.addEventListener("focus", this._focusHandler);+ titleInput.addEventListener("blur", this._blurHandler);++ if (this.focusTarget === "title") {+ putCursorAtEnd(titleInput);+ }++ if (this.get("composer.titleLength") > 0) {+ discourseDebounce(this, this._titleChanged, 10);+ }+ }++ willDestroyElement() {+ super.willDestroyElement(...arguments);+ const titleInput = this.element.querySelector("input");++ if (titleInput) {+ titleInput.removeEventListener("focus", this._focusHandler);+ titleInput.removeEventListener("blur", this._blurHandler);+ }+ }++ @discourseComputed(+ "composer.titleLength",+ "composer.missingTitleCharacters",+ "composer.minimumTitleLength",+ "lastValidatedAt",+ "isTitleFocused"+ )+ validation(+ titleLength,+ missingTitleChars,+ minimumTitleLength,+ lastValidatedAt,+ isTitleFocused+ ) {+ let reason;+ if (isTitleFocused) {+ return;+ }+ if (titleLength < 1) {+ reason = i18n("composer.error.title_missing");+ } else if (missingTitleChars > 0) {+ reason = i18n("composer.error.title_too_short", {+ count: minimumTitleLength,+ });+ } else if (titleLength > this.siteSettings.max_topic_title_length) {+ reason = i18n("composer.error.title_too_long", {+ count: this.siteSettings.max_topic_title_length,+ });+ }++ if (reason) {+ return EmberObject.create({+ failed: true,+ reason,+ lastShownAt: lastValidatedAt,+ });+ }+ }++ @discourseComputed("watchForLink")+ titleMaxLength(watchForLink) {+ // maxLength gets in the way of pasting long links, so don't use it if featured links are allowed.+ // Validation will display a message if titles are too long.+ return watchForLink ? null : this.siteSettings.max_topic_title_length;+ }++ @observes("composer.titleLength", "watchForLink")+ _titleChanged() {+ if (this.get("composer.titleLength") === 0) {+ this.set("autoPosted", false);+ }+ if (this.autoPosted || !this.watchForLink) {+ return;+ }++ if (isTesting()) {+ next(() =>+ // not ideal but we don't want to run this in current+ // runloop to avoid an error in console+ this._checkForUrl()+ );+ } else {+ discourseDebounce(this, this._checkForUrl, 500);+ }+ }++ @observes("composer.replyLength")+ _clearFeaturedLink() {+ if (this.watchForLink && this.bodyIsDefault()) {+ this.set("composer.featuredLink", null);+ }+ }++ _checkForUrl() {+ if (!this.element || this.isDestroying || this.isDestroyed) {+ return;+ }++ if (this.isAbsoluteUrl && this.bodyIsDefault()) {+ // only feature links to external sites+ if (+ this.get("composer.title").match(+ new RegExp("^https?:\\/\\/" + window.location.hostname, "i")+ )+ ) {+ return;+ }++ // Try to onebox. If success, update post body and title.+ this.set("composer.loading", true);++ const link = document.createElement("a");+ link.href = this.get("composer.title");++ const loadOnebox = load({+ elem: link,+ refresh: false,+ ajax,+ synchronous: true,+ categoryId: this.get("composer.category.id"),+ topicId: this.get("composer.topic.id"),+ });++ if (loadOnebox && loadOnebox.then) {+ loadOnebox+ .then(() => {+ const v = lookupCache(this.get("composer.title"));+ this._updatePost(v ? v : link);+ })+ .finally(() => {+ this.set("composer.loading", false);+ schedule("afterRender", () => {+ putCursorAtEnd(this.element.querySelector("input"));+ });+ });+ } else {+ this._updatePost(loadOnebox);+ this.set("composer.loading", false);+ schedule("afterRender", () => {+ putCursorAtEnd(this.element.querySelector("input"));+ });+ }+ }+ }++ _updatePost(html) {+ if (html) {+ const frag = document.createRange().createContextualFragment(html),+ composer = this.composer;++ this.set("autoPosted", true);+ this.set("composer.featuredLink", this.get("composer.title"));++ composer.appendText(this.get("composer.title"), null, { block: true });++ if (frag.querySelector(".twitterstatus")) {+ this.set("composer.title", "");+ return;+ }++ const heading = frag.querySelector("h3, h4");++ const title =+ (heading && heading.textContent) ||+ (frag.firstElementChild && frag.firstElementChild.title);++ if (title) {+ this.changeTitle(title);+ } else {+ const firstTitle =+ (frag.firstChild &&+ frag.firstChild.attributes &&+ frag.firstChild.attributes.title) ||+ (frag.querySelector("[title]") &&+ frag.querySelector("[title]").attributes.title);++ if (firstTitle) {+ this.changeTitle(firstTitle);+ }+ }+ }+ }++ changeTitle(val) {+ if (val && val.length > 0) {+ this.set("composer.title", val.trim());+ }+ }++ @discourseComputed("composer.title", "composer.titleLength")+ isAbsoluteUrl(title, titleLength) {+ return (+ titleLength > 0 &&+ /^(https?:)?\/\/[\w\.\-]+/i.test(title) &&+ !/\s/.test(title)+ );+ }++ bodyIsDefault() {+ const reply = this.get("composer.reply") || "";+ return (+ reply.length === 0 ||+ reply === (this.get("composer.category.topic_template") || "")+ );+ }+ }+++<TextField+ @value={{this.composer.title}}+ @id="reply-title"+ @maxLength={{this.titleMaxLength}}+ @placeholderKey={{this.composer.titlePlaceholder}}+ @aria-label={{i18n this.composer.titlePlaceholder}}+ @disabled={{this.disabled}}+ @autocomplete="off"+/>++<PluginOutlet+ @name="after-composer-title-input"+ @connectorTagName="div"+ @outletArgs={{hash composer=this.composer}}+/>++<PopupInputTip @validation={{this.validation}} />diff --cc app/assets/javascripts/discourse/app/components/composer-toggles.gjsindex 64599357350,334dc9a03e2..69e0b46c416--- a/app/assets/javascripts/discourse/app/components/composer-toggles.gjs+++ b/app/assets/javascripts/discourse/app/components/composer-toggles.gjs@@@ -1,31 -1,51 +1,83 @@@+ import Component from "@ember/component";+ import { tagName } from "@ember-decorators/component";+ import discourseComputed from "discourse/lib/decorators";++ @tagName("")+ export default class ComposerToggles extends Component {+ @discourseComputed("composeState")+ toggleTitle(composeState) {+ return composeState === "draft" || composeState === "saving"+ ? "composer.abandon"+ : "composer.collapse";+ }++ @discourseComputed("showToolbar")+ toggleToolbarTitle(showToolbar) {+ return showToolbar ? "composer.hide_toolbar" : "composer.show_toolbar";+ }++ @discourseComputed("composeState")+ fullscreenTitle(composeState) {+ return composeState === "draft"+ ? "composer.open"+ : composeState === "fullscreen"+ ? "composer.exit_fullscreen"+ : "composer.enter_fullscreen";+ }++ @discourseComputed("composeState")+ toggleIcon(composeState) {+ return composeState === "draft" || composeState === "saving"+ ? "xmark"+ : "angles-down";+ }++ @discourseComputed("composeState")+ fullscreenIcon(composeState) {+ return composeState === "draft"+ ? "angles-up"+ : composeState === "fullscreen"+ ? "discourse-compress"+ : "discourse-expand";+ }++ @discourseComputed("disableTextarea")+ showFullScreenButton(disableTextarea) {+ if (this.site.mobileView) {+ return false;+ }+ return !disableTextarea;+ }+ }+++<div class="composer-controls">+ <span>+ <PluginOutlet @name="before-composer-toggles" @connectorTagName="div" />+ </span>++ {{#if this.site.mobileView}}+ <DButton+ @icon="bars"+ @action={{this.toggleToolbar}}+ @title={{this.toggleToolbarTitle}}+ @preventFocus={{true}}+ class="btn-flat toggle-toolbar btn-mini-toggle"+ />+ {{/if}}++ {{#if this.showFullScreenButton}}+ <DButton+ @icon={{this.fullscreenIcon}}+ @action={{this.toggleFullscreen}}+ @title={{this.fullscreenTitle}}+ class="btn-transparent toggle-fullscreen btn-mini-toggle"+ />+ {{/if}}++ <DButton+ @icon={{this.toggleIcon}}+ @action={{this.toggleComposer}}+ @title={{this.toggleTitle}}+ class="btn-transparent toggler toggle-minimize btn-mini-toggle"+ />+</div>diff --cc app/assets/javascripts/discourse/app/components/conditional-loading-section.gjsindex c6a424f5989,de9e508010a..e5847d11095--- a/app/assets/javascripts/discourse/app/components/conditional-loading-section.gjs+++ b/app/assets/javascripts/discourse/app/components/conditional-loading-section.gjs@@@ -1,6 -1,10 +1,17 @@@+ import Component from "@ember/component";+ import { classNameBindings, classNames } from "@ember-decorators/component";+ import { i18n } from "discourse-i18n";++ @classNames("conditional-loading-section")+ @classNameBindings("isLoading")+ export default class ConditionalLoadingSection extends Component {+ isLoading = false;+ title = i18n("conditional_loading_section.loading");+ }+++{{#if this.isLoading}}+ <span class="title">{{this.title}}</span>+ <div class="spinner {{this.size}}"></div>+{{else}}+ {{yield}}+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/copy-button.gjsindex 3eccc6b803f,ee010f80da0..265c9bc814a--- a/app/assets/javascripts/discourse/app/components/copy-button.gjs+++ b/app/assets/javascripts/discourse/app/components/copy-button.gjs@@@ -1,7 -1,49 +1,57 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { tagName } from "@ember-decorators/component";+ import discourseDebounce from "discourse/lib/debounce";+ import { bind } from "discourse/lib/decorators";++ @tagName("")+ export default class CopyButton extends Component {+ copyIcon = "copy";+ copyClass = "btn-primary";++ init() {+ super.init(...arguments);++ this.copyTranslatedLabel = this.translatedLabel;+ }++ @bind+ _restoreButton() {+ if (this.isDestroying || this.isDestroyed) {+ return;+ }++ this.set("copyIcon", "copy");+ this.set("copyClass", "btn-primary");+ this.set("copyTranslatedLabel", this.translatedLabel);+ }++ @action+ copy() {+ const target = document.querySelector(this.selector);+ target.select();+ target.setSelectionRange(0, target.value.length);++ try {+ document.execCommand("copy");++ if (this.copied) {+ this.copied();+ }++ this.set("copyIcon", "check");+ this.set("copyClass", "btn-primary ok");+ this.set("copyTranslatedLabel", this.translatedLabelAfterCopy);++ discourseDebounce(this._restoreButton, 3000);+ } catch {}+ }+ }+++<DButton+ @icon={{this.copyIcon}}+ @action={{this.copy}}+ class="copy-button {{this.copyClass}}"+ @ariaLabel={{this.ariaLabel}}+ @translatedLabel={{this.copyTranslatedLabel}}+/>diff --cc app/assets/javascripts/discourse/app/components/create-invite-uploader.gjsindex 9ce3d560d12,4b953a6401d..a18e12983eb--- a/app/assets/javascripts/discourse/app/components/create-invite-uploader.gjs+++ b/app/assets/javascripts/discourse/app/components/create-invite-uploader.gjs@@@ -1,11 -1,34 +1,46 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { getOwner } from "@ember/owner";+ import { tagName } from "@ember-decorators/component";+ import discourseComputed from "discourse/lib/decorators";+ import UppyUpload from "discourse/lib/uppy/uppy-upload";++ @tagName("div")+ export default class CreateInviteUploader extends Component {+ uppyUpload = new UppyUpload(getOwner(this), {+ id: "create-invite-uploader",+ type: "csv",+ autoStartUploads: false,+ uploadUrl: "/invites/upload_csv",+ preventDirectS3Uploads: true,+ validateUploadedFilesOptions: {+ bypassNewUserRestriction: true,+ csvOnly: true,+ },+ uploadDone: () => {+ this.set("uploaded", true);+ },+ });++ @discourseComputed("uppyUpload.filesAwaitingUpload", "uppyUpload.uploading")+ submitDisabled(filesAwaitingUpload, uploading) {+ return !filesAwaitingUpload || uploading;+ }++ @action+ startUpload() {+ this.uppyUpload.startUpload();+ }+ }+++{{yield+ (hash+ data=this.data+ uploading=this.uploading+ uploadProgress=this.uploadProgress+ uploaded=this.uploaded+ submitDisabled=this.submitDisabled+ startUpload=this.startUpload+ )+ this.uppyUpload.setup+}}diff --cc app/assets/javascripts/discourse/app/components/create-topic-button.gjsindex 9329d9bb83d,c0357b24819..7ff581bca27--- a/app/assets/javascripts/discourse/app/components/create-topic-button.gjs+++ b/app/assets/javascripts/discourse/app/components/create-topic-button.gjs@@@ -1,23 -1,16 +1,40 @@@+ import Component from "@ember/component";+ import { tagName } from "@ember-decorators/component";++ @tagName("")+ export default class CreateTopicButton extends Component {+ label = "topic.create";+ btnClass = "btn-default";++ get disallowedReason() {+ if (this.canCreateTopicOnTag === false) {+ return "topic.create_disabled_tag";+ } else if (this.disabled) {+ return "topic.create_disabled_category";+ }+ }+ }+++{{#if this.canCreateTopic}}+ <DButtonTooltip>+ <:button>+ <DButton+ @action={{this.action}}+ @icon="far-pen-to-square"+ @disabled={{this.disabled}}+ @label={{this.label}}+ id="create-topic"+ class={{this.btnClass}}+ />+ </:button>+ <:tooltip>+ {{#if @disabled}}+ <DTooltip @icon="circle-info" @content={{i18n this.disallowedReason}} />+ {{/if}}+ </:tooltip>+ </DButtonTooltip>++ {{#if @showDrafts}}+ <TopicDraftsDropdown @disabled={{this.disabled}} />+ {{/if}}+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/d-navigation-item.gjsindex 9b4688f8b68,bb10be80a85..f9e22564b5e--- a/app/assets/javascripts/discourse/app/components/d-navigation-item.gjs+++ b/app/assets/javascripts/discourse/app/components/d-navigation-item.gjs@@@ -1,16 -1,34 +1,51 @@@+ import Component from "@glimmer/component";+ import { service } from "@ember/service";+ import { makeArray } from "discourse/lib/helpers";++ export default class DNavigationItem extends Component {+ @service router;++ get ariaCurrent() {+ // when there are multiple levels of navigation+ // we want the active parent to get `aria-current="page"`+ // and the active child to get `aria-current="location"`+ if (+ this.args.ariaCurrentContext === "parentNav" &&+ this.router.currentRouteName !== this.args.route && // not the current route+ this.router.currentRoute.parent.name.includes(this.args.route) // but is the current parent route+ ) {+ return "page";+ }++ if (this.router.currentRouteName !== this.args.route) {+ return null;+ }++ if (this.args.ariaCurrentContext === "subNav") {+ return "location";+ } else {+ return "page";+ }+ }++ get models() {+ return makeArray(this.args.models || this.args.model);+ }+ }+++<li+ aria-current={{this.ariaCurrent}}+ title={{@title}}+ class={{@class}}+ ...attributes+>+ {{#if this.models}}+ <LinkTo @route={{@route}} @models={{this.models}}>+ {{yield}}+ </LinkTo>+ {{else}}+ <LinkTo @route={{@route}}>+ {{yield}}+ </LinkTo>+ {{/if}}+</li>diff --cc app/assets/javascripts/discourse/app/components/date-input.gjsindex 80ac09a293c,b5ac5bdcd13..06dc832556d--- a/app/assets/javascripts/discourse/app/components/date-input.gjs+++ b/app/assets/javascripts/discourse/app/components/date-input.gjs@@@ -1,12 -1,172 +1,185 @@@+ /* global Pikaday:true */+ import Component from "@ember/component";+ import { action, computed } from "@ember/object";+ import { schedule } from "@ember/runloop";+ import { classNames } from "@ember-decorators/component";+ import { on } from "@ember-decorators/object";+ import { Promise } from "rsvp";+ import discourseComputed from "discourse/lib/decorators";+ import loadScript from "discourse/lib/load-script";+ import { i18n } from "discourse-i18n";++ function isInputDateSupported() {+ const input = document.createElement("input");+ const value = "a";+ input.setAttribute("type", "date");+ input.setAttribute("value", value);+ return input.value !== value;+ }++ @classNames("d-date-input")+ export default class DateInput extends Component {+ date = null;+ useNativePicker = isInputDateSupported();+ _picker = null;++ @discourseComputed("site.mobileView")+ inputType() {+ return this.useNativePicker ? "date" : "text";+ }++ click(event) {+ event.stopPropagation();+ }++ didInsertElement() {+ super.didInsertElement(...arguments);++ schedule("afterRender", () => {+ if (!this.element || this.isDestroying || this.isDestroying) {+ return;+ }++ let promise;+ const container = document.getElementById(this.containerId);++ if (this.useNativePicker) {+ promise = this._loadNativePicker(container);+ } else {+ promise = this._loadPikadayPicker(container);+ }++ promise.then((picker) => {+ this._picker = picker;++ if (this._picker && this.date) {+ const parsedDate =+ this.date instanceof moment ? this.date : moment(this.date);+ this._picker.setDate(parsedDate, true);+ }+ });+ });+ }++ didUpdateAttrs() {+ super.didUpdateAttrs(...arguments);++ if (this._picker && this.date) {+ const parsedDate =+ this.date instanceof moment ? this.date : moment(this.date);+ this._picker.setDate(parsedDate, true);+ }++ if (this._picker && this.relativeDate) {+ const parsedRelativeDate =+ this.relativeDate instanceof moment+ ? this.relativeDate+ : moment(this.relativeDate);++ this._picker.setMinDate(parsedRelativeDate, true);+ }++ if (this._picker && !this.date) {+ this._picker.setDate(null);+ }+ }++ _loadPikadayPicker(container) {+ return loadScript("/javascripts/pikaday.js").then(() => {+ let defaultOptions = {+ field: this.element.querySelector(".date-picker"),+ container: container || this.element.querySelector(".picker-container"),+ bound: container === null,+ format: "LL",+ firstDay: 1,+ i18n: {+ previousMonth: i18n("dates.previous_month"),+ nextMonth: i18n("dates.next_month"),+ months: moment.months(),+ weekdays: moment.weekdays(),+ weekdaysShort: moment.weekdaysShort(),+ },+ onSelect: (date) => this._handleSelection(date),+ };++ if (this.relativeDate) {+ defaultOptions.minDate = moment(this.relativeDate).toDate();+ }++ return new Pikaday({ ...defaultOptions, ...this._opts() });+ });+ }++ _loadNativePicker(container) {+ const wrapper = container || this.element;+ const picker = wrapper.querySelector("input.date-picker");+ picker.onchange = () => this._handleSelection(picker.value);+ picker.hide = () => {+ /* do nothing for native */+ };+ picker.destroy = () => {+ /* do nothing for native */+ };+ picker.setDate = (date) => {+ picker.value = date ? moment(date).format("YYYY-MM-DD") : null;+ };+ picker.setMinDate = (date) => {+ picker.min = date;+ };++ if (this.date) {+ picker.setDate(this.date);+ }++ return Promise.resolve(picker);+ }++ _handleSelection(value) {+ if (!this.element || this.isDestroying || this.isDestroyed) {+ return;+ }++ if (this.onChange) {+ this.onChange(value ? moment(value) : null);+ }+ }++ @on("willDestroyElement")+ _destroy() {+ if (this._picker) {+ this._picker.destroy();+ this._picker = null;+ }+ }++ @computed("_placeholder")+ get placeholder() {+ return this._placeholder || i18n("dates.placeholder");+ }++ set placeholder(value) {+ this.set("_placeholder", value);+ }++ _opts() {+ return null;+ }++ @action+ onChangeDate(event) {+ this._handleSelection(event.target.value);+ }+ }+++<Input+ @type={{this.inputType}}+ class="date-picker"+ placeholder={{this.placeholder}}+ @value={{readonly this.value}}+ id={{this.inputId}}+ {{on "input" (action "onChangeDate")}}+/>++{{#unless this.useGlobalPickerContainer}}+ <div class="picker-container"></div>+{{/unless}}diff --cc app/assets/javascripts/discourse/app/components/date-picker.gjsindex 27037d14bb9,769d88b5842..4af71984ea6--- a/app/assets/javascripts/discourse/app/components/date-picker.gjs+++ b/app/assets/javascripts/discourse/app/components/date-picker.gjs@@@ -1,8 -1,111 +1,120 @@@+ /* global Pikaday:true */+ import Component from "@ember/component";+ import { computed } from "@ember/object";+ import { schedule } from "@ember/runloop";+ import { classNames } from "@ember-decorators/component";+ import { on } from "@ember-decorators/object";+ import discourseComputed from "discourse/lib/decorators";+ import loadScript from "discourse/lib/load-script";+ import { i18n } from "discourse-i18n";++ const DATE_FORMAT = "YYYY-MM-DD";++ @classNames("date-picker-wrapper")+ export default class DatePicker extends Component {+ value = null;+ minDate = null;+ maxDate = null;+ _picker = null;++ @discourseComputed("site.mobileView")+ inputType(mobileView) {+ return mobileView ? "date" : "text";+ }++ @on("didInsertElement")+ _loadDatePicker() {+ if (this.site.mobileView) {+ this._loadNativePicker();+ } else {+ const container = document.getElementById(this.containerId);+ this._loadPikadayPicker(container);+ }+ }++ _loadPikadayPicker(container) {+ loadScript("/javascripts/pikaday.js").then(() => {+ schedule("afterRender", () => {+ const options = {+ field: this.element.querySelector(".date-picker"),+ container: container || null,+ bound: container === null,+ format: DATE_FORMAT,+ firstDay: 1,+ minDate: this.minDate,+ maxDate: this.maxDate,+ i18n: {+ previousMonth: i18n("dates.previous_month"),+ nextMonth: i18n("dates.next_month"),+ months: moment.months(),+ weekdays: moment.weekdays(),+ weekdaysShort: moment.weekdaysMin(),+ },+ onSelect: (date) => this._handleSelection(date),+ };++ this._picker = new Pikaday(Object.assign(options, this._opts()));++ if (this.value) {+ this._picker.setDate(moment(this.value).toDate(), true);+ } else {+ this._picker.setDate(null);+ }+ });+ });+ }++ _loadNativePicker() {+ const picker = this.element.querySelector("input.date-picker");+ picker.onchange = () => this._handleSelection(picker.value);+ picker.hide = () => {+ /* do nothing for native */+ };+ picker.destroy = () => {+ /* do nothing for native */+ };+ this._picker = picker;+ }++ _handleSelection(value) {+ const formattedDate = moment(value).format(DATE_FORMAT);++ if (!this.element || this.isDestroying || this.isDestroyed) {+ return;+ }++ if (this.onSelect) {+ this.onSelect(formattedDate);+ }+ }++ @on("willDestroyElement")+ _destroy() {+ if (this._picker) {+ this._picker.destroy();+ this._picker = null;+ }+ }++ @computed("_placeholder")+ get placeholder() {+ return this._placeholder || i18n("dates.placeholder");+ }++ set placeholder(value) {+ this.set("_placeholder", value);+ }++ _opts() {+ return null;+ }+ }+++<Input+ @type={{this.inputType}}+ class="date-picker"+ placeholder={{this.placeholder}}+ @value={{this.value}}+ autocomplete="off"+ ...attributes+/>diff --cc app/assets/javascripts/discourse/app/components/date-time-input-range.gjsindex 492c06deda5,4ac18568343..cab368469b8--- a/app/assets/javascripts/discourse/app/components/date-time-input-range.gjs+++ b/app/assets/javascripts/discourse/app/components/date-time-input-range.gjs@@@ -1,20 -1,47 +1,68 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { classNames } from "@ember-decorators/component";++ @classNames("d-date-time-input-range")+ export default class DateTimeInputRange extends Component {+ from = null;+ to = null;+ onChangeTo = null;+ onChangeFrom = null;+ toTimeFirst = false;+ showToTime = true;+ showFromTime = true;+ clearable = false;++ @action+ onChangeRanges(options, value) {+ if (this.onChange) {+ const state = {+ from: this.from,+ to: this.to,+ };++ const diff = {};++ if (options.prop === "from") {+ if (this.to && value?.isAfter(this.to)) {+ diff[options.prop] = value;+ diff["to"] = value.clone().add(1, "hour");+ } else {+ diff[options.prop] = value;+ }+ }++ if (options.prop === "to") {+ if (value && value.isBefore(this.from)) {+ diff[options.prop] = this.from.clone().add(1, "hour");+ } else {+ diff[options.prop] = value;+ }+ }++ const newState = { ...state, ...diff };+ this.onChange(newState);+ }+ }+ }+++<DateTimeInput+ @date={{this.from}}+ @onChange={{action "onChangeRanges" (hash prop="from")}}+ @showTime={{this.showFromTime}}+ @placeholder={{i18n "dates.from_placeholder"}}+ @timezone={{@timezone}}+ class="from"+/>++<DateTimeInput+ @date={{this.to}}+ @relativeDate={{this.from}}+ @onChange={{action "onChangeRanges" (hash prop="to")}}+ @timeFirst={{this.toTimeFirst}}+ @showTime={{this.showToTime}}+ @clearable={{this.clearable}}+ @placeholder={{i18n "dates.to_placeholder"}}+ @timezone={{@timezone}}+ class="to"+/>diff --cc app/assets/javascripts/discourse/app/components/date-time-input.gjsindex c5951debb97,5f80b512e55..41e6ff583b2--- a/app/assets/javascripts/discourse/app/components/date-time-input.gjs+++ b/app/assets/javascripts/discourse/app/components/date-time-input.gjs@@@ -1,35 -1,76 +1,112 @@@+ import Component from "@ember/component";+ import { action, computed } from "@ember/object";+ import { classNames } from "@ember-decorators/component";++ @classNames("d-date-time-input")+ export default class DateTimeInput extends Component {+ date = null;+ relativeDate = null;+ showTime = true;+ clearable = false;++ @computed("date", "showTime")+ get hours() {+ return this.date && this.get("showTime") ? this.date.hours() : null;+ }++ @computed("date", "showTime")+ get minutes() {+ return this.date && this.get("showTime") ? this.date.minutes() : null;+ }++ @action+ onClear() {+ this.onChange(null);+ }++ @action+ onChangeTime(time) {+ if (this.onChange) {+ const date = this.date+ ? this.date+ : this.relativeDate+ ? this.relativeDate+ : moment.tz(this.resolvedTimezone);++ this.onChange(+ moment.tz(+ {+ year: date.year(),+ month: date.month(),+ day: date.date(),+ hours: time.hours,+ minutes: time.minutes,+ },+ this.resolvedTimezone+ )+ );+ }+ }++ @action+ onChangeDate(date) {+ if (!date) {+ this.onClear();+ return;+ }++ this.onChange?.(+ moment.tz(+ {+ year: date.year(),+ month: date.month(),+ day: date.date(),+ hours: this.hours || 0,+ minutes: this.minutes || 0,+ },+ this.resolvedTimezone+ )+ );+ }++ @computed("timezone")+ get resolvedTimezone() {+ return this.timezone || moment.tz.guess();+ }+ }+++{{#unless this.timeFirst}}+ <DateInput+ @date={{this.date}}+ @placeholder={{this.placeholder}}+ @relativeDate={{this.relativeDate}}+ @onChange={{action "onChangeDate"}}+ @useGlobalPickerContainer={{this.useGlobalPickerContainer}}+ />+{{/unless}}++{{#if this.showTime}}+ <TimeInput+ @date={{this.date}}+ @relativeDate={{this.relativeDate}}+ @onChange={{action "onChangeTime"}}+ />+{{/if}}++{{#if this.timeFirst}}+ <DateInput+ @date={{this.date}}+ @placeholder={{this.placeholder}}+ @relativeDate={{this.relativeDate}}+ @onChange={{action "onChangeDate"}}+ @useGlobalPickerContainer={{this.useGlobalPickerContainer}}+ />+{{/if}}++{{#if this.clearable}}+ <DButton+ @icon="xmark"+ @action={{this.onClear}}+ class="btn-default clear-date-time"+ />+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/dialog-messages/second-factor-confirm-phrase.gjsindex 47faec691fc,445e955918d..a5fe44b831c--- a/app/assets/javascripts/discourse/app/components/dialog-messages/second-factor-confirm-phrase.gjs+++ b/app/assets/javascripts/discourse/app/components/dialog-messages/second-factor-confirm-phrase.gjs@@@ -1,32 -1,22 +1,55 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import { i18n } from "discourse-i18n";++ export default class SecondFactorConfirmPhrase extends Component {+ @service dialog;+ @service currentUser;++ @tracked confirmPhraseInput = "";+ disabledString = i18n("user.second_factor.disable");++ @action+ onConfirmPhraseInput() {+ if (this.confirmPhraseInput === this.disabledString) {+ this.dialog.set("confirmButtonDisabled", false);+ } else {+ this.dialog.set("confirmButtonDisabled", true);+ }+ }+ }+++{{i18n "user.second_factor.delete_confirm_header"}}++<ul>+ {{#each @model.totps as |totp|}}+ <li>{{totp.name}}</li>+ {{/each}}++ {{#each @model.security_keys as |sk|}}+ <li>{{sk.name}}</li>+ {{/each}}++ {{#if this.currentUser.second_factor_backup_enabled}}+ <li>{{i18n "user.second_factor_backup.title"}}</li>+ {{/if}}+</ul>++<p>+ {{html-safe+ (i18n+ "user.second_factor.delete_confirm_instruction"+ confirm=this.disabledString+ )+ }}+</p>++<TextField+ @value={{this.confirmPhraseInput}}+ {{on "input" this.onConfirmPhraseInput}}+ @id="confirm-phrase"+ @autocorrect="off"+ @autocapitalize="off"+/>diff --cc app/assets/javascripts/discourse/app/components/directory-item.gjsindex 406c25d7bc3,a5dfaaa971a..e782ec792e9--- a/app/assets/javascripts/discourse/app/components/directory-item.gjs+++ b/app/assets/javascripts/discourse/app/components/directory-item.gjs@@@ -1,38 -1,19 +1,58 @@@+ import Component from "@ember/component";+ import {+ attributeBindings,+ classNameBindings,+ classNames,+ tagName,+ } from "@ember-decorators/component";+ import { propertyEqual } from "discourse/lib/computed";++ @tagName("div")+ @classNames("directory-table__row")+ @classNameBindings("me")+ @attributeBindings("role")+ export default class DirectoryItem extends Component {+ role = "row";++ @propertyEqual("item.user.id", "currentUser.id") me;+ columns = null;+ }+++<div class="directory-table__cell" role="rowheader">+ <UserInfo @user={{this.item.user}} />+</div>++{{#each this.columns as |column|}}+ {{#if (directory-column-is-user-field column=column)}}+ <div class="directory-table__cell--user-field" role="cell">+ <span class="directory-table__label">+ <span>{{column.name}}</span>+ </span>+ {{directory-item-user-field-value item=this.item column=column}}+ </div>+ {{else}}+ <div class="directory-table__cell" role="cell">+ <span class="directory-table__label">+ <span>+ {{#if column.icon}}+ {{d-icon column.icon}}+ {{/if}}+ {{directory-item-label item=this.item column=column}}+ </span>+ </span>+ {{directory-item-value item=this.item column=column}}+ </div>+ {{/if}}++{{/each}}++{{#if this.showTimeRead}}+ <div class="directory-table__cell time-read" role="cell">+ <span class="directory-table__label">+ <span>{{i18n "directory.time_read"}}</span>+ </span>+ <span class="directory-table__value">+ {{format-duration this.item.time_read}}+ </span>+ </div>+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/discourse-linked-text.gjsindex 81cfa236e5a,1d82196dad3..ac8b92cfdec--- a/app/assets/javascripts/discourse/app/components/discourse-linked-text.gjs+++ b/app/assets/javascripts/discourse/app/components/discourse-linked-text.gjs@@@ -1,1 -1,22 +1,24 @@@+ import Component from "@ember/component";+ import { tagName } from "@ember-decorators/component";+ import discourseComputed from "discourse/lib/decorators";+ import { i18n } from "discourse-i18n";++ @tagName("span")+ export default class DiscourseLinkedText extends Component {+ @discourseComputed("text", "textParams")+ translatedText(text) {+ if (text) {+ return i18n(...arguments);+ }+ }++ click(event) {+ if (event.target.tagName.toUpperCase() === "A") {+ this.action(this.actionParam);+ }++ return false;+ }+ }+++{{html-safe this.translatedText}}diff --cc app/assets/javascripts/discourse/app/components/discourse-tag-bound.gjsindex a1e740c90de,9ea4ca9add5..3527fb226b3--- a/app/assets/javascripts/discourse/app/components/discourse-tag-bound.gjs+++ b/app/assets/javascripts/discourse/app/components/discourse-tag-bound.gjs@@@ -1,1 -1,23 +1,25 @@@+ import Component from "@ember/component";+ import {+ attributeBindings,+ classNameBindings,+ tagName,+ } from "@ember-decorators/component";+ import discourseComputed from "discourse/lib/decorators";+ import getURL from "discourse/lib/get-url";++ @tagName("a")+ @classNameBindings(":discourse-tag", "style", "tagClass")+ @attributeBindings("href")+ export default class DiscourseTagBound extends Component {+ @discourseComputed("tagRecord.id")+ tagClass(tagRecordId) {+ return "tag-" + tagRecordId;+ }++ @discourseComputed("tagRecord.id")+ href(tagRecordId) {+ return getURL("/tag/" + tagRecordId);+ }+ }+++{{this.tagRecord.id}}diff --cc app/assets/javascripts/discourse/app/components/discovery/filter-navigation.gjsindex ceeb3a8c8cb,3e8435854a7..134193d0df4--- a/app/assets/javascripts/discourse/app/components/discovery/filter-navigation.gjs+++ b/app/assets/javascripts/discourse/app/components/discovery/filter-navigation.gjs@@@ -1,49 -1,45 +1,95 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import discourseDebounce from "discourse/lib/debounce";+ import { bind } from "discourse/lib/decorators";+ import { resettableTracked } from "discourse/lib/tracked-tools";++ export default class DiscoveryFilterNavigation extends Component {+ @service site;++ @tracked copyIcon = "link";+ @tracked copyClass = "btn-default";+ @resettableTracked newQueryString = this.args.queryString;++ @bind+ updateQueryString(string) {+ this.newQueryString = string;+ }++ @action+ clearInput() {+ this.newQueryString = "";+ this.args.updateTopicsListQueryParams(this.newQueryString);+ }++ @action+ copyQueryString() {+ this.copyIcon = "check";+ this.copyClass = "btn-default ok";++ navigator.clipboard.writeText(window.location);++ discourseDebounce(this._restoreButton, 3000);+ }++ @bind+ _restoreButton() {+ if (this.isDestroying || this.isDestroyed) {+ return;+ }+ this.copyIcon = "link";+ this.copyClass = "btn-default";+ }+ }+++{{body-class "navigation-filter"}}++<section class="navigation-container">+ <div class="topic-query-filter">+ {{#if (and this.site.mobileView @canBulkSelect)}}+ <div class="topic-query-filter__bulk-action-btn">+ <BulkSelectToggle @bulkSelectHelper={{@bulkSelectHelper}} />+ </div>+ {{/if}}++ <div class="topic-query-filter__input">+ {{d-icon "filter" class="topic-query-filter__icon"}}+ <Input+ class="topic-query-filter__filter-term"+ @value={{this.newQueryString}}+ @enter={{action @updateTopicsListQueryParams this.newQueryString}}+ @type="text"+ id="queryStringInput"+ autocomplete="off"+ />+ {{! EXPERIMENTAL OUTLET - don't use because it will be removed soon }}+ <PluginOutlet+ @name="below-filter-input"+ @outletArgs={{hash+ updateQueryString=this.updateQueryString+ newQueryString=this.newQueryString+ }}+ />+ </div>+ {{#if this.newQueryString}}+ <div class="topic-query-filter__controls">+ <DButton+ @icon="xmark"+ @action={{this.clearInput}}+ @disabled={{unless this.newQueryString "true"}}+ />++ {{#if this.discoveryFilter.q}}+ <DButton+ @icon={{this.copyIcon}}+ @action={{this.copyQueryString}}+ @disabled={{unless this.newQueryString "true"}}+ class={{this.copyClass}}+ />+ {{/if}}+ </div>+ {{/if}}+ </div>+</section>diff --cc app/assets/javascripts/discourse/app/components/discovery/navigation.gjsindex d7b84f9d94c,26c55490552..02c5939c49d--- a/app/assets/javascripts/discourse/app/components/discovery/navigation.gjs+++ b/app/assets/javascripts/discourse/app/components/discovery/navigation.gjs@@@ -1,80 -1,62 +1,143 @@@+ import Component from "@glimmer/component";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import ReorderCategories from "discourse/components/modal/reorder-categories";+ import { calculateFilterMode } from "discourse/lib/filter-mode";+ import { TRACKED_QUERY_PARAM_VALUE } from "discourse/lib/topic-list-tracked-filter";+ import DiscourseURL from "discourse/lib/url";+ import Category from "discourse/models/category";++ export default class DiscoveryNavigation extends Component {+ @service router;+ @service currentUser;+ @service modal;++ get filterMode() {+ return calculateFilterMode({+ category: this.args.category,+ filterType: this.args.filterType,+ noSubcategories: this.args.noSubcategories,+ });+ }++ get skipCategoriesNavItem() {+ return this.router.currentRoute.queryParams.f === TRACKED_QUERY_PARAM_VALUE;+ }++ get canCreateTopic() {+ return this.currentUser?.can_create_topic;+ }++ get bodyClass() {+ if (this.args.tag) {+ return [+ "tags-page",+ this.args.additionalTags ? "tags-intersection" : null,+ ]+ .filter(Boolean)+ .join(" ");+ } else if (this.filterMode === "categories") {+ return "navigation-categories";+ } else if (this.args.category) {+ return "navigation-category";+ } else {+ return "navigation-topics";+ }+ }++ @action+ editCategory() {+ DiscourseURL.routeTo(`/c/${Category.slugFor(this.args.category)}/edit`);+ }++ @action+ createCategory() {+ this.router.transitionTo("newCategory");+ }++ @action+ reorderCategories() {+ this.modal.show(ReorderCategories);+ }+ }+++<AddCategoryTagClasses+ @category={{@category}}+ @tags={{if @tag (array @tag.id)}}+/>++{{#if @category}}+ <PluginOutlet+ @name="above-category-heading"+ @outletArgs={{hash category=@category tag=@tag}}+ />++ <section class="category-heading">+ {{#if @category.uploaded_logo.url}}+ <CategoryLogo @category={{@category}} />+ {{#if @category.description}}+ <p>{{dir-span @category.description htmlSafe="true"}}</p>+ {{/if}}+ {{/if}}++ <span>+ <PluginOutlet+ @name="category-heading"+ @connectorTagName="div"+ @outletArgs={{hash category=@category tag=@tag}}+ />+ </span>+ </section>+{{/if}}++{{body-class this.bodyClass}}++<section+ class={{concat-class+ "navigation-container"+ (if @category "category-navigation")+ }}+>+ <DNavigation+ @category={{@category}}+ @tag={{@tag}}+ @additionalTags={{@additionalTags}}+ @filterMode={{this.filterMode}}+ @noSubcategories={{@noSubcategories}}+ @canCreateTopic={{this.canCreateTopic}}+ @canCreateTopicOnTag={{@canCreateTopicOnTag}}+ @createTopic={{@createTopic}}+ @createTopicDisabled={{@createTopicDisabled}}+ @draftCount={{this.currentUser.draft_count}}+ @editCategory={{this.editCategory}}+ @showCategoryAdmin={{@showCategoryAdmin}}+ @createCategory={{this.createCategory}}+ @reorderCategories={{this.reorderCategories}}+ @canBulkSelect={{@canBulkSelect}}+ @bulkSelectHelper={{@bulkSelectHelper}}+ @skipCategoriesNavItem={{this.skipCategoriesNavItem}}+ @toggleInfo={{@toggleTagInfo}}+ @tagNotification={{@tagNotification}}+ @model={{@model}}+ @showDismissRead={{@showDismissRead}}+ @showResetNew={{@showResetNew}}+ @dismissRead={{@dismissRead}}+ @resetNew={{@resetNew}}+ />++ {{#if @category}}+ <PluginOutlet+ @name="category-navigation"+ @connectorTagName="div"+ @outletArgs={{hash category=@category tag=@tag}}+ />+ {{/if}}++ {{#if @tag}}+ <PluginOutlet+ @name="tag-navigation"+ @connectorTagName="div"+ @outletArgs={{hash category=@category tag=@tag}}+ />+ {{/if}}+</section>diff --cc app/assets/javascripts/discourse/app/components/edit-category-images.gjsindex 19de371f549,f47b1a5d0f8..4c7e01d60fa--- a/app/assets/javascripts/discourse/app/components/edit-category-images.gjs+++ b/app/assets/javascripts/discourse/app/components/edit-category-images.gjs@@@ -1,51 -1,85 +1,137 @@@+ import EmberObject, { action } from "@ember/object";+ import { buildCategoryPanel } from "discourse/components/edit-category-panel";+ import discourseComputed from "discourse/lib/decorators";++ export default class EditCategoryImages extends buildCategoryPanel("images") {+ @discourseComputed("category.uploaded_background.url")+ backgroundImageUrl(uploadedBackgroundUrl) {+ return uploadedBackgroundUrl || "";+ }++ @discourseComputed("category.uploaded_background_dark.url")+ backgroundDarkImageUrl(uploadedBackgroundDarkUrl) {+ return uploadedBackgroundDarkUrl || "";+ }++ @discourseComputed("category.uploaded_logo.url")+ logoImageUrl(uploadedLogoUrl) {+ return uploadedLogoUrl || "";+ }++ @discourseComputed("category.uploaded_logo_dark.url")+ logoImageDarkUrl(uploadedLogoDarkUrl) {+ return uploadedLogoDarkUrl || "";+ }++ @action+ logoUploadDone(upload) {+ this._setFromUpload("category.uploaded_logo", upload);+ }++ @action+ logoUploadDeleted() {+ this._deleteUpload("category.uploaded_logo");+ }++ @action+ logoDarkUploadDone(upload) {+ this._setFromUpload("category.uploaded_logo_dark", upload);+ }++ @action+ logoDarkUploadDeleted() {+ this._deleteUpload("category.uploaded_logo_dark");+ }++ @action+ backgroundUploadDone(upload) {+ this._setFromUpload("category.uploaded_background", upload);+ }++ @action+ backgroundUploadDeleted() {+ this._deleteUpload("category.uploaded_background");+ }++ @action+ backgroundDarkUploadDone(upload) {+ this._setFromUpload("category.uploaded_background_dark", upload);+ }++ @action+ backgroundDarkUploadDeleted() {+ this._deleteUpload("category.uploaded_background_dark");+ }++ _deleteUpload(path) {+ this.set(+ path,+ EmberObject.create({+ id: null,+ url: null,+ })+ );+ }++ _setFromUpload(path, upload) {+ this.set(+ path,+ EmberObject.create({+ url: upload.url,+ id: upload.id,+ })+ );+ }+ }+++<section class="field category-logo">+ <label>{{i18n "category.logo"}}</label>+ <UppyImageUploader+ @imageUrl={{this.logoImageUrl}}+ @onUploadDone={{action "logoUploadDone"}}+ @onUploadDeleted={{action "logoUploadDeleted"}}+ @type="category_logo"+ @id="category-logo-uploader"+ class="no-repeat contain-image"+ />+ <div class="category-logo-description">+ {{i18n "category.logo_description"}}+ </div>+</section>++<section class="field category-logo">+ <label>{{i18n "category.logo_dark"}}</label>+ <UppyImageUploader+ @imageUrl={{this.logoImageDarkUrl}}+ @onUploadDone={{action "logoDarkUploadDone"}}+ @onUploadDeleted={{action "logoDarkUploadDeleted"}}+ @type="category_logo_dark"+ @id="category-dark-logo-uploader"+ class="no-repeat contain-image"+ />+ <div class="category-logo-description">+ {{i18n "category.logo_description"}}+ </div>+</section>++<section class="field category-background-image">+ <label>{{i18n "category.background_image"}}</label>+ <UppyImageUploader+ @imageUrl={{this.backgroundImageUrl}}+ @onUploadDone={{action "backgroundUploadDone"}}+ @onUploadDeleted={{action "backgroundUploadDeleted"}}+ @type="category_background"+ @id="category-background-uploader"+ />+</section>++<section class="field category-background-image">+ <label>{{i18n "category.background_image_dark"}}</label>+ <UppyImageUploader+ @imageUrl={{this.backgroundDarkImageUrl}}+ @onUploadDone={{action "backgroundDarkUploadDone"}}+ @onUploadDeleted={{action "backgroundDarkUploadDeleted"}}+ @type="category_background_dark"+ @id="category-dark-background-uploader"+ />+</section>diff --cc app/assets/javascripts/discourse/app/components/edit-category-tab.gjsindex 12a8f0a0bbd,8aec53f3819..4a6a4f13bd6--- a/app/assets/javascripts/discourse/app/components/edit-category-tab.gjs+++ b/app/assets/javascripts/discourse/app/components/edit-category-tab.gjs@@@ -1,5 -1,61 +1,67 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { empty } from "@ember/object/computed";+ import { scheduleOnce } from "@ember/runloop";+ import { underscore } from "@ember/string";+ import { classNameBindings, tagName } from "@ember-decorators/component";+ import { propertyEqual } from "discourse/lib/computed";+ import discourseComputed from "discourse/lib/decorators";+ import getURL from "discourse/lib/get-url";+ import DiscourseURL from "discourse/lib/url";+ import { i18n } from "discourse-i18n";++ @tagName("li")+ @classNameBindings("active", "tabClassName")+ export default class EditCategoryTab extends Component {+ @empty("params.slug") newCategory;+ @propertyEqual("selectedTab", "tab") active;++ @discourseComputed("tab")+ tabClassName(tab) {+ return "edit-category-" + tab;+ }++ @discourseComputed("tab")+ title(tab) {+ return i18n(`category.${underscore(tab)}`);+ }++ didInsertElement() {+ super.didInsertElement(...arguments);+ scheduleOnce("afterRender", this, this._addToCollection);+ }++ willDestroyElement() {+ super.willDestroyElement(...arguments);++ this.setProperties({+ selectedTab: "general",+ params: {},+ });+ }++ _addToCollection() {+ this.panels.addObject(this.tabClassName);+ }++ @discourseComputed("params.slug", "params.parentSlug")+ fullSlug(slug, parentSlug) {+ const slugPart = parentSlug && slug ? `${parentSlug}/${slug}` : slug;+ return getURL(`/c/${slugPart}/edit/${this.tab}`);+ }++ @action+ select(event) {+ event?.preventDefault();+ this.set("selectedTab", this.tab);+ if (!this.newCategory) {+ DiscourseURL.routeTo(this.fullSlug);+ }+ }+ }+++<a+ href+ {{on "click" this.select}}+ class={{if this.active "active"}}+>{{this.title}}</a>diff --cc app/assets/javascripts/discourse/app/components/featured-topic.gjsindex bcb506e0ba5,0d9b695c0f9..a74e10162ea--- a/app/assets/javascripts/discourse/app/components/featured-topic.gjs+++ b/app/assets/javascripts/discourse/app/components/featured-topic.gjs@@@ -1,13 -1,20 +1,34 @@@+ import Component from "@ember/component";+ import {+ attributeBindings,+ classNameBindings,+ } from "@ember-decorators/component";+ import $ from "jquery";++ @classNameBindings(":featured-topic")+ @attributeBindings("topic.id:data-topic-id")+ export default class FeaturedTopic extends Component {+ click(e) {+ if (e.target.closest(".last-posted-at")) {+ this.appEvents.trigger("topic-entrance:show", {+ topic: this.topic,+ position: $(e.target).offset(),+ });+ return false;+ }+ }+ }+++{{raw "topic-status" topic=this.topic}}+<a href={{this.topic.lastUnreadUrl}} class="title">{{html-safe+ this.topic.fancyTitle+ }}</a>+<TopicPostBadges+ @unreadPosts={{this.topic.unread_posts}}+ @unseen={{this.topic.unseen}}+ @url={{this.topic.lastUnreadUrl}}+/>++<a href={{this.topic.lastPostUrl}} class="last-posted-at">{{format-age+ this.topic.last_posted_at+ }}</a>diff --cc app/assets/javascripts/discourse/app/components/flag-action-type.gjsindex 2bc094db0e2,e4df1bb158d..a928fddd609--- a/app/assets/javascripts/discourse/app/components/flag-action-type.gjs+++ b/app/assets/javascripts/discourse/app/components/flag-action-type.gjs@@@ -1,83 -1,68 +1,152 @@@+ import Component from "@ember/component";+ import { and, equal } from "@ember/object/computed";+ import { tagName } from "@ember-decorators/component";+ import discourseComputed from "discourse/lib/decorators";+ import { MAX_MESSAGE_LENGTH } from "discourse/models/post-action-type";+ import { i18n } from "discourse-i18n";++ @tagName("")+ export default class FlagActionType extends Component {+ @and("flag.require_message", "selected") showMessageInput;+ @and("flag.isIllegal", "selected") showConfirmation;+ @equal("flag.name_key", "notify_user") isNotifyUser;++ @discourseComputed("flag.name_key")+ wrapperClassNames(nameKey) {+ return `flag-action-type ${nameKey}`;+ }++ @discourseComputed("flag.name_key")+ customPlaceholder(nameKey) {+ return i18n("flagging.custom_placeholder_" + nameKey, {+ defaultValue: i18n("flagging.custom_placeholder_notify_moderators"),+ });+ }++ @discourseComputed("flag.name", "flag.name_key", "username")+ formattedName(name, nameKey, username) {+ if (["notify_user", "notify_moderators"].includes(nameKey)) {+ return name.replace(/{{username}}|%{username}/, username);+ } else {+ return i18n("flagging.formatted_name." + nameKey, {+ defaultValue: name,+ });+ }+ }++ @discourseComputed("flag", "selectedFlag")+ selected(flag, selectedFlag) {+ return flag === selectedFlag;+ }++ @discourseComputed("flag.description", "flag.short_description")+ description(long_description, short_description) {+ return this.site.mobileView ? short_description : long_description;+ }++ @discourseComputed("message.length")+ customMessageLengthClasses(messageLength) {+ return messageLength < this.siteSettings.min_personal_message_post_length+ ? "too-short"+ : "ok";+ }++ @discourseComputed("message.length")+ customMessageLength(messageLength) {+ const len = messageLength || 0;+ const minLen = this.siteSettings.min_personal_message_post_length;+ if (len === 0) {+ return i18n("flagging.custom_message.at_least", { count: minLen });+ } else if (len < minLen) {+ return i18n("flagging.custom_message.more", { count: minLen - len });+ } else {+ return i18n("flagging.custom_message.left", {+ count: MAX_MESSAGE_LENGTH - len,+ });+ }+ }+ }+++<div class={{this.wrapperClassNames}}>+ {{#if this.isNotifyUser}}+ <h3>{{this.formattedName}}</h3>+ <div class="controls">+ <label class="radio checkbox-label">+ <input+ id="radio_{{this.flag.name_key}}"+ {{on "click" (fn this.changePostActionType this.flag)}}+ type="radio"+ name="post_action_type_index"+ />++ <div class="flag-action-type-details">+ <span class="description">{{html-safe this.flag.description}}</span>+ {{#if this.showMessageInput}}+ <Textarea+ name="message"+ class="flag-message"+ placeholder={{this.customPlaceholder}}+ aria-label={{i18n "flagging.notify_user_textarea_label"}}+ @value={{this.message}}+ />+ <div+ class={{concat-class+ "custom-message-length"+ this.customMessageLengthClasses+ }}+ >+ {{this.customMessageLength}}+ </div>+ {{/if}}+ </div>+ </label>+ </div>+ {{#if this.staffFlagsAvailable}}+ <hr />+ <h3>{{i18n "flagging.notify_staff"}}</h3>+ {{/if}}+ {{else}}+ <div class="controls {{this.flag.name_key}}">+ <label class="radio checkbox-label">+ <input+ id="radio_{{this.flag.name_key}}"+ {{on "click" (fn this.changePostActionType this.flag)}}+ checked={{this.selected}}+ type="radio"+ name="post_action_type_index"+ />+ <div class="flag-action-type-details">+ <strong>{{this.formattedName}}</strong>+ <div class="description">{{html-safe this.description}}</div>+ {{#if this.showMessageInput}}+ <Textarea+ name="message"+ class="flag-message"+ placeholder={{this.customPlaceholder}}+ aria-label={{i18n "flagging.notify_moderators_textarea_label"}}+ @value={{this.message}}+ />+ <div+ class={{concat-class+ "custom-message-length"+ this.customMessageLengthClasses+ }}+ >+ {{this.customMessageLength}}+ </div>+ {{/if}}+ </div>+ </label>+ {{#if this.showConfirmation}}+ <label class="checkbox-label flag-confirmation">+ <Input+ name="confirmation"+ @type="checkbox"+ @checked={{this.isConfirmed}}+ />+ <span>{{i18n "flagging.confirmation_illegal"}}</span>+ </label>+ {{/if}}+ </div>+ {{/if}}+</div>diff --cc app/assets/javascripts/discourse/app/components/flag-selection.gjsindex 0504c6b8562,dfc8c409b3f..b588ead6c82--- a/app/assets/javascripts/discourse/app/components/flag-selection.gjs+++ b/app/assets/javascripts/discourse/app/components/flag-selection.gjs@@@ -1,5 -1,25 +1,31 @@@+ import Component from "@ember/component";+ import { next } from "@ember/runloop";+ import { observes } from "@ember-decorators/object";++ // Mostly hacks because `flag.hbs` didn't use `radio-button`+ export default class FlagSelection extends Component {+ _selectRadio() {+ this.element.querySelector("input[type='radio']").checked = false;++ const nameKey = this.nameKey;+ if (!nameKey) {+ return;+ }++ const selector = this.element.querySelector("#radio_" + nameKey);+ if (selector) {+ selector.checked = "true";+ }+ }++ @observes("nameKey")+ selectedChanged() {+ next(this, this._selectRadio);+ }+ }+++{{#each this.flags as |f|}}+ {{yield f}}+{{else}}+ {{i18n "flagging.cant"}}+{{/each}}diff --cc app/assets/javascripts/discourse/app/components/flat-button.gjsindex f3a5872abde,b3b85ec430e..8a7f82058a4--- a/app/assets/javascripts/discourse/app/components/flat-button.gjs+++ b/app/assets/javascripts/discourse/app/components/flat-button.gjs@@@ -1,1 -1,34 +1,36 @@@+ import Component from "@ember/component";+ import {+ attributeBindings,+ classNames,+ tagName,+ } from "@ember-decorators/component";+ import discourseComputed from "discourse/lib/decorators";+ import { i18n } from "discourse-i18n";++ @tagName("button")+ @classNames("btn-flat")+ @attributeBindings("disabled", "resolvedTitle:title")+ export default class FlatButton extends Component {+ @discourseComputed("title", "translatedTitle")+ resolvedTitle(title, translatedTitle) {+ if (title) {+ return i18n(title);+ } else if (translatedTitle) {+ return translatedTitle;+ }+ }++ keyDown(event) {+ if (event.key === "Enter") {+ this.action?.();+ return false;+ }+ }++ click() {+ this.action?.();+ return false;+ }+ }+++{{d-icon this.icon}}diff --cc app/assets/javascripts/discourse/app/components/footer-message.gjsindex f60c0fc7a1c,21da288297b..2c3bd00098a--- a/app/assets/javascripts/discourse/app/components/footer-message.gjs+++ b/app/assets/javascripts/discourse/app/components/footer-message.gjs@@@ -1,9 -1,5 +1,15 @@@+ import Component from "@ember/component";+ import { classNames } from "@ember-decorators/component";++ @classNames("footer-message")+ export default class FooterMessage extends Component {}+++<h3>+ {{this.message}}+ {{yield}}+</h3>+{{#if this.education}}+ <div class="education">+ {{html-safe this.education}}+ </div>+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/global-notice.gjsindex 66fd7b7a033,e23cb8105aa..63916673da2--- a/app/assets/javascripts/discourse/app/components/global-notice.gjs+++ b/app/assets/javascripts/discourse/app/components/global-notice.gjs@@@ -1,26 -1,224 +1,251 @@@+ import Component from "@ember/component";+ import EmberObject, { action } from "@ember/object";+ import { service } from "@ember/service";+ import { htmlSafe } from "@ember/template";+ import { tagName } from "@ember-decorators/component";+ import cookie, { removeCookie } from "discourse/lib/cookie";+ import { bind } from "discourse/lib/decorators";+ import { DeferredTrackedSet } from "discourse/lib/tracked-tools";+ import { i18n } from "discourse-i18n";++ const _pluginNotices = new DeferredTrackedSet();++ export function addGlobalNotice(text, id, options = {}) {+ _pluginNotices.add(Notice.create({ text, id, options }));+ }++ const GLOBAL_NOTICE_DISMISSED_PROMPT_KEY = "dismissed-global-notice-v2";++ class Notice extends EmberObject {+ @service("logsNotice") logsNoticeService;++ text = null;+ id = null;+ options = null;++ init() {+ super.init(...arguments);++ const defaults = {+ // can this banner be hidden+ dismissable: false,+ // prepend html content+ html: null,+ // will define the style of the banner, follows alerts styling+ level: "info",+ // should the banner be permanently hidden?+ persistentDismiss: true,+ // callback function when dismissing a banner+ onDismiss: null,+ // show/hide banner function, will take precedence over everything+ visibility: null,+ // how long before banner should show again, eg: moment.duration(1, "week")+ dismissDuration: null,+ };++ this.options = this.set(+ "options",+ Object.assign(defaults, this.options || {})+ );+ }+ }++ @tagName("")+ export default class GlobalNotice extends Component {+ @service keyValueStore;+ @service("logsNotice") logsNoticeService;+ @service router;++ logNotice = null;++ constructor() {+ super(...arguments);++ this.logsNoticeService.addObserver("hidden", this._handleLogsNoticeUpdate);+ this.logsNoticeService.addObserver("text", this._handleLogsNoticeUpdate);+ }++ willDestroyElement() {+ super.willDestroyElement(...arguments);++ this.logsNoticeService.removeObserver("text", this._handleLogsNoticeUpdate);+ this.logsNoticeService.removeObserver(+ "hidden",+ this._handleLogsNoticeUpdate+ );+ }++ get visible() {+ return !this.router.currentRouteName.startsWith("wizard.");+ }++ get notices() {+ let notices = [];++ if (cookie("dosp") === "1") {+ removeCookie("dosp", { path: "/" });+ notices.push(+ Notice.create({+ text: this.siteSettings.login_required+ ? i18n("forced_anonymous_login_required")+ : i18n("forced_anonymous"),+ id: "forced-anonymous",+ })+ );+ }++ if (this.session.get("safe_mode")) {+ notices.push(+ Notice.create({ text: i18n("safe_mode.enabled"), id: "safe-mode" })+ );+ }++ if (this.site.get("isStaffWritesOnly")) {+ notices.push(+ Notice.create({+ text: i18n("staff_writes_only_mode.enabled"),+ id: "alert-staff-writes-only",+ })+ );+ } else if (this.site.get("isReadOnly")) {+ notices.push(+ Notice.create({+ text: i18n("read_only_mode.enabled"),+ id: "alert-read-only",+ })+ );+ }++ if (this.router.currentRoute?.queryParams?.preview_theme_id) {+ notices.push(+ Notice.create({+ text: i18n("theme_preview_notice"),+ id: "theme-preview",+ })+ );+ }++ if (this.siteSettings.disable_emails === "yes") {+ notices.push(+ Notice.create({+ text: i18n("emails_are_disabled"),+ id: "alert-emails-disabled",+ options: {+ dismissable: true,+ persistentDismiss: false,+ },+ })+ );+ } else if (this.siteSettings.disable_emails === "non-staff") {+ notices.push(+ Notice.create({+ text: i18n("emails_are_disabled_non_staff"),+ id: "alert-emails-disabled",+ options: {+ dismissable: true,+ persistentDismiss: false,+ },+ })+ );+ }++ if (this.siteSettings.global_notice?.length > 0) {+ notices.push(+ Notice.create({+ text: this.siteSettings.global_notice,+ id: "alert-global-notice",+ })+ );+ }++ if (this.get("logNotice")) {+ notices.push(this.get("logNotice"));+ }++ return notices.concat(Array.from(_pluginNotices)).filter((notice) => {+ if (notice.options.visibility) {+ return notice.options.visibility(notice);+ }++ const key = `${GLOBAL_NOTICE_DISMISSED_PROMPT_KEY}-${notice.id}`;+ const value = this.keyValueStore.get(key);++ // banner has never been dismissed+ if (!value) {+ return true;+ }++ // banner has no persistent dismiss and should always show on load+ if (!notice.options.persistentDismiss) {+ return true;+ }++ if (notice.options.dismissDuration) {+ const resetAt = moment(value).add(notice.options.dismissDuration);+ return moment().isAfter(resetAt);+ } else {+ return false;+ }+ });+ }++ @action+ dismissNotice(notice) {+ notice.options.onDismiss?.(notice);++ if (notice.options.persistentDismiss) {+ this.keyValueStore.set({+ key: `${GLOBAL_NOTICE_DISMISSED_PROMPT_KEY}-${notice.id}`,+ value: moment().toISOString(true),+ });+ }++ const alert = document.getElementById(`global-notice-${notice.id}`);+ if (alert) {+ alert.style.display = "none";+ }+ }++ @bind+ _handleLogsNoticeUpdate() {+ const logNotice = Notice.create({+ text: htmlSafe(this.logsNoticeService.message),+ id: "alert-logs-notice",+ options: {+ dismissable: true,+ persistentDismiss: false,+ visibility: () => !this.logsNoticeService.hidden,+ onDismiss: () => this.logsNoticeService.set("text", ""),+ },+ });++ this.set("logNotice", logNotice);+ }+ }+++<div class="global-notice">+ {{#if this.visible}}+ {{#each this.notices as |notice|}}+ <div class="row">+ <div+ id="global-notice-{{notice.id}}"+ class="alert alert-{{notice.options.level}} {{notice.id}}"+ >+ {{#if notice.options.html}}+ {{html-safe notice.options.html}}+ {{/if}}++ <span class="text">{{html-safe notice.text}}</span>++ {{#if notice.options.dismissable}}+ <DButton+ @icon="xmark"+ @action={{fn this.dismissNotice notice}}+ class="btn-transparent close"+ />+ {{/if}}+ </div>+ </div>+ {{/each}}+ {{/if}}+</div>diff --cc app/assets/javascripts/discourse/app/components/google-search.gjsindex 1d357934613,627760e3db5..84d5587f60f--- a/app/assets/javascripts/discourse/app/components/google-search.gjs+++ b/app/assets/javascripts/discourse/app/components/google-search.gjs@@@ -1,18 -1,16 +1,35 @@@+ import Component from "@ember/component";+ import { alias } from "@ember/object/computed";+ import { classNameBindings, classNames } from "@ember-decorators/component";+ import discourseComputed from "discourse/lib/decorators";+ import getURL from "discourse/lib/get-url";++ @classNames("google-search-form")+ @classNameBindings("hidden:hidden")+ export default class GoogleSearch extends Component {+ @alias("siteSettings.login_required") hidden;++ @discourseComputed+ siteUrl() {+ return `${location.protocol}//${location.host}${getURL("/")}`;+ }+ }+++<PluginOutlet+ @name="google-search"+ @outletArgs={{hash searchTerm=this.searchTerm siteUrl=this.siteUrl}}+ @defaultGlimmer={{true}}+>+ <form action="//google.com/search" id="google-search" class="inline-form">+ <input+ type="text"+ name="q"+ aria-label={{i18n "search.search_google"}}+ value={{@searchTerm}}+ />+ <input name="as_sitesearch" value={{@siteUrl}} type="hidden" />+ <button class="btn btn-primary" type="submit">{{i18n+ "search.search_google_button"+ }}</button>+ </form>+</PluginOutlet>diff --cc app/assets/javascripts/discourse/app/components/group-card-contents.gjsindex 8e8e5037eec,f8ea6e75436..330f5eae9b6--- a/app/assets/javascripts/discourse/app/components/group-card-contents.gjs+++ b/app/assets/javascripts/discourse/app/components/group-card-contents.gjs@@@ -1,102 -1,126 +1,229 @@@+ import { action } from "@ember/object";+ import { alias, gt } from "@ember/object/computed";+ import { service } from "@ember/service";+ import { classNameBindings, classNames } from "@ember-decorators/component";+ import { on } from "@ember-decorators/object";+ import CardContentsBase from "discourse/components/card-contents-base";+ import { setting } from "discourse/lib/computed";+ import discourseComputed from "discourse/lib/decorators";+ import { wantsNewWindow } from "discourse/lib/intercept-click";+ import { groupPath } from "discourse/lib/url";++ const maxMembersToDisplay = 10;++ @classNames("no-bg", "group-card")+ @classNameBindings(+ "visible:show",+ "showBadges",+ "hasCardBadgeImage",+ "isFixed:fixed",+ "groupClass"+ )+ export default class GroupCardContents extends CardContentsBase {+ @service composer;++ @setting("allow_profile_backgrounds") allowBackgrounds;+ @setting("enable_badges") showBadges;++ @alias("topic.postStream") postStream;+ @gt("moreMembersCount", 0) showMoreMembers;++ elementId = "group-card";+ mentionSelector = "a.mention-group";++ group = null;++ @discourseComputed("group.members.[]")+ highlightedMembers(members) {+ return members.slice(0, maxMembersToDisplay);+ }++ @discourseComputed("group.user_count", "group.members.[]")+ moreMembersCount(memberCount) {+ return Math.max(memberCount - maxMembersToDisplay, 0);+ }++ @discourseComputed("group.name")+ groupClass(name) {+ return name ? `group-card-${name}` : "";+ }++ @discourseComputed("group")+ groupPath(group) {+ return groupPath(group.name);+ }++ @on("didInsertElement")+ _inserted() {+ this.appEvents.on("dom:clean", this, this._close);+ }++ @on("didDestroyElement")+ _destroyed() {+ this.appEvents.off("dom:clean", this, this._close);+ }++ async _showCallback(username) {+ this.setProperties({ visible: true, loading: true });++ try {+ const group = await this.store.find("group", username);+ this.setProperties({ group });++ if (!group.flair_url && !group.flair_bg_color) {+ group.set("flair_url", "users");+ }++ if (group.can_see_members && group.members.length < maxMembersToDisplay) {+ return group.reloadMembers({ limit: maxMembersToDisplay }, true);+ }+ } catch {+ this._close();+ } finally {+ this.set("loading", null);+ }+ }++ _close() {+ this.set("group", null);++ super._close(...arguments);+ }++ @action+ close(event) {+ event?.preventDefault();+ this._close();+ }++ @action+ handleShowGroup(event) {+ if (wantsNewWindow(event)) {+ return;+ }++ event.preventDefault();+ // Invokes `showGroup` argument. Convert to `this.args.showGroup` when+ // refactoring this to a glimmer component.+ this.showGroup(this.group);+ this._close();+ }++ @action+ cancelFilter() {+ this.postStream.cancelFilter();+ this.postStream.refresh();+ this._close();+ }++ @action+ messageGroup() {+ this.composer.openNewMessage({+ recipients: this.get("group.name"),+ hasGroups: true,+ });+ }+ }+++{{#if this.visible}}+ <div class="card-content">+ {{#if this.loading}}+ <div class="card-row first-row">+ <div class="group-card-avatar">+ <div+ class="card-avatar-placeholder animated-placeholder placeholder-animation"+ ></div>+ </div>+ </div>++ <div class="card-row second-row">+ <div class="animated-placeholder placeholder-animation"></div>+ </div>+ {{else}}+ <div class="card-row first-row">+ <div class="group-card-avatar">+ <a+ {{on "click" this.handleShowGroup}}+ href={{this.groupPath}}+ class="card-huge-avatar"+ >+ <AvatarFlair+ @flairName={{this.group.name}}+ @flairUrl={{this.group.flair_url}}+ @flairBgColor={{this.group.flair_bg_color}}+ @flairColor={{this.group.flair_color}}+ />+ </a>+ </div>+ <div class="names">+ <span>+ <div class="names__primary {{this.group.name}}">+ <a+ {{on "click" this.handleShowGroup}}+ href={{this.groupPath}}+ class="group-page-link"+ >{{this.group.name}}</a>+ </div>+ {{#if this.group.full_name}}+ <div class="names__secondary full-name">+ {{this.group.full_name}}+ </div>+ {{else}}+ <div class="names__secondary username">{{this.group.name}}</div>+ {{/if}}+ </span>+ </div>+ <ul class="usercard-controls group-details-button">+ <li>+ <GroupMembershipButton+ @model={{this.group}}+ @showLogin={{route-action "showLogin"}}+ />+ </li>+ {{#if this.group.messageable}}+ <li>+ <DButton+ @action={{action "messageGroup"}}+ @icon="envelope"+ @label="groups.message"+ class="btn-primary group-message-button inline"+ />+ </li>+ {{/if}}+ </ul>+ </div>++ {{#if this.group.bio_excerpt}}+ <div class="card-row second-row">+ <div class="bio">+ {{html-safe this.group.bio_excerpt}}+ </div>+ </div>+ {{/if}}++ {{#if this.group.members}}+ <div class="card-row third-row">+ <div class="members metadata">+ {{#each this.highlightedMembers as |user|}}+ <a+ {{on "click" this.close}}+ href={{user.path}}+ class="card-tiny-avatar"+ >{{bound-avatar user "tiny"}}</a>+ {{/each}}+ {{#if this.showMoreMembers}}+ <a+ {{on "click" this.handleShowGroup}}+ href={{this.groupPath}}+ class="more-members-link"+ >+ <span class="more-members-count">+{{this.moreMembersCount}}+ {{i18n "more"}}</span>+ </a>+ {{/if}}+ </div>+ </div>+ {{/if}}+ {{/if}}+ </div>+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/group-manage-email-settings.gjsindex 0948b6e16d5,6fe492a7e09..b041b1c3f23--- a/app/assets/javascripts/discourse/app/components/group-manage-email-settings.gjs+++ b/app/assets/javascripts/discourse/app/components/group-manage-email-settings.gjs@@@ -1,90 -1,115 +1,206 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import { isEmpty } from "@ember/utils";+ import { tagName } from "@ember-decorators/component";+ import { on } from "@ember-decorators/object";+ import discourseComputed from "discourse/lib/decorators";+ import { i18n } from "discourse-i18n";++ @tagName("")+ export default class GroupManageEmailSettings extends Component {+ @service dialog;++ imapSettingsValid = false;+ smtpSettingsValid = false;++ @on("init")+ _determineSettingsValid() {+ this.set(+ "imapSettingsValid",+ this.group.imap_enabled && this.group.imap_server+ );+ this.set(+ "smtpSettingsValid",+ this.group.smtp_enabled && this.group.smtp_server+ );+ }++ @discourseComputed(+ "emailSettingsValid",+ "group.smtp_enabled",+ "group.imap_enabled"+ )+ enableImapSettings(emailSettingsValid, smtpEnabled, imapEnabled) {+ return smtpEnabled && (emailSettingsValid || imapEnabled);+ }++ @discourseComputed(+ "smtpSettingsValid",+ "imapSettingsValid",+ "group.smtp_enabled",+ "group.imap_enabled"+ )+ emailSettingsValid(+ smtpSettingsValid,+ imapSettingsValid,+ smtpEnabled,+ imapEnabled+ ) {+ return (+ (!smtpEnabled || smtpSettingsValid) && (!imapEnabled || imapSettingsValid)+ );+ }++ _anySmtpFieldsFilled() {+ return [+ this.group.smtp_server,+ this.group.smtp_port,+ this.group.email_username,+ this.group.email_password,+ ].some((value) => !isEmpty(value));+ }++ _anyImapFieldsFilled() {+ return [this.group.imap_server, this.group.imap_port].some(+ (value) => !isEmpty(value)+ );+ }++ @action+ onChangeSmtpSettingsValid(valid) {+ this.set("smtpSettingsValid", valid);+ }++ @action+ smtpEnabledChange(event) {+ if (+ !event.target.checked &&+ this.group.smtp_enabled &&+ this._anySmtpFieldsFilled()+ ) {+ this.dialog.confirm({+ message: i18n("groups.manage.email.smtp_disable_confirm"),+ didConfirm: () => this.group.set("smtp_enabled", true),+ didCancel: () => this.group.set("imap_enabled", false),+ });+ }++ this.group.set("smtp_enabled", event.target.checked);+ }++ @action+ imapEnabledChange(event) {+ if (+ !event.target.checked &&+ this.group.imap_enabled &&+ this._anyImapFieldsFilled()+ ) {+ this.dialog.confirm({+ message: i18n("groups.manage.email.imap_disable_confirm"),+ didConfirm: () => this.group.set("imap_enabled", true),+ });+ }++ this.group.set("imap_enabled", event.target.checked);+ }++ @action+ afterSave() {+ // reload the group to get the updated imap_mailboxes+ this.store.find("group", this.group.name).then(() => {+ this._determineSettingsValid();+ });+ }+ }+++<div class="group-manage-email-settings">+ <h3>{{i18n "groups.manage.email.smtp_title"}}</h3>+ <p>{{i18n "groups.manage.email.smtp_instructions"}}</p>++ <label for="enable_smtp">+ <Input+ @type="checkbox"+ @checked={{this.group.smtp_enabled}}+ id="enable_smtp"+ tabindex="1"+ {{on "input" this.smtpEnabledChange}}+ />+ {{i18n "groups.manage.email.enable_smtp"}}+ </label>++ {{#if this.group.smtp_enabled}}+ <GroupSmtpEmailSettings+ @group={{this.group}}+ @smtpSettingsValid={{this.smtpSettingsValid}}+ @onChangeSmtpSettingsValid={{this.onChangeSmtpSettingsValid}}+ />+ {{/if}}++ {{#if this.siteSettings.enable_imap}}+ <div class="group-manage-email-imap-wrapper">+ <br />++ <h3>{{i18n "groups.manage.email.imap_title"}}</h3>+ <p>+ {{html-safe (i18n "groups.manage.email.imap_instructions")}}+ </p>++ <div class="alert alert-warning">{{i18n+ "groups.manage.email.imap_alpha_warning"+ }}</div>++ <label for="enable_imap">+ <Input+ @type="checkbox"+ disabled={{not this.enableImapSettings}}+ @checked={{this.group.imap_enabled}}+ id="enable_imap"+ tabindex="8"+ {{on "input" this.imapEnabledChange}}+ />+ {{i18n "groups.manage.email.enable_imap"}}+ </label>++ {{#if this.group.imap_enabled}}+ <GroupImapEmailSettings+ @group={{this.group}}+ @imapSettingsValid={{this.imapSettingsValid}}+ />+ {{/if}}+ </div>+ {{/if}}++ <div class="group-manage-email-additional-settings-wrapper">+ <div class="control-group">+ <h3>{{i18n "groups.manage.email.imap_additional_settings"}}</h3>+ <label+ class="control-group-inline"+ for="allow_unknown_sender_topic_replies"+ >+ <Input+ @type="checkbox"+ name="allow_unknown_sender_topic_replies"+ id="allow_unknown_sender_topic_replies"+ @checked={{this.group.allow_unknown_sender_topic_replies}}+ tabindex="13"+ />+ <span>{{i18n+ "groups.manage.email.settings.allow_unknown_sender_topic_replies"+ }}</span>+ </label>+ <p>{{i18n+ "groups.manage.email.settings.allow_unknown_sender_topic_replies_hint"+ }}</p>+ </div>+ </div>++ <br />+ <GroupManageSaveButton+ @model={{this.group}}+ @disabled={{not this.emailSettingsValid}}+ @beforeSave={{this.beforeSave}}+ @afterSave={{this.afterSave}}+ @tabindex="15"+ />+</div>diff --cc app/assets/javascripts/discourse/app/components/group-manage-logs-filter.gjsindex e23b38fbba2,f856a9ddf2b..209752dd2e8--- a/app/assets/javascripts/discourse/app/components/group-manage-logs-filter.gjs+++ b/app/assets/javascripts/discourse/app/components/group-manage-logs-filter.gjs@@@ -1,8 -1,17 +1,26 @@@+ import Component from "@ember/component";+ import { tagName } from "@ember-decorators/component";+ import discourseComputed from "discourse/lib/decorators";+ import { i18n } from "discourse-i18n";++ @tagName("")+ export default class GroupManageLogsFilter extends Component {+ @discourseComputed("type")+ label(type) {+ return i18n(`groups.manage.logs.${type}`);+ }++ @discourseComputed("value", "type")+ filterText(value, type) {+ return type === "action" ? i18n(`group_histories.actions.${value}`) : value;+ }+ }+++{{#if this.value}}+ <DButton+ @action={{fn this.clearFilter this.type}}+ @icon="circle-xmark"+ @translatedLabel={{concat this.label ": " this.filterText}}+ class="btn-default group-manage-logs-filter"+ />+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/group-manage-logs-row.gjsindex f5c8c3a85aa,d9e3a392ee3..203d50cdf92--- a/app/assets/javascripts/discourse/app/components/group-manage-logs-row.gjs+++ b/app/assets/javascripts/discourse/app/components/group-manage-logs-row.gjs@@@ -1,72 -1,18 +1,91 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { tagName } from "@ember-decorators/component";++ @tagName("")+ export default class GroupManageLogsRow extends Component {+ expandDetails = false;++ @action+ toggleDetails() {+ this.toggleProperty("expandDetails");+ }++ @action+ filter(params) {+ this.set(`filters.${params.key}`, params.value);+ }+ }+++<tr class="group-manage-logs-row">+ <td>+ <DButton+ @action={{fn this.filter (hash value=this.log.action key="action")}}+ @translatedLabel={{this.log.actionTitle}}+ class="btn-default"+ />+ </td>++ <td>+ <span>{{avatar this.log.acting_user imageSize="tiny"}}</span>+ <DButton+ @action={{fn+ this.filter+ (hash value=this.log.acting_user.username key="acting_user")+ }}+ @translatedLabel={{this.log.acting_user.username}}+ class="btn-default"+ />+ </td>++ <td>+ {{#if this.log.target_user}}+ <span>{{avatar this.log.target_user imageSize="tiny"}}</span>+ <DButton+ @action={{fn+ this.filter+ (hash value=this.log.target_user.username key="target_user")+ }}+ @translatedLabel={{this.log.target_user.username}}+ class="btn-default"+ />+ {{/if}}+ </td>++ <td>+ {{#if this.log.subject}}+ <DButton+ @action={{fn this.filter (hash value=this.log.subject key="subject")}}+ @translatedLabel={{this.log.subject}}+ class="btn-default"+ />+ {{/if}}+ </td>++ <td>{{bound-date this.log.created_at}}</td>++ <td class="group-manage-logs-expand-details">+ {{#if this.log.prev_value}}+ <DButton+ @action={{this.toggleDetails}}+ @icon={{if this.expandDetails "angle-up" "angle-down"}}+ />+ {{/if}}+ </td>+</tr>++{{#if this.expandDetails}}+ <tr>+ <td colspan="6">+ <p>+ <strong>{{i18n "groups.manage.logs.from"}}</strong>:+ <code>{{this.log.prev_value}}</code>+ </p>++ <p>+ <strong>{{i18n "groups.manage.logs.to"}}</strong>:+ <code>{{this.log.new_value}}</code>+ </p>+ </td>+ </tr>+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/group-manage-save-button.gjsindex 01b9eb010c3,25c686efa09..09731e08690--- a/app/assets/javascripts/discourse/app/components/group-manage-save-button.gjs+++ b/app/assets/javascripts/discourse/app/components/group-manage-save-button.gjs@@@ -1,18 -1,103 +1,122 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { or } from "@ember/object/computed";+ import { service } from "@ember/service";+ import GroupDefaultNotificationsModal from "discourse/components/modal/group-default-notifications";+ import { popupAutomaticMembershipAlert } from "discourse/controllers/groups-new";+ import { popupAjaxError } from "discourse/lib/ajax-error";+ import discourseComputed from "discourse/lib/decorators";+ import { i18n } from "discourse-i18n";++ export default class GroupManageSaveButton extends Component {+ @service modal;++ saving = null;+ disabled = false;+ updateExistingUsers = null;++ @or("model.flair_icon", "model.flair_upload_id") hasFlair;++ @discourseComputed("saving")+ savingText(saving) {+ return saving ? i18n("saving") : i18n("save");+ }++ @discourseComputed(+ "model.visibility_level",+ "model.primary_group",+ "hasFlair"+ )+ privateGroupNameNotice(visibilityLevel, isPrimaryGroup, hasFlair) {+ if (visibilityLevel === 0) {+ return;+ }++ if (isPrimaryGroup) {+ return i18n("admin.groups.manage.alert.primary_group", {+ group_name: this.model.name,+ });+ } else if (hasFlair) {+ return i18n("admin.groups.manage.alert.flair_group", {+ group_name: this.model.name,+ });+ }+ }++ @action+ setUpdateExistingUsers(value) {+ this.updateExistingUsers = value;+ }++ @action+ save() {+ if (this.beforeSave) {+ this.beforeSave();+ }++ this.set("saving", true);+ const group = this.model;++ popupAutomaticMembershipAlert(+ group.id,+ group.automatic_membership_email_domains+ );++ const opts = {};+ if (this.updateExistingUsers !== null) {+ opts.update_existing_users = this.updateExistingUsers;+ }++ return group+ .save(opts)+ .then(() => {+ this.setProperties({+ saved: true,+ updateExistingUsers: null,+ });++ if (this.afterSave) {+ this.afterSave();+ }+ })+ .catch((error) => {+ const json = error.jqXHR.responseJSON;+ if (error.jqXHR.status === 422 && json.user_count) {+ this.editGroupNotifications(json);+ } else {+ popupAjaxError(error);+ }+ })+ .finally(() => this.set("saving", false));+ }++ @action+ async editGroupNotifications(json) {+ await this.modal.show(GroupDefaultNotificationsModal, {+ model: {+ count: json.user_count,+ setUpdateExistingUsers: this.setUpdateExistingUsers,+ },+ });+ this.save();+ }+ }+++{{#if this.privateGroupNameNotice}}+ <div class="row">+ <div class="alert alert-warning alert-private-group-name">+ {{this.privateGroupNameNotice}}+ </div>+ </div>+{{/if}}+<div class="control-group buttons group-manage-save-button">+ <DButton+ @action={{this.save}}+ @disabled={{or this.disabled this.saving}}+ @translatedLabel={{this.savingText}}+ class="btn-primary group-manage-save"+ />+ {{#if this.saved}}+ <span>{{i18n "saved"}}</span>+ {{/if}}+</div>diff --cc app/assets/javascripts/discourse/app/components/group-member.gjsindex 052925f4c5d,97d75faf69d..9447e71293c--- a/app/assets/javascripts/discourse/app/components/group-member.gjs+++ b/app/assets/javascripts/discourse/app/components/group-member.gjs@@@ -1,9 -1,12 +1,22 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { classNames } from "@ember-decorators/component";++ @classNames("item")+ export default class GroupMember extends Component {+ @action+ remove(event) {+ event?.preventDefault();+ this.removeAction(this.member);+ }+ }+++<a href={{this.member.adminPath}}>+ {{avatar this.member imageSize="small"}}+</a>+<span>{{this.member.username}}</span>+{{#unless this.automatic}}+ <a href {{on "click" this.remove}} class="remove">+ {{d-icon "xmark"}}+ </a>+{{/unless}}diff --cc app/assets/javascripts/discourse/app/components/group-membership-button.gjsindex db0b3b7b65c,7270e66fb66..c19ef963c31--- a/app/assets/javascripts/discourse/app/components/group-membership-button.gjs+++ b/app/assets/javascripts/discourse/app/components/group-membership-button.gjs@@@ -1,27 -1,103 +1,131 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import { classNames } from "@ember-decorators/component";+ import { popupAjaxError } from "discourse/lib/ajax-error";+ import cookie from "discourse/lib/cookie";+ import discourseComputed from "discourse/lib/decorators";+ import { i18n } from "discourse-i18n";+ import RequestGroupMembershipForm from "./modal/request-group-membership-form";++ @classNames("group-membership-button")+ export default class GroupMembershipButton extends Component {+ @service appEvents;+ @service currentUser;+ @service dialog;+ @service modal;++ @discourseComputed("model.public_admission", "userIsGroupUser")+ canJoinGroup(publicAdmission, userIsGroupUser) {+ return publicAdmission && !userIsGroupUser;+ }++ @discourseComputed("model.public_exit", "userIsGroupUser")+ canLeaveGroup(publicExit, userIsGroupUser) {+ return publicExit && userIsGroupUser;+ }++ @discourseComputed("model.allow_membership_requests", "userIsGroupUser")+ canRequestMembership(allowMembershipRequests, userIsGroupUser) {+ return allowMembershipRequests && !userIsGroupUser;+ }++ @discourseComputed("model.is_group_user")+ userIsGroupUser(isGroupUser) {+ return !!isGroupUser;+ }++ _showLoginModal() {+ this.showLogin();+ cookie("destination_url", window.location.href);+ }++ removeFromGroup() {+ const model = this.model;+ model+ .leave()+ .then(() => {+ model.set("is_group_user", false);+ this.appEvents.trigger("group:leave", model);+ })+ .catch(popupAjaxError)+ .finally(() => this.set("updatingMembership", false));+ }++ @action+ joinGroup() {+ if (this.currentUser) {+ this.set("updatingMembership", true);+ const group = this.model;++ group+ .join()+ .then(() => {+ group.set("is_group_user", true);+ this.appEvents.trigger("group:join", group);+ })+ .catch(popupAjaxError)+ .finally(() => {+ this.set("updatingMembership", false);+ });+ } else {+ this._showLoginModal();+ }+ }++ @action+ leaveGroup() {+ this.set("updatingMembership", true);++ if (this.model.public_admission) {+ this.removeFromGroup();+ } else {+ return this.dialog.yesNoConfirm({+ message: i18n("groups.confirm_leave"),+ didConfirm: () => this.removeFromGroup(),+ didCancel: () => this.set("updatingMembership", false),+ });+ }+ }++ @action+ showRequestMembershipForm() {+ if (this.currentUser) {+ this.modal.show(RequestGroupMembershipForm, {+ model: {+ group: this.model,+ },+ });+ } else {+ this._showLoginModal();+ }+ }+ }+++{{#if this.canJoinGroup}}+ <DButton+ @action={{action "joinGroup"}}+ @icon="user-plus"+ @label="groups.join"+ @disabled={{this.updatingMembership}}+ class="btn-default group-index-join"+ />+{{else if this.canLeaveGroup}}+ <DButton+ @action={{action "leaveGroup"}}+ @icon="user-xmark"+ @label="groups.leave"+ @disabled={{this.updatingMembership}}+ class="btn-danger group-index-leave"+ />+{{else if this.canRequestMembership}}+ <DButton+ @action={{action "showRequestMembershipForm"}}+ @disabled={{this.loading}}+ @icon="user-plus"+ @label="groups.request"+ class="btn-default group-index-request"+ />+{{else}}+ {{yield}}+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/group-selector.gjsindex 4275e68d3f3,4f55b60457c..0f18233b20f--- a/app/assets/javascripts/discourse/app/components/group-selector.gjs+++ b/app/assets/javascripts/discourse/app/components/group-selector.gjs@@@ -1,6 -1,66 +1,73 @@@+ import Component from "@ember/component";+ import { isEmpty } from "@ember/utils";+ import { observes, on } from "@ember-decorators/object";+ import $ from "jquery";+ import discourseComputed from "discourse/lib/decorators";+ import { findRawTemplate } from "discourse/lib/raw-templates";+ import { i18n } from "discourse-i18n";++ export default class GroupSelector extends Component {+ @discourseComputed("placeholderKey")+ placeholder(placeholderKey) {+ return placeholderKey ? i18n(placeholderKey) : "";+ }++ @observes("groupNames")+ _update() {+ if (this.canReceiveUpdates === "true") {+ this._initializeAutocomplete({ updateData: true });+ }+ }++ @on("didInsertElement")+ _initializeAutocomplete(opts) {+ let selectedGroups;+ let groupNames = this.groupNames;++ $(this.element.querySelector("input")).autocomplete({+ debounced: true,+ allowAny: false,+ items: Array.isArray(groupNames)+ ? groupNames+ : isEmpty(groupNames)+ ? []+ : [groupNames],+ single: this.single,+ fullWidthWrap: this.fullWidthWrap,+ updateData: opts && opts.updateData ? opts.updateData : false,+ onChangeItems: (items) => {+ selectedGroups = items;++ if (this.onChange) {+ this.onChange(items.join(","));+ } else if (this.onChangeCallback) {+ this.onChangeCallback(this.groupNames, selectedGroups);+ } else {+ this.set("groupNames", items.join(","));+ }+ },+ transformComplete: (g) => {+ return g.name;+ },+ dataSource: (term) => {+ return this.groupFinder(term).then((groups) => {+ if (!selectedGroups) {+ return groups;+ }++ return groups.filter((group) => {+ return !selectedGroups.any((s) => s === group.name);+ });+ });+ },+ template: findRawTemplate("group-selector-autocomplete"),+ });+ }+ }+++<input+ placeholder={{this.placeholder}}+ class="group-selector"+ type="text"+ name="groups"+/>diff --cc app/assets/javascripts/discourse/app/components/groups-form-profile-fields.gjsindex af746b4928b,7f5a7d5cf70..676fc94b079--- a/app/assets/javascripts/discourse/app/components/groups-form-profile-fields.gjs+++ b/app/assets/javascripts/discourse/app/components/groups-form-profile-fields.gjs@@@ -1,51 -1,114 +1,166 @@@+ import Component from "@ember/component";+ import EmberObject from "@ember/object";+ import { not } from "@ember/object/computed";+ import { isEmpty } from "@ember/utils";+ import { observes } from "@ember-decorators/object";+ import { popupAjaxError } from "discourse/lib/ajax-error";+ import discourseDebounce from "discourse/lib/debounce";+ import discourseComputed from "discourse/lib/decorators";+ import Group from "discourse/models/group";+ import { i18n } from "discourse-i18n";++ export default class GroupsFormProfileFields extends Component {+ disableSave = null;+ nameInput = null;++ @not("model.automatic") canEdit;++ didInsertElement() {+ super.didInsertElement(...arguments);+ const name = this.get("model.name");++ if (name) {+ this.set("nameInput", name);+ } else {+ this.set("disableSave", true);+ }+ }++ @discourseComputed("basicNameValidation", "uniqueNameValidation")+ nameValidation(basicNameValidation, uniqueNameValidation) {+ return uniqueNameValidation ? uniqueNameValidation : basicNameValidation;+ }++ @observes("nameInput")+ _validateName() {+ if (this.nameInput === this.get("model.name")) {+ return;+ }++ if (this.nameInput === undefined) {+ return this._failedInputValidation();+ }++ if (this.nameInput === "") {+ this.set("uniqueNameValidation", null);+ return this._failedInputValidation(i18n("admin.groups.new.name.blank"));+ }++ if (this.nameInput.length < this.siteSettings.min_username_length) {+ return this._failedInputValidation(+ i18n("admin.groups.new.name.too_short")+ );+ }++ if (this.nameInput.length > this.siteSettings.max_username_length) {+ return this._failedInputValidation(+ i18n("admin.groups.new.name.too_long")+ );+ }++ this.checkGroupNameDebounced();++ return this._failedInputValidation(i18n("admin.groups.new.name.checking"));+ }++ checkGroupNameDebounced() {+ discourseDebounce(this, this._checkGroupName, 500);+ }++ _checkGroupName() {+ if (isEmpty(this.nameInput)) {+ return;+ }++ Group.checkName(this.nameInput)+ .then((response) => {+ const validationName = "uniqueNameValidation";++ if (response.available) {+ this.set(+ validationName,+ EmberObject.create({+ ok: true,+ reason: i18n("admin.groups.new.name.available"),+ })+ );++ this.set("disableSave", false);+ this.set("model.name", this.nameInput);+ } else {+ let reason;++ if (response.errors) {+ reason = response.errors.join(" ");+ } else {+ reason = i18n("admin.groups.new.name.not_available");+ }++ this.set(validationName, this._failedInputValidation(reason));+ }+ })+ .catch(popupAjaxError);+ }++ _failedInputValidation(reason) {+ this.set("disableSave", true);++ const options = { failed: true };+ if (reason) {+ options.reason = reason;+ }+ this.set("basicNameValidation", EmberObject.create(options));+ }+ }+++{{#if this.canEdit}}+ {{#if this.currentUser.can_create_group}}+ <div class="control-group">+ <label class="control-label" for="name">{{i18n "groups.name"}}</label>++ <TextField+ @name="name"+ @value={{this.nameInput}}+ @placeholderKey="admin.groups.name_placeholder"+ class="input-xxlarge group-form-name"+ />++ <InputTip @validation={{this.nameValidation}} />+ </div>+ {{/if}}++ <div class="control-group">+ <label class="control-label" for="full_name">{{i18n+ "groups.manage.full_name"+ }}</label>++ <TextField+ @name="full_name"+ @value={{this.model.full_name}}+ class="input-xxlarge group-form-full-name"+ />+ </div>+{{/if}}++<div class="control-group">+ <label class="control-label" for="bio">{{i18n "groups.bio"}}</label>+ <DEditor @value={{this.model.bio_raw}} class="group-form-bio input-xxlarge" />+</div>++{{#if this.model.automatic}}+ <div class="control-group">+ <GroupFlairInputs @model={{this.model}} />+ </div>+{{/if}}++{{#if this.canEdit}}+ {{yield}}++ <span>+ <PluginOutlet+ @name="group-edit"+ @connectorTagName="div"+ @outletArgs={{hash group=this.model}}+ />+ </span>+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/horizontal-overflow-nav.gjsindex 5c5685974d8,5d1cf35ed82..c120a8364f0--- a/app/assets/javascripts/discourse/app/components/horizontal-overflow-nav.gjs+++ b/app/assets/javascripts/discourse/app/components/horizontal-overflow-nav.gjs@@@ -1,49 -1,129 +1,179 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import { bind } from "discourse/lib/decorators";++ export default class HorizontalOverflowNav extends Component {+ @service site;++ @tracked hasScroll;+ @tracked hideRightScroll = false;+ @tracked hideLeftScroll = true;+ scrollInterval;++ @bind+ scrollToActive(element) {+ const activeElement = element.querySelector("a.active");++ activeElement?.scrollIntoView({+ block: "nearest",+ inline: "center",+ });+ }++ @bind+ onResize(entries) {+ if (this.site.mobileView) {+ return;+ }++ const element = entries[0].target;+ this.watchScroll(element);+ this.hasScroll = element.scrollWidth > element.offsetWidth;+ }++ @bind+ stopScroll() {+ clearInterval(this.scrollInterval);+ }++ @bind+ onScroll(event) {+ if (this.site.mobileView) {+ return;+ }++ this.watchScroll(event.target);+ }++ watchScroll(element) {+ const { scrollWidth, scrollLeft, offsetWidth } = element;++ // Check if the content overflows+ this.hasScroll = scrollWidth > offsetWidth;++ // Ensure the right arrow disappears only when fully scrolled+ if (scrollWidth - scrollLeft - offsetWidth <= 2) {+ this.hideRightScroll = true;+ clearInterval(this.scrollInterval);+ } else {+ this.hideRightScroll = false;+ }++ // Ensure the left arrow disappears only when fully scrolled to the start+ if (scrollLeft <= 2) {+ this.hideLeftScroll = true;+ clearInterval(this.scrollInterval);+ } else {+ this.hideLeftScroll = false;+ }+ }++ @bind+ scrollDrag(event) {+ if (this.site.mobileView || !this.hasScroll) {+ return;+ }++ event.preventDefault();++ const navPills = event.target.closest(".nav-pills");++ const position = {+ left: navPills.scrollLeft, // current scroll+ x: event.clientX, // mouse position+ };++ const mouseDragScroll = function (e) {+ let mouseChange = e.clientX - position.x;+ navPills.scrollLeft = position.left - mouseChange;+ };++ navPills.querySelectorAll("a").forEach((a) => {+ a.style.cursor = "grabbing";+ });++ const removeDragScroll = function () {+ document.removeEventListener("mousemove", mouseDragScroll);+ navPills.querySelectorAll("a").forEach((a) => {+ a.style.cursor = "pointer";+ });+ };++ document.addEventListener("mousemove", mouseDragScroll);+ document.addEventListener("mouseup", removeDragScroll, { once: true });+ }++ @action+ horizontalScroll(event) {+ // Do nothing if it is not left mousedown+ if (event.which !== 1) {+ return;+ }++ let scrollSpeed = 175;+ let siblingTarget = event.target.previousElementSibling;++ if (event.target.dataset.direction === "left") {+ scrollSpeed = scrollSpeed * -1;+ siblingTarget = event.target.nextElementSibling;+ }++ siblingTarget.scrollLeft += scrollSpeed;++ this.scrollInterval = setInterval(function () {+ siblingTarget.scrollLeft += scrollSpeed;+ }, 50);+ }+ }+++{{! template-lint-disable no-pointer-down-event-binding }}+{{! template-lint-disable no-invalid-interactive }}++<nav+ class="horizontal-overflow-nav {{if this.hasScroll 'has-scroll'}}"+ aria-label={{@ariaLabel}}+>+ {{#if this.hasScroll}}+ <a+ role="button"+ {{on "mousedown" this.horizontalScroll}}+ {{on "mouseup" this.stopScroll}}+ {{on "mouseleave" this.stopScroll}}+ data-direction="left"+ class={{concat-class+ "horizontal-overflow-nav__scroll-left"+ (if this.hideLeftScroll "disabled")+ }}+ >+ {{d-icon "chevron-left"}}+ </a>+ {{/if}}++ <ul+ {{on-resize this.onResize}}+ {{on "scroll" this.onScroll}}+ {{did-insert this.scrollToActive}}+ {{on "mousedown" this.scrollDrag}}+ class="nav-pills action-list {{@className}}"+ ...attributes+ >+ {{yield}}+ </ul>++ {{#if this.hasScroll}}+ <a+ role="button"+ {{on "mousedown" this.horizontalScroll}}+ {{on "mouseup" this.stopScroll}}+ {{on "mouseleave" this.stopScroll}}+ class={{concat-class+ "horizontal-overflow-nav__scroll-right"+ (if this.hideRightScroll "disabled")+ }}+ >+ {{d-icon "chevron-right"}}+ </a>+ {{/if}}+</nav>diff --cc app/assets/javascripts/discourse/app/components/ignored-user-list-item.gjsindex 42b20b0ea34,58e32098628..7d06f0dc65f--- a/app/assets/javascripts/discourse/app/components/ignored-user-list-item.gjs+++ b/app/assets/javascripts/discourse/app/components/ignored-user-list-item.gjs@@@ -1,8 -1,13 +1,22 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { tagName } from "@ember-decorators/component";++ @tagName("div")+ export default class IgnoredUserListItem extends Component {+ items = null;++ @action+ removeIgnoredUser(item) {+ this.onRemoveIgnoredUser(item);+ }+ }+++<div class="ignored-user-list-item">+ <span class="ignored-user-name">{{this.item}}</span>+ <DButton+ @action={{fn (action "removeIgnoredUser") this.item}}+ @icon="xmark"+ class="remove-ignored-user no-text btn-icon"+ />+</div>diff --cc app/assets/javascripts/discourse/app/components/latest-topic-list-item.gjsindex 04d67377f11,46d82e80910..4c61e082213--- a/app/assets/javascripts/discourse/app/components/latest-topic-list-item.gjs+++ b/app/assets/javascripts/discourse/app/components/latest-topic-list-item.gjs@@@ -1,56 -1,52 +1,109 @@@+ import Component from "@ember/component";+ import {+ attributeBindings,+ classNameBindings,+ } from "@ember-decorators/component";+ import {+ navigateToTopic,+ showEntrance,+ } from "discourse/components/topic-list-item";+ import discourseComputed from "discourse/lib/decorators";++ @attributeBindings("topic.id:data-topic-id")+ @classNameBindings(":latest-topic-list-item", "unboundClassNames")+ export default class LatestTopicListItem extends Component {+ showEntrance = showEntrance;+ navigateToTopic = navigateToTopic;++ click(e) {+ // for events undefined has a different meaning than false+ if (this.showEntrance(e) === false) {+ return false;+ }++ return this.unhandledRowClick(e, this.topic);+ }++ // Can be overwritten by plugins to handle clicks on other parts of the row+ unhandledRowClick() {}++ @discourseComputed("topic")+ unboundClassNames(topic) {+ let classes = [];++ if (topic.get("category")) {+ classes.push("category-" + topic.get("category.fullSlug"));+ }++ if (topic.get("tags")) {+ topic.get("tags").forEach((tagName) => classes.push("tag-" + tagName));+ }++ ["liked", "archived", "bookmarked", "pinned", "closed", "visited"].forEach(+ (name) => {+ if (topic.get(name)) {+ classes.push(name);+ }+ }+ );++ return classes.join(" ");+ }+ }+++<PluginOutlet+ @name="above-latest-topic-list-item"+ @connectorTagName="div"+ @outletArgs={{hash topic=this.topic}}+/>+<div class="topic-poster">+ <UserLink+ @user={{this.topic.lastPosterUser}}+ aria-label={{if+ this.topic.lastPosterUser.username+ (i18n "latest_poster_link" username=this.topic.lastPosterUser.username)+ }}+ >+ {{avatar this.topic.lastPosterUser imageSize="large"}}+ </UserLink>+ <UserAvatarFlair @user={{this.topic.lastPosterUser}} />+</div>+<div class="main-link">+ <div class="top-row">+ {{raw "topic-status" topic=this.topic}}+ {{topic-link this.topic}}+ {{~#if this.topic.featured_link}}+ {{topic-featured-link this.topic}}+ {{/if}}{{! intentionally inline+ to avoid whitespace}}<TopicPostBadges+ @unreadPosts={{this.topic.unread_posts}}+ @unseen={{this.topic.unseen}}+ @url={{this.topic.lastUnreadUrl}}+ />+ </div>+ <div class="bottom-row">+ {{category-link this.topic.category}}{{discourse-tags+ this.topic+ mode="list"+ }}{{! intentionally inline to avoid whitespace}}+ <PluginOutlet+ @name="below-latest-topic-list-item-bottom-row"+ @connectorTagName="span"+ @outletArgs={{hash topic=this.topic}}+ />+ </div>+</div>+<div class="topic-stats">+ <PluginOutlet+ @name="above-latest-topic-list-item-post-count"+ @connectorTagName="div"+ @outletArgs={{hash topic=this.topic}}+ />+ {{raw "list/posts-count-column" topic=this.topic tagName="div"}}+ <div class="topic-last-activity">+ <a+ href={{this.topic.lastPostUrl}}+ title={{this.topic.bumpedAtTitle}}+ >{{format-date this.topic.bumpedAt format="tiny" noTitle="true"}}</a>+ </div>+</div>diff --cc app/assets/javascripts/discourse/app/components/link-to-input.gjsindex a147e707f84,97b9b912b1f..2b99fbbd38d--- a/app/assets/javascripts/discourse/app/components/link-to-input.gjs+++ b/app/assets/javascripts/discourse/app/components/link-to-input.gjs@@@ -1,12 -1,17 +1,30 @@@+ import Component from "@ember/component";+ import { schedule } from "@ember/runloop";+ import $ from "jquery";++ export default class LinkToInput extends Component {+ showInput = false;++ click() {+ this.onClick();++ schedule("afterRender", () => {+ $(this.element).find("input").focus();+ });++ return false;+ }+ }+++{{#if this.showInput}}+ {{yield}}+{{else}}+ <a href>+ {{#if this.key}}+ {{i18n this.key}}+ {{/if}}+ {{#if this.icon}}+ {{d-icon this.icon}}+ {{/if}}+ </a>+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/local-login-form.gjsindex 9f42ace95fb,138dd0ece0e..cac1ee68351--- a/app/assets/javascripts/discourse/app/components/local-login-form.gjs+++ b/app/assets/javascripts/discourse/app/components/local-login-form.gjs@@@ -1,103 -1,142 +1,246 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import { htmlSafe } from "@ember/template";+ import { isEmpty } from "@ember/utils";+ import ForgotPassword from "discourse/components/modal/forgot-password";+ import { ajax } from "discourse/lib/ajax";+ import { popupAjaxError } from "discourse/lib/ajax-error";+ import { escapeExpression } from "discourse/lib/utilities";+ import { getWebauthnCredential } from "discourse/lib/webauthn";+ import { i18n } from "discourse-i18n";++ export default class LocalLoginForm extends Component {+ @service modal;++ @tracked maskPassword = true;+ @tracked processingEmailLink = false;+ @tracked capsLockOn = false;++ get credentialsClass() {+ return this.args.showSecondFactor || this.args.showSecurityKey+ ? "hidden"+ : "";+ }++ get showSecondFactorForm() {+ return this.args.showSecondFactor || this.args.showSecurityKey;+ }++ get disableLoginFields() {+ return this.args.showSecondFactor || this.args.showSecurityKey;+ }++ @action+ passkeyConditionalLogin() {+ if (this.args.canUsePasskeys) {+ this.args.passkeyLogin("conditional");+ }+ }++ @action+ scrollInputIntoView(event) {+ event.target.scrollIntoView({+ behavior: "smooth",+ block: "center",+ });+ }++ @action+ togglePasswordMask() {+ this.maskPassword = !this.maskPassword;+ }++ @action+ async emailLogin(event) {+ event?.preventDefault();++ if (this.processingEmailLink) {+ return;+ }++ if (isEmpty(this.args.loginName)) {+ this.args.flashChanged(i18n("login.blank_username"));+ this.args.flashTypeChanged("info");+ return;+ }++ try {+ this.processingEmailLink = true;+ const data = await ajax("/u/email-login", {+ data: { login: this.args.loginName.trim() },+ type: "POST",+ });+ const loginName = escapeExpression(this.args.loginName);+ const isEmail = loginName.match(/@/);+ const key = isEmail+ ? "email_login.complete_email"+ : "email_login.complete_username";+ if (data.user_found === false) {+ this.args.flashChanged(+ htmlSafe(+ i18n(`${key}_not_found`, {+ email: loginName,+ username: loginName,+ })+ )+ );+ this.args.flashTypeChanged("error");+ } else {+ const postfix = data.hide_taken ? "" : "_found";+ this.args.flashChanged(+ htmlSafe(+ i18n(`${key}${postfix}`, {+ email: loginName,+ username: loginName,+ })+ )+ );+ this.args.flashTypeChanged("success");+ }+ } catch (e) {+ popupAjaxError(e);+ } finally {+ this.processingEmailLink = false;+ }+ }++ @action+ loginOnEnter(event) {+ if (event.key === "Enter") {+ this.args.login();+ }+ }++ @action+ handleForgotPassword(event) {+ event?.preventDefault();++ this.modal.show(ForgotPassword, {+ model: {+ emailOrUsername: this.args.loginName,+ },+ });+ }++ @action+ authenticateSecurityKey() {+ getWebauthnCredential(+ this.args.securityKeyChallenge,+ this.args.securityKeyAllowedCredentialIds,+ (credentialData) => {+ this.args.securityKeyCredentialChanged(credentialData);+ this.args.login();+ },+ (error) => {+ this.args.flashChanged(error);+ this.args.flashTypeChanged("error");+ }+ );+ }+ }+++<form id="login-form" method="post">+ <div id="credentials" class={{this.credentialsClass}}>+ <div class="input-group" {{did-insert this.passkeyConditionalLogin}}>+ <Input+ {{on "focusin" this.scrollInputIntoView}}+ @value={{@loginName}}+ @type="email"+ id="login-account-name"+ class={{value-entered @loginName}}+ autocomplete={{if @canUsePasskeys "username webauthn" "username"}}+ autocorrect="off"+ autocapitalize="off"+ disabled={{@showSecondFactor}}+ autofocus="autofocus"+ tabindex="1"+ {{on "input" @loginNameChanged}}+ {{on "keydown" this.loginOnEnter}}+ />+ <label class="alt-placeholder" for="login-account-name">+ {{i18n "login.email_placeholder"}}+ </label>+ {{#if @canLoginLocalWithEmail}}+ <a+ href+ class={{if @loginName "" "no-login-filled"}}+ tabindex="3"+ id="email-login-link"+ {{on "click" this.emailLogin}}+ >+ {{i18n "email_login.login_link"}}+ </a>+ {{/if}}+ </div>+ <div class="input-group">+ <PasswordField+ {{on "focusin" this.scrollInputIntoView}}+ {{on "keydown" this.loginOnEnter}}+ @value={{@loginPassword}}+ @capsLockOn={{this.capsLockOn}}+ type={{if this.maskPassword "password" "text"}}+ disabled={{this.disableLoginFields}}+ autocomplete="current-password"+ maxlength="200"+ tabindex="1"+ id="login-account-password"+ class={{value-entered @loginPassword}}+ />+ <label class="alt-placeholder" for="login-account-password">+ {{i18n "login.password"}}+ </label>+ {{#if @loginPassword}}+ <TogglePasswordMask+ @maskPassword={{this.maskPassword}}+ @togglePasswordMask={{this.togglePasswordMask}}+ tabindex="3"+ />+ {{/if}}+ <div class="login__password-links">+ <a+ href+ id="forgot-password-link"+ tabindex="2"+ {{on "click" this.handleForgotPassword}}+ >+ {{i18n "forgot_password.action"}}+ </a>+ </div>+ <div class="caps-lock-warning {{unless this.capsLockOn 'hidden'}}">+ {{d-icon "triangle-exclamation"}}+ {{i18n "login.caps_lock_warning"}}</div>+ </div>+ </div>+ {{#if this.showSecondFactorForm}}+ <SecondFactorForm+ @secondFactorMethod={{@secondFactorMethod}}+ @secondFactorToken={{@secondFactorToken}}+ @backupEnabled={{@backupEnabled}}+ @totpEnabled={{@totpEnabled}}+ @isLogin={{true}}+ >+ {{#if @showSecurityKey}}+ <SecurityKeyForm+ @setShowSecurityKey={{fn (mut @showSecurityKey)}}+ @setShowSecondFactor={{fn (mut @showSecondFactor)}}+ @setSecondFactorMethod={{fn (mut @secondFactorMethod)}}+ @backupEnabled={{@backupEnabled}}+ @totpEnabled={{@totpEnabled}}+ @otherMethodAllowed={{@otherMethodAllowed}}+ @action={{this.authenticateSecurityKey}}+ />+ {{else}}+ <SecondFactorInput+ {{on "keydown" this.loginOnEnter}}+ {{on "input" (with-event-value (fn (mut @secondFactorToken)))}}+ {{on "focusin" this.scrollInputIntoView}}+ @secondFactorMethod={{@secondFactorMethod}}+ value={{@secondFactorToken}}+ id="login-second-factor"+ />+ {{/if}}+ </SecondFactorForm>+ {{/if}}+</form>diff --cc app/assets/javascripts/discourse/app/components/login-buttons.gjsindex b7684227d22,81a52a5beb4..d0fc7397209--- a/app/assets/javascripts/discourse/app/components/login-buttons.gjs+++ b/app/assets/javascripts/discourse/app/components/login-buttons.gjs@@@ -1,23 -1,39 +1,63 @@@+ import Component from "@ember/component";+ import { classNameBindings } from "@ember-decorators/component";+ import discourseComputed from "discourse/lib/decorators";+ import { isWebauthnSupported } from "discourse/lib/webauthn";+ import { findAll } from "discourse/models/login-method";++ @classNameBindings("hidden", "multiple")+ export default class LoginButtons extends Component {+ elementId = "login-buttons";++ @discourseComputed(+ "buttons.length",+ "showLoginWithEmailLink",+ "showPasskeysButton"+ )+ hidden(buttonsCount, showLoginWithEmailLink, showPasskeysButton) {+ return buttonsCount === 0 && !showLoginWithEmailLink && !showPasskeysButton;+ }++ @discourseComputed("buttons.length")+ multiple(buttonsCount) {+ return buttonsCount > 1;+ }++ @discourseComputed+ buttons() {+ return findAll();+ }++ @discourseComputed+ showPasskeysButton() {+ return (+ this.siteSettings.enable_local_logins &&+ this.siteSettings.enable_passkeys &&+ this.context === "login" &&+ isWebauthnSupported()+ );+ }+ }+++{{#each this.buttons as |b|}}+ <button+ type="button"+ class="btn btn-social {{b.name}}"+ {{on "click" (action this.externalLogin b)}}+ aria-label={{b.screenReaderTitle}}+ >+ {{#if b.isGoogle}}+ <GoogleIcon />+ {{else if b.icon}}+ {{d-icon b.icon}}+ {{else}}+ {{d-icon "right-to-bracket"}}+ {{/if}}+ <span class="btn-social-title">{{b.title}}</span>+ </button>+{{/each}}++{{#if this.showPasskeysButton}}+ <PasskeyLoginButton @passkeyLogin={{this.passkeyLogin}} />+{{/if}}++<PluginOutlet @name="after-login-buttons" />diff --cc app/assets/javascripts/discourse/app/components/mobile-category-topic.gjsindex 2a7f26d78b9,f02ad5080f3..104be6560e5--- a/app/assets/javascripts/discourse/app/components/mobile-category-topic.gjs+++ b/app/assets/javascripts/discourse/app/components/mobile-category-topic.gjs@@@ -1,18 -1,9 +1,28 @@@+ import Component from "@ember/component";+ import { classNameBindings, tagName } from "@ember-decorators/component";+ import { showEntrance } from "discourse/components/topic-list-item";++ @tagName("tr")+ @classNameBindings(":category-topic-link", "topic.archived", "topic.visited")+ export default class MobileCategoryTopic extends Component {+ click = showEntrance;+ }+++<td class="main-link">+ <div class="topic-inset">+ {{raw "topic-status" topic=this.topic}}+ {{topic-link this.topic}}+ {{#if this.topic.unseen}}+ <span class="badge-notification new-topic"></span>+ {{/if}}+ <span+ class={{cold-age-class this.topic.last_posted_at}}+ title={{raw-date this.topic.last_posted_at}}+ >{{format-age this.topic.last_posted_at}}</span>+ </div>+</td>+<td class="num posts">{{raw+ "list/post-count-or-badges"+ topic=this.topic+ postBadgesEnabled="true"+ }}</td>diff --cc app/assets/javascripts/discourse/app/components/mobile-nav.gjsindex 1bcce4d2536,3fdd701ab6d..6fbcac93c88--- a/app/assets/javascripts/discourse/app/components/mobile-nav.gjs+++ b/app/assets/javascripts/discourse/app/components/mobile-nav.gjs@@@ -1,15 -1,78 +1,94 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { next } from "@ember/runloop";+ import { service } from "@ember/service";+ import { classNames, tagName } from "@ember-decorators/component";+ import { on } from "@ember-decorators/object";+ import $ from "jquery";++ @tagName("ul")+ @classNames("mobile-nav")+ export default class MobileNav extends Component {+ @service router;++ selectedHtml = null;++ @on("init")+ _init() {+ if (this.site.desktopView) {+ let classes = this.desktopClass;+ if (classes) {+ classes = classes.split(" ");+ this.set("classNames", classes);+ }+ }+ }++ currentRouteChanged() {+ this.set("expanded", false);+ next(() => this._updateSelectedHtml());+ }++ _updateSelectedHtml() {+ if (!this.element || this.isDestroying || this.isDestroyed) {+ return;+ }++ const active = this.element.querySelector(".active");+ if (active && active.innerHTML) {+ this.set("selectedHtml", active.innerHTML);+ }+ }++ didInsertElement() {+ super.didInsertElement(...arguments);++ this._updateSelectedHtml();+ this.router.on("routeDidChange", this, this.currentRouteChanged);+ }++ willDestroyElement() {+ super.willDestroyElement(...arguments);+ this.router.off("routeDidChange", this, this.currentRouteChanged);+ }++ @action+ toggleExpanded(event) {+ event?.preventDefault();+ this.toggleProperty("expanded");++ next(() => {+ if (this.expanded) {+ $(window)+ .off("click.mobile-nav")+ .on("click.mobile-nav", (e) => {+ if (!this.element || this.isDestroying || this.isDestroyed) {+ return;+ }++ const expander = this.element.querySelector(".expander");+ if (expander && e.target !== expander) {+ this.set("expanded", false);+ $(window).off("click.mobile-nav");+ }+ });+ }+ });+ }+ }+++{{#if this.site.mobileView}}+ {{#if this.selectedHtml}}+ <li>+ <a href {{on "click" this.toggleExpanded}} class="expander">+ <span class="selection">{{html-safe this.selectedHtml}}</span>+ {{d-icon "caret-down"}}+ </a>+ </li>+ {{/if}}+ <ul class="drop {{if this.expanded 'expanded'}}">+ {{yield}}+ </ul>+{{else}}+ {{yield}}+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/modal/associate-account-confirm.gjsindex fcd33674869,8513a46f5b5..113c3f9c97c--- a/app/assets/javascripts/discourse/app/components/modal/associate-account-confirm.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/associate-account-confirm.gjs@@@ -1,46 -1,35 +1,82 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import { ajax } from "discourse/lib/ajax";+ import { popupAjaxError } from "discourse/lib/ajax-error";++ export default class AssociateAccountConfirm extends Component {+ @service router;+ @service currentUser;++ @tracked flash;++ @action+ async finishConnect() {+ try {+ const result = await ajax({+ url: `/associate/${encodeURIComponent(this.args.model.token)}`,+ type: "POST",+ });++ if (result.success) {+ this.router.transitionTo(+ "preferences.account",+ this.currentUser.findDetails()+ );+ this.args.closeModal();+ } else {+ this.flash = result.error;+ }+ } catch (e) {+ popupAjaxError(e);+ }+ }+ }+++<DModal+ @title={{i18n+ "user.associated_accounts.confirm_modal_title"+ provider=(i18n (concat "login." @model.provider_name ".name"))+ }}+ @closeModal={{@closeModal}}+ @flash={{this.flash}}+ @flashType="error"+>+ <:body>+ {{#if @model.existing_account_description}}+ <p>+ {{i18n+ "user.associated_accounts.confirm_description.disconnect"+ provider=(i18n (concat "login." @model.provider_name ".name"))+ [email protected]_account_description+ }}+ </p>+ {{/if}}++ <p>+ {{#if @model.account_description}}+ {{i18n+ "user.associated_accounts.confirm_description.account_specific"+ provider=(i18n (concat "login." @model.provider_name ".name"))+ [email protected]_description+ }}+ {{else}}+ {{i18n+ "user.associated_accounts.confirm_description.generic"+ provider=(i18n (concat "login." @model.provider_name ".name"))+ }}+ {{/if}}+ </p>+ </:body>++ <:footer>+ <DButton+ @label="user.associated_accounts.connect"+ @action={{this.finishConnect}}+ @icon="plug"+ class="btn-primary"+ />+ <DButton @label="user.associated_accounts.cancel" @action={{@closeModal}} />+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/auth-token.gjsindex 665a6d60df6,aac5b33c578..a82484c6851--- a/app/assets/javascripts/discourse/app/components/modal/auth-token.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/auth-token.gjs@@@ -1,51 -1,34 +1,86 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import { ajax } from "discourse/lib/ajax";+ import { userPath } from "discourse/lib/url";++ export default class AuthTokenComponent extends Component {+ @service currentUser;++ @tracked expanded = false;+ @tracked latestPost = null;++ constructor() {+ super(...arguments);+ this.fetchActivity();+ }++ @action+ async fetchActivity() {+ const posts = await ajax(+ userPath(`${this.currentUser.username_lower}/activity.json`)+ );+ if (posts.length > 0) {+ this.latestPost = posts[0];+ }+ }++ @action+ toggleExpanded(event) {+ event?.preventDefault();+ this.expanded = !this.expanded;+ }+ }+++<DModal+ @title={{i18n "user.auth_tokens.was_this_you"}}+ @closeModal={{@closeModal}}+>+ <:body>+ <div>+ <p>{{i18n "user.auth_tokens.was_this_you_description"}}</p>+ <p>{{html-safe (i18n "user.second_factor.extended_description")}}</p>+ </div>+ <div>+ <h3>{{i18n "user.auth_tokens.details"}}</h3>+ <ul>+ <li>{{d-icon "far-clock"}} {{format-date @model.seen_at}}</li>+ <li>{{d-icon "location-dot"}} {{@model.location}}</li>+ <li>{{d-icon @model.icon}}+ {{i18n+ "user.auth_tokens.browser_and_device"+ }}</li>+ </ul>+ </div>++ {{#if this.latestPost}}+ <div>+ <h3>+ {{i18n "user.auth_tokens.latest_post"}}+ {{! when this.fetchActivity is called, the modal focus is reset }}+ {{! allowing you to tab behind the modal, so we need to refocus }}+ <a href {{on "click" this.toggleExpanded}} {{auto-focus}}>+ {{d-icon (if this.expanded "caret-up" "caret-down")}}+ </a>+ </h3>+ {{#if this.expanded}}+ <blockquote>{{html-safe this.latestPost.cooked}}</blockquote>+ {{else}}+ <blockquote>{{html-safe this.latestPost.excerpt}}</blockquote>+ {{/if}}+ </div>+ {{/if}}+ </:body>+ <:footer>+ <DButton+ class="btn-primary"+ @action={{@closeModal}}+ @icon="lock"+ @label="user.auth_tokens.secure_account"+ />+ <DModalCancel @close={{@closeModal}} />+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/avatar-selector.gjsindex dfd6dc4829c,1c8b80ccb9e..ddb3aa10233--- a/app/assets/javascripts/discourse/app/components/modal/avatar-selector.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/avatar-selector.gjs@@@ -1,141 -1,159 +1,301 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import { ajax } from "discourse/lib/ajax";+ import { popupAjaxError } from "discourse/lib/ajax-error";+ import { isTesting } from "discourse/lib/environment";+ import { allowsImages } from "discourse/lib/uploads";++ export default class AvatarSelectorModal extends Component {+ @service currentUser;+ @service siteSettings;++ @tracked gravatarRefreshDisabled = false;+ @tracked gravatarFailed = false;+ @tracked uploading = false;+ @tracked _selected = null;++ get user() {+ return this.args.model.user;+ }++ get selected() {+ return this._selected ?? this.defaultSelection;+ }++ set selected(value) {+ this._selected = value;+ }++ get submitDisabled() {+ return this.selected === "logo" || this.uploading;+ }++ get selectableAvatars() {+ const mode = this.siteSettings.selectable_avatars_mode;+ const list = this.siteSettings.selectable_avatars;+ return mode !== "disabled" ? (list ? list.split("|") : []) : null;+ }++ get showSelectableAvatars() {+ return this.siteSettings.selectable_avatars_mode !== "disabled";+ }++ get showCustomAvatarSelector() {+ const mode = this.siteSettings.selectable_avatars_mode;+ switch (mode) {+ case "no_one":+ return false;+ case "tl1":+ case "tl2":+ case "tl3":+ case "tl4":+ const allowedTl = parseInt(mode.replace("tl", ""), 10);+ return (+ this.user.admin ||+ this.user.moderator ||+ this.user.trust_level >= allowedTl+ );+ case "staff":+ return this.user.admin || this.user.moderator;+ case "everyone":+ default:+ return true;+ }+ }++ get defaultSelection() {+ if (this.user.use_logo_small_as_avatar) {+ return "logo";+ } else if (this.user.avatar_template === this.user.system_avatar_template) {+ return "system";+ } else if (+ this.user.avatar_template === this.user.gravatar_avatar_template+ ) {+ return "gravatar";+ } else {+ return "custom";+ }+ }++ get selectedUploadId() {+ const selected = this.selected;+ switch (selected) {+ case "system":+ return this.user.system_avatar_upload_id;+ case "gravatar":+ return this.user.gravatar_avatar_upload_id;+ default:+ return this.user.custom_avatar_upload_id;+ }+ }++ get allowAvatarUpload() {+ return (+ this.currentUser.can_upload_avatar &&+ allowsImages(this.currentUser.staff, this.siteSettings)+ );+ }++ @action+ onSelectedChanged(value) {+ this.selected = value;+ }++ @action+ async selectAvatar(url, event) {+ event?.preventDefault();+ try {+ await this.user.selectAvatar(url);+ window.location.reload();+ } catch (error) {+ popupAjaxError(error);+ }+ }++ @action+ uploadComplete() {+ this.selected = "custom";+ }++ @action+ async refreshGravatar() {+ this.gravatarRefreshDisabled = true;++ try {+ const result = await ajax(+ `/user_avatar/${this.user.username}/refresh_gravatar.json`,+ {+ type: "POST",+ }+ );++ if (!result.gravatar_upload_id) {+ this.gravatarFailed = true;+ } else {+ this.gravatarFailed = false;+ this.user.setProperties({+ gravatar_avatar_upload_id: result.gravatar_upload_id,+ gravatar_avatar_template: result.gravatar_avatar_template,+ });+ }+ } finally {+ this.gravatarRefreshDisabled = false;+ }+ }++ @action+ async saveAvatarSelection() {+ try {+ await this.user.pickAvatar(this.selectedUploadId, this.selected);+ if (!isTesting()) {+ window.location.reload();+ }+ } catch (error) {+ popupAjaxError(error);+ }+ }+ }+++<DModal+ @bodyClass="avatar-selector"+ @closeModal={{@closeModal}}+ @title={{i18n "user.change_avatar.title"}}+ class="avatar-selector-modal"+>+ <:body>+ {{#if this.showSelectableAvatars}}+ <div class="selectable-avatars">+ {{#each this.selectableAvatars as |avatar|}}+ <a+ href+ class="selectable-avatar"+ {{on "click" (fn this.selectAvatar avatar)}}+ >+ {{bound-avatar-template avatar "huge"}}+ </a>+ {{/each}}+ </div>+ {{#if this.showCustomAvatarSelector}}+ <h4>{{i18n "user.change_avatar.use_custom"}}</h4>+ {{/if}}+ {{/if}}+ {{#if this.showCustomAvatarSelector}}+ {{#if this.user.use_logo_small_as_avatar}}+ <div class="avatar-choice">+ <RadioButton+ @id="logo-small"+ @name="logo"+ @value="logo"+ @selection={{this.selected}}+ @onChange={{this.onSelectedChanged}}+ />+ <label class="radio" for="logo-small">+ {{bound-avatar-template+ this.siteSettings.site_logo_small_url+ "large"+ }}+ {{i18n "user.change_avatar.logo_small"}}+ </label>+ </div>+ {{/if}}+ <div class="avatar-choice">+ <RadioButton+ @id="system-avatar"+ @name="avatar"+ @value="system"+ @selection={{this.selected}}+ @onChange={{this.onSelectedChanged}}+ />+ <label class="radio" for="system-avatar">+ {{bound-avatar-template this.user.system_avatar_template "large"}}+ {{i18n "user.change_avatar.letter_based"}}+ </label>+ </div>+ {{#if this.allowAvatarUpload}}+ <div class="avatar-choice">+ <RadioButton+ @id="gravatar"+ @name="avatar"+ @value="gravatar"+ @selection={{this.selected}}+ @onChange={{this.onSelectedChanged}}+ />+ <label class="radio" for="gravatar">+ {{bound-avatar-template this.user.gravatar_avatar_template "large"}}+ <span>+ {{html-safe+ (i18n+ "user.change_avatar.gravatar"+ gravatarName=this.siteSettings.gravatar_name+ gravatarBaseUrl=this.siteSettings.gravatar_base_url+ gravatarLoginUrl=this.siteSettings.gravatar_login_url+ )+ }}+ {{this.user.email}}+ </span>+ </label>++ <DButton+ @action={{this.refreshGravatar}}+ @translatedTitle={{i18n+ "user.change_avatar.refresh_gravatar_title"+ gravatarName=this.siteSettings.gravatar_name+ }}+ @disabled={{this.gravatarRefreshDisabled}}+ @icon="arrows-rotate"+ class="btn-default avatar-selector-refresh-gravatar"+ />++ {{#if this.gravatarFailed}}+ <p class="error">+ {{i18n+ "user.change_avatar.gravatar_failed"+ gravatarName=this.siteSettings.gravatar_name+ }}+ </p>+ {{/if}}+ </div>+ <div class="avatar-choice">+ <RadioButton+ @id="uploaded-avatar"+ @name="avatar"+ @value="custom"+ @selection={{this.selected}}+ @onChange={{this.onSelectedChanged}}+ />+ <label class="radio" for="uploaded-avatar">+ {{#if this.user.custom_avatar_template}}+ {{bound-avatar-template this.user.custom_avatar_template "large"}}+ {{i18n "user.change_avatar.uploaded_avatar"}}+ {{else}}+ {{i18n "user.change_avatar.uploaded_avatar_empty"}}+ {{/if}}+ </label>+ <AvatarUploader+ @user_id={{this.user.id}}+ @uploadedAvatarTemplate={{this.user.custom_avatar_template}}+ @uploadedAvatarId={{this.user.custom_avatar_upload_id}}+ @uploading={{this.uploading}}+ @id="avatar-uploader"+ @done={{this.uploadComplete}}+ class="avatar-uploader"+ />+ </div>+ {{/if}}+ {{/if}}+ </:body>++ <:footer>+ {{#if this.showCustomAvatarSelector}}+ <DButton+ @action={{this.saveAvatarSelection}}+ @disabled={{this.submitDisabled}}+ @label="save"+ class="btn-primary"+ />+ <DModalCancel @close={{@closeModal}} />+ {{/if}}+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/change-timestamp.gjsindex 6c2a19cc211,dafd067309e..d8124f858ab--- a/app/assets/javascripts/discourse/app/components/modal/change-timestamp.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/change-timestamp.gjs@@@ -1,32 -1,45 +1,78 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { next } from "@ember/runloop";+ import { isEmpty } from "@ember/utils";+ import DiscourseURL from "discourse/lib/url";+ import Topic from "discourse/models/topic";+ import { i18n } from "discourse-i18n";++ // Modal related to changing the timestamp of posts+ export default class ChangeTimestamp extends Component {+ @tracked saving = false;+ @tracked date = moment().format("YYYY-MM-DD");+ @tracked time;+ @tracked flash;++ get createdAt() {+ return moment(`${this.date} ${this.time}`, "YYYY-MM-DD HH:mm:ss");+ }++ get validTimestamp() {+ return moment().diff(this.createdAt, "minutes") < 0;+ }++ get buttonDisabled() {+ return this.saving || this.validTimestamp || isEmpty(this.date);+ }++ @action+ async changeTimestamp() {+ this.saving = true;+ try {+ await Topic.changeTimestamp(+ this.args.model.topic.id,+ this.createdAt.unix()+ );+ this.args.closeModal();+ next(() => DiscourseURL.routeTo(this.args.model.topic.url));+ } catch {+ this.flash = i18n("topic.change_timestamp.error");+ } finally {+ this.saving = false;+ }+ }+ }+++<DModal+ @bodyClass="change-timestamp"+ @closeModal={{@closeModal}}+ @flash={{this.flash}}+ @title={{i18n "topic.change_timestamp.title"}}+>+ <:body>+ <p>+ {{i18n "topic.change_timestamp.instructions"}}+ </p>+ <p class="alert alert-error {{unless this.validTimestamp 'hidden'}}">+ {{i18n "topic.change_timestamp.invalid_timestamp"}}+ </p>+ <form>+ <DatePickerPast+ @value={{readonly this.date}}+ @containerId="date-container"+ @onSelect={{fn (mut this.date)}}+ />+ <Input @type="time" @value={{this.time}} />+ </form>+ <div id="date-container"></div>+ </:body>+ <:footer>+ <DButton+ class="btn-primary"+ @disabled={{this.buttonDisabled}}+ @action={{this.changeTimestamp}}+ @label={{if this.saving "saving" "topic.change_timestamp.action"}}+ />+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/create-account.gjsindex 5276e6db345,14f1c1d7fe6..7edba7f31f0--- a/app/assets/javascripts/discourse/app/components/modal/create-account.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/create-account.gjs@@@ -1,301 -1,540 +1,842 @@@+ import { tracked } from "@glimmer/tracking";+ import { A } from "@ember/array";+ import Component from "@ember/component";+ import EmberObject, { action } from "@ember/object";+ import { dependentKeyCompat } from "@ember/object/compat";+ import { service } from "@ember/service";+ import { isEmpty } from "@ember/utils";+ import { observes } from "@ember-decorators/object";+ import { Promise } from "rsvp";+ import { ajax } from "discourse/lib/ajax";+ import { setting } from "discourse/lib/computed";+ import cookie, { removeCookie } from "discourse/lib/cookie";+ import discourseDebounce from "discourse/lib/debounce";+ import discourseComputed, { bind } from "discourse/lib/decorators";+ import NameValidationHelper from "discourse/lib/name-validation-helper";+ import PasswordValidationHelper from "discourse/lib/password-validation-helper";+ import { userPath } from "discourse/lib/url";+ import UsernameValidationHelper from "discourse/lib/username-validation-helper";+ import { emailValid } from "discourse/lib/utilities";+ import UserFieldsValidation from "discourse/mixins/user-fields-validation";+ import { findAll } from "discourse/models/login-method";+ import User from "discourse/models/user";+ import { i18n } from "discourse-i18n";++ export default class CreateAccount extends Component.extend(+ UserFieldsValidation+ ) {+ @service site;+ @service siteSettings;+ @service login;++ @tracked isDeveloper = false;+ @tracked accountName = this.model.accountName;+ @tracked accountEmail = this.model.accountEmail;+ @tracked accountUsername = this.model.accountUsername;+ @tracked accountPassword = this.model.accountPassword;+ @tracked authOptions = this.model.authOptions;+ @tracked skipConfirmation = this.model.skipConfirmation;+ accountChallenge = 0;+ accountHoneypot = 0;+ formSubmitted = false;+ rejectedEmails = A();+ prefilledUsername = null;+ userFields = null;+ maskPassword = true;+ emailValidationVisible = false;+ nameValidationHelper = new NameValidationHelper(this);+ usernameValidationHelper = new UsernameValidationHelper(this);+ passwordValidationHelper = new PasswordValidationHelper(this);++ @setting("enable_local_logins") canCreateLocal;+ @setting("require_invite_code") requireInviteCode;++ init() {+ super.init(...arguments);++ if (cookie("email")) {+ this.accountEmail = cookie("email");+ }++ this.fetchConfirmationValue();++ if (this.model.skipConfirmation) {+ this.performAccountCreation().finally(+ () => (this.skipConfirmation = false)+ );+ }+ }++ @action+ setAccountUsername(event) {+ this.accountUsername = event.target.value;+ }++ @dependentKeyCompat+ get usernameValidation() {+ return this.usernameValidationHelper.usernameValidation;+ }++ get passwordValidation() {+ return this.passwordValidationHelper.passwordValidation;+ }++ get nameTitle() {+ return this.nameValidationHelper.nameTitle;+ }++ get nameValidation() {+ return this.nameValidationHelper.nameValidation;+ }++ @dependentKeyCompat+ get hasAuthOptions() {+ return !isEmpty(this.authOptions);+ }++ @dependentKeyCompat+ get forceValidationReason() {+ return this.nameValidationHelper.forceValidationReason;+ }++ @bind+ actionOnEnter(event) {+ if (!this.submitDisabled && event.key === "Enter") {+ event.preventDefault();+ event.stopPropagation();+ this.createAccount();+ return false;+ }+ }++ @bind+ selectKitFocus(event) {+ const target = document.getElementById(event.target.getAttribute("for"));+ if (target?.classList.contains("select-kit")) {+ event.preventDefault();+ target.querySelector(".select-kit-header").click();+ }+ }++ get showCreateForm() {+ return (+ (this.hasAuthOptions || this.canCreateLocal) && !this.skipConfirmation+ );+ }++ @discourseComputed("site.desktopView", "hasAuthOptions")+ showExternalLoginButtons(desktopView, hasAuthOptions) {+ return desktopView && !hasAuthOptions;+ }++ @discourseComputed("formSubmitted")+ submitDisabled() {+ return this.formSubmitted;+ }++ @discourseComputed("userFields", "hasAtLeastOneLoginButton", "hasAuthOptions")+ modalBodyClasses(userFields, hasAtLeastOneLoginButton, hasAuthOptions) {+ const classes = [];+ if (userFields) {+ classes.push("has-user-fields");+ }+ if (hasAtLeastOneLoginButton && !hasAuthOptions) {+ classes.push("has-alt-auth");+ }+ if (!this.canCreateLocal) {+ classes.push("no-local-logins");+ }+ return classes.join(" ");+ }++ get usernameDisabled() {+ return this.authOptions && !this.authOptions.can_edit_username;+ }++ get nameDisabled() {+ return this.authOptions && !this.authOptions.can_edit_name;+ }++ @discourseComputed+ showFullname() {+ return this.site.full_name_visible_in_signup;+ }++ @discourseComputed+ fullnameRequired() {+ return this.site.full_name_required_for_signup;+ }++ @discourseComputed(+ "emailValidation.ok",+ "emailValidation.reason",+ "emailValidationVisible"+ )+ showEmailValidation(+ emailValidationOk,+ emailValidationReason,+ emailValidationVisible+ ) {+ return (+ emailValidationOk || (emailValidationReason && emailValidationVisible)+ );+ }++ get showPasswordValidation() {+ return this.passwordValidation.ok || this.passwordValidation.reason;+ }++ get showUsernameInstructions() {+ return (+ this.siteSettings.show_signup_form_username_instructions &&+ !this.usernameValidation.reason+ );+ }++ get passwordRequired() {+ return isEmpty(this.authOptions?.auth_provider);+ }++ @discourseComputed+ disclaimerHtml() {+ if (this.site.tos_url && this.site.privacy_policy_url) {+ return i18n("create_account.disclaimer", {+ tos_link: this.site.tos_url,+ privacy_link: this.site.privacy_policy_url,+ });+ }+ }++ // Check the email address+ @discourseComputed(+ "serverAccountEmail",+ "serverEmailValidation",+ "accountEmail",+ "rejectedEmails.[]",+ "forceValidationReason"+ )+ emailValidation(+ serverAccountEmail,+ serverEmailValidation,+ email,+ rejectedEmails,+ forceValidationReason+ ) {+ const failedAttrs = {+ failed: true,+ ok: false,+ element: document.querySelector("#new-account-email"),+ };++ if (serverAccountEmail === email && serverEmailValidation) {+ return serverEmailValidation;+ }++ // If blank, fail without a reason+ if (isEmpty(email)) {+ return EmberObject.create(+ Object.assign(failedAttrs, {+ message: i18n("user.email.required"),+ reason: forceValidationReason ? i18n("user.email.required") : null,+ })+ );+ }++ if (rejectedEmails.includes(email) || !emailValid(email)) {+ return EmberObject.create(+ Object.assign(failedAttrs, {+ reason: i18n("user.email.invalid"),+ })+ );+ }++ if (this.authOptions?.email === email && this.authOptions?.email_valid) {+ return EmberObject.create({+ ok: true,+ reason: i18n("user.email.authenticated", {+ provider: this.authProviderDisplayName(+ this.authOptions?.auth_provider+ ),+ }),+ });+ }++ return EmberObject.create({+ ok: true,+ reason: i18n("user.email.ok"),+ });+ }++ @action+ checkEmailAvailability() {+ this.set("emailValidationVisible", Boolean(this.emailValidation.reason));++ if (+ !this.emailValidation.ok ||+ this.serverAccountEmail === this.accountEmail+ ) {+ return;+ }++ return User.checkEmail(this.accountEmail)+ .then((result) => {+ if (this.isDestroying || this.isDestroyed) {+ return;+ }++ if (result.failed) {+ this.setProperties({+ serverAccountEmail: this.accountEmail,+ serverEmailValidation: EmberObject.create({+ failed: true,+ element: document.querySelector("#new-account-email"),+ reason: result.errors[0],+ }),+ });+ } else {+ this.setProperties({+ serverAccountEmail: this.accountEmail,+ serverEmailValidation: EmberObject.create({+ ok: true,+ reason: i18n("user.email.ok"),+ }),+ });+ }+ })+ .catch(() => {+ this.setProperties({+ serverAccountEmail: null,+ serverEmailValidation: null,+ });+ });+ }++ get emailDisabled() {+ return (+ this.authOptions?.email === this.accountEmail &&+ this.authOptions?.email_valid+ );+ }++ authProviderDisplayName(providerName) {+ const matchingProvider = findAll().find((provider) => {+ return provider.name === providerName;+ });+ return matchingProvider ? matchingProvider.get("prettyName") : providerName;+ }++ @observes("emailValidation", "accountEmail")+ prefillUsername() {+ if (this.prefilledUsername) {+ // If username field has been filled automatically, and email field just changed,+ // then remove the username.+ if (this.accountUsername === this.prefilledUsername) {+ this.accountUsername = "";+ }+ this.set("prefilledUsername", null);+ }+ if (+ this.get("emailValidation.ok") &&+ (isEmpty(this.accountUsername) || this.authOptions?.email)+ ) {+ // If email is valid and username has not been entered yet,+ // or email and username were filled automatically by 3rd party auth,+ // then look for a registered username that matches the email.+ discourseDebounce(+ this,+ this.usernameValidationHelper.fetchExistingUsername,+ 500+ );+ }+ }++ // Determines whether at least one login button is enabled+ @discourseComputed+ hasAtLeastOneLoginButton() {+ return findAll().length > 0;+ }++ fetchConfirmationValue() {+ if (this._challengeDate === undefined && this._hpPromise) {+ // Request already in progress+ return this._hpPromise;+ }++ this._hpPromise = ajax("/session/hp.json")+ .then((json) => {+ if (this.isDestroying || this.isDestroyed) {+ return;+ }++ this._challengeDate = new Date();+ // remove 30 seconds for jitter, make sure this works for at least+ // 30 seconds so we don't have hard loops+ this._challengeExpiry = parseInt(json.expires_in, 10) - 30;+ if (this._challengeExpiry < 30) {+ this._challengeExpiry = 30;+ }++ this.setProperties({+ accountHoneypot: json.value,+ accountChallenge: json.challenge.split("").reverse().join(""),+ });+ })+ .finally(() => (this._hpPromise = undefined));++ return this._hpPromise;+ }++ performAccountCreation() {+ if (+ !this._challengeDate ||+ new Date() - this._challengeDate > 1000 * this._challengeExpiry+ ) {+ return this.fetchConfirmationValue().then(() =>+ this.performAccountCreation()+ );+ }++ const attrs = {+ accountName: this.accountName,+ accountEmail: this.accountEmail,+ accountPassword: this.accountPassword,+ accountUsername: this.accountUsername,+ accountChallenge: this.accountChallenge,+ inviteCode: this.inviteCode,+ accountPasswordConfirm: this.accountHoneypot,+ };++ const destinationUrl = this.authOptions?.destination_url;++ if (!isEmpty(destinationUrl)) {+ cookie("destination_url", destinationUrl, { path: "/" });+ }++ // Add the userFields to the data+ if (!isEmpty(this.userFields)) {+ attrs.userFields = {};+ this.userFields.forEach(+ (f) => (attrs.userFields[f.get("field.id")] = f.get("value"))+ );+ }++ this.set("formSubmitted", true);+ return User.createAccount(attrs).then(+ (result) => {+ if (this.isDestroying || this.isDestroyed) {+ return;+ }++ this.isDeveloper = false;+ if (result.success) {+ // invalidate honeypot+ this._challengeExpiry = 1;++ // Trigger the browser's password manager using the hidden static login form:+ const hiddenLoginForm = document.querySelector("#hidden-login-form");+ if (hiddenLoginForm) {+ hiddenLoginForm.querySelector("input[name=username]").value =+ attrs.accountUsername;+ hiddenLoginForm.querySelector("input[name=password]").value =+ attrs.accountPassword;+ hiddenLoginForm.querySelector("input[name=redirect]").value =+ userPath("account-created");+ hiddenLoginForm.submit();+ }+ return new Promise(() => {}); // This will never resolve, the page will reload instead+ } else {+ this.set("flash", result.message || i18n("create_account.failed"));+ if (result.is_developer) {+ this.isDeveloper = true;+ }+ if (+ result.errors &&+ result.errors.email &&+ result.errors.email.length > 0 &&+ result.values+ ) {+ this.rejectedEmails.pushObject(result.values.email);+ }+ if (result.errors?.["user_password.password"]?.length > 0) {+ this.passwordValidationHelper.rejectedPasswords.push(+ attrs.accountPassword+ );+ }+ this.set("formSubmitted", false);+ removeCookie("destination_url");+ }+ },+ () => {+ this.set("formSubmitted", false);+ removeCookie("destination_url");+ return this.set("flash", i18n("create_account.failed"));+ }+ );+ }++ get associateHtml() {+ const url = this.authOptions?.associate_url;+ if (!url) {+ return;+ }+ return i18n("create_account.associate", {+ associate_link: url,+ provider: i18n(`login.${this.authOptions.auth_provider}.name`),+ });+ }++ @action+ scrollInputIntoView(event) {+ event.target.scrollIntoView({+ behavior: "smooth",+ block: "center",+ });+ }++ @action+ togglePasswordMask() {+ this.toggleProperty("maskPassword");+ }++ @action+ externalLogin(provider) {+ // we will automatically redirect to the external auth service+ this.login.externalLogin(provider, { signup: true });+ }++ @action+ createAccount() {+ this.set("flash", "");+ this.nameValidationHelper.forceValidationReason = true;+ this.set("emailValidationVisible", true);++ const validation = [+ this.emailValidation,+ this.usernameValidation,+ this.nameValidation,+ this.passwordValidation,+ this.userFieldsValidation,+ ].find((v) => v.failed);++ if (validation) {+ const element = validation.element;+ if (element) {+ if (element.tagName === "DIV") {+ if (element.scrollIntoView) {+ element.scrollIntoView();+ }+ element.click();+ } else {+ element.focus();+ }+ }++ return;+ }++ this.nameValidationHelper.forceValidationReason = false;+ this.performAccountCreation();+ }+ }+++{{! template-lint-disable no-duplicate-id }}+<DModal+ class="create-account -large"+ {{on "keydown" this.actionOnEnter}}+ {{on "click" this.selectKitFocus}}+ @closeModal={{@closeModal}}+ @bodyClass={{this.modalBodyClasses}}+ @flash={{this.flash}}+ @flashType="error"+ aria-labelledby="create-account-title"+>+ <:body>+ <PluginOutlet+ @name="create-account-before-modal-body"+ @connectorTagName="div"+ />++ <div+ class={{concat-class+ (if this.site.desktopView "login-left-side")+ this.authOptions?.auth_provider+ }}+ >+ <SignupProgressBar @step="signup" />+ <WelcomeHeader+ id="create-account-title"+ @header={{i18n "create_account.header_title"}}+ >+ <PluginOutlet+ @name="create-account-header-bottom"+ @outletArgs={{hash showLogin=(route-action "showLogin")}}+ />+ </WelcomeHeader>+ {{#if this.showCreateForm}}+ <form id="login-form">+ {{#if this.associateHtml}}+ <div class="input-group create-account-associate-link">+ <span>{{html-safe this.associateHtml}}</span>+ </div>+ {{/if}}+ <div class="input-group create-account-email">+ <Input+ {{on "focusout" this.checkEmailAvailability}}+ {{on "focusin" this.scrollInputIntoView}}+ @type="email"+ @value={{this.accountEmail}}+ disabled={{this.emailDisabled}}+ autofocus="autofocus"+ aria-describedby="account-email-validation account-email-validation-more-info"+ aria-invalid={{this.emailValidation.failed}}+ name="email"+ id="new-account-email"+ class={{value-entered this.accountEmail}}+ />+ <label class="alt-placeholder" for="new-account-email">+ {{i18n "user.email.title"}}+ </label>+ {{#if this.showEmailValidation}}+ <InputTip+ @validation={{this.emailValidation}}+ id="account-email-validation"+ />+ {{else}}+ <span class="more-info" id="account-email-validation-more-info">+ {{#if this.siteSettings.show_signup_form_email_instructions}}+ {{i18n "user.email.instructions"}}+ {{/if}}+ </span>+ {{/if}}+ </div>++ <div class="input-group create-account__username">+ <input+ {{on "focusin" this.scrollInputIntoView}}+ {{on "input" this.setAccountUsername}}+ type="text"+ value={{this.accountUsername}}+ disabled={{this.usernameDisabled}}+ maxlength={{this.maxUsernameLength}}+ aria-describedby="username-validation username-validation-more-info"+ aria-invalid={{this.usernameValidation.failed}}+ autocomplete="off"+ name="username"+ id="new-account-username"+ class={{value-entered this.accountUsername}}+ />+ <label class="alt-placeholder" for="new-account-username">+ {{i18n "user.username.title"}}+ </label>++ {{#if this.showUsernameInstructions}}+ <span class="more-info" id="username-validation-more-info">+ {{i18n "user.username.instructions"}}+ </span>++ {{else}}+ <InputTip+ @validation={{this.usernameValidation}}+ id="username-validation"+ />+ {{/if}}+ </div>++ {{#if (and this.showFullname this.fullnameRequired)}}+ <FullnameInput+ @nameValidation={{this.nameValidation}}+ @nameTitle={{this.nameTitle}}+ @accountName={{this.accountName}}+ @nameDisabled={{this.nameDisabled}}+ @onFocusIn={{this.scrollInputIntoView}}+ class="input-group create-account__fullname required"+ />+ {{/if}}++ <PluginOutlet+ @name="create-account-before-password"+ @outletArgs={{hash+ accountName=this.accountName+ accountUsername=this.accountUsername+ accountPassword=this.accountPassword+ userFields=this.userFields+ authOptions=this.authOptions+ }}+ />++ <div class="input-group create-account__password">+ {{#if this.passwordRequired}}+ <PasswordField+ {{on "focusin" this.scrollInputIntoView}}+ @value={{this.accountPassword}}+ @capsLockOn={{this.capsLockOn}}+ type={{if this.maskPassword "password" "text"}}+ autocomplete="current-password"+ aria-describedby="password-validation password-validation-more-info"+ aria-invalid={{this.passwordValidation.failed}}+ id="new-account-password"+ class={{value-entered this.accountPassword}}+ />+ <label class="alt-placeholder" for="new-account-password">+ {{i18n "user.password.title"}}+ </label>+ <TogglePasswordMask+ @maskPassword={{this.maskPassword}}+ @togglePasswordMask={{this.togglePasswordMask}}+ />+ <div class="create-account__password-info">+ <div class="create-account__password-tip-validation">+ {{#if this.showPasswordValidation}}+ <InputTip+ @validation={{this.passwordValidation}}+ id="password-validation"+ />+ {{else if+ this.siteSettings.show_signup_form_password_instructions+ }}+ <span class="more-info" id="password-validation-more-info">+ {{this.passwordValidationHelper.passwordInstructions}}+ </span>+ {{/if}}+ <div+ class={{concat-class+ "caps-lock-warning"+ (unless this.capsLockOn "hidden")+ }}+ >+ {{d-icon "triangle-exclamation"}}+ {{i18n "login.caps_lock_warning"}}+ </div>+ </div>+ </div>+ {{/if}}++ <div class="password-confirmation">+ <label for="new-account-password-confirmation">+ {{i18n "user.password_confirmation.title"}}+ </label>+ <HoneypotInput+ @id="new-account-confirmation"+ @autocomplete="new-password"+ @value={{this.accountHoneypot}}+ />+ <Input+ @value={{this.accountChallenge}}+ id="new-account-challenge"+ />+ </div>+ </div>++ {{#if this.requireInviteCode}}+ <div class="input-group create-account__invite-code">+ <Input+ {{on "focusin" this.scrollInputIntoView}}+ @value={{this.inviteCode}}+ id="inviteCode"+ class={{value-entered this.inviteCode}}+ />+ <label class="alt-placeholder" for="invite-code">+ {{i18n "user.invite_code.title"}}+ </label>+ <span class="more-info">+ {{i18n "user.invite_code.instructions"}}+ </span>+ </div>+ {{/if}}++ <PluginOutlet+ @name="create-account-after-password"+ @outletArgs={{hash+ accountName=this.accountName+ accountUsername=this.accountUsername+ accountPassword=this.accountPassword+ userFields=this.userFields+ }}+ />++ {{#if (and this.showFullname (not this.fullnameRequired))}}+ <FullnameInput+ @nameValidation={{this.nameValidation}}+ @nameTitle={{this.nameTitle}}+ @accountName={{this.accountName}}+ @nameDisabled={{this.nameDisabled}}+ @onFocusIn={{this.scrollInputIntoView}}+ class="input-group create-account__fullname"+ />+ {{/if}}++ {{#if this.userFields}}+ <div class="user-fields">+ {{#each this.userFields as |f|}}+ <div class="input-group">+ <UserField+ {{on "focusin" this.scrollInputIntoView}}+ @field={{f.field}}+ @value={{f.value}}+ @validation={{f.validation}}+ class={{value-entered f.value}}+ />+ </div>+ {{/each}}+ </div>+ {{/if}}++ <PluginOutlet+ @name="create-account-after-user-fields"+ @outletArgs={{hash+ accountName=this.accountName+ accountUsername=this.accountUsername+ accountPassword=this.accountPassword+ userFields=this.userFields+ }}+ />+ </form>++ {{#if this.site.desktopView}}+ <div class="d-modal__footer">+ <SignupPageCta+ @formSubmitted={{this.formSubmitted}}+ @hasAuthOptions={{this.hasAuthOptions}}+ @createAccount={{this.createAccount}}+ @submitDisabled={{this.submitDisabled}}+ @disclaimerHtml={{this.disclaimerHtml}}+ />+ </div>++ <PluginOutlet+ @name="create-account-after-modal-footer"+ @connectorTagName="div"+ />+ {{/if}}+ {{/if}}++ {{#if this.skipConfirmation}}+ {{loading-spinner size="large"}}+ {{/if}}+ </div>++ {{#if this.hasAtLeastOneLoginButton}}+ {{#if this.site.mobileView}}+ <div class="login-or-separator"><span>+ {{i18n "login.or"}}</span></div>{{/if}}+ <div class="login-right-side">+ <LoginButtons+ @externalLogin={{this.externalLogin}}+ @context="create-account"+ />+ </div>+ {{/if}}+ </:body>++ <:footer>+ {{#if (and this.showCreateForm this.site.mobileView)}}+ <SignupPageCta+ @formSubmitted={{this.formSubmitted}}+ @hasAuthOptions={{this.hasAuthOptions}}+ @createAccount={{this.createAccount}}+ @submitDisabled={{this.submitDisabled}}+ @disclaimerHtml={{this.disclaimerHtml}}+ />+ {{/if}}+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/delete-themes-confirm.gjsindex 48f30115714,3a772138f04..52be24d38b8--- a/app/assets/javascripts/discourse/app/components/modal/delete-themes-confirm.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/delete-themes-confirm.gjs@@@ -1,18 -1,21 +1,40 @@@+ import Component from "@glimmer/component";+ import { action } from "@ember/object";+ import { ajax } from "discourse/lib/ajax";+ import { popupAjaxError } from "discourse/lib/ajax-error";++ export default class DeleteThemesConfirmComponent extends Component {+ @action+ delete() {+ ajax(`/admin/themes/bulk_destroy.json`, {+ type: "DELETE",+ data: {+ theme_ids: this.args.model.selectedThemesOrComponents.mapBy("id"),+ },+ })+ .then(() => {+ this.args.model.refreshAfterDelete();+ this.args.closeModal();+ })+ .catch(popupAjaxError);+ }+ }+++<DModal+ @closeModal={{@closeModal}}+ @title={{i18n "admin.customize.bulk_delete"}}+>+ <:body>+ {{i18n (concat "admin.customize.bulk_" @model.type "_delete_confirm")}}+ <ul>+ {{#each @model.selectedThemesOrComponents as |theme|}}+ <li>{{theme.name}}</li>+ {{/each}}+ </ul>++ </:body>+ <:footer>+ <DButton class="btn-primary" @action={{this.delete}} @label="yes_value" />+ <DModalCancel @close={{@closeModal}} />+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/delete-topic-confirm.gjsindex a399846da77,cd6354baa76..50a7ad2c463--- a/app/assets/javascripts/discourse/app/components/modal/delete-topic-confirm.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/delete-topic-confirm.gjs@@@ -1,32 -1,27 +1,60 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import { i18n } from "discourse-i18n";++ // Modal that displays confirmation text when user deletes a topic+ // The modal will display only if the topic exceeds a certain amount of views+ export default class DeleteTopicConfirm extends Component {+ @service currentUser;+ @service siteSettings;++ @tracked deletingTopic = false;+ @tracked flash;++ @action+ async deleteTopic() {+ try {+ this.deletingTopic = true;+ await this.args.model.topic.destroy(this.currentUser);+ this.args.closeModal();+ } catch {+ this.flash = i18n("post.controls.delete_topic_error");+ this.deletingTopic = false;+ }+ }+ }+++<DModal+ @title={{i18n "topic.actions.delete"}}+ @closeModal={{@closeModal}}+ class="delete-topic-confirm-modal"+ @flash={{this.flash}}+>+ <:body>+ <p>+ {{i18n+ "post.controls.delete_topic_confirm_modal"+ count=this.siteSettings.min_topic_views_for_delete_confirm+ }}+ </p>+ </:body>+ <:footer>+ <DButton+ @action={{this.deleteTopic}}+ @disabled={{this.deletingTopic}}+ @label={{if+ this.deletingTopic+ "deleting"+ "post.controls.delete_topic_confirm_modal_yes"+ }}+ class="btn-danger"+ />+ <DButton+ @action={{@closeModal}}+ @label="post.controls.delete_topic_confirm_modal_no"+ class="btn-primary"+ />+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/dismiss-notification-confirmation.gjsindex 92df144fc5a,1af22ceef50..dbd113244ce--- a/app/assets/javascripts/discourse/app/components/modal/dismiss-notification-confirmation.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/dismiss-notification-confirmation.gjs@@@ -1,22 -1,10 +1,33 @@@+ import Component from "@glimmer/component";+ import { action } from "@ember/object";++ export default class DismissNotificationConfirmation extends Component {+ @action+ dismiss() {+ this.args.model?.dismissNotifications?.();+ this.args.closeModal();+ }+ }+++<DModal+ @headerClass="hidden"+ class="dismiss-notification-confirmation"+ @closeModal={{@closeModal}}+>+ <:body>+ {{@model.confirmationMessage}}+ </:body>+ <:footer>+ <DButton+ @icon="check"+ class="btn-primary"+ @action={{this.dismiss}}+ @label="notifications.dismiss_confirmation.dismiss"+ />+ <DButton+ @action={{@closeModal}}+ @label="notifications.dismiss_confirmation.cancel"+ class="btn-default"+ />+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/download-calendar.gjsindex 2ec84769b81,0b7fc223ec8..28b04c1a515--- a/app/assets/javascripts/discourse/app/components/modal/download-calendar.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/download-calendar.gjs@@@ -1,56 -1,50 +1,107 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import { downloadGoogle, downloadIcs } from "discourse/lib/download-calendar";++ export default class DownloadCalendar extends Component {+ @service currentUser;++ @tracked selectedCalendar = "ics";+ @tracked remember = false;++ @action+ downloadCalendar() {+ if (this.remember) {+ this.currentUser.set(+ "user_option.default_calendar",+ this.selectedCalendar+ );+ this.currentUser.save(["default_calendar"]);+ }+ if (this.selectedCalendar === "ics") {+ downloadIcs(+ this.args.model.calendar.title,+ this.args.model.calendar.dates,+ {+ recurrenceRule: this.args.model.calendar.recurrenceRule,+ location: this.args.model.calendar.location,+ details: this.args.model.calendar.details,+ }+ );+ } else {+ downloadGoogle(+ this.args.model.calendar.title,+ this.args.model.calendar.dates,+ {+ recurrenceRule: this.args.model.calendar.recurrenceRule,+ location: this.args.model.calendar.location,+ details: this.args.model.calendar.details,+ }+ );+ }+ this.args.closeModal();+ }++ @action+ selectCalendar(calendar) {+ this.selectedCalendar = calendar;+ }+ }+++<DModal+ @title={{i18n "download_calendar.title"}}+ class="download-calendar-modal"+ @closeModal={{@closeModal}}+>+ <:body>+ <div class="control-group">+ <div class="ics">+ <label class="radio" for="ics">+ <RadioButton+ id="ics"+ @name="select-calendar"+ @value="ics"+ @selection={{this.selectedCalendar}}+ @onChange={{fn this.selectCalendar "ics"}}+ />+ {{i18n "download_calendar.save_ics"}}+ </label>+ </div>+ <div class="google">+ <label class="radio" for="google">+ <RadioButton+ id="google"+ @name="select-calendar"+ @value="google"+ @selection={{this.selectedCalendar}}+ @onChange={{fn this.selectCalendar "google"}}+ />+ {{i18n "download_calendar.save_google"}}+ </label>+ </div>+ </div>++ {{#if this.currentUser}}+ <div class="control-group remember">+ <label class="checkbox-label">+ <Input @type="checkbox" @checked={{this.remember}} />+ <span>{{i18n "download_calendar.remember"}}</span>+ </label>+ <span>{{i18n "download_calendar.remember_explanation"}}</span>+ </div>+ {{/if}}+ </:body>+ <:footer>+ <DButton+ class="btn-primary"+ @action={{this.downloadCalendar}}+ @label="download_calendar.download"+ />+ <DButton+ class="btn-flat d-modal-cancel"+ @action={{@closeModal}}+ @label="cancel"+ />+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/edit-topic-timer.gjsindex 83bde72319d,fcc8275a996..bfb0d810f8c--- a/app/assets/javascripts/discourse/app/components/modal/edit-topic-timer.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/edit-topic-timer.gjs@@@ -1,36 -1,229 +1,266 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { next } from "@ember/runloop";+ import { service } from "@ember/service";+ import { TrackedObject } from "@ember-compat/tracked-built-ins";+ import { popupAjaxError } from "discourse/lib/ajax-error";+ import TopicTimer from "discourse/models/topic-timer";+ import { i18n } from "discourse-i18n";+ import { FORMAT } from "select-kit/components/future-date-input-selector";++ export const CLOSE_STATUS_TYPE = "close";+ export const CLOSE_AFTER_LAST_POST_STATUS_TYPE = "close_after_last_post";+ export const OPEN_STATUS_TYPE = "open";+ export const PUBLISH_TO_CATEGORY_STATUS_TYPE = "publish_to_category";+ export const DELETE_STATUS_TYPE = "delete";+ export const BUMP_TYPE = "bump";+ export const DELETE_REPLIES_TYPE = "delete_replies";++ export default class EditTopicTimer extends Component {+ @service currentUser;++ @tracked topicTimer;+ @tracked loading = false;+ @tracked flash;++ constructor() {+ super(...arguments);++ if (this.args.model.topic?.topic_timer) {+ this.topicTimer = new TrackedObject(this.args.model.topic?.topic_timer);+ } else {+ // TODO: next() is a hack, to-be-removed+ next(() => {+ this.topicTimer = new TrackedObject(this.createDefaultTimer());+ });+ }+ }++ get defaultStatusType() {+ return this.publicTimerTypes[0].id;+ }++ get publicTimerTypes() {+ const types = [];+ const { closed, category, isPrivateMessage, invisible } =+ this.args.model.topic;++ if (!closed) {+ types.push({+ id: CLOSE_STATUS_TYPE,+ name: i18n("topic.auto_close.title"),+ });+ types.push({+ id: CLOSE_AFTER_LAST_POST_STATUS_TYPE,+ name: i18n("topic.auto_close_after_last_post.title"),+ });+ }++ if (closed) {+ types.push({+ id: OPEN_STATUS_TYPE,+ name: i18n("topic.auto_reopen.title"),+ });+ }++ if (this.args.model.topic.details.can_delete) {+ types.push({+ id: DELETE_STATUS_TYPE,+ name: i18n("topic.auto_delete.title"),+ });+ }++ types.push({+ id: BUMP_TYPE,+ name: i18n("topic.auto_bump.title"),+ });++ if (this.args.model.topic.details.can_delete) {+ types.push({+ id: DELETE_REPLIES_TYPE,+ name: i18n("topic.auto_delete_replies.title"),+ });+ }++ if (closed) {+ types.push({+ id: CLOSE_STATUS_TYPE,+ name: i18n("topic.temp_open.title"),+ });+ }++ if (!closed) {+ types.push({+ id: OPEN_STATUS_TYPE,+ name: i18n("topic.temp_close.title"),+ });+ }++ if (+ (category && category.read_restricted) ||+ isPrivateMessage ||+ invisible+ ) {+ types.push({+ id: PUBLISH_TO_CATEGORY_STATUS_TYPE,+ name: i18n("topic.publish_to_category.title"),+ });+ }++ return types;+ }++ _setTimer(time, durationMinutes, statusType, basedOnLastPost, categoryId) {+ this.loading = true;++ TopicTimer.update(+ this.args.model.topic.id,+ time,+ basedOnLastPost,+ statusType,+ categoryId,+ durationMinutes+ )+ .then((result) => {+ if (time || durationMinutes) {+ this.args.model.updateTopicTimerProperty(+ "execute_at",+ result.execute_at+ );+ this.args.model.updateTopicTimerProperty(+ "duration_minutes",+ result.duration_minutes+ );+ this.args.model.updateTopicTimerProperty(+ "category_id",+ result.category_id+ );+ this.args.model.updateTopicTimerProperty("closed", result.closed);+ this.args.closeModal();+ } else {+ const topicTimer = this.createDefaultTimer();+ this.topicTime = topicTimer;+ this.args.model.setTopicTimer(topicTimer);+ this.onChangeInput(null, null);+ }+ })+ .catch(popupAjaxError)+ .finally(() => (this.loading = false));+ }++ @action+ createDefaultTimer() {+ const defaultTimer = TopicTimer.create({+ status_type: this.defaultStatusType,+ });+ this.args.model.setTopicTimer(defaultTimer);+ return defaultTimer;+ }++ @action+ onChangeStatusType(value) {+ const basedOnLastPost = CLOSE_AFTER_LAST_POST_STATUS_TYPE === value;+ this.topicTimer.based_on_last_post = basedOnLastPost;+ this.args.model.updateTopicTimerProperty(+ "based_on_last_post",+ basedOnLastPost+ );+ this.topicTimer.status_type = value;+ this.args.model.updateTopicTimerProperty("status_type", value);+ }++ @action+ onChangeInput(_type, time) {+ if (moment.isMoment(time)) {+ time = time.format(FORMAT);+ }+ this.topicTimer.updateTime = time;+ this.args.model.updateTopicTimerProperty("updateTime", time);+ }++ @action+ async saveTimer() {+ this.flash = null;++ if (!this.topicTimer.updateTime && !this.topicTimer.duration_minutes) {+ this.flash = i18n("topic.topic_status_update.time_frame_required");+ return;+ }++ if (this.topicTimer.duration_minutes && !this.topicTimer.updateTime) {+ if (this.topicTimer.duration_minutes <= 0) {+ this.flash = i18n("topic.topic_status_update.min_duration");+ return;+ }++ // cannot be more than 20 years+ if (this.topicTimer.duration_minutes > 20 * 365 * 1440) {+ this.flash = i18n("topic.topic_status_update.max_duration");+ return;+ }+ }++ let statusType = this.topicTimer.status_type;+ if (statusType === CLOSE_AFTER_LAST_POST_STATUS_TYPE) {+ statusType = CLOSE_STATUS_TYPE;+ }++ await this._setTimer(+ this.topicTimer.updateTime,+ this.topicTimer.duration_minutes,+ statusType,+ this.topicTimer.based_on_last_post,+ this.topicTimer.category_id+ );+ }++ @action+ async removeTimer() {+ let statusType = this.topicTimer.status_type;+ if (statusType === CLOSE_AFTER_LAST_POST_STATUS_TYPE) {+ statusType = CLOSE_STATUS_TYPE;+ }+ await this._setTimer(null, null, statusType);+ // timer has been removed and we are removing `execute_at`+ // which will hide the remove timer button from the modal+ this.topicTimer.execute_at = null;+ }+ }+++<DModal+ @title={{i18n "topic.topic_status_update.title"}}+ @flash={{this.flash}}+ @closeModal={{@closeModal}}+ autoFocus="false"+ id="topic-timer-modal"+ class="edit-topic-timer-modal"+>+ <:body>+ {{#if this.topicTimer}}+ <EditTopicTimerForm+ @topic={{@model.topic}}+ @topicTimer={{this.topicTimer}}+ @timerTypes={{this.publicTimerTypes}}+ @onChangeStatusType={{this.onChangeStatusType}}+ @onChangeInput={{this.onChangeInput}}+ />+ {{/if}}+ </:body>+ <:footer>+ <DButton+ class="btn-primary"+ @disabled={{this.saveDisabled}}+ @label="topic.topic_status_update.save"+ @action={{this.saveTimer}}+ @isLoading={{this.loading}}+ />+ {{#if this.topicTimer.execute_at}}+ <DButton+ class="btn-danger"+ @action={{this.removeTimer}}+ @label="topic.topic_status_update.remove"+ />+ {{/if}}+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/edit-user-directory-columns.gjsindex 3f0d3cac934,05b2ca7f16a..2040c2cb898--- a/app/assets/javascripts/discourse/app/components/modal/edit-user-directory-columns.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/edit-user-directory-columns.gjs@@@ -1,65 -1,106 +1,172 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { reload } from "discourse/helpers/page-reloader";+ import { ajax } from "discourse/lib/ajax";+ import { extractError, popupAjaxError } from "discourse/lib/ajax-error";++ const UP = "up";+ const DOWN = "down";++ export default class EditUserDirectoryColumns extends Component {+ @tracked loading = true;+ @tracked columns;+ @tracked labelKey;+ @tracked flash;++ constructor() {+ super(...arguments);+ this.setupColumns();+ }++ @action+ async setupColumns() {+ try {+ const response = await ajax("edit-directory-columns.json");+ this.loading = false;+ this.columns = response.directory_columns+ .sort((a, b) => (a.position > b.position ? 1 : -1))+ .map((c) => ({ ...c, enabled: Boolean(c.enabled) }));+ } catch (e) {+ popupAjaxError(e);+ }+ }++ @action+ async save() {+ this.loading = true;+ this.flash = null;+ const data = {+ directory_columns: this.columns.map((c) => ({+ id: c.id,+ enabled: c.enabled,+ position: c.position,+ })),+ };++ try {+ await ajax("edit-directory-columns.json", { type: "PUT", data });+ reload();+ } catch (e) {+ this.loading = false;+ this.flash = extractError(e);+ }+ }++ @action+ resetToDefault() {+ const resetColumns = this.columns+ .sort((a, b) => {+ const a1 = a.automatic_position || (a.user_field?.position || 0) + 1000;+ const b1 = b.automatic_position || (b.user_field?.position || 0) + 1000;++ if (a1 === b1) {+ return a.name.localeCompare(b.name);+ } else {+ return a1 > b1 ? 1 : -1;+ }+ })+ .map((column, index) => ({+ ...column,+ position: column.automatic_position || index + 1,+ enabled: column.type === "automatic",+ }));++ this.columns = resetColumns;+ }++ @action+ moveUp(column) {+ this._moveColumn(UP, column);+ }++ @action+ moveDown(column) {+ this._moveColumn(DOWN, column);+ }++ _moveColumn(direction, column) {+ if (+ (direction === UP && column.position === 1) ||+ (direction === DOWN && column.position === this.columns.length)+ ) {+ return;+ }++ const positionOnClick = column.position;+ const newPosition =+ direction === UP ? positionOnClick - 1 : positionOnClick + 1;+ const previousColumn = this.columns.find((c) => c.position === newPosition);+ column.position = newPosition;+ previousColumn.position = positionOnClick;+ this.columns = this.columns.sort((a, b) =>+ a.position > b.position ? 1 : -1+ );+ }+ }+++<DModal+ @closeModal={{@closeModal}}+ @title={{i18n "directory.edit_columns.title"}}+ class="edit-user-directory-columns-modal"+ @flash={{this.flash}}+>+ <:body>+ {{#if this.loading}}+ {{loading-spinner size="large"}}+ {{else}}+ <div class="edit-directory-columns-container">+ {{#each this.columns as |column|}}+ <div class="edit-directory-column">+ <div class="left-content">+ <label class="column-name">+ <Input @type="checkbox" @checked={{column.enabled}} />+ {{#if (directory-column-is-automatic column=column)}}+ {{directory-table-header-title+ field=column.name+ labelKey=this.labelKey+ icon=column.icon+ }}+ {{else if (directory-column-is-user-field column=column)}}+ {{directory-table-header-title+ field=column.user_field.name+ translated=true+ }}+ {{else}}+ {{directory-table-header-title+ field=(i18n column.name)+ translated=true+ }}+ {{/if}}+ </label>+ </div>+ <div class="right-content">+ <DButton+ @icon="arrow-up"+ @action={{fn this.moveUp column}}+ class="button-secondary move-column-up"+ />+ <DButton+ @icon="arrow-down"+ @action={{fn this.moveDown column}}+ class="button-secondary"+ />+ </div>+ </div>+ {{/each}}+ </div>+ {{/if}}+ </:body>+ <:footer>+ <DButton+ @label="directory.edit_columns.save"+ @action={{this.save}}+ class="btn-primary"+ />+ <DButton+ @label="directory.edit_columns.reset_to_default"+ @action={{this.resetToDefault}}+ class="btn-secondary reset-to-default"+ />+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/explain-reviewable.gjsindex d4d751e5d3c,4bdef5f35a9..25965f6e28e--- a/app/assets/javascripts/discourse/app/components/modal/explain-reviewable.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/explain-reviewable.gjs@@@ -1,65 -1,29 +1,95 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { service } from "@ember/service";++ export default class ExplainReviewable extends Component {+ @service store;++ @tracked loading = true;+ @tracked reviewableExplanation = null;++ constructor() {+ super(...arguments);+ this.loadExplanation();+ }++ @action+ async loadExplanation() {+ try {+ const result = await this.store.find(+ "reviewable-explanation",+ this.args.model.reviewable.id+ );+ this.reviewableExplanation = result;+ } finally {+ this.loading = false;+ }+ }+ }+++<DModal+ class="explain-reviewable"+ @closeModal={{@closeModal}}+ @title={{i18n "review.explain.title"}}+>+ <:body>+ <ConditionalLoadingSpinner @condition={{this.loading}}>+ <table>+ <tbody>+ <tr>+ <th>{{i18n "review.explain.formula"}}</th>+ <th>{{i18n "review.explain.subtotal"}}</th>+ </tr>+ {{#each this.reviewableExplanation.scores as |s|}}+ <tr>+ <td>+ <ScoreValue @value="1.0" />+ <ScoreValue @value={{s.type_bonus}} @label="type_bonus" />+ <ScoreValue+ @value={{s.take_action_bonus}}+ @label="take_action_bonus"+ />+ <ScoreValue+ @value={{s.trust_level_bonus}}+ @label="trust_level_bonus"+ />+ <ScoreValue+ @value={{s.user_accuracy_bonus}}+ @label="user_accuracy_bonus"+ />+ </td>+ <td class="sum">{{float s.score}}</td>+ </tr>+ {{/each}}+ <tr class="total">+ <td>{{i18n "review.explain.total"}}</td>+ <td class="sum">+ {{float this.reviewableExplanation.total_score}}+ </td>+ </tr>+ </tbody>+ </table>++ <table class="thresholds">+ <tbody>+ <tr>+ <td>{{i18n "review.explain.min_score_visibility"}}</td>+ <td class="sum">+ {{float this.reviewableExplanation.min_score_visibility}}+ </td>+ </tr>+ <tr>+ <td>{{i18n "review.explain.score_to_hide"}}</td>+ <td class="sum">+ {{float this.reviewableExplanation.hide_post_score}}+ </td>+ </tr>+ </tbody>+ </table>+ </ConditionalLoadingSpinner>+ </:body>+ <:footer>+ <DButton @action={{@closeModal}} @label="close" />+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/feature-topic-on-profile.gjsindex b80ecb29035,8b289119d75..5081ddea128--- a/app/assets/javascripts/discourse/app/components/modal/feature-topic-on-profile.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/feature-topic-on-profile.gjs@@@ -1,25 -1,37 +1,63 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { ajax } from "discourse/lib/ajax";+ import { popupAjaxError } from "discourse/lib/ajax-error";++ export default class FeatureTopicOnProfile extends Component {+ @tracked newFeaturedTopic = null;+ @tracked saving = false;++ get noTopicSelected() {+ return !this.newFeaturedTopic;+ }++ @action+ async save() {+ try {+ this.saving = true;+ await ajax(`/u/${this.args.model.user.username}/feature-topic`, {+ type: "PUT",+ data: { topic_id: this.newFeaturedTopic.id },+ });++ this.args.model.setFeaturedTopic(this.newFeaturedTopic);+ this.args.closeModal();+ } catch (error) {+ popupAjaxError(error);+ } finally {+ this.saving = false;+ }+ }++ @action+ newTopicSelected(topic) {+ this.newFeaturedTopic = topic;+ }+ }+++<DModal+ @closeModal={{@closeModal}}+ class="feature-topic-on-profile choose-topic-modal"+ id="choosing-topic"+ @title={{i18n "user.feature_topic_on_profile.title"}}+>+ <:body>+ <ChooseTopic+ @topicChangedCallback={{this.newTopicSelected}}+ @currentTopicId={{@model.user.featured_topic.id}}+ @loadOnInit={{true}}+ @additionalFilters="status:public"+ @label="user.feature_topic_on_profile.search_label"+ />+ </:body>+ <:footer>+ <DButton+ @action={{this.save}}+ class="btn-primary save-featured-topic-on-profile"+ @disabled={{this.noTopicSelected}}+ @label="user.feature_topic_on_profile.save"+ />+ <DButton @action={{@closeModal}} @label="cancel" class="btn-flat" />+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/feature-topic.gjsindex 3d97a250c46,2a45c36987a..b68e279779d--- a/app/assets/javascripts/discourse/app/components/modal/feature-topic.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/feature-topic.gjs@@@ -1,232 -1,180 +1,413 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import EmberObject, { action } from "@ember/object";+ import { service } from "@ember/service";+ import { categoryLinkHTML } from "discourse/helpers/category-link";+ import { ajax } from "discourse/lib/ajax";+ import { i18n } from "discourse-i18n";++ export default class FeatureTopic extends Component {+ @service currentUser;+ @service dialog;++ @tracked loading = true;+ @tracked pinnedInCategoryCount = 0;+ @tracked pinnedGloballyCount = 0;+ @tracked bannerCount = 0;+ @tracked pinInCategoryTipShownAt = false;+ @tracked pinGloballyTipShownAt = false;++ constructor() {+ super(...arguments);+ this.loadFeatureStats();+ }++ get categoryLink() {+ return categoryLinkHTML(this.args.model.topic.category, {+ allowUncategorized: true,+ });+ }++ get unPinMessage() {+ let name = "topic.feature_topic.unpin";+ if (this.args.model.topic.pinned_globally) {+ name += "_globally";+ }+ if (moment(this.args.model.topic.pinned_until) > moment()) {+ name += "_until";+ }+ const until = moment(this.args.model.topic.pinned_until).format("LL");+ return i18n(name, { categoryLink: this.categoryLink, until });+ }++ get canPinGlobally() {+ return (+ this.currentUser.canManageTopic &&+ this.args.model.topic.details.can_pin_unpin_topic+ );+ }++ get pinMessage() {+ return i18n("topic.feature_topic.pin", {+ categoryLink: this.categoryLink,+ });+ }++ get alreadyPinnedMessage() {+ const key =+ this.pinnedInCategoryCount === 0+ ? "topic.feature_topic.not_pinned"+ : "topic.feature_topic.already_pinned";+ return i18n(key, {+ categoryLink: this.categoryLink,+ count: this.pinnedInCategoryCount,+ });+ }++ get pinDisabled() {+ return !this._isDateValid(this.parsedPinnedInCategoryUntil);+ }++ get pinGloballyDisabled() {+ return !this._isDateValid(this.parsedPinnedGloballyUntil);+ }++ get parsedPinnedInCategoryUntil() {+ return this._parseDate(this.args.model.topic.pinnedInCategoryUntil);+ }++ get parsedPinnedGloballyUntil() {+ return this._parseDate(this.args.model.topic.pinnedGloballyUntil);+ }++ get pinInCategoryValidation() {+ if (this.pinDisabled) {+ return EmberObject.create({+ failed: true,+ reason: i18n("topic.feature_topic.pin_validation"),+ });+ }+ }++ get pinGloballyValidation() {+ if (this.pinGloballyDisabled) {+ return EmberObject.create({+ failed: true,+ reason: i18n("topic.feature_topic.pin_validation"),+ });+ }+ }++ _parseDate(date) {+ return moment(date, ["YYYY-MM-DD", "YYYY-MM-DD HH:mm"]);+ }++ _isDateValid(parsedDate) {+ return parsedDate.isValid() && parsedDate > moment();+ }++ @action+ async loadFeatureStats() {+ try {+ this.loading = true;+ const result = await ajax("/topics/feature_stats.json", {+ data: { category_id: this.args.model.topic.category.id },+ });++ if (result) {+ this.pinnedInCategoryCount = result.pinned_in_category_count;+ this.pinnedGloballyCount = result.pinned_globally_count;+ this.bannerCount = result.banner_count;+ }+ } finally {+ this.loading = false;+ }+ }++ async _confirmBeforePinningGlobally() {+ if (this.pinnedGloballyCount < 4) {+ this.args.model.pinGlobally();+ this.args.closeModal();+ } else {+ this.dialog.yesNoConfirm({+ message: i18n("topic.feature_topic.confirm_pin_globally", {+ count: this.pinnedGloballyCount,+ }),+ didConfirm: () => {+ this.args.model.pinGlobally();+ this.args.closeModal();+ },+ });+ }+ }++ @action+ pin() {+ if (this.pinDisabled) {+ this.pinInCategoryTipShownAt = Date.now();+ } else {+ this.args.model.togglePinned();+ this.args.closeModal();+ }+ }++ @action+ pinGlobally() {+ if (this.pinGloballyDisabled) {+ this.pinGloballyTipShownAt = Date.now();+ } else {+ this._confirmBeforePinningGlobally();+ }+ }++ @action+ unpin() {+ this.args.model.togglePinned();+ this.args.closeModal();+ }++ @action+ makeBanner() {+ this.args.model.makeBanner();+ this.args.closeModal();+ }++ @action+ removeBanner() {+ this.args.model.removeBanner();+ this.args.closeModal();+ }+ }+++<DModal+ class="feature-topic"+ @title={{i18n "topic.feature_topic.title"}}+ @closeModal={{@closeModal}}+>+ <:body>+ {{#if @model.topic.pinned_at}}+ <div class="feature-section">+ <div class="desc">+ {{#if @model.topic.pinned_globally}}+ <p>+ <ConditionalLoadingSpinner+ @size="small"+ @condition={{this.loading}}+ >+ {{#if this.pinnedGloballyCount}}+ {{html-safe+ (i18n+ "topic.feature_topic.already_pinned_globally"+ count=this.pinnedGloballyCount+ )+ }}+ {{else}}+ {{html-safe (i18n "topic.feature_topic.not_pinned_globally")}}+ {{/if}}+ </ConditionalLoadingSpinner>+ </p>+ <p>{{i18n "topic.feature_topic.global_pin_note"}}</p>+ {{else}}+ <p>+ <ConditionalLoadingSpinner+ @size="small"+ @condition={{this.loading}}+ >+ {{html-safe this.alreadyPinnedMessage}}+ </ConditionalLoadingSpinner>+ </p>+ <p>{{i18n "topic.feature_topic.pin_note"}}</p>+ {{/if}}+ <p>{{html-safe this.unPinMessage}}</p>+ <p><DButton+ @action={{this.unpin}}+ @icon="thumbtack"+ @label="topic.feature.unpin"+ class="btn-primary"+ /></p>+ </div>+ </div>+ {{else}}+ <div class="feature-section">+ <div class="desc">+ <p>+ <ConditionalLoadingSpinner+ @size="small"+ @condition={{this.loading}}+ >+ {{html-safe this.alreadyPinnedMessage}}+ </ConditionalLoadingSpinner>+ </p>+ <p>+ {{i18n "topic.feature_topic.pin_note"}}+ </p>+ {{#if this.site.isMobileDevice}}+ <p>+ {{html-safe this.pinMessage}}+ </p>+ <p class="with-validation">+ <FutureDateInput+ class="pin-until"+ @clearable={{true}}+ @input={{@model.topic.pinnedInCategoryUntil}}+ @onChangeInput={{action+ (mut @model.topic.pinnedInCategoryUntil)+ }}+ />+ <PopupInputTip+ @validation={{this.pinInCategoryValidation}}+ @shownAt={{this.pinInCategoryTipShownAt}}+ />+ </p>+ {{else}}+ <p class="with-validation">+ {{html-safe this.pinMessage}}+ <span>+ {{d-icon "far-clock"}}+ <FutureDateInput+ class="pin-until"+ @clearable={{true}}+ @input={{@model.topic.pinnedInCategoryUntil}}+ @onChangeInput={{action+ (mut @model.topic.pinnedInCategoryUntil)+ }}+ />+ <PopupInputTip+ @validation={{this.pinInCategoryValidation}}+ @shownAt={{this.pinInCategoryTipShownAt}}+ />+ </span>+ </p>+ {{/if}}+ <p>+ <DButton+ @action={{this.pin}}+ @icon="thumbtack"+ @label="topic.feature.pin"+ class="btn-primary"+ />+ </p>+ </div>+ </div>+ {{#if this.canPinGlobally}}+ <hr />+ <div class="feature-section">+ <div class="desc">+ <p>+ <ConditionalLoadingSpinner+ @size="small"+ @condition={{this.loading}}+ >+ {{#if this.pinnedGloballyCount}}+ {{html-safe+ (i18n+ "topic.feature_topic.already_pinned_globally"+ count=this.pinnedGloballyCount+ )+ }}+ {{else}}+ {{html-safe (i18n "topic.feature_topic.not_pinned_globally")}}+ {{/if}}+ </ConditionalLoadingSpinner>+ </p>+ <p>+ {{i18n "topic.feature_topic.global_pin_note"}}+ </p>+ {{#if this.site.isMobileDevice}}+ <p>+ {{i18n "topic.feature_topic.pin_globally"}}+ </p>+ <p class="with-validation">+ <FutureDateInput+ class="pin-until"+ @clearable={{true}}+ @input={{@model.topic.pinnedGloballyUntil}}+ @onChangeInput={{action+ (mut @model.topic.pinnedGloballyUntil)+ }}+ />+ <PopupInputTip+ @validation={{this.pinGloballyValidation}}+ @shownAt={{this.pinGloballyTipShownAt}}+ />+ </p>+ {{else}}+ <p class="with-validation">+ {{i18n "topic.feature_topic.pin_globally"}}+ <span>+ {{d-icon "far-clock"}}+ <FutureDateInput+ class="pin-until"+ @clearable={{true}}+ @input={{@model.topic.pinnedGloballyUntil}}+ @onChangeInput={{action+ (mut @model.topic.pinnedGloballyUntil)+ }}+ />+ <PopupInputTip+ @validation={{this.pinGloballyValidation}}+ @shownAt={{this.pinGloballyTipShownAt}}+ />+ </span>+ </p>+ {{/if}}+ <p>+ <DButton+ @action={{this.pinGlobally}}+ @icon="thumbtack"+ @label="topic.feature.pin_globally"+ class="btn-primary"+ />+ </p>+ </div>+ </div>+ {{/if}}+ {{/if}}+ <hr />+ {{#if this.currentUser.staff}}+ <div class="feature-section">+ <div class="desc">+ <p>+ <ConditionalLoadingSpinner+ @size="small"+ @condition={{this.loading}}+ >+ {{#if this.bannerCount}}+ {{html-safe (i18n "topic.feature_topic.banner_exists")}}+ {{else}}+ {{html-safe (i18n "topic.feature_topic.no_banner_exists")}}+ {{/if}}+ </ConditionalLoadingSpinner>+ </p>+ <p>+ {{i18n "topic.feature_topic.banner_note"}}+ </p>+ <p>+ {{#if @model.topic.isBanner}}+ {{i18n "topic.feature_topic.remove_banner"}}+ {{else}}+ {{i18n "topic.feature_topic.make_banner"}}+ {{/if}}+ </p>+ <p>+ {{#if @model.topic.isBanner}}+ <DButton+ @action={{this.removeBanner}}+ @icon="thumbtack"+ @label="topic.feature.remove_banner"+ class="btn-primary"+ />+ {{else}}+ <DButton+ @action={{this.makeBanner}}+ @icon="thumbtack"+ @label="topic.feature.make_banner"+ class="btn-primary make-banner"+ />+ {{/if}}+ </p>+ </div>+ </div>+ {{/if}}+ </:body>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/flag.gjsindex 6710c558197,140de6a5824..eacabb8c5c4--- a/app/assets/javascripts/discourse/app/components/modal/flag.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/flag.gjs@@@ -1,87 -1,214 +1,302 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import { reload } from "discourse/helpers/page-reloader";+ import { MAX_MESSAGE_LENGTH } from "discourse/models/post-action-type";+ import User from "discourse/models/user";+ import { i18n } from "discourse-i18n";++ const NOTIFY_MODERATORS_KEY = "notify_moderators";++ export default class Flag extends Component {+ @service adminTools;+ @service currentUser;+ @service siteSettings;+ @service site;+ @service appEvents;++ @tracked userDetails;+ @tracked selected;+ @tracked message;+ @tracked isConfirmed = false;+ @tracked isWarning = false;+ @tracked spammerDetails;++ constructor() {+ super(...arguments);++ this.adminTools+ ?.checkSpammer(this.args.model.flagModel.user_id)+ .then((result) => (this.spammerDetails = result));++ if (this.flagsAvailable.length === 1) {+ this.selected = this.flagsAvailable[0];+ }+ }++ get flagActions() {+ return {+ icon: "gavel",+ label: i18n("flagging.take_action"),+ actions: [+ {+ id: "agree_and_hide",+ icon: "thumbs-up",+ label: i18n("flagging.take_action_options.default.title"),+ description: i18n("flagging.take_action_options.default.details"),+ },+ {+ id: "agree_and_suspend",+ icon: "ban",+ label: i18n("flagging.take_action_options.suspend.title"),+ description: i18n("flagging.take_action_options.suspend.details"),+ client_action: "suspend",+ },+ {+ id: "agree_and_silence",+ icon: "microphone-slash",+ label: i18n("flagging.take_action_options.silence.title"),+ description: i18n("flagging.take_action_options.silence.details"),+ client_action: "silence",+ },+ ],+ };+ }++ get canSendWarning() {+ return (+ !this.args.model.flagTarget.targetsTopic() &&+ this.currentUser.staff &&+ this.selected?.name_key === "notify_user"+ );+ }++ get showDeleteSpammer() {+ return this.spammerDetails?.canDelete && this.selected?.name_key === "spam";+ }++ get submitLabel() {+ if (this.selected?.require_message) {+ return this.args.model.flagTarget.customSubmitLabel();+ }++ return this.args.model.flagTarget.submitLabel();+ }++ get title() {+ return this.args.model.flagTarget.title();+ }++ get flagsAvailable() {+ return this.args.model.flagTarget.flagsAvailable(this).filterBy("enabled");+ }++ get staffFlagsAvailable() {+ return this.flagsAvailable.length > 1;+ }++ get submitEnabled() {+ if (!this.selected) {+ return false;+ }++ if (!this.selected.require_message) {+ return true;+ }++ if (this.selected.isIllegal && !this.isConfirmed) {+ return false;+ }++ const len = this.message?.length || 0;+ return (+ len >= this.siteSettings.min_personal_message_post_length &&+ len <= MAX_MESSAGE_LENGTH+ );+ }++ get notifyModeratorsFlag() {+ return this.flagsAvailable.find((f) => f.id === NOTIFY_MODERATORS_KEY);+ }++ get canTakeAction() {+ return (+ !this.args.model.flagTarget.targetsTopic() &&+ !this.selected?.require_message &&+ this.currentUser.staff+ );+ }++ @action+ onKeydown(event) {+ if (+ this.submitEnabled &&+ event.key === "Enter" &&+ (event.ctrlKey || event.metaKey)+ ) {+ this.createFlag();+ return false;+ }+ }++ @action+ async penalize(adminToolMethod, performAction) {+ if (!this.adminTools) {+ return;+ }++ const createdBy = await User.findByUsername(+ this.args.model.flagModel.username+ );+ const opts = { before: performAction };++ if (this.args.model.flagTarget.editable()) {+ opts.postId = this.args.model.flagModel.id;+ opts.postEdit = this.args.model.flagModel.cooked;+ }++ return this.adminTools[adminToolMethod](createdBy, opts);+ }++ @action+ async deleteSpammer() {+ if (this.spammerDetails) {+ await this.spammerDetails.deleteUser();+ reload();+ }+ }++ @action+ async takeAction(actionable) {+ if (actionable.client_action === "suspend") {+ await this.penalize("showSuspendModal", () =>+ this.createFlag({ takeAction: true, skipClose: true })+ );+ } else if (actionable.client_action === "silence") {+ await this.penalize("showSilenceModal", () =>+ this.createFlag({ takeAction: true, skipClose: true })+ );+ } else if (actionable.client_action) {+ // eslint-disable-next-line no-console+ console.error(`No handler for ${actionable.client_action} found`);+ } else {+ this.args.model.setHidden();+ this.createFlag({ takeAction: true });+ }+ }++ @action+ createFlag(opts = {}) {+ if (this.selected.require_message) {+ opts.message = this.message;+ }+ this.args.model.flagTarget.create(this, opts);+ }++ @action+ createFlagAsWarning() {+ this.createFlag({ isWarning: true });+ this.args.model.setHidden();+ }++ @action+ flagForReview() {+ this.selected ||= this.notifyModeratorsFlag;+ this.createFlag({ queue_for_review: true });+ this.args.model.setHidden();+ }++ @action+ changePostActionType(actionType) {+ this.selected = actionType;+ }+ }+++<DModal+ class="flag-modal"+ @bodyClass="flag-modal-body"+ @title={{i18n this.title}}+ @submitOnEnter={{false}}+ @closeModal={{@closeModal}}+ {{on "keydown" this.onKeydown}}+>+ <:body>+ <p>{{html-safe (i18n "flagging.review_process_description")}}</p>+ <PluginOutlet+ @name="after-flag-modal-review-process-description"+ @connectorTagName="div"+ @outletArgs={{hash [email protected]}}+ />+ <form>+ <FlagSelection+ @nameKey={{this.selected.name_key}}+ @flags={{this.flagsAvailable}}+ as |f|+ >+ <FlagActionType+ @flag={{f}}+ @message={{this.message}}+ @isConfirmed={{this.isConfirmed}}+ @isWarning={{this.isWarning}}+ @selectedFlag={{this.selected}}+ @username={{@model.flagModel.username}}+ @staffFlagsAvailable={{this.staffFlagsAvailable}}+ @changePostActionType={{this.changePostActionType}}+ />+ </FlagSelection>+ </form>+ <PluginOutlet+ @name="flag-modal-bottom"+ @connectorTagName="div"+ @outletArgs={{hash [email protected]}}+ />+ </:body>+ <:footer>+ <DButton+ class="btn-primary flag-modal__create-flag"+ @action={{this.createFlag}}+ @disabled={{not this.submitEnabled}}+ @title="flagging.submit_tooltip"+ @icon={{if this.selected.is_custom_flag "envelope" "flag"}}+ @label={{this.submitLabel}}+ />++ {{#if this.canSendWarning}}+ <DButton+ class="btn-danger flag-modal__send-warning"+ @action={{this.createFlagAsWarning}}+ @disabled={{not this.submitEnabled}}+ @icon="triangle-exclamation"+ @label="flagging.official_warning"+ />+ {{/if}}++ {{#if this.canTakeAction}}+ <ReviewableBundledAction+ class="flag-modal__take-action"+ @bundle={{this.flagActions}}+ @performAction={{this.takeAction}}+ @reviewableUpdating={{not this.submitEnabled}}+ />++ <DButton+ class="btn-danger flag-modal__flag-for-review"+ @action={{this.flagForReview}}+ @disabled={{not this.submitEnabled this.notifyModeratorsFlag}}+ @icon="triangle-exclamation"+ @label="flagging.flag_for_review"+ />+ {{/if}}++ {{#if this.showDeleteSpammer}}+ <DButton+ class="btn-danger delete-spammer flag-modal__delete-spammer"+ @action={{this.deleteSpammer}}+ @disabled={{not this.submitEnabled}}+ @icon="triangle-exclamation"+ @label="flagging.delete_spammer"+ />+ {{/if}}+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/forgot-password.gjsindex b4c7cd70a62,1b78a2ccbf9..18c75c3dbe6--- a/app/assets/javascripts/discourse/app/components/modal/forgot-password.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/forgot-password.gjs@@@ -1,67 -1,91 +1,159 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import { htmlSafe } from "@ember/template";+ import { isEmpty } from "@ember/utils";+ import { ajax } from "discourse/lib/ajax";+ import { extractError } from "discourse/lib/ajax-error";+ import cookie from "discourse/lib/cookie";+ import getURL from "discourse/lib/get-url";+ import { escapeExpression } from "discourse/lib/utilities";+ import { i18n } from "discourse-i18n";++ export default class ForgotPassword extends Component {+ @service siteSettings;++ @tracked+ emailOrUsername = cookie("email") || this.args.model?.emailOrUsername || "";+ @tracked disabled = false;+ @tracked helpSeen = false;+ @tracked offerHelp;+ @tracked flash;++ get submitDisabled() {+ if (this.disabled) {+ return true;+ } else if (this.siteSettings.hide_email_address_taken) {+ return !this.emailOrUsername.includes("@");+ } else {+ return isEmpty(this.emailOrUsername.trim());+ }+ }++ @action+ updateEmailOrUsername(event) {+ this.emailOrUsername = event.target.value;+ }++ @action+ help() {+ this.offerHelp = i18n("forgot_password.help", { basePath: getURL("") });+ this.helpSeen = true;+ }++ @action+ async resetPassword() {+ if (this.submitDisabled) {+ return false;+ }++ this.disabled = true;+ this.flash = null;++ try {+ const data = await ajax("/session/forgot_password", {+ data: { login: this.emailOrUsername.trim() },+ type: "POST",+ });++ const emailOrUsername = escapeExpression(this.emailOrUsername);++ let key = "forgot_password.complete";+ key += emailOrUsername.match(/@/) ? "_email" : "_username";++ if (data.user_found === false) {+ key += "_not_found";++ this.flash = htmlSafe(+ i18n(key, {+ email: emailOrUsername,+ username: emailOrUsername,+ })+ );+ } else {+ key += data.user_found ? "_found" : "";++ this.emailOrUsername = "";+ this.offerHelp = i18n(key, {+ email: emailOrUsername,+ username: emailOrUsername,+ });++ this.helpSeen = !data.user_found;+ }+ } catch (error) {+ this.flash = extractError(error);+ } finally {+ this.disabled = false;+ }+ }+ }+++<DModal+ @title={{i18n "forgot_password.title"}}+ @closeModal={{@closeModal}}+ @flash={{this.flash}}+ @flashType="error"+ class="forgot-password-modal"+>+ <:body>+ {{#if this.offerHelp}}+ {{html-safe this.offerHelp}}+ {{else if this.siteSettings.hide_email_address_taken}}+ <label for="username-or-email">+ {{i18n "forgot_password.invite_no_username"}}+ </label>+ <input+ {{on "input" this.updateEmailOrUsername}}+ value={{this.emailOrUsername}}+ placeholder={{i18n "email"}}+ type="text"+ id="username-or-email"+ autocorrect="off"+ autocapitalize="off"+ />+ {{else}}+ <p>{{i18n "forgot_password.invite"}}</p>+ <label for="username-or-email">+ {{i18n "forgot_password.email-username"}}+ </label>+ <input+ {{on "input" this.updateEmailOrUsername}}+ value={{this.emailOrUsername}}+ placeholder={{i18n "login.email_placeholder"}}+ type="text"+ id="username-or-email"+ autocorrect="off"+ autocapitalize="off"+ />+ {{/if}}+ </:body>++ <:footer>+ {{#if this.offerHelp}}+ <DButton+ @action={{@closeModal}}+ @label="forgot_password.button_ok"+ type="submit"+ class="btn-large btn-primary"+ />+ {{#unless this.helpSeen}}+ <DButton+ @action={{this.help}}+ @label="forgot_password.button_help"+ @icon="circle-question"+ class="btn-large"+ />+ {{/unless}}+ {{else}}+ <DButton+ @action={{this.resetPassword}}+ @disabled={{this.submitDisabled}}+ @label="forgot_password.reset"+ type="submit"+ class="btn-primary forgot-password-reset"+ />+ {{/if}}+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/fullscreen-code.gjsindex 9ee649f73f4,de74709bab1..b6773572c01--- a/app/assets/javascripts/discourse/app/components/modal/fullscreen-code.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/fullscreen-code.gjs@@@ -1,14 -1,28 +1,43 @@@+ import Component from "@glimmer/component";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import CodeblockButtons from "discourse/lib/codeblock-buttons";+ import highlightSyntax from "discourse/lib/highlight-syntax";++ export default class FullscreenCode extends Component {+ @service siteSettings;+ @service session;++ @action+ closeModal() {+ this.codeBlockButtons.cleanup();+ this.args.closeModal();+ }++ @action+ applyCodeblockButtons(element) {+ const modalElement = element.querySelector(".d-modal__body");+ highlightSyntax(modalElement, this.siteSettings, this.session);++ this.codeBlockButtons = new CodeblockButtons({+ showFullscreen: false,+ showCopy: true,+ });+ this.codeBlockButtons.attachToGeneric(modalElement);+ }+ }+++<DModal+ @title={{i18n "copy_codeblock.view_code"}}+ @closeModal={{this.closeModal}}+ {{did-insert this.applyCodeblockButtons}}+ class="fullscreen-code-modal -max"+>+ <:body>+ <pre>+ <code+ class={{@model.codeClasses}}+ >{{@model.code}}</code>+ </pre>+ </:body>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/group-default-notifications.gjsindex a27d0ac6d74,1c6dae86ff3..ce98fc38107--- a/app/assets/javascripts/discourse/app/components/modal/group-default-notifications.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/group-default-notifications.gjs@@@ -1,19 -1,16 +1,36 @@@+ import Component from "@glimmer/component";+ import { action } from "@ember/object";++ export default class GroupDefaultNotifications extends Component {+ @action+ updateExistingUsers() {+ this.args.model.setUpdateExistingUsers(true);+ this.args.closeModal();+ }++ @action+ cancel() {+ this.args.model.setUpdateExistingUsers(false);+ this.args.closeModal();+ }+ }+++<DModal+ @title={{i18n "groups.default_notifications.modal_title"}}+ @closeModal={{@closeModal}}+>+ <:body>+ {{i18n "groups.default_notifications.modal_description" [email protected]}}+ </:body>+ <:footer>+ <DButton+ @action={{this.updateExistingUsers}}+ @label="groups.default_notifications.modal_yes"+ class="btn-primary"+ />+ <DButton+ @action={{this.cancel}}+ @label="groups.default_notifications.modal_no"+ />+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/history.gjsindex 0fa74655808,13efa09936d..bce79226ae8--- a/app/assets/javascripts/discourse/app/components/modal/history.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/history.gjs@@@ -1,62 -1,359 +1,422 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import { categoryBadgeHTML } from "discourse/helpers/category-link";+ import { iconHTML } from "discourse/lib/icon-library";+ import { sanitizeAsync } from "discourse/lib/text";+ import Category from "discourse/models/category";+ import Post from "discourse/models/post";+ import { i18n } from "discourse-i18n";++ function customTagArray(val) {+ if (!val) {+ return [];+ }+ if (!Array.isArray(val)) {+ val = [val];+ }+ return val;+ }++ export default class History extends Component {+ @service dialog;+ @service site;+ @service currentUser;+ @service siteSettings;+ @service appEvents;++ @tracked loading;+ @tracked postRevision;+ @tracked viewMode = this.site.mobileView ? "inline" : "side_by_side";+ @tracked bodyDiff;+ @tracked initialLoad = true;++ constructor() {+ super(...arguments);+ this.refresh(this.args.model.postId, this.args.model.postVersion);+ }++ get loadFirstDisabled() {+ return (+ this.loading ||+ this.postRevision?.current_revision <= this.postRevision?.first_revision+ );+ }++ get loadPreviousDisabled() {+ return (+ this.loading ||+ !this.postRevision.previous_revision ||+ (!this.postRevision.previous_revision &&+ this.postRevision.current_revision <=+ this.postRevision.previous_revision)+ );+ }++ get loadNextDisabled() {+ return (+ this.loading ||+ this.postRevision?.current_revision >= this.postRevision?.next_revision+ );+ }++ get loadLastDisabled() {+ return (+ this.loading ||+ this.postRevision?.current_revision >= this.postRevision?.next_revision+ );+ }++ get displayRevisions() {+ return this.postRevision?.version_count > 2;+ }++ get modalTitleKey() {+ return this.args.model.post.version > 100+ ? "history_capped_revisions"+ : "history";+ }++ get previousVersion() {+ return this.postRevision?.current_version+ ? this.postRevision.current_version - 1+ : null;+ }++ get revisionsText() {+ return i18n(+ "post.revisions.controls.comparing_previous_to_current_out_of_total",+ {+ previous: this.previousVersion,+ icon: iconHTML("left-right"),+ current: this.postRevision?.current_version,+ total: this.postRevision?.version_count,+ }+ );+ }++ get titleDiff() {+ let mode = this.viewMode;+ if (mode === "side_by_side_markdown") {+ mode = "side_by_side";+ }+ return this.postRevision?.title_changes?.[mode];+ }++ get bodyDiffHTML() {+ return this.postRevision?.body_changes?.[this.viewMode];+ }++ @action+ async calculateBodyDiff(_, bodyDiff) {+ let html = bodyDiff;+ if (this.viewMode !== "side_by_side_markdown") {+ const opts = {+ features: { editHistory: true, historyOneboxes: true },+ allowListed: {+ editHistory: { custom: (tag, attr) => attr === "class" },+ historyOneboxes: ["header", "article", "div[style]"],+ },+ };+ html = await sanitizeAsync(html, opts);+ }+ this.bodyDiff = html;+ }++ get previousTagChanges() {+ const previousArray = customTagArray(+ this.postRevision.tags_changes?.previous+ );+ const currentSet = new Set(+ customTagArray(this.postRevision.tags_changes?.current)+ );++ return previousArray.map((name) => ({+ name,+ deleted: !currentSet.has(name),+ }));+ }++ get currentTagChanges() {+ const previousSet = new Set(+ customTagArray(this.postRevision.tags_changes?.previous)+ );+ const currentArray = customTagArray(+ this.postRevision.tags_changes?.current+ );++ return currentArray.map((name) => ({+ name,+ inserted: !previousSet.has(name),+ }));+ }++ get createdAtDate() {+ return moment(this.postRevision.created_at).format("LLLL");+ }++ get displayEdit() {+ return !!(+ this.postRevision?.can_edit &&+ this.args.model.editPost &&+ this.postRevision?.last_revision === this.postRevision?.current_revision+ );+ }++ get revertToRevisionText() {+ if (this.previousVersion) {+ return i18n("post.revisions.controls.revert", {+ revision: this.previousVersion,+ });+ }+ }++ async refresh(postId, postVersion) {+ this.loading = true;+ try {+ const result = await Post.loadRevision(postId, postVersion);+ this.postRevision = result;+ } catch (error) {+ this.args.closeModal();+ this.dialog.alert(error.jqXHR.responseJSON.errors[0]);++ const postStream = this.args.model.post?.topic?.postStream;+ if (!postStream) {+ return;+ }++ postStream+ .triggerChangedPost(postId, this.args.model)+ .then(() =>+ this.appEvents.trigger("post-stream:refresh", { id: postId })+ );+ } finally {+ this.loading = false;+ this.initialLoad = false;+ }+ }++ hide(postId, postVersion) {+ Post.hideRevision(postId, postVersion).then(() =>+ this.refresh(postId, postVersion)+ );+ }++ show(postId, postVersion) {+ Post.showRevision(postId, postVersion).then(() =>+ this.refresh(postId, postVersion)+ );+ }++ async revert(post, postVersion) {+ try {+ const result = await post.revertToRevision(postVersion);+ this.refresh(post.id, postVersion);+ if (result.topic) {+ post.set("topic.slug", result.topic.slug);+ post.set("topic.title", result.topic.title);+ post.set("topic.fancy_title", result.topic.fancy_title);+ }+ if (result.category_id) {+ post.set(+ "topic.category",+ await Category.asyncFindById(result.category_id)+ );+ }+ this.args.closeModal();+ } catch (e) {+ if (e.jqXHR.responseJSON?.errors?.[0]) {+ this.dialog.alert(e.jqXHR.responseJSON.errors[0]);+ }+ }+ }++ get editButtonLabel() {+ return `post.revisions.controls.${+ this.postRevision.wiki ? "edit_wiki" : "edit_post"+ }`;+ }++ get hiddenClasses() {+ if (this.viewMode === "inline") {+ return this.postRevision?.previous_hidden ||+ this.postRevision?.current_hidden+ ? "hidden-revision-either"+ : null;+ } else {+ let result = [];+ if (this.postRevision?.previous_hidden) {+ result.push("hidden-revision-previous");+ }+ if (this.postRevision?.current_hidden) {+ result.push("hidden-revision-current");+ }+ return result.join(" ");+ }+ }++ get previousCategory() {+ if (this.postRevision?.category_id_changes?.previous) {+ let category = Category.findById(+ this.postRevision.category_id_changes.previous+ );+ return categoryBadgeHTML(category, {+ allowUncategorized: true,+ extraClasses: "diff-del",+ });+ }+ }++ get currentCategory() {+ if (this.postRevision?.category_id_changes?.current) {+ let category = Category.findById(+ this.postRevision.category_id_changes.current+ );+ return categoryBadgeHTML(category, {+ allowUncategorized: true,+ extraClasses: "diff-ins",+ });+ }+ }++ @action+ displayInline(event) {+ event?.preventDefault();+ this.viewMode = "inline";+ }++ @action+ displaySideBySide(event) {+ event?.preventDefault();+ this.viewMode = "side_by_side";+ }++ @action+ displaySideBySideMarkdown(event) {+ event?.preventDefault();+ this.viewMode = "side_by_side_markdown";+ }++ @action+ loadFirstVersion() {+ this.refresh(this.postRevision.post_id, this.postRevision.first_revision);+ }++ @action+ loadPreviousVersion() {+ this.refresh(+ this.postRevision.post_id,+ this.postRevision.previous_revision+ );+ }++ @action+ loadNextVersion() {+ this.refresh(this.postRevision.post_id, this.postRevision.next_revision);+ }++ @action+ loadLastVersion() {+ return this.refresh(+ this.postRevision.post_id,+ this.postRevision.last_revision+ );+ }++ @action+ hideVersion() {+ this.hide(this.postRevision.post_id, this.postRevision.current_revision);+ }++ @action+ permanentlyDeleteVersions() {+ this.dialog.yesNoConfirm({+ message: i18n("post.revisions.controls.destroy_confirm"),+ didConfirm: () => {+ Post.permanentlyDeleteRevisions(this.postRevision.post_id).then(() => {+ this.args.closeModal();+ });+ },+ });+ }++ @action+ showVersion() {+ this.show(this.postRevision.post_id, this.postRevision.current_revision);+ }++ @action+ editPost() {+ this.args.model.editPost(this.args.model.post);+ this.args.closeModal();+ }++ @action+ revertToVersion() {+ this.revert(this.args.model.post, this.postRevision.current_revision);+ }+ }+++<DModal+ @title={{i18n this.modalTitleKey}}+ @closeModal={{@closeModal}}+ class="history-modal -max {{concat '--mode-' (dasherize this.viewMode)}}"+>+ <:body>+ <ConditionalLoadingSpinner @condition={{this.initialLoad}}>+ <Modal::History::Revision+ @model={{this.postRevision}}+ @previousCategory={{this.previousCategory}}+ @currentCategory={{this.currentCategory}}+ @displayInline={{this.displayInline}}+ @displaySideBySide={{this.displaySideBySide}}+ @displaySideBySideMarkdown={{this.displaySideBySideMarkdown}}+ @viewMode={{this.viewMode}}+ />+ <Modal::History::Revisions+ @model={{this.postRevision}}+ @hiddenClasses={{this.hiddenClasses}}+ @mobileView={{this.site.mobileView}}+ @userChanges={{this.user_changes}}+ @previousCategory={{this.previousCategory}}+ @currentCategory={{this.currentCategory}}+ @previousTagChanges={{this.previousTagChanges}}+ @currentTagChanges={{this.currentTagChanges}}+ @bodyDiffHTML={{this.bodyDiffHTML}}+ @bodyDiff={{this.bodyDiff}}+ @calculateBodyDiff={{this.calculateBodyDiff}}+ @titleDiff={{this.titleDiff}}+ @viewMode={{this.viewMode}}+ />+ </ConditionalLoadingSpinner>+ </:body>+ <:footer>+ {{#if @model.editPost}}+ <Modal::History::TopicFooter+ @model={{this.postRevision}}+ @loadFirstVersion={{this.loadFirstVersion}}+ @loadPreviousVersion={{this.loadPreviousVersion}}+ @loadNextVersion={{this.loadNextVersion}}+ @loadLastVersion={{this.loadLastVersion}}+ @displayEdit={{this.displayEdit}}+ @editPost={{this.editPost}}+ @editButtonLabel={{this.editButtonLabel}}+ @revertToVersion={{this.revertToVersion}}+ @hideVersion={{this.hideVersion}}+ @showVersion={{this.showVersion}}+ @permanentlyDeleteVersions={{this.permanentlyDeleteVersions}}+ @loading={{this.loading}}+ @canPermanentlyDelete={{this.siteSettings.can_permanently_delete}}+ @loadFirstDisabled={{this.loadFirstDisabled}}+ @loadPreviousDisabled={{this.loadPreviousDisabled}}+ @displayRevisions={{this.displayRevisions}}+ @revisionsText={{this.revisionsText}}+ @loadNextDisabled={{this.loadNextDisabled}}+ @loadLastDisabled={{this.loadLastDisabled}}+ @revertToRevisionText={{this.revertToRevisionText}}+ @isStaff={{this.currentUser.staff}}+ />+ {{/if}}+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/history/revision.gjsindex 6250351d4e7,fc335155ac3..00a1abf57c8--- a/app/assets/javascripts/discourse/app/components/modal/history/revision.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/history/revision.gjs@@@ -1,142 -1,7 +1,150 @@@+ import Component from "@glimmer/component";+ import { service } from "@ember/service";++ export default class Revision extends Component {+ @service site;+ @service siteSettings;+ }+++<div id="revision">+ <div id="revision-details">+ {{d-icon "pencil"}}+ <LinkTo+ @route="user"+ @model={{@model.username}}+ class="revision-details__user"+ >+ {{bound-avatar-template @model.avatar_template "small"}}+ {{#if this.siteSettings.prioritize_full_name_in_ux}}+ {{@model.acting_user_name}}+ {{else}}+ {{@model.username}}+ {{/if}}+ </LinkTo>+ <PluginOutlet+ @name="revision-user-details-after"+ @outletArgs={{hash model=@model}}+ />+ <span class="date">{{bound-date @model.created_at}}</span>+ {{#if @model.edit_reason}}+ <span class="edit-reason">{{@model.edit_reason}}</span>+ {{/if}}++ {{#if this.site.desktopView}}+ <span>+ {{#if @model.user_changes}}+ {{bound-avatar-template+ @model.user_changes.previous.avatar_template+ "small"+ }}+ {{@model.user_changes.previous.username}}+ →+ {{bound-avatar-template+ @model.user_changes.current.avatar_template+ "small"+ }}+ {{@model.user_changes.current.username}}+ {{/if}}++ {{#if @model.wiki_changes}}+ {{d-icon+ "far-pen-to-square"+ class=(if @model.wiki_changes.current "diff-ins" "diff-del")+ }}+ {{/if}}++ {{#if @model.post_type_changes}}+ {{d-icon+ "shield-halved"+ class=(if+ (eq+ @model.post_type_changes.current+ @site.post_types.moderator_action+ )+ "diff-del"+ "diff-ins"+ )+ }}+ {{/if}}++ {{#if @model.archetype_changes}}+ {{d-icon+ (if+ (eq @model.archetype_changes.current "private_message")+ "envelope"+ "comment"+ )+ }}+ {{/if}}++ {{#if (and @model.category_id_changes (not @model.archetype_changes))}}+ {{#if @previousCategory}}+ {{html-safe @previousCategory}}+ {{else}}+ {{d-icon "far-eye-slash" class="diff-del"}}+ {{/if}}+ →+ {{#if @currentCategory}}+ {{html-safe @currentCategory}}+ {{else}}+ {{d-icon "far-eye-slash" class="diff-ins"}}+ {{/if}}+ {{/if}}+ </span>+ {{/if}}+ </div>++ {{#if this.site.desktopView}}+ <div id="display-modes">+ <ul class="nav nav-pills">+ <li>+ <a+ href+ class={{concat-class+ "inline-mode"+ (if (eq @viewMode "inline") "active")+ }}+ {{on "click" @displayInline}}+ title={{i18n "post.revisions.displays.inline.title"}}+ aria-label={{i18n "post.revisions.displays.inline.title"}}+ >+ {{d-icon "far-square"}}+ {{i18n "post.revisions.displays.inline.button"}}+ </a>+ </li>+ <li>+ <a+ href+ class={{concat-class+ "side-by-side-mode"+ (if (eq @viewMode "side_by_side") "active")+ }}+ {{on "click" @displaySideBySide}}+ title={{i18n "post.revisions.displays.side_by_side.title"}}+ aria-label={{i18n "post.revisions.displays.side_by_side.title"}}+ >+ {{d-icon "table-columns"}}+ {{i18n "post.revisions.displays.side_by_side.button"}}+ </a>+ </li>+ <li>+ <a+ href+ class={{concat-class+ "side-by-side-markdown-mode"+ (if (eq @viewMode "side_by_side_markdown") "active")+ }}+ {{on "click" @displaySideBySideMarkdown}}+ title={{i18n "post.revisions.displays.side_by_side_markdown.title"}}+ aria-label={{i18n+ "post.revisions.displays.side_by_side_markdown.title"+ }}+ >+ {{d-icon "table-columns"}}+ {{i18n "post.revisions.displays.side_by_side_markdown.button"}}+ </a>+ </li>+ </ul>+ </div>+ {{/if}}+</div>diff --cc app/assets/javascripts/discourse/app/components/modal/json-schema-editor.gjsindex ac1edd72088,99818a88f8f..3358c9c06ff--- a/app/assets/javascripts/discourse/app/components/modal/json-schema-editor.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/json-schema-editor.gjs@@@ -1,23 -1,86 +1,110 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { waitForPromise } from "@ember/test-waiters";+ import { create } from "virtual-dom";+ import { iconNode } from "discourse/lib/icon-library";++ export default class JsonSchemaEditorModal extends Component {+ @tracked editor = null;+ @tracked value = this.args.model.value;+ @tracked flash;+ @tracked flashType;++ get settingName() {+ return this.args.model.settingName.replace(/\_/g, " ");+ }++ @action+ teardownJsonEditor() {+ this.editor?.destroy();+ }++ @action+ saveChanges() {+ const errors = this.editor.validate();++ if (!errors.length) {+ this.value = JSON.stringify(this.editor.getValue());+ this.args.model.updateValue(this.value);+ this.args.closeModal();+ } else {+ this.flash = errors.mapBy("message").join("\n");+ this.flashType = "error";+ }+ }++ @action+ async buildJsonEditor(element) {+ const promise = import("@json-editor/json-editor");+ waitForPromise(promise);+ const { JSONEditor } = await promise;++ JSONEditor.defaults.options.theme = "barebones";+ JSONEditor.defaults.iconlibs = {+ discourseIcons: DiscourseJsonSchemaEditorIconlib,+ };+ JSONEditor.defaults.options.iconlib = "discourseIcons";++ this.editor = new JSONEditor(element, {+ schema: this.args.model.jsonSchema,+ disable_array_delete_all_rows: true,+ disable_array_delete_last_row: true,+ disable_array_reorder: false,+ disable_array_copy: false,+ enable_array_copy: true,+ disable_edit_json: true,+ disable_properties: true,+ disable_collapse: false,+ show_errors: "never",+ startval: this.value ? JSON.parse(this.value) : null,+ });+ }+ }++ class DiscourseJsonSchemaEditorIconlib {+ constructor() {+ this.mapping = {+ delete: "trash-can",+ add: "plus",+ moveup: "arrow-up",+ movedown: "arrow-down",+ moveleft: "chevron-left",+ moveright: "chevron-right",+ copy: "copy",+ collapse: "chevron-down",+ expand: "chevron-up",+ };+ }++ getIcon(key) {+ if (!this.mapping[key]) {+ return;+ }+ return create(iconNode(this.mapping[key]));+ }+ }+++<DModal+ @flash={{this.flash}}+ @flashType={{this.flashType}}+ @closeModal={{@closeModal}}+ @title={{i18n+ "admin.site_settings.json_schema.modal_title"+ }}+ @inline={{@inline}}+ class="json-schema-editor-modal"+>+ <:body>+ <div+ id="json-editor-holder"+ {{did-insert this.buildJsonEditor}}+ {{will-destroy this.teardownJsonEditor}}+ ></div>+ </:body>++ <:footer>+ <DButton @action={{this.saveChanges}} @label="save" class="btn-primary" />+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/login.gjsindex 014f0bae49f,73a4d02727c..90467484904--- a/app/assets/javascripts/discourse/app/components/modal/login.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/login.gjs@@@ -1,131 -1,380 +1,512 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { schedule } from "@ember/runloop";+ import { service } from "@ember/service";+ import { htmlSafe } from "@ember/template";+ import { isEmpty } from "@ember/utils";+ import { ajax } from "discourse/lib/ajax";+ import { popupAjaxError } from "discourse/lib/ajax-error";+ import cookie, { removeCookie } from "discourse/lib/cookie";+ import escape from "discourse/lib/escape";+ import getURL from "discourse/lib/get-url";+ import { wantsNewWindow } from "discourse/lib/intercept-click";+ import { areCookiesEnabled } from "discourse/lib/utilities";+ import {+ getPasskeyCredential,+ isWebauthnSupported,+ } from "discourse/lib/webauthn";+ import { findAll } from "discourse/models/login-method";+ import { SECOND_FACTOR_METHODS } from "discourse/models/user";+ import { i18n } from "discourse-i18n";+ import ForgotPassword from "./forgot-password";++ export default class Login extends Component {+ @service capabilities;+ @service dialog;+ @service siteSettings;+ @service site;+ @service login;+ @service modal;++ @tracked loggingIn = false;+ @tracked loggedIn = false;+ @tracked showLoginButtons = true;+ @tracked showSecondFactor = false;+ @tracked loginPassword = "";+ @tracked loginName = "";+ @tracked flash = this.args.model.flash;+ @tracked flashType = this.args.model.flashType;+ @tracked canLoginLocal = this.siteSettings.enable_local_logins;+ @tracked+ canLoginLocalWithEmail = this.siteSettings.enable_local_logins_via_email;+ @tracked secondFactorMethod = SECOND_FACTOR_METHODS.TOTP;+ @tracked securityKeyCredential;+ @tracked otherMethodAllowed;+ @tracked secondFactorRequired;+ @tracked backupEnabled;+ @tracked totpEnabled;+ @tracked showSecurityKey;+ @tracked securityKeyChallenge;+ @tracked securityKeyAllowedCredentialIds;+ @tracked secondFactorToken;++ get awaitingApproval() {+ return (+ this.args.model.awaitingApproval &&+ !this.canLoginLocal &&+ !this.canLoginLocalWithEmail+ );+ }++ get loginDisabled() {+ return this.loggingIn || this.loggedIn;+ }++ get modalBodyClasses() {+ const classes = ["login-modal-body"];+ if (this.awaitingApproval) {+ classes.push("awaiting-approval");+ }+ if (+ this.hasAtLeastOneLoginButton &&+ !this.showSecondFactor &&+ !this.showSecurityKey+ ) {+ classes.push("has-alt-auth");+ }+ if (!this.canLoginLocal) {+ classes.push("no-local-login");+ }+ if (this.showSecondFactor || this.showSecurityKey) {+ classes.push("second-factor");+ }+ return classes.join(" ");+ }++ get canUsePasskeys() {+ return (+ this.siteSettings.enable_local_logins &&+ this.siteSettings.enable_passkeys &&+ isWebauthnSupported()+ );+ }++ get hasAtLeastOneLoginButton() {+ return findAll().length > 0 || this.canUsePasskeys;+ }++ get hasNoLoginOptions() {+ return !this.hasAtLeastOneLoginButton && !this.canLoginLocal;+ }++ get loginButtonLabel() {+ return this.loggingIn ? "login.logging_in" : "login.title";+ }++ get showSignupLink() {+ return this.args.model.canSignUp && !this.showSecondFactor;+ }++ get adminLoginPath() {+ return getURL("/u/admin-login");+ }++ @action+ async passkeyLogin(mediation = "optional") {+ try {+ const publicKeyCredential = await getPasskeyCredential(+ (e) => this.dialog.alert(e),+ mediation,+ this.capabilities.isFirefox+ );++ if (publicKeyCredential) {+ const authResult = await ajax("/session/passkey/auth.json", {+ type: "POST",+ data: { publicKeyCredential },+ });++ if (authResult && !authResult.error) {+ const destinationUrl = cookie("destination_url");+ const ssoDestinationUrl = cookie("sso_destination_url");++ if (ssoDestinationUrl) {+ removeCookie("sso_destination_url");+ window.location.assign(ssoDestinationUrl);+ } else if (destinationUrl) {+ removeCookie("destination_url");+ window.location.assign(destinationUrl);+ } else if (this.args.model.referrerTopicUrl) {+ window.location.assign(this.args.model.referrerTopicUrl);+ } else {+ window.location.reload();+ }+ } else {+ this.dialog.alert(authResult.error);+ }+ }+ } catch (e) {+ popupAjaxError(e);+ }+ }++ @action+ preloadLogin() {+ const prefillUsername = document.querySelector(+ "#hidden-login-form input[name=username]"+ )?.value;+ if (prefillUsername) {+ this.loginName = prefillUsername;+ this.loginPassword = document.querySelector(+ "#hidden-login-form input[name=password]"+ ).value;+ } else if (cookie("email")) {+ this.loginName = cookie("email");+ }+ }++ @action+ securityKeyCredentialChanged(value) {+ this.securityKeyCredential = value;+ }++ @action+ flashChanged(value) {+ this.flash = value;+ }++ @action+ flashTypeChanged(value) {+ this.flashType = value;+ }++ @action+ loginNameChanged(event) {+ this.loginName = event.target.value;+ }++ @action+ async triggerLogin() {+ if (this.loginDisabled) {+ return;+ }++ if (isEmpty(this.loginName) || isEmpty(this.loginPassword)) {+ this.flash = i18n("login.blank_username_or_password");+ this.flashType = "error";+ return;+ }++ try {+ this.loggingIn = true;+ const result = await ajax("/session", {+ type: "POST",+ data: {+ login: this.loginName,+ password: this.loginPassword,+ second_factor_token:+ this.securityKeyCredential || this.secondFactorToken,+ second_factor_method: this.secondFactorMethod,+ timezone: moment.tz.guess(),+ },+ });+ if (result && result.error) {+ this.loggingIn = false;+ this.flash = null;++ if (+ (result.security_key_enabled || result.totp_enabled) &&+ !this.secondFactorRequired+ ) {+ this.otherMethodAllowed = result.multiple_second_factor_methods;+ this.secondFactorRequired = true;+ this.showLoginButtons = false;+ this.backupEnabled = result.backup_enabled;+ this.totpEnabled = result.totp_enabled;+ this.showSecondFactor = result.totp_enabled;+ this.showSecurityKey = result.security_key_enabled;+ this.secondFactorMethod = result.security_key_enabled+ ? SECOND_FACTOR_METHODS.SECURITY_KEY+ : SECOND_FACTOR_METHODS.TOTP;+ this.securityKeyChallenge = result.challenge;+ this.securityKeyAllowedCredentialIds = result.allowed_credential_ids;++ // only need to focus the 2FA input for TOTP+ if (!this.showSecurityKey) {+ schedule("afterRender", () =>+ document+ .getElementById("second-factor")+ .querySelector("input")+ .focus()+ );+ }++ return;+ } else if (result.reason === "not_activated") {+ this.args.model.showNotActivated({+ username: this.loginName,+ sentTo: escape(result.sent_to_email),+ currentEmail: escape(result.current_email),+ });+ } else if (result.reason === "suspended") {+ this.args.closeModal();+ this.dialog.alert(result.error);+ } else if (result.reason === "expired") {+ this.flash = htmlSafe(+ i18n("login.password_expired", {+ reset_url: getURL("/password-reset"),+ })+ );+ this.flashType = "error";+ } else {+ this.flash = result.error;+ this.flashType = "error";+ }+ } else {+ this.loggedIn = true;+ // Trigger the browser's password manager using the hidden static login form:+ const hiddenLoginForm = document.getElementById("hidden-login-form");+ const applyHiddenFormInputValue = (value, key) => {+ if (!hiddenLoginForm) {+ return;+ }++ hiddenLoginForm.querySelector(`input[name=${key}]`).value = value;+ };++ const destinationUrl = cookie("destination_url");+ const ssoDestinationUrl = cookie("sso_destination_url");++ applyHiddenFormInputValue(this.loginName, "username");+ applyHiddenFormInputValue(this.loginPassword, "password");++ if (ssoDestinationUrl) {+ removeCookie("sso_destination_url");+ window.location.assign(ssoDestinationUrl);+ return;+ } else if (destinationUrl) {+ // redirect client to the original URL+ removeCookie("destination_url");++ applyHiddenFormInputValue(destinationUrl, "redirect");+ } else if (this.args.model.referrerTopicUrl) {+ applyHiddenFormInputValue(+ this.args.model.referrerTopicUrl,+ "redirect"+ );+ } else {+ applyHiddenFormInputValue(window.location.href, "redirect");+ }++ if (hiddenLoginForm) {+ if (+ navigator.userAgent.match(/(iPad|iPhone|iPod)/g) &&+ navigator.userAgent.match(/Safari/g)+ ) {+ // In case of Safari on iOS do not submit hidden login form+ window.location.href = hiddenLoginForm.querySelector(+ "input[name=redirect]"+ ).value;+ } else {+ hiddenLoginForm.submit();+ }+ }+ return;+ }+ } catch (e) {+ // Failed to login+ if (e.jqXHR && e.jqXHR.status === 429) {+ this.flash = i18n("login.rate_limit");+ this.flashType = "error";+ } else if (+ e.jqXHR &&+ e.jqXHR.status === 503 &&+ e.jqXHR.responseJSON.error_type === "read_only"+ ) {+ this.flash = i18n("read_only_mode.login_disabled");+ this.flashType = "error";+ } else if (!areCookiesEnabled()) {+ this.flash = i18n("login.cookies_error");+ this.flashType = "error";+ } else {+ this.flash = i18n("login.error");+ this.flashType = "error";+ }+ this.loggingIn = false;+ }+ }++ @action+ externalLoginAction(loginMethod) {+ if (this.loginDisabled) {+ return;+ }+ this.login.externalLogin(loginMethod, {+ signup: false,+ setLoggingIn: (value) => (this.loggingIn = value),+ });+ }++ @action+ createAccount() {+ let createAccountProps = {};+ if (this.loginName && this.loginName.indexOf("@") > 0) {+ createAccountProps.accountEmail = this.loginName;+ createAccountProps.accountUsername = null;+ } else {+ createAccountProps.accountUsername = this.loginName;+ createAccountProps.accountEmail = null;+ }+ this.args.model.showCreateAccount(createAccountProps);+ }++ @action+ interceptResetLink(event) {+ if (+ !wantsNewWindow(event) &&+ event.target.href &&+ new URL(event.target.href).pathname === getURL("/password-reset")+ ) {+ event.preventDefault();+ event.stopPropagation();+ this.modal.show(ForgotPassword, {+ model: {+ emailOrUsername: this.loginName,+ },+ });+ }+ }+ }+++<DModal+ class="login-modal -large"+ @bodyClass={{this.modalBodyClasses}}+ @closeModal={{@closeModal}}+ @flash={{this.flash}}+ @flashType={{this.flashType}}+ {{did-insert this.preloadLogin}}+ {{on "click" this.interceptResetLink}}+>+ <:body>+ <PluginOutlet @name="login-before-modal-body" @connectorTagName="div" />++ {{#if this.hasNoLoginOptions}}+ <div class={{if this.site.desktopView "login-left-side"}}>+ <div class="login-welcome-header no-login-methods-configured">+ <h1 class="login-title">{{i18n "login.no_login_methods.title"}}</h1>+ <img />+ <p class="login-subheader">+ {{html-safe+ (i18n+ "login.no_login_methods.description"+ (hash adminLoginPath=this.adminLoginPath)+ )+ }}+ </p>+ </div>+ </div>+ {{else}}+ {{#if this.site.mobileView}}+ <WelcomeHeader @header={{i18n "login.header_title"}}>+ <PluginOutlet+ @name="login-header-bottom"+ @outletArgs={{hash createAccount=this.createAccount}}+ />+ </WelcomeHeader>+ {{#if this.showLoginButtons}}+ <LoginButtons+ @externalLogin={{this.externalLoginAction}}+ @passkeyLogin={{this.passkeyLogin}}+ @context="login"+ />+ {{/if}}+ {{/if}}++ {{#if this.canLoginLocal}}+ <div class={{if this.site.desktopView "login-left-side"}}>+ {{#if this.site.desktopView}}+ <WelcomeHeader @header={{i18n "login.header_title"}}>+ <PluginOutlet+ @name="login-header-bottom"+ @outletArgs={{hash createAccount=this.createAccount}}+ />+ </WelcomeHeader>+ {{/if}}+ <LocalLoginForm+ @loginName={{this.loginName}}+ @loginNameChanged={{this.loginNameChanged}}+ @canLoginLocalWithEmail={{this.canLoginLocalWithEmail}}+ @canUsePasskeys={{this.canUsePasskeys}}+ @passkeyLogin={{this.passkeyLogin}}+ @loginPassword={{this.loginPassword}}+ @secondFactorMethod={{this.secondFactorMethod}}+ @secondFactorToken={{this.secondFactorToken}}+ @backupEnabled={{this.backupEnabled}}+ @totpEnabled={{this.totpEnabled}}+ @securityKeyAllowedCredentialIds={{this.securityKeyAllowedCredentialIds}}+ @securityKeyChallenge={{this.securityKeyChallenge}}+ @showSecurityKey={{this.showSecurityKey}}+ @otherMethodAllowed={{this.otherMethodAllowed}}+ @showSecondFactor={{this.showSecondFactor}}+ @handleForgotPassword={{this.handleForgotPassword}}+ @login={{this.triggerLogin}}+ @flashChanged={{this.flashChanged}}+ @flashTypeChanged={{this.flashTypeChanged}}+ @securityKeyCredentialChanged={{this.securityKeyCredentialChanged}}+ />+ {{#if this.site.desktopView}}+ <div class="d-modal__footer">+ <LoginPageCta+ @canLoginLocal={{this.canLoginLocal}}+ @showSecurityKey={{this.showSecurityKey}}+ @login={{this.triggerLogin}}+ @loginButtonLabel={{this.loginButtonLabel}}+ @loginDisabled={{this.loginDisabled}}+ @showSignupLink={{this.showSignupLink}}+ @createAccount={{this.createAccount}}+ @loggingIn={{this.loggingIn}}+ @showSecondFactor={{this.showSecondFactor}}+ />+ </div>+ {{/if}}+ </div>+ {{/if}}++ {{#if (and this.showLoginButtons this.site.desktopView)}}+ {{#unless this.canLoginLocal}}+ <div class="login-left-side">+ <WelcomeHeader @header={{i18n "login.header_title"}} />+ </div>+ {{/unless}}+ {{#if this.hasAtLeastOneLoginButton}}+ <div class="login-right-side">+ <LoginButtons+ @externalLogin={{this.externalLoginAction}}+ @passkeyLogin={{this.passkeyLogin}}+ @context="login"+ />+ </div>+ {{/if}}+ {{/if}}+ {{/if}}+ </:body>++ <:footer>+ {{#if this.site.mobileView}}+ {{#unless this.hasNoLoginOptions}}+ <LoginPageCta+ @canLoginLocal={{this.canLoginLocal}}+ @showSecurityKey={{this.showSecurityKey}}+ @login={{this.triggerLogin}}+ @loginButtonLabel={{this.loginButtonLabel}}+ @loginDisabled={{this.loginDisabled}}+ @showSignupLink={{this.showSignupLink}}+ @createAccount={{this.createAccount}}+ @loggingIn={{this.loggingIn}}+ @showSecondFactor={{this.showSecondFactor}}+ />+ {{/unless}}+ {{/if}}+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/not-activated.gjsindex 1d4e0c3a37e,39727b8454d..5264f5f8a2f--- a/app/assets/javascripts/discourse/app/components/modal/not-activated.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/not-activated.gjs@@@ -1,15 -1,29 +1,45 @@@+ import Component from "@glimmer/component";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import { resendActivationEmail } from "discourse/lib/user-activation";+ import ActivationEdit from "./activation-edit";+ import ActivationResent from "./activation-resent";++ export default class NotActivated extends Component {+ @service modal;++ @action+ sendActivationEmail() {+ resendActivationEmail(this.args.model.currentEmail).then(() => {+ this.modal.show(ActivationResent, {+ model: { currentEmail: this.args.model.currentEmail },+ });+ });+ }++ @action+ editActivationEmail() {+ this.modal.show(ActivationEdit, {+ model: {+ currentEmail: this.args.model.currentEmail,+ newEmail: this.args.model.currentEmail,+ },+ });+ }+ }+++<DModal+ @closeModal={{@closeModal}}+ @title={{i18n "log_in"}}+ class="not-activated-modal"+>+ <:body>+ {{html-safe (i18n "login.not_activated" [email protected])}}+ </:body>+ <:footer>+ <ActivationControls+ @sendActivationEmail={{this.sendActivationEmail}}+ @editActivationEmail={{this.editActivationEmail}}+ />+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/publish-page.gjsindex 96b4edba810,ddc24721b6c..c7aec48e5ee--- a/app/assets/javascripts/discourse/app/components/modal/publish-page.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/publish-page.gjs@@@ -1,105 -1,165 +1,271 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import { ajax } from "discourse/lib/ajax";+ import { popupAjaxError } from "discourse/lib/ajax-error";++ const States = {+ initializing: "initializing",+ checking: "checking",+ valid: "valid",+ invalid: "invalid",+ saving: "saving",+ new: "new",+ existing: "existing",+ unpublishing: "unpublishing",+ unpublished: "unpublished",+ };++ export default class PublishPageModal extends Component {+ @service store;++ @tracked state = States.initializing;+ @tracked reason = null;+ @tracked publishedPage = null;++ constructor() {+ super(...arguments);+ this.store+ .find("published_page", this.args.model.id)+ .then((page) => {+ this.state = States.existing;+ this.publishedPage = page;+ })+ .catch(this.startNew);+ }++ get initializing() {+ return this.state === States.initializing;+ }++ get checking() {+ return this.state === States.checking;+ }++ get valid() {+ return this.state === States.valid;+ }++ get invalid() {+ return this.state === States.invalid;+ }++ get saving() {+ return this.state === States.saving;+ }++ get new() {+ return this.state === States.new;+ }++ get existing() {+ return this.state === States.existing;+ }++ get unpublishing() {+ return this.state === States.unpublishing;+ }++ get unpublished() {+ return this.state === States.unpublished;+ }++ get disabled() {+ return this.state !== States.valid;+ }++ get showUrl() {+ return (+ this.state === States.valid ||+ this.state === States.saving ||+ this.state === States.existing+ );+ }++ get showUnpublish() {+ return this.state === States.existing || this.state === States.unpublishing;+ }++ @action+ startCheckSlug() {+ if (this.state === States.existing) {+ return;+ }++ this.state = States.checking;+ }++ @action+ checkSlug() {+ if (this.state === States.existing) {+ return;+ }+ return ajax("/pub/check-slug", {+ data: { slug: this.publishedPage.slug },+ }).then((result) => {+ if (result.valid_slug) {+ this.state = States.valid;+ } else {+ this.state = States.invalid;+ this.reason = result.reason;+ }+ });+ }++ @action+ unpublish() {+ this.state = States.unpublishing;+ return this.publishedPage+ .destroyRecord()+ .then(() => {+ this.state = States.unpublished;+ this.args.model.set("publishedPage", null);+ })+ .catch((result) => {+ this.state = States.existing;+ popupAjaxError(result);+ });+ }++ @action+ publish() {+ this.state = States.saving;++ return this.publishedPage+ .update(this.publishedPage.getProperties("slug", "public"))+ .then(() => {+ this.state = States.existing;+ this.args.model.set("publishedPage", this.publishedPage);+ })+ .catch((errResult) => {+ popupAjaxError(errResult);+ this.state = States.existing;+ });+ }++ @action+ startNew() {+ this.state = States.new;+ this.publishedPage = this.store.createRecord(+ "published_page",+ this.args.model.getProperties("id", "slug", "public")+ );+ this.checkSlug();+ }++ @action+ onChangePublic(event) {+ this.publishedPage.set("public", event.target.checked);++ if (this.showUnpublish) {+ this.publish();+ }+ }+ }+++<DModal+ @closeModal={{@closeModal}}+ @title={{i18n "topic.publish_page.title"}}+ class="publish-page-modal"+>+ <:body>+ {{#if this.unpublished}}+ <p>{{i18n "topic.publish_page.unpublished"}}</p>+ {{else}}+ <ConditionalLoadingSpinner @condition={{this.initializing}}>+ <p class="publish-description">{{i18n+ "topic.publish_page.description"+ }}</p>++ <form>+ <div class="controls">+ <label>{{i18n "topic.publish_page.slug"}}</label>+ <TextField+ @value={{this.publishedPage.slug}}+ @onChange={{this.checkSlug}}+ @onChangeImmediate={{this.startCheckSlug}}+ @disabled={{this.existing}}+ class="publish-slug"+ />+ </div>++ <div class="controls">+ <label>{{i18n "topic.publish_page.public"}}</label>++ <p class="description">+ <Input+ @type="checkbox"+ @checked={{readonly this.publishedPage.public}}+ {{on "click" this.onChangePublic}}+ />+ {{i18n "topic.publish_page.public_description"}}+ </p>+ </div>+ </form>++ <div class="publish-url">+ <ConditionalLoadingSpinner @condition={{this.checking}} />++ {{#if this.existing}}+ <div class="current-url">+ {{i18n "topic.publish_page.publish_url"}}+ <div>+ <a+ href={{this.publishedPage.url}}+ target="_blank"+ rel="noopener noreferrer"+ >{{this.publishedPage.url}}</a>+ </div>+ </div>+ {{else}}+ {{#if this.showUrl}}+ <div class="valid-slug">+ {{i18n "topic.publish_page.preview_url"}}+ <div class="example-url">{{this.publishedPage.url}}</div>+ </div>+ {{/if}}++ {{#if this.invalid}}+ {{i18n "topic.publish_page.invalid_slug"}}+ <span class="invalid-slug">{{this.reason}}.</span>+ {{/if}}+ {{/if}}++ </div>+ </ConditionalLoadingSpinner>+ {{/if}}+ </:body>+ <:footer>+ {{#if this.showUnpublish}}+ <DButton+ @label="topic.publish_page.unpublish"+ @icon="trash-can"+ @isLoading={{this.unpublishing}}+ @action={{this.unpublish}}+ class="btn-danger"+ />++ <DButton+ @icon="xmark"+ @label="close"+ @action={{@closeModal}}+ class="close-publish-page"+ />+ {{else if this.unpublished}}+ <DButton+ @label="topic.publish_page.publishing_settings"+ @action={{this.startNew}}+ />+ {{else}}+ <DButton+ @label="topic.publish_page.publish"+ @icon="file"+ @disabled={{this.disabled}}+ @isLoading={{this.saving}}+ @action={{this.publish}}+ class="btn-primary publish-page"+ />+ {{/if}}+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/raw-email.gjsindex 23e5b867a54,b3032cb1c8f..dc19e1413a4--- a/app/assets/javascripts/discourse/app/components/modal/raw-email.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/raw-email.gjs@@@ -1,50 -1,41 +1,92 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import Post from "discourse/models/post";++ export default class RawEmailComponent extends Component {+ @tracked rawEmail = this.args.model.rawEmail || "";+ @tracked textPart = "";+ @tracked htmlPart = "";+ @tracked tab = "raw";++ constructor() {+ super(...arguments);+ if (this.args.model.id) {+ this.loadRawEmail(this.args.model.id);+ }+ }++ @action+ async loadRawEmail(postId) {+ const result = await Post.loadRawEmail(postId);+ this.rawEmail = result.raw_email;+ this.textPart = result.text_part;+ this.htmlPart = result.html_part;+ }++ @action+ displayRaw() {+ this.tab = "raw";+ }++ @action+ displayTextPart() {+ this.tab = "text_part";+ }++ @action+ displayHtmlPart() {+ this.tab = "html_part";+ }+ }+++<DModal+ @title={{i18n "raw_email.title"}}+ class="incoming-email-modal"+ @closeModal={{@closeModal}}+>+ <:body>+ <div class="incoming-email-tabs">+ <DButton+ @action={{this.displayRaw}}+ @label="post.raw_email.displays.raw.button"+ @title="post.raw_email.displays.raw.title"+ class={{if (eq this.tab "raw") "active"}}+ />++ {{#if this.textPart}}+ <DButton+ @action={{this.displayTextPart}}+ @label="post.raw_email.displays.text_part.button"+ @title="post.raw_email.displays.text_part.title"+ class={{if (eq this.tab "text_part") "active"}}+ />+ {{/if}}++ {{#if this.htmlPart}}+ <DButton+ @action={{this.displayHtmlPart}}+ @label="post.raw_email.displays.html_part.button"+ @title="post.raw_email.displays.html_part.title"+ class={{if (eq this.tab "html_part") "active"}}+ />+ {{/if}}+ </div>++ <div class="incoming-email-content">+ {{#if (eq this.tab "raw")}}+ {{#if this.rawEmail}}+ <Textarea @value={{this.rawEmail}} />+ {{else}}+ {{i18n "raw_email.not_available"}}+ {{/if}}+ {{/if}}+ {{#if (eq this.tab "text_part")}}+ <Textarea @value={{this.textPart}} />+ {{/if}}+ {{#if (eq this.tab "html_part")}}+ <IframedHtml @html={{this.htmlPart}} class="incoming-email-html-part" />+ {{/if}}+ </div>+ </:body>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/reject-reason-reviewable.gjsindex b5eaa52ab6b,2e76ca2d6f5..d7200bc3810--- a/app/assets/javascripts/discourse/app/components/modal/reject-reason-reviewable.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/reject-reason-reviewable.gjs@@@ -1,30 -1,17 +1,48 @@@+ import Component from "@glimmer/component";+ import { action } from "@ember/object";++ export default class RejectReasonReviewableModal extends Component {+ rejectReason;+ sendEmail = false;++ @action+ async perform() {+ this.args.model.reviewable.setProperties({+ rejectReason: this.rejectReason,+ sendEmail: this.sendEmail,+ });+ this.args.closeModal();+ await this.args.model.performConfirmed(this.args.model.action);+ }+ }+++<DModal+ @bodyClass="reject-reason-reviewable-modal__explain-reviewable"+ @closeModal={{@closeModal}}+ @title={{i18n "review.reject_reason.title"}}+ class="reject-reason-reviewable-modal"+>+ <:body>+ <Textarea @value={{this.rejectReason}} />+ <div class="control-group">+ <label>+ <Input+ @type="checkbox"+ class="reject-reason-reviewable-modal__send_email--inline"+ @checked={{this.sendEmail}}+ />+ {{i18n "review.reject_reason.send_email"}}+ </label>+ </div>+ </:body>++ <:footer>+ <DButton+ @icon="trash-can"+ @action={{this.perform}}+ @label="admin.user.delete"+ class="btn-danger"+ />+ <DButton @action={{@closeModal}} @label="cancel" class="cancel" />+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/reorder-categories.gjsindex b4c4c706cdd,010e3d93a9e..a12060ca593--- a/app/assets/javascripts/discourse/app/components/modal/reorder-categories.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/reorder-categories.gjs@@@ -1,64 -1,178 +1,243 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import { ajax } from "discourse/lib/ajax";+ import { popupAjaxError } from "discourse/lib/ajax-error";++ class Entry {+ @tracked position;++ constructor({ position, depth, category, descendantCount }) {+ this.position = position;+ this.depth = depth;+ this.category = category;+ this.descendantCount = descendantCount;+ }+ }++ export default class ReorderCategories extends Component {+ @service site;++ @tracked changed = false;+ @tracked entries = this.reorder();+ @tracked highlightedCategoryId = null;++ get sortedEntries() {+ return this.entries.sortBy("position");+ }++ reorder(from) {+ from ??= this.site.categories.map((category) => ({+ category,+ position: category.position,+ }));++ return this.createEntries([...from.sortBy("position")]);+ }++ /**+ * 1. Make sure all categories have unique position numbers.+ * 2. Place sub-categories after their parent categories while maintaining+ * the same relative order.+ *+ * e.g.+ * parent/c2/c1 parent+ * parent/c1 parent/c1+ * parent => parent/c2+ * other parent/c2/c1+ * parent/c2 other+ **/+ createEntries(from, position = 0, categoryId = null, depth = 0) {+ let result = [];++ for (const entry of from) {+ if (+ (categoryId === null && !entry.category.parent_category_id) ||+ entry.category.parent_category_id === categoryId+ ) {+ const descendants = this.createEntries(+ from,+ position + result.length + 1,+ entry.category.id,+ depth + 1+ );++ result = [+ ...result,+ new Entry({+ position: position + result.length,+ depth,+ category: entry.category,+ descendantCount: descendants.length,+ }),+ ...descendants,+ ];+ }+ }++ return result;+ }++ @action+ move(entry, delta) {+ let targetPosition = entry.position + delta;++ // Adjust target position for sub-categories+ if (delta > 0) {+ // Moving down (position gets larger)+ if (entry.descendantCount) {+ // This category has subcategories, adjust targetPosition to account for them+ if (entry.descendantCount >= delta) {+ // Only apply offset if target position is occupied by a subcategory+ // Seems weird but fixes a UX quirk+ targetPosition += entry.descendantCount;+ }+ }+ } else {+ // Moving up (position gets smaller)+ const ancestors = this.sortedEntries[targetPosition]?.category?.ancestors;+ if (ancestors) {+ // Target category is a subcategory, adjust targetPosition to account for ancestors+ const highestAncestorEntry = this.sortedEntries.findBy(+ "category.id",+ ancestors[0].id+ );+ targetPosition = highestAncestorEntry.position;+ }+ }++ // Adjust target position for range bounds+ if (targetPosition >= this.entries.length) {+ // Set to max+ targetPosition = this.entries.length - 1;+ } else if (targetPosition < 0) {+ // Set to min+ targetPosition = 0;+ }++ // Update other categories between current and target position+ for (const e of this.sortedEntries) {+ if (delta > 0) {+ // Moving down (position gets larger)+ if (e.position > entry.position && e.position <= targetPosition) {+ e.position -= 1;+ }+ } else {+ // Moving up (position gets smaller)+ if (e.position < entry.position && e.position >= targetPosition) {+ e.position += 1;+ }+ }+ }++ // Update this category's position to target position+ entry.position = targetPosition;++ this.entries = this.reorder(this.sortedEntries);+ this.changed = true;++ this.toggleHighlight(entry.category.id);+ }++ @action+ toggleHighlight(categoryId) {+ this.highlightedCategoryId = categoryId;+ setTimeout(() => {+ if (this.highlightedCategoryId === categoryId) {+ this.highlightedCategoryId = null;+ }+ }, 3000);+ }++ @action+ change(entry, newPosition) {+ const delta = parseInt(newPosition, 10) - entry.position;+ this.move(entry, delta);+ }++ @action+ async save() {+ const entries = this.reorder(this.sortedEntries);++ const data = {};+ for (const { category, position } of entries) {+ data[category.id] = position;+ }++ try {+ await ajax("/categories/reorder", {+ type: "POST",+ data: { mapping: JSON.stringify(data) },+ });+ window.location.reload();+ } catch (e) {+ popupAjaxError(e);+ }+ }+ }+++<DModal+ @title={{i18n "categories.reorder.title"}}+ @closeModal={{@closeModal}}+ @inline={{@inline}}+ class="reorder-categories"+>+ <:body>+ <table>+ <thead>+ <th>{{i18n "categories.category"}}</th>+ <th class="reorder-categories__header-position">+ {{i18n "categories.reorder.position"}}+ </th>+ </thead>+ <tbody>+ {{#each this.sortedEntries as |entry|}}+ <tr+ data-category-id={{entry.category.id}}+ class={{if+ (eq this.highlightedCategoryId entry.category.id)+ "highlighted"+ }}+ >+ <td>+ <div class={{concat "reorder-categories-depth-" entry.depth}}>+ {{category-badge entry.category allowUncategorized="true"}}+ </div>+ </td>++ <td>+ <div class="reorder-categories-actions">+ <input+ {{on "change" (with-event-value (fn this.change entry))}}+ value={{entry.position}}+ type="number"+ min="0"+ />+ <DButton+ @action={{fn this.move entry -1}}+ @icon="arrow-up"+ class="btn-default no-text move-up"+ />+ <DButton+ @action={{fn this.move entry 1}}+ @icon="arrow-down"+ class="btn-default no-text move-down"+ />+ </div>+ </td>+ </tr>+ {{/each}}+ </tbody>+ </table>+ </:body>++ <:footer>+ <DButton+ @action={{this.save}}+ @label="categories.reorder.save"+ @disabled={{not this.changed}}+ class="btn-primary"+ />+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/request-group-membership-form.gjsindex 8b74d264178,135b4e840cc..1eb402d25ac--- a/app/assets/javascripts/discourse/app/components/modal/request-group-membership-form.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/request-group-membership-form.gjs@@@ -1,32 -1,36 +1,69 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { isEmpty } from "@ember/utils";+ import { popupAjaxError } from "discourse/lib/ajax-error";+ import DiscourseURL from "discourse/lib/url";+ import { i18n } from "discourse-i18n";++ export default class RequestGroupMembershipForm extends Component {+ @tracked loading = false;+ @tracked reason = this.args.model.group.membership_request_template;++ get title() {+ return i18n("groups.membership_request.title", {+ group_name: this.args.model.group.name,+ });+ }++ get disableSubmit() {+ return this.loading || isEmpty(this.reason);+ }++ @action+ async requestMember() {+ this.loading = true;++ try {+ const result = await this.args.model.group.requestMembership(this.reason);+ DiscourseURL.routeTo(result.relative_url);+ } catch (e) {+ popupAjaxError(e);+ } finally {+ this.loading = false;+ }+ }+ }+++<DModal+ @title={{this.title}}+ @closeModal={{@closeModal}}+ @inline={{@inline}}+ class="request-group-membership-form"+>+ <:body>+ <div class="control-group">+ <label>+ {{i18n "groups.membership_request.reason"}}+ </label>++ <ExpandingTextArea+ {{on "input" (with-event-value (fn (mut this.reason)))}}+ value={{this.reason}}+ maxlength="5000"+ />+ </div>+ </:body>++ <:footer>+ <DButton+ @action={{this.requestMember}}+ @label="groups.membership_request.submit"+ @disabled={{this.disableSubmit}}+ class="btn-primary"+ />++ <DModalCancel @close={{@closeModal}} />+ <ConditionalLoadingSpinner @size="small" @condition={{this.loading}} />+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/second-factor-add-security-key.gjsindex e1ce954901e,0db28dd8db6..fcd04c9fef2--- a/app/assets/javascripts/discourse/app/components/modal/second-factor-add-security-key.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/second-factor-add-security-key.gjs@@@ -1,48 -1,157 +1,206 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import {+ bufferToBase64,+ isWebauthnSupported,+ stringToBuffer,+ } from "discourse/lib/webauthn";+ import { MAX_SECOND_FACTOR_NAME_LENGTH } from "discourse/models/user";+ import { i18n } from "discourse-i18n";++ export default class SecondFactorAddSecurityKey extends Component {+ @service capabilities;++ @tracked loading = false;+ @tracked errorMessage = null;+ @tracked securityKeyName;++ maxSecondFactorNameLength = MAX_SECOND_FACTOR_NAME_LENGTH;++ get webauthnUnsupported() {+ return !isWebauthnSupported();+ }++ @action+ securityKeyRequested() {+ let key;+ if (this.capabilities.isIOS && !this.capabilities.isIpadOS) {+ key = "user.second_factor.security_key.iphone_default_name";+ } else if (this.capabilities.isAndroid) {+ key = "user.second_factor.security_key.android_default_name";+ } else {+ key = "user.second_factor.security_key.default_name";+ }+ this.securityKeyName = i18n(key);++ this.loading = true;+ this.args.model.secondFactor+ .requestSecurityKeyChallenge()+ .then((response) => {+ if (response.error) {+ this.errorMessage = response.error;+ return;+ }++ this.errorMessage = isWebauthnSupported()+ ? null+ : i18n("login.security_key_support_missing_error");+ this.loading = false;+ this.challenge = response.challenge;+ this.relayingParty = {+ id: response.rp_id,+ name: response.rp_name,+ };+ this.supported_algorithms = response.supported_algorithms;+ this.user_secure_id = response.user_secure_id;+ this.existing_active_credential_ids =+ response.existing_active_credential_ids;+ })+ .catch((error) => {+ this.args.closeModal();+ this.args.model.onError(error);+ })+ .finally(() => (this.loading = false));+ }++ @action+ registerSecurityKey() {+ if (!this.securityKeyName) {+ this.errorMessage = i18n(+ "user.second_factor.security_key.name_required_error"+ );+ return;+ }+ const publicKeyCredentialCreationOptions = {+ challenge: Uint8Array.from(this.challenge, (c) => c.charCodeAt(0)),+ rp: {+ name: this.relayingParty.name,+ id: this.relayingParty.id,+ },+ user: {+ id: Uint8Array.from(this.user_secure_id, (c) => c.charCodeAt(0)),+ displayName: this.args.model.secondFactor.username_lower,+ name: this.args.model.secondFactor.username_lower,+ },+ pubKeyCredParams: this.supported_algorithms.map((alg) => {+ return { type: "public-key", alg };+ }),+ excludeCredentials: this.existing_active_credential_ids.map(+ (credentialId) => {+ return {+ type: "public-key",+ id: stringToBuffer(atob(credentialId)),+ };+ }+ ),+ timeout: 20000,+ attestation: "none",+ authenticatorSelection: {+ // see https://chromium.googlesource.com/chromium/src/+/master/content/browser/webauth/uv_preferred.md for why+ // default value of preferred is not necessarily what we want, it limits webauthn to only devices that support+ // user verification, which usually requires entering a PIN+ userVerification: "discouraged",+ },+ };++ navigator.credentials+ .create({+ publicKey: publicKeyCredentialCreationOptions,+ })+ .then(+ (credential) => {+ let serverData = {+ id: credential.id,+ rawId: bufferToBase64(credential.rawId),+ type: credential.type,+ attestation: bufferToBase64(credential.response.attestationObject),+ clientData: bufferToBase64(credential.response.clientDataJSON),+ name: this.securityKeyName,+ };++ this.args.model.secondFactor+ .registerSecurityKey(serverData)+ .then((response) => {+ if (response.error) {+ this.errorMessage = response.error;+ return;+ }+ this.args.model.markDirty();+ this.errorMessage = null;+ this.args.closeModal();+ if (this.args.model.enforcedSecondFactor) {+ window.location.reload();+ }+ })+ .catch((error) => this.args.model.onError(error))+ .finally(() => (this.loading = false));+ },+ (err) => {+ if (err.name === "InvalidStateError") {+ this.errorMessage = i18n(+ "user.second_factor.security_key.already_added_error"+ );+ return;+ }+ if (err.name === "NotAllowedError") {+ this.errorMessage = i18n(+ "user.second_factor.security_key.not_allowed_error"+ );+ return;+ }+ this.errorMessage = err.message;+ }+ );+ }+ }+++<DModal+ @closeModal={{@closeModal}}+ @title={{i18n "user.second_factor.security_key.add"}}+ {{did-insert this.securityKeyRequested}}+>+ <:body>+ <ConditionalLoadingSpinner @condition={{this.loading}}>+ {{#if this.errorMessage}}+ <div class="control-group">+ <div class="controls">+ <div class="alert alert-error">{{this.errorMessage}}</div>+ </div>+ </div>+ {{/if}}++ <div class="control-group">+ <div class="controls">+ {{html-safe+ (i18n "user.second_factor.enable_security_key_description")+ }}+ </div>+ </div>++ <div class="control-group">+ <div class="controls">+ <Input+ @value={{this.securityKeyName}}+ id="security-key-name"+ placeholder="security key name"+ maxlength={{this.maxSecondFactorNameLength}}+ />+ </div>+ </div>++ <div class="control-group">+ <div class="controls">+ {{#unless this.webauthnUnsupported}}+ <DButton+ class="btn-primary add-security-key"+ @action={{this.registerSecurityKey}}+ @label="user.second_factor.security_key.register"+ />+ {{/unless}}+ </div>+ </div>+ </ConditionalLoadingSpinner>+ </:body>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/second-factor-add-totp.gjsindex 20564edd1a5,d46ed97be63..793fc5a60fe--- a/app/assets/javascripts/discourse/app/components/modal/second-factor-add-totp.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/second-factor-add-totp.gjs@@@ -1,83 -1,75 +1,159 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import {+ MAX_SECOND_FACTOR_NAME_LENGTH,+ SECOND_FACTOR_METHODS,+ } from "discourse/models/user";+ import { i18n } from "discourse-i18n";++ export default class SecondFactorAddTotp extends Component {+ @tracked loading = false;+ @tracked secondFactorImage;+ @tracked secondFactorKey;+ @tracked showSecondFactorKey = false;+ @tracked errorMessage;+ @tracked secondFactorToken;++ maxSecondFactorNameLength = MAX_SECOND_FACTOR_NAME_LENGTH;+ totpType = SECOND_FACTOR_METHODS.TOTP;++ @action+ totpRequested() {+ this.args.model.secondFactor+ .createSecondFactorTotp()+ .then((response) => {+ if (response.error) {+ this.errorMessage = response.error;+ return;+ }++ this.errorMessage = null;+ this.secondFactorKey = response.key;+ this.secondFactorImage = response.qr;+ })+ .catch((error) => {+ this.args.closeModal();+ this.args.model.onError(error);+ })+ .finally(() => (this.loading = false));+ }++ @action+ enableShowSecondFactorKey(e) {+ e.preventDefault();+ e.stopImmediatePropagation();+ this.showSecondFactorKey = true;+ }++ @action+ enableSecondFactor() {+ if (!this.secondFactorToken || !this.secondFactorName) {+ this.errorMessage = i18n(+ "user.second_factor.totp.name_and_code_required_error"+ );+ return;+ }+ this.loading = true;+ this.args.model.secondFactor+ .enableSecondFactorTotp(this.secondFactorToken, this.secondFactorName)+ .then((response) => {+ if (response.error) {+ this.errorMessage = response.error;+ return;+ }+ this.args.model.markDirty();+ this.errorMessage = null;+ this.args.closeModal();+ if (this.args.model.enforcedSecondFactor) {+ window.location.reload();+ }+ })+ .catch((error) => this.args.model.onError(error))+ .finally(() => (this.loading = false));+ }+ }+++<DModal+ @closeModal={{@closeModal}}+ @title={{i18n "user.second_factor.totp.add"}}+ {{did-insert this.totpRequested}}+>+ <:body>+ <ConditionalLoadingSpinner @condition={{this.loading}}>+ {{#if this.errorMessage}}+ <div class="control-group">+ <div class="controls">+ <div class="alert alert-error">{{this.errorMessage}}</div>+ </div>+ </div>+ {{/if}}++ <div class="control-group">+ <div class="controls">+ {{html-safe (i18n "user.second_factor.enable_description")}}+ </div>+ </div>++ <div class="control-group">+ <div class="controls">+ <div class="qr-code">+ <img src={{html-safe this.secondFactorImage}} />+ </div>+ <p>+ {{#if this.showSecondFactorKey}}+ <div class="second-factor-key">+ {{this.secondFactorKey}}+ </div>+ {{else}}+ <a+ href+ class="show-second-factor-key"+ {{on "click" this.enableShowSecondFactorKey}}+ >{{i18n "user.second_factor.show_key_description"}}</a>+ {{/if}}+ </p>+ </div>+ </div>++ <div class="control-group">+ <label class="control-label input-prepend">{{i18n+ "user.second_factor.name"+ }}</label>+ <div class="controls">+ <input+ {{on "input" (with-event-value (fn (mut this.secondFactorName)))}}+ value={{this.secondFactorName}}+ type="text"+ placeholder={{i18n "user.second_factor.totp.default_name"}}+ maxlength={{this.maxSecondFactorNameLength}}+ id="second-factor-name"+ />+ </div>++ <label class="control-label input-prepend">+ {{i18n "user.second_factor.label"}}+ </label>+ <div class="controls">+ <SecondFactorInput+ {{on "input" (with-event-value (fn (mut this.secondFactorToken)))}}+ @secondFactorMethod={{this.totpType}}+ value={{this.secondFactorToken}}+ placeholder="123456"+ id="second-factor-token"+ />+ </div>+ </div>++ <div class="control-group">+ <div class="controls">+ <DButton+ class="btn-primary add-totp"+ @action={{this.enableSecondFactor}}+ @label="enable"+ />+ </div>+ </div>+ </ConditionalLoadingSpinner>+ </:body>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/second-factor-backup-edit.gjsindex a597e5ebe02,91d9b0c224a..3983d71f69e--- a/app/assets/javascripts/discourse/app/components/modal/second-factor-backup-edit.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/second-factor-backup-edit.gjs@@@ -1,62 -1,65 +1,128 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { debounce } from "discourse/lib/decorators";+ import { SECOND_FACTOR_METHODS } from "discourse/models/user";+ import { i18n } from "discourse-i18n";++ export default class SecondFactorBackupEdit extends Component {+ @tracked loading = false;+ @tracked errorMessage;+ @tracked successMessage;+ @tracked+ backupEnabled = this.args.model.secondFactor.second_factor_backup_enabled;+ @tracked+ remainingCodes =+ this.args.model.secondFactor.second_factor_remaining_backup_codes;+ @tracked backupCodes;+ @tracked secondFactorMethod = SECOND_FACTOR_METHODS.TOTP;++ @action+ copyBackupCode(successful) {+ if (successful) {+ this.successMessage = i18n(+ "user.second_factor_backup.copied_to_clipboard"+ );+ } else {+ this.errorMessage = i18n(+ "user.second_factor_backup.copy_to_clipboard_error"+ );+ }+ this._hideCopyMessage();+ }++ @action+ generateSecondFactorCodes() {+ this.loading = true;+ this.args.model.secondFactor+ .generateSecondFactorCodes()+ .then((response) => {+ if (response.error) {+ this.errorMessage = response.error;+ return;+ }++ this.args.model.markDirty();+ this.errorMessage = null;+ this.backupCodes = response.backup_codes;+ this.args.model.setBackupEnabled(true);+ this.backupEnabled = true;+ this.remainingCodes = response.backup_codes.length;+ this.args.model.setCodesRemaining(this.remainingCodes);+ })+ .catch((error) => {+ this.args.closeModal();+ this.args.model.onError(error);+ })+ .finally(() => (this.loading = false));+ }++ @debounce(2000)+ _hideCopyMessage() {+ this.successMessage = null;+ this.errorMessage = null;+ }+ }+++<DModal+ @title={{i18n "user.second_factor_backup.title"}}+ @closeModal={{@closeModal}}+ class="second-factor-backup-edit-modal"+>+ <:body>+ {{#if this.successMessage}}+ <div class="alert alert-success">+ {{this.successMessage}}+ </div>+ {{/if}}++ {{#if this.errorMessage}}+ <div class="alert alert-error">+ {{this.errorMessage}}+ </div>+ {{/if}}++ <ConditionalLoadingSection @isLoading={{this.loading}}>+ {{#if this.backupCodes}}+ <h3>{{i18n "user.second_factor_backup.codes.title"}}</h3>+ <p>{{i18n "user.second_factor_backup.codes.description"}}</p>+ <BackupCodes+ @copyBackupCode={{this.copyBackupCode}}+ @backupCodes={{this.backupCodes}}+ />+ {{/if}}+ </ConditionalLoadingSection>++ {{#if this.backupEnabled}}+ {{html-safe+ (i18n+ "user.second_factor_backup.remaining_codes" count=this.remainingCodes+ )+ }}+ {{else}}+ {{html-safe (i18n "user.second_factor_backup.not_enabled")}}+ {{/if}}+ </:body>+ <:footer>+ <div class="actions">+ {{#if this.backupEnabled}}+ <DButton+ class="btn-primary"+ @icon="arrow-rotate-right"+ @action={{this.generateSecondFactorCodes}}+ @type="submit"+ @isLoading={{this.loading}}+ @label="user.second_factor_backup.regenerate"+ />+ {{else}}+ <DButton+ class="btn-primary"+ @action={{this.generateSecondFactorCodes}}+ @type="submit"+ @disabled={{this.loading}}+ @label="user.second_factor_backup.enable"+ />+ {{/if}}+ </div>+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/second-factor-edit-security-key.gjsindex 6aa9e14a7bf,e806608433d..edb7f991dbe--- a/app/assets/javascripts/discourse/app/components/modal/second-factor-edit-security-key.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/second-factor-edit-security-key.gjs@@@ -1,28 -1,34 +1,63 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { MAX_SECOND_FACTOR_NAME_LENGTH } from "discourse/models/user";++ export default class SecondFactorEditSecurityKey extends Component {+ @tracked loading = false;++ maxSecondFactorNameLength = MAX_SECOND_FACTOR_NAME_LENGTH;++ @action+ editSecurityKey() {+ this.loading = true;+ this.args.model.user+ .updateSecurityKey(+ this.args.model.securityKey.id,+ this.args.model.securityKey.name,+ false+ )+ .then((response) => {+ if (response.error) {+ return;+ }+ this.args.model.markDirty();+ })+ .catch((error) => {+ this.args.model.onError(error);+ })+ .finally(() => {+ this.loading = false;+ this.args.closeModal();+ });+ }+ }+++<DModal+ @title={{i18n "user.second_factor.security_key.edit"}}+ @closeModal={{@closeModal}}+ @tagName="form"+>+ <:body>+ <div class="input-group">+ <label for="security-key-name">{{i18n+ "user.second_factor.security_key.edit_description"+ }}</label>+ <Input+ name="security-key-name"+ id="security-key-name"+ maxlength={{this.maxSecondFactorNameLength}}+ @type="text"+ @value={{@model.securityKey.name}}+ />+ </div>+ </:body>+ <:footer>+ <DButton+ @action={{this.editSecurityKey}}+ class="btn-primary"+ @label="user.second_factor.security_key.save"+ @type="submit"+ />+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/second-factor-edit.gjsindex 99038d08162,9d3f2ec4026..4c5fea3e651--- a/app/assets/javascripts/discourse/app/components/modal/second-factor-edit.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/second-factor-edit.gjs@@@ -1,25 -1,36 +1,62 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { MAX_SECOND_FACTOR_NAME_LENGTH } from "discourse/models/user";++ export default class SecondFactorEdit extends Component {+ @tracked loading = false;++ maxSecondFactorNameLength = MAX_SECOND_FACTOR_NAME_LENGTH;++ @action+ editSecondFactor() {+ this.loading = true;+ this.args.model.user+ .updateSecondFactor(+ this.args.model.secondFactor.id,+ this.args.model.secondFactor.name,+ false,+ this.args.model.secondFactor.method+ )+ .then((response) => {+ if (response.error) {+ return;+ }+ this.args.model.markDirty();+ })+ .catch((error) => {+ this.args.closeModal();+ this.args.model.onError(error);+ })+ .finally(() => {+ this.loading = false;+ this.args.closeModal();+ });+ }+ }+++<DModal+ @title={{i18n "user.second_factor.edit_title"}}+ @closeModal={{@closeModal}}+>+ <:body>+ <div class="input-group">+ <label for="authenticator-name">{{i18n+ "user.second_factor.edit_description"+ }}</label>+ <Input+ name="authenticator-name"+ maxlength={{this.maxSecondFactorNameLength}}+ @type="text"+ @value={{@model.secondFactor.name}}+ />+ </div>+ </:body>+ <:footer>+ <DButton+ @action={{this.editSecondFactor}}+ class="btn-primary"+ @label="user.second_factor.save"+ />+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/share-topic.gjsindex 680ab57639c,39e0f5fadb8..05077cad5d0--- a/app/assets/javascripts/discourse/app/components/modal/share-topic.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/share-topic.gjs@@@ -1,78 -1,117 +1,196 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { readOnly } from "@ember/object/computed";+ import { getOwner } from "@ember/owner";+ import { service } from "@ember/service";+ import CreateInvite from "discourse/components/modal/create-invite";+ import discourseComputed, { afterRender } from "discourse/lib/decorators";+ import { longDateNoYear } from "discourse/lib/formatter";+ import { getAbsoluteURL } from "discourse/lib/get-url";+ import Sharing from "discourse/lib/sharing";+ import { bufferedProperty } from "discourse/mixins/buffered-content";+ import Category from "discourse/models/category";+ import { i18n } from "discourse-i18n";++ export default class ShareTopicModal extends Component.extend(+ bufferedProperty("invite")+ ) {+ @service modal;++ @readOnly("model.topic") topic;+ @readOnly("model.post") post;+ @readOnly("model.category") category;+ @readOnly("model.allowInvites") allowInvites;++ didInsertElement() {+ this._showRestrictedGroupWarning();+ this._selectUrl();+ super.didInsertElement();+ }++ @afterRender+ _showRestrictedGroupWarning() {+ if (!this.category) {+ return;+ }++ Category.fetchVisibleGroups(this.category.id).then((result) => {+ if (result.groups.length > 0) {+ this.setProperties({+ flash: i18n("topic.share.restricted_groups", {+ count: result.groups.length,+ groupNames: result.groups.join(", "),+ }),+ flashType: "warning",+ });+ }+ });+ }++ @afterRender+ _selectUrl() {+ const input = document.querySelector("input.invite-link");+ if (input && this.site.desktopView) {+ // if the input is auto-focused on mobile, iOS requires two taps of the copy button+ input.setSelectionRange(0, this.url.length);+ input.focus();+ }+ }++ @discourseComputed("post.shareUrl", "topic.shareUrl")+ url(postUrl, topicUrl) {+ if (postUrl) {+ return getAbsoluteURL(postUrl);+ } else if (topicUrl) {+ return getAbsoluteURL(topicUrl);+ }+ }++ @discourseComputed("post.created_at", "post.wiki", "post.last_wiki_edit")+ displayDate(createdAt, wiki, lastWikiEdit) {+ const date = wiki && lastWikiEdit ? lastWikiEdit : createdAt;+ return longDateNoYear(new Date(date));+ }++ @discourseComputed(+ "topic.{isPrivateMessage,invisible,category.read_restricted}"+ )+ sources(topic) {+ const privateContext =+ this.siteSettings.login_required ||+ topic?.isPrivateMessage ||+ topic?.invisible ||+ topic?.category?.read_restricted;++ return Sharing.activeSources(this.siteSettings.share_links, privateContext);+ }++ @action+ share(source) {+ Sharing.shareSource(source, {+ title: this.topic.title,+ url: this.url,+ });+ }++ @action+ inviteUsers() {+ this.modal.show(CreateInvite, {+ model: {+ inviteToTopic: true,+ topics: [this.topic],+ topicId: this.topic.id,+ topicTitle: this.topic.title,+ },+ });+ }++ @action+ replyAsNewTopic() {+ const postStream = this.topic.postStream;+ const postId = this.post?.id || postStream.findPostIdForPostNumber(1);+ const post = postStream.findLoadedPost(postId);+ const topicController = getOwner(this).lookup("controller:topic");+ topicController.actions.replyAsNewTopic.call(topicController, post);+ this.closeModal();+ }+ }+++<DModal+ @title={{if+ this.post+ (i18n "post.share.title" post_number=this.post.post_number)+ (i18n "topic.share.title")+ }}+ @subtitle={{if this.post this.displayDate}}+ @closeModal={{@closeModal}}+ @flash={{this.flash}}+ @flashType={{this.flashType}}+ class="share-topic-modal"+>+ <form>+ <div class="input-group invite-link">+ <label for="invite-link">+ {{if+ this.post+ (i18n "post.share.instructions" post_number=this.post.post_number)+ (i18n "topic.share.instructions")+ }}+ </label>+ <div class="link-share-container">+ <Input+ id="invite-link"+ name="invite-link"+ class="invite-link"+ @value={{this.url}}+ readonly={{true}}+ size="200"+ />+ <CopyButton @selector="input.invite-link" @ariaLabel="share.url" />+ </div>+ </div>++ <div class="link-share-actions">+ <div class="sources">+ {{#each this.sources as |source|}}+ <ShareSource @source={{source}} @action={{this.share}} />+ {{/each}}++ {{#if this.allowInvites}}+ <DButton+ @label="topic.share.invite_users"+ @icon="user-plus"+ @action={{this.inviteUsers}}+ class="btn-default invite"+ />+ {{/if}}++ {{#if this.topic.details.can_reply_as_new_topic}}+ {{#if this.topic.isPrivateMessage}}+ <DButton+ @action={{this.replyAsNewTopic}}+ @icon="plus"+ @ariaLabel="post.reply_as_new_private_message"+ @title="post.reply_as_new_private_message"+ @label="user.new_private_message"+ class="btn-default new-topic"+ />+ {{else}}+ <DButton+ @action={{this.replyAsNewTopic}}+ @icon="plus"+ @ariaLabel="post.reply_as_new_topic"+ @title="post.reply_as_new_topic"+ @label="topic.create"+ class="btn-default new-topic"+ />+ {{/if}}+ {{/if}}+ <PluginOutlet+ @name="share-topic-sources"+ @outletArgs={{hash topic=this.topic post=this.post}}+ />+ </div>+ </div>+ </form>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/sidebar-section-form.gjsindex 912930d72b6,241d74fdc40..8a43df95155--- a/app/assets/javascripts/discourse/app/components/modal/sidebar-section-form.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/sidebar-section-form.gjs@@@ -1,166 -1,526 +1,693 @@@+ import { cached, tracked } from "@glimmer/tracking";+ import { A } from "@ember/array";+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import { isEmpty } from "@ember/utils";+ import { ajax } from "discourse/lib/ajax";+ import { extractError } from "discourse/lib/ajax-error";+ import { SIDEBAR_SECTION, SIDEBAR_URL } from "discourse/lib/constants";+ import { afterRender, bind } from "discourse/lib/decorators";+ import { sanitize } from "discourse/lib/text";+ import { i18n } from "discourse-i18n";++ class Section {+ @tracked title;+ @tracked links;+ @tracked secondaryLinks;++ constructor({+ title,+ links,+ secondaryLinks,+ id,+ publicSection,+ sectionType,+ hideTitleInput,+ }) {+ this.title = title;+ this.public = publicSection;+ this.sectionType = sectionType;+ this.links = links;+ this.secondaryLinks = secondaryLinks;+ this.id = id;+ this.hideTitleInput = hideTitleInput;+ }++ get valid() {+ const allLinks = this.links+ .filter((link) => !link._destroy)+ .concat(this.secondaryLinks?.filter((link) => !link._destroy) || []);+ const validLinks =+ allLinks.length > 0 && allLinks.every((link) => link.valid);+ return this.validTitle && validLinks;+ }++ get validTitle() {+ return !this.#blankTitle && !this.#tooLongTitle;+ }++ get invalidTitleMessage() {+ if (this.title === undefined) {+ return;+ }+ if (this.#blankTitle) {+ return i18n("sidebar.sections.custom.title.validation.blank");+ }+ if (this.#tooLongTitle) {+ return i18n("sidebar.sections.custom.title.validation.maximum", {+ count: SIDEBAR_SECTION.max_title_length,+ });+ }+ }++ get titleCssClass() {+ return this.title === undefined || this.validTitle ? "" : "warning";+ }++ get #blankTitle() {+ return isEmpty(this.title);+ }++ get #tooLongTitle() {+ return this.title.length > SIDEBAR_SECTION.max_title_length;+ }+ }++ class SectionLink {+ @tracked icon;+ @tracked name;+ @tracked value;+ @tracked _destroy;++ constructor({ router, icon, name, value, id, objectId, segment }) {+ this.router = router;+ this.icon = icon || "link";+ this.name = name;+ this.value = value;+ this.id = id;+ this.httpHost = "http://" + window.location.host;+ this.httpsHost = "https://" + window.location.host;+ this.objectId = objectId;+ this.segment = segment;+ }++ get path() {+ return this.value?.replace(this.httpHost, "").replace(this.httpsHost, "");+ }++ get valid() {+ return this.validIcon && this.validName && this.validValue;+ }++ get validIcon() {+ return !this.#blankIcon && !this.#tooLongIcon;+ }++ get validName() {+ return !this.#blankName && !this.#tooLongName;+ }++ get validValue() {+ return !this.#blankValue && !this.#tooLongValue && !this.#invalidValue;+ }++ get invalidIconMessage() {+ if (this.#blankIcon) {+ return i18n("sidebar.sections.custom.links.icon.validation.blank");+ }+ if (this.#tooLongIcon) {+ return i18n("sidebar.sections.custom.links.icon.validation.maximum", {+ count: SIDEBAR_URL.max_icon_length,+ });+ }+ }++ get invalidNameMessage() {+ if (this.name === undefined) {+ return;+ }+ if (this.#blankName) {+ return i18n("sidebar.sections.custom.links.name.validation.blank");+ }+ if (this.#tooLongName) {+ return i18n("sidebar.sections.custom.links.name.validation.maximum", {+ count: SIDEBAR_URL.max_name_length,+ });+ }+ }++ get invalidValueMessage() {+ if (this.value === undefined) {+ return;+ }+ if (this.#blankValue) {+ return i18n("sidebar.sections.custom.links.value.validation.blank");+ }+ if (this.#tooLongValue) {+ return i18n("sidebar.sections.custom.links.value.validation.maximum", {+ count: SIDEBAR_URL.max_value_length,+ });+ }+ if (this.#invalidValue) {+ return i18n("sidebar.sections.custom.links.value.validation.invalid");+ }+ }++ get iconCssClass() {+ return this.icon === undefined || this.validIcon ? "" : "warning";+ }++ get nameCssClass() {+ return this.name === undefined || this.validName ? "" : "warning";+ }++ get valueCssClass() {+ return this.value === undefined || this.validValue ? "" : "warning";+ }++ get isPrimary() {+ return this.segment === "primary";+ }++ get #blankIcon() {+ return isEmpty(this.icon);+ }++ get #tooLongIcon() {+ return this.icon.length > SIDEBAR_URL.max_icon_length;+ }++ get #blankName() {+ return isEmpty(this.name);+ }++ get #tooLongName() {+ return this.name.length > SIDEBAR_URL.max_name_length;+ }++ get #blankValue() {+ return isEmpty(this.value);+ }++ get #tooLongValue() {+ return this.value.length > SIDEBAR_URL.max_value_length;+ }++ get #invalidValue() {+ return this.path && !this.#validLink();+ }++ #validLink() {+ try {+ return new URL(this.value, document.location.origin);+ } catch {+ return false;+ }+ }+ }++ export default class SidebarSectionForm extends Component {+ @service dialog;+ @service router;++ @tracked flash;+ @tracked flashType;++ nextObjectId = 0;++ @cached+ get transformedModel() {+ const section = this.model?.section;++ if (section) {+ return new Section({+ title: section.title,+ publicSection: section.public,+ sectionType: section.section_type,+ links: section.links.reduce((acc, link) => {+ if (link.segment === "primary") {+ this.nextObjectId++;+ acc.push(this.initLink(link));+ }+ return acc;+ }, A()),+ secondaryLinks: section.links.reduce((acc, link) => {+ if (link.segment === "secondary") {+ this.nextObjectId++;+ acc.push(this.initLink(link));+ }+ return acc;+ }, A()),+ id: section.id,+ hideTitleInput: this.model.hideSectionHeader,+ });+ } else {+ return new Section({+ links: A([+ new SectionLink({+ router: this.router,+ objectId: this.nextObjectId,+ segment: "primary",+ }),+ ]),+ });+ }+ }++ initLink(link) {+ return new SectionLink({+ router: this.router,+ icon: link.icon,+ name: link.name,+ value: link.value,+ id: link.id,+ objectId: this.nextObjectId,+ segment: link.segment,+ });+ }++ create() {+ return ajax(`/sidebar_sections`, {+ type: "POST",+ contentType: "application/json",+ dataType: "json",+ data: JSON.stringify({+ title: this.transformedModel.title,+ public: this.transformedModel.public,+ links: this.transformedModel.links.map((link) => {+ return {+ icon: link.icon,+ name: link.name,+ value: link.path,+ };+ }),+ }),+ })+ .then((data) => {+ this.currentUser.set(+ "sidebar_sections",+ this.currentUser.sidebar_sections.concat(data.sidebar_section)+ );+ this.closeModal();+ })+ .catch((e) => {+ this.flash = sanitize(extractError(e));+ this.flashType = "error";+ });+ }++ update() {+ this.wasPublic || this.isPublic+ ? this.#updateWithConfirm()+ : this.#updateCall();+ }++ #updateWithConfirm() {+ return this.dialog.yesNoConfirm({+ message: this.isPublic+ ? i18n("sidebar.sections.custom.update_public_confirm")+ : i18n("sidebar.sections.custom.mark_as_private_confirm"),+ didConfirm: () => {+ return this.#updateCall();+ },+ });+ }++ #updateCall() {+ return ajax(`/sidebar_sections/${this.transformedModel.id}`, {+ type: "PUT",+ contentType: "application/json",+ dataType: "json",+ data: JSON.stringify({+ title: this.transformedModel.title,+ public: this.transformedModel.public,+ links: this.transformedModel.links+ .concat(this.transformedModel?.secondaryLinks || [])+ .map((link) => {+ return {+ id: link.id,+ icon: link.icon,+ name: link.name,+ value: link.path,+ segment: link.segment,+ _destroy: link._destroy,+ };+ }),+ }),+ })+ .then((data) => {+ const newSidebarSections = this.currentUser.sidebar_sections.map(+ (section) => {+ if (section.id === data["sidebar_section"].id) {+ return data["sidebar_section"];+ }+ return section;+ }+ );+ this.currentUser.set("sidebar_sections", newSidebarSections);+ this.closeModal();+ })+ .catch((e) => {+ this.flash = sanitize(extractError(e));+ this.flashType = "error";+ });+ }++ get activeLinks() {+ return this.transformedModel.links.filter((link) => !link._destroy);+ }++ get activeSecondaryLinks() {+ return this.transformedModel.secondaryLinks?.filter(+ (link) => !link._destroy+ );+ }++ get header() {+ return this.transformedModel.id+ ? "sidebar.sections.custom.edit"+ : "sidebar.sections.custom.add";+ }++ get isPublic() {+ return this.transformedModel.public;+ }++ get wasPublic() {+ return this.model?.section?.public;+ }++ @afterRender+ focusNewRowInput(id) {+ document+ .querySelector(`[data-row-id="${id}"] .icon-picker summary`)+ .focus();+ }++ @bind+ setDraggedLink(link) {+ this.draggedLink = link;+ }++ @bind+ reorder(targetLink, above) {+ if (this.draggedLink === targetLink) {+ return;+ }++ if (this.draggedLink.isPrimary) {+ this.transformedModel.links.removeObject(this.draggedLink);+ } else {+ this.transformedModel.secondaryLinks?.removeObject(this.draggedLink);+ }++ if (targetLink.isPrimary) {+ const toPosition = this.transformedModel.links.indexOf(targetLink);+ this.draggedLink.segment = "primary";+ this.transformedModel.links.insertAt(+ above ? toPosition : toPosition + 1,+ this.draggedLink+ );+ } else {+ this.draggedLink.segment = "secondary";+ const toPosition =+ this.transformedModel.secondaryLinks.indexOf(targetLink);+ this.transformedModel.secondaryLinks.insertAt(+ above ? toPosition : toPosition + 1,+ this.draggedLink+ );+ }+ }++ get canDelete() {+ return this.transformedModel.id && !this.transformedModel.sectionType;+ }++ @bind+ deleteLink(link) {+ if (link.id) {+ link._destroy = "1";+ } else {+ if (link.isPrimary) {+ this.transformedModel.links.removeObject(link);+ } else {+ this.transformedModel.secondaryLinks.removeObject(link);+ }+ }+ }++ @action+ addLink() {+ this.nextObjectId = this.nextObjectId + 1;+ this.transformedModel.links.pushObject(+ new SectionLink({+ router: this.router,+ objectId: this.nextObjectId,+ segment: "primary",+ })+ );++ this.focusNewRowInput(this.nextObjectId);+ }++ @action+ addSecondaryLink() {+ this.nextObjectId = this.nextObjectId + 1;+ this.transformedModel.secondaryLinks.pushObject(+ new SectionLink({+ router: this.router,+ objectId: this.nextObjectId,+ segment: "secondary",+ })+ );++ this.focusNewRowInput(this.nextObjectId);+ }++ @action+ resetToDefault() {+ return this.dialog.yesNoConfirm({+ message: i18n("sidebar.sections.custom.reset_confirm"),+ didConfirm: () => {+ return ajax(`/sidebar_sections/reset/${this.transformedModel.id}`, {+ type: "PUT",+ })+ .then((data) => {+ this.currentUser.sidebar_sections.shiftObject();+ this.currentUser.sidebar_sections.unshiftObject(+ data["sidebar_section"]+ );+ this.closeModal();+ })+ .catch((e) => {+ this.flash = sanitize(extractError(e));+ this.flashType = "error";+ });+ },+ didCancel: () => {+ this.closeModal();+ },+ });+ }++ @action+ save() {+ this.transformedModel.id ? this.update() : this.create();+ }++ @action+ delete() {+ return this.dialog.yesNoConfirm({+ message: this.model.section.public+ ? i18n("sidebar.sections.custom.delete_public_confirm")+ : i18n("sidebar.sections.custom.delete_confirm"),+ didConfirm: () => {+ return ajax(`/sidebar_sections/${this.transformedModel.id}`, {+ type: "DELETE",+ })+ .then(() => {+ const newSidebarSections = this.currentUser.sidebar_sections.filter(+ (section) => {+ return section.id !== this.transformedModel.id;+ }+ );++ this.currentUser.set("sidebar_sections", newSidebarSections);+ this.closeModal();+ })+ .catch((e) => {+ this.flash = sanitize(extractError(e));+ this.flashType = "error";+ });+ },+ });+ }+ }+++<DModal+ @closeModal={{@closeModal}}+ @flash={{this.flash}}+ @flashType={{this.flashType}}+ @title={{i18n this.header}}+ class="sidebar-section-form-modal"+>+ <:body>+ <form class="form-horizontal sidebar-section-form">+ {{#unless this.transformedModel.hideTitleInput}}+ <div class="sidebar-section-form__input-wrapper">+ <label for="section-name">+ {{i18n "sidebar.sections.custom.title.label"}}+ </label>++ <Input+ name="section-name"+ @type="text"+ @value={{this.transformedModel.title}}+ class={{this.transformedModel.titleCssClass}}+ id="section-name"+ {{on+ "input"+ (with-event-value (fn (mut this.transformedModel.title)))+ }}+ />++ {{#if this.transformedModel.invalidTitleMessage}}+ <div class="title warning">+ {{this.transformedModel.invalidTitleMessage}}+ </div>+ {{/if}}+ </div>+ {{/unless}}+ <div+ role="table"+ aria-rowcount={{this.activeLinks.length}}+ class="sidebar-section-form__links-wrapper"+ >++ <div class="row-wrapper header" role="row">+ <div+ class="input-group link-icon"+ role="columnheader"+ aria-sort="none"+ >+ <label>{{i18n "sidebar.sections.custom.links.icon.label"}}</label>+ </div>++ <div+ class="input-group link-name"+ role="columnheader"+ aria-sort="none"+ >+ <label>{{i18n "sidebar.sections.custom.links.name.label"}}</label>+ </div>++ <div+ class="input-group link-url"+ role="columnheader"+ aria-sort="none"+ >+ <label>{{i18n "sidebar.sections.custom.links.value.label"}}</label>+ </div>+ </div>++ {{#each this.activeLinks as |link|}}+ <Sidebar::SectionFormLink+ @link={{link}}+ @deleteLink={{this.deleteLink}}+ @reorderCallback={{this.reorder}}+ @setDraggedLinkCallback={{this.setDraggedLink}}+ />+ {{/each}}++ </div>+ <DButton+ @action={{this.addLink}}+ @title="sidebar.sections.custom.links.add"+ @icon="plus"+ @label="sidebar.sections.custom.links.add"+ @ariaLabel="sidebar.sections.custom.links.add"+ class="btn-flat btn-text add-link"+ />++ {{#if this.transformedModel.sectionType}}+ <hr />+ <h3>{{i18n "sidebar.sections.custom.more_menu"}}</h3>+ {{#each this.activeSecondaryLinks as |link|}}+ <Sidebar::SectionFormLink+ @link={{link}}+ @deleteLink={{this.deleteLink}}+ @reorderCallback={{this.reorder}}+ @setDraggedLinkCallback={{this.setDraggedLink}}+ />+ {{/each}}+ <DButton+ @action={{this.addSecondaryLink}}+ @title="sidebar.sections.custom.links.add"+ @icon="plus"+ @label="sidebar.sections.custom.links.add"+ @ariaLabel="sidebar.sections.custom.links.add"+ class="btn-flat btn-text add-link"+ />+ {{/if}}+ </form>+ </:body>+ <:footer>+ <DButton+ @action={{this.save}}+ @label="sidebar.sections.custom.save"+ @ariaLabel="sidebar.sections.custom.save"+ @disabled={{not this.transformedModel.valid}}+ id="save-section"+ class="btn-primary"+ />+ {{#if (and this.currentUser.admin)}}+ <div+ class="mark-public-wrapper+ {{if this.transformedModel.sectionType '-disabled'}}"+ >+ <label class="checkbox-label">+ {{#if this.transformedModel.sectionType}}+ <DTooltip+ @content={{i18n "sidebar.sections.custom.always_public"}}+ class="always-public-tooltip"+ >+ <:trigger>+ {{d-icon "square-check"}}+ <span>{{i18n "sidebar.sections.custom.public"}}</span>+ </:trigger>+ </DTooltip>+ {{else}}+ <Input+ @type="checkbox"+ @checked={{this.transformedModel.public}}+ class="mark-public"+ disabled={{this.transformedModel.sectionType}}+ />+ <span>{{i18n "sidebar.sections.custom.public"}}</span>+ {{/if}}+ </label>+ </div>+ {{/if}}+ {{#if this.canDelete}}+ <DButton+ @icon="trash-can"+ @action={{this.delete}}+ @label="sidebar.sections.custom.delete"+ @ariaLabel="sidebar.sections.custom.delete"+ id="delete-section"+ class="btn-danger delete"+ />+ {{/if}}+ {{#if this.transformedModel.sectionType}}+ <DButton+ @action={{this.resetToDefault}}+ @icon="arrow-rotate-left"+ @title="sidebar.sections.custom.links.reset"+ @label="sidebar.sections.custom.links.reset"+ @ariaLabel="sidebar.sections.custom.links.reset"+ class="btn-flat btn-text reset-link"+ />+ {{/if}}+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/mount-widget.gjsindex d23784b3468,bab26cf9b78..6312a986ff0--- a/app/assets/javascripts/discourse/app/components/mount-widget.gjs+++ b/app/assets/javascripts/discourse/app/components/mount-widget.gjs@@@ -1,8 -1,205 +1,214 @@@+ import ArrayProxy from "@ember/array/proxy";+ import Component from "@ember/component";+ import { cancel, scheduleOnce } from "@ember/runloop";+ import { camelize } from "@ember/string";+ import { diff, patch } from "virtual-dom";+ import DirtyKeys from "discourse/lib/dirty-keys";+ import { getRegister } from "discourse/lib/get-owner";+ import { WidgetClickHook } from "discourse/widgets/hooks";+ import { queryRegistry, traverseCustomWidgets } from "discourse/widgets/widget";++ let _cleanCallbacks = {};++ export function addWidgetCleanCallback(widgetName, fn) {+ _cleanCallbacks[widgetName] = _cleanCallbacks[widgetName] || [];+ _cleanCallbacks[widgetName].push(fn);+ }++ export function removeWidgetCleanCallback(widgetName, fn) {+ const callbacks = _cleanCallbacks[widgetName];+ if (!callbacks) {+ return;+ }++ const index = callbacks.indexOf(fn);+ if (index === -1) {+ return;+ }++ callbacks.splice(index, 1);+ }++ export function resetWidgetCleanCallbacks() {+ _cleanCallbacks = {};+ }++ export default class MountWidget extends Component {+ dirtyKeys = null;+ _tree = null;+ _rootNode = null;+ _timeout = null;+ _widgetClass = null;+ _renderCallback = null;+ _childEvents = null;+ _dispatched = null;++ init() {+ super.init(...arguments);+ const name = this.widget;++ if (name === "post-cooked") {+ throw [+ "Cannot use <MountWidget /> with `post-cooked`.",+ "It's a special-case that needs to be wrapped in another widget.",+ "For example:",+ " createWidget('test-widget', {",+ " html(attrs) {",+ " return [",+ " new PostCooked(attrs, new DecoratorHelper(this), this.currentUser),",+ " ];",+ " },",+ " });",+ ].join("\n");+ }++ this.register = getRegister(this);++ this._widgetClass =+ queryRegistry(name) || this.register.lookupFactory(`widget:${name}`);++ if (this._widgetClass?.class) {+ this._widgetClass = this._widgetClass.class;+ }++ if (!this._widgetClass) {+ // eslint-disable-next-line no-console+ console.error(`Error: Could not find widget: ${name}`);+ }++ this._childEvents = [];+ this._connected = [];+ this._childComponents = ArrayProxy.create({ content: [] });+ this._dispatched = [];+ this.dirtyKeys = new DirtyKeys(name);+ }++ didInsertElement() {+ super.didInsertElement(...arguments);+ WidgetClickHook.setupDocumentCallback();++ this._rootNode = document.createElement("div");+ this.element.appendChild(this._rootNode);+ this._timeout = scheduleOnce("render", this, this.rerenderWidget);+ }++ willClearRender() {+ super.willClearRender(...arguments);+ const callbacks = _cleanCallbacks[this.widget];+ if (callbacks) {+ callbacks.forEach((cb) => cb(this._tree));+ }++ this._connected.forEach((v) => v.destroy());+ this._connected.length = 0;++ traverseCustomWidgets(this._tree, (w) => w.destroy());+ this._rootNode = patch(this._rootNode, diff(this._tree, null));+ this._tree = null;+ }++ willDestroyElement() {+ super.willDestroyElement(...arguments);+ this._dispatched.forEach((evt) => {+ const [eventName, caller] = evt;+ this.appEvents.off(eventName, this, caller);+ });+ cancel(this._timeout);+ }++ afterRender() {}+ beforePatch() {}+ afterPatch() {}++ eventDispatched(eventName, key, refreshArg) {+ key = typeof key === "function" ? key(refreshArg) : key;+ const onRefresh = camelize(eventName.replace(/:/, "-"));+ this.dirtyKeys.keyDirty(key, { onRefresh, refreshArg });+ this.queueRerender();+ }++ dispatch(eventName, key) {+ this._childEvents.push(eventName);++ const caller = (refreshArg) =>+ this.eventDispatched(eventName, key, refreshArg);+ this._dispatched.push([eventName, caller]);+ this.appEvents.on(eventName, this, caller);+ }++ queueRerender(callback) {+ if (callback && !this._renderCallback) {+ this._renderCallback = callback;+ }++ scheduleOnce("render", this, this.rerenderWidget);+ }++ buildArgs() {}++ rerenderWidget() {+ cancel(this._timeout);++ if (this._rootNode) {+ if (!this._widgetClass) {+ return;+ }++ const t0 = Date.now();+ const args = this.args || this.buildArgs();+ const opts = {+ model: this.model,+ dirtyKeys: this.dirtyKeys,+ };+ const newTree = new this._widgetClass(args, this.register, opts);++ newTree._rerenderable = this;+ newTree._emberView = this;+ const patches = diff(this._tree || this._rootNode, newTree);++ traverseCustomWidgets(this._tree, (w) => w.willRerenderWidget());++ this.beforePatch();+ this._rootNode = patch(this._rootNode, patches);+ this.afterPatch();++ this._tree = newTree;++ traverseCustomWidgets(newTree, (w) => w.didRenderWidget());++ if (this._renderCallback) {+ this._renderCallback();+ this._renderCallback = null;+ }+ this.afterRender();+ this.dirtyKeys.renderedKey("*");++ if (this.profileWidget) {+ // eslint-disable-next-line no-console+ console.log(Date.now() - t0);+ }+ }+ }++ mountChildComponent(info) {+ this._childComponents.pushObject(info);+ }++ unmountChildComponent(info) {+ this._childComponents.removeObject(info);+ }++ didUpdateAttrs() {+ super.didUpdateAttrs(...arguments);+ this.queueRerender();+ }+ }+++{{#each this._childComponents as |info|}}+ {{#in-element info.element insertBefore=null}}+ <info.component+ @data={{info.data}}+ @setWrapperElementAttrs={{info.setWrapperElementAttrs}}+ />+ {{/in-element}}+{{/each}}diff --cc app/assets/javascripts/discourse/app/components/navigation-item.gjsindex 76513101d68,9d2d70cfe14..3ad6829f833--- a/app/assets/javascripts/discourse/app/components/navigation-item.gjs+++ b/app/assets/javascripts/discourse/app/components/navigation-item.gjs@@@ -1,10 -1,99 +1,110 @@@+ import { tracked } from "@glimmer/tracking";+ import Component from "@ember/component";+ import { dependentKeyCompat } from "@ember/object/compat";+ import {+ attributeBindings,+ classNameBindings,+ tagName,+ } from "@ember-decorators/component";+ import discourseComputed from "discourse/lib/decorators";+ import { filterTypeForMode } from "discourse/lib/filter-mode";++ @tagName("li")+ @classNameBindings(+ "active",+ "content.hasIcon:has-icon",+ "content.classNames",+ "isHidden:hidden",+ "content.name"+ )+ @attributeBindings("content.title:title")+ export default class NavigationItem extends Component {+ @tracked filterMode;++ hidden = false;+ activeClass = "";+ hrefLink = null;++ @dependentKeyCompat+ get filterType() {+ return filterTypeForMode(this.filterMode);+ }++ @discourseComputed("content.filterType", "filterType", "content.active")+ active(contentFilterType, filterType, active) {+ if (active !== undefined) {+ return active;+ }+ return contentFilterType === filterType;+ }++ @discourseComputed("content.count", "content.name")+ isHidden(count, name) {+ return (+ !this.active &&+ this.currentUser &&+ !this.currentUser.new_new_view_enabled &&+ this.currentUser.trust_level > 0 &&+ (name === "new" || name === "unread") &&+ count < 1+ );+ }++ didReceiveAttrs() {+ super.didReceiveAttrs(...arguments);+ const content = this.content;++ let [href, searchParams] = content.get("href")?.split("?") || [];++ let urlSearchParams = new URLSearchParams(searchParams);+ let addParamsEvenIfEmpty = false;++ // Include the category id if the option is present+ if (content.get("includeCategoryId")) {+ let categoryId = this.get("content.category.id");+ if (categoryId) {+ urlSearchParams.set("category_id", categoryId);+ }+ }++ // To reset the "filter" sticky param, at least one query param is needed.+ // If no query param is present, add an empty one to ensure a ? is+ // appended to the URL.+ if (content.currentRouteQueryParams) {+ if (content.currentRouteQueryParams.filter) {+ addParamsEvenIfEmpty = true;+ }++ if (content.currentRouteQueryParams.f) {+ urlSearchParams.set("f", content.currentRouteQueryParams.f);+ }+ }++ if (+ this.siteSettings.desktop_category_page_style ===+ "categories_and_latest_topics_created_date" &&+ urlSearchParams.get("order") == null+ ) {+ urlSearchParams.set("order", "created");+ }++ const queryString = urlSearchParams.toString();+ if (addParamsEvenIfEmpty || (queryString && href)) {+ href = (href || "") + `?${queryString}`;+ }+ this.set("hrefLink", href);++ this.set("activeClass", this.active ? "active" : "");+ }+ }+++<a+ href={{this.hrefLink}}+ class={{this.activeClass}}+ aria-current={{if this.activeClass "page"}}+>+ {{#if this.hasIcon}}+ <span class={{this.content.name}}></span>+ {{/if}}+ {{this.content.displayName}}+</a>diff --cc app/assets/javascripts/discourse/app/components/parent-category-row.gjsindex 14a8e7f5096,6f84f8eaddd..fa450c9c8a1--- a/app/assets/javascripts/discourse/app/components/parent-category-row.gjs+++ b/app/assets/javascripts/discourse/app/components/parent-category-row.gjs@@@ -1,219 -1,3 +1,223 @@@+ import CategoryListItem from "discourse/components/category-list-item";++ export default class ParentCategoryRow extends CategoryListItem {}+++{{#unless this.isHidden}}+ <PluginOutlet+ @name="category-list-above-each-category"+ @outletArgs={{hash category=this.category}}+ />++ {{#if this.site.mobileView}}+ <PluginOutlet+ @name="category-list-before-category-mobile"+ @outletArgs={{hash+ category=this.category+ listType=this.listType+ isMuted=this.isMuted+ }}+ />+ <div+ data-category-id={{this.category.id}}+ data-notification-level={{this.category.notificationLevelString}}+ style={{border-color this.category.color}}+ class="category-list-item category {{if this.isMuted 'muted'}}"+ >+ <table class="topic-list">+ <tbody>+ <tr>+ <th class="main-link">+ <CategoryTitleLink @category={{this.category}} />+ </th>+ <PluginOutlet+ @name="category-list-after-title-mobile-section"+ @outletArgs={{hash category=this.category}}+ />+ </tr>+ {{#if this.category.description_excerpt}}+ <tr class="category-description">+ <td colspan="3">+ {{html-safe this.category.description_excerpt}}+ </td>+ </tr>+ {{/if}}+ {{#unless this.isMuted}}+ {{#if this.showTopics}}+ {{#each this.category.featuredTopics as |t|}}+ <MobileCategoryTopic @topic={{t}} />+ {{/each}}+ {{/if}}+ {{/unless}}+ {{#if this.category.isGrandParent}}+ {{#each this.category.subcategories as |subcategory|}}+ <SubCategoryRow+ @category={{subcategory}}+ @listType={{this.listType}}+ />+ {{/each}}+ {{else if this.category.subcategories}}+ <tr class="subcategories-list">+ <td>+ <div class="subcategories">+ {{#each this.category.subcategories as |subcategory|}}+ <SubCategoryItem+ @category={{subcategory}}+ @listType={{this.listType}}+ />+ {{/each}}+ </div>+ </td>+ </tr>+ {{/if}}+ </tbody>+ </table>+ <footer class="clearfix category-topics-count">+ <div class="category-stat">+ <a href={{this.category.url}}>+ {{html-safe this.category.statTotal}}+ </a>+ </div>+ {{#unless this.category.pickAll}}+ <div class="category-stat">+ <a href={{this.category.url}}>+ {{html-safe this.category.stat}}+ </a>+ </div>+ {{/unless}}+ </footer>+ </div>+ {{else}}++ <tr+ data-category-id={{this.category.id}}+ data-notification-level={{this.category.notificationLevelString}}+ class="{{if+ this.category.description_excerpt+ 'has-description'+ 'no-description'+ }}+ {{this.applyValueTransformer+ 'parent-category-row-class'+ (array)+ (hash category=this.category)+ }}+ {{if this.category.uploaded_logo.url 'has-logo' 'no-logo'}}"+ >++ <PluginOutlet+ @name="category-list-before-category-section"+ @outletArgs={{hash category=this.category listType=this.listType}}+ />++ <td+ class="category {{if this.isMuted 'muted'}}"+ style={{category-color-variable this.category.color}}+ >+ <CategoryTitleLink @category={{this.category}} />+ <PluginOutlet+ @name="below-category-title-link"+ @connectorTagName="div"+ @outletArgs={{hash category=this.category}}+ />++ {{#if this.category.description_excerpt}}+ <div class="category-description">+ {{dir-span this.category.description_excerpt htmlSafe="true"}}+ </div>+ {{/if}}++ {{#if this.category.isGrandParent}}+ <table class="category-list subcategories-with-subcategories">+ <tbody>+ {{#each this.category.subcategories as |subcategory|}}+ <SubCategoryRow+ @category={{subcategory}}+ @listType={{this.listType}}+ />+ {{/each}}+ {{#if (gt this.category.unloadedSubcategoryCount 0)}}+ {{i18n+ "category_row.subcategory_count"+ count=this.category.unloadedSubcategoryCount+ }}+ {{/if}}+ </tbody>+ </table>+ {{else if this.category.subcategories}}+ <div class="subcategories">+ {{#each this.category.subcategories as |subcategory|}}+ <SubCategoryItem+ @category={{subcategory}}+ @listType={{this.listType}}+ />+ {{/each}}+ {{#if (gt this.category.unloadedSubcategoryCount 0)}}+ <div class="subcategories__more-subcategories">+ <LinkTo+ @route="discovery.subcategories"+ @model={{this.slugPath}}+ >+ {{i18n+ "category_row.subcategory_count"+ count=this.category.unloadedSubcategoryCount+ }}+ </LinkTo>+ </div>+ {{/if}}+ </div>+ {{/if}}+ </td>++ <PluginOutlet+ @name="category-list-before-topics-section"+ @outletArgs={{hash category=this.category}}+ />++ <PluginOutlet+ @name="category-list-topics-wrapper"+ @outletArgs={{hash category=this.category}}+ >+ <td class="topics">+ <div title={{this.category.statTitle}}>{{html-safe+ this.category.stat+ }}</div>+ <CategoryUnread+ @category={{this.category}}+ @tagName="div"+ @unreadTopicsCount={{this.unreadTopicsCount}}+ @newTopicsCount={{this.newTopicsCount}}+ class="unread-new"+ />+ </td>+ </PluginOutlet>++ <PluginOutlet+ @name="category-list-after-topics-section"+ @outletArgs={{hash category=this.category}}+ />++ <PluginOutlet+ @name="category-list-latest-wrapper"+ @outletArgs={{hash category=this.category showTopics=this.showTopics}}+ >+ {{#unless this.isMuted}}+ {{#if this.showTopics}}+ <td class="latest">+ {{#each this.category.featuredTopics as |t|}}+ {{#if this.site.useGlimmerTopicList}}+ <TopicList::FeaturedTopic @topic={{t}} />+ {{else}}+ <FeaturedTopic @topic={{t}} />+ {{/if}}+ {{/each}}+ </td>+ <PluginOutlet+ @name="category-list-after-latest-section"+ @outletArgs={{hash category=this.category}}+ />+ {{/if}}+ {{/unless}}+ </PluginOutlet>+ </tr>+ {{/if}}+{{/unless}}diff --cc app/assets/javascripts/discourse/app/components/pick-files-button.gjsindex f35485a4448,b0e66d83297..25c0c7f20c8--- a/app/assets/javascripts/discourse/app/components/pick-files-button.gjs+++ b/app/assets/javascripts/discourse/app/components/pick-files-button.gjs@@@ -1,27 -1,122 +1,150 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import { isBlank } from "@ember/utils";+ import { classNames } from "@ember-decorators/component";+ import discourseComputed, { bind } from "discourse/lib/decorators";+ import {+ authorizedExtensions,+ authorizesAllExtensions,+ } from "discourse/lib/uploads";+ import { i18n } from "discourse-i18n";++ // This picker is intended to be used with UppyUploadMixin or with+ // ComposerUploadUppy, which is why there are no change events registered+ // for the input. They are handled by the uppy mixins directly.+ //+ // However, if you provide an onFilesPicked action to this component, the change+ // binding will still be added, and the file type will be validated here. This+ // is sometimes useful if you need to do something outside the uppy upload with+ // the file, such as directly using JSON or CSV data from a file in JS.+ @classNames("pick-files-button")+ export default class PickFilesButton extends Component {+ @service dialog;++ fileInputId = null;+ fileInputClass = null;+ fileInputDisabled = false;+ acceptedFormatsOverride = null;+ allowMultiple = false;+ showButton = false;++ didInsertElement() {+ super.didInsertElement(...arguments);++ if (this.onFilesPicked) {+ const fileInput = this.element.querySelector("input");+ this.set("fileInput", fileInput);+ fileInput.addEventListener("change", this.onChange, false);+ }+ }++ willDestroyElement() {+ super.willDestroyElement(...arguments);++ if (this.onFilesPicked) {+ this.fileInput.removeEventListener("change", this.onChange);+ }+ }++ @bind+ onChange() {+ const files = this.fileInput.files;+ this._filesPicked(files);+ }++ @discourseComputed()+ acceptsAllFormats() {+ return (+ this.capabilities.isIOS ||+ authorizesAllExtensions(this.currentUser.staff, this.siteSettings)+ );+ }++ @discourseComputed()+ acceptedFormats() {+ // the acceptedFormatsOverride can be a list of extensions or mime types+ if (!isBlank(this.acceptedFormatsOverride)) {+ return this.acceptedFormatsOverride;+ }++ const extensions = authorizedExtensions(+ this.currentUser.staff,+ this.siteSettings+ );++ return extensions.map((ext) => `.${ext}`).join();+ }++ @action+ openSystemFilePicker() {+ this.fileInput.click();+ }++ _filesPicked(files) {+ if (!files || !files.length) {+ return;+ }++ if (!this._haveAcceptedTypes(files)) {+ const message = i18n("pick_files_button.unsupported_file_picked", {+ types: this.acceptedFileTypesString,+ });+ this.dialog.alert(message);+ return;+ }++ if (typeof this.onFilesPicked === "function") {+ this.onFilesPicked(files);+ }+ }++ _haveAcceptedTypes(files) {+ for (const file of files) {+ if (!this._hasAcceptedExtensionOrType(file)) {+ return false;+ }+ }+ return true;+ }++ _hasAcceptedExtensionOrType(file) {+ const extension = this._fileExtension(file.name);+ return (+ this.acceptedFormats.includes(`.${extension}`) ||+ this.acceptedFormats.includes(file.type)+ );+ }++ _fileExtension(fileName) {+ return fileName.split(".").pop();+ }+ }+++{{#if this.showButton}}+ <DButton+ @action={{action "openSystemFilePicker"}}+ @label={{this.label}}+ @icon={{this.icon}}+ />+{{/if}}+{{#if this.acceptsAllFormats}}+ <input+ {{did-insert (or @registerFileInput (noop))}}+ type="file"+ id={{this.fileInputId}}+ class={{this.fileInputClass}}+ multiple={{this.allowMultiple}}+ disabled={{this.fileInputDisabled}}+ />+{{else}}+ <input+ {{did-insert (or @registerFileInput (noop))}}+ type="file"+ id={{this.fileInputId}}+ class={{this.fileInputClass}}+ accept={{this.acceptedFormats}}+ multiple={{this.allowMultiple}}+ disabled={{this.fileInputDisabled}}+ />+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/plugin-outlet.gjsindex fd84c55acb4,a0e4c5fa9ca..7a5b41c5a53--- a/app/assets/javascripts/discourse/app/components/plugin-outlet.gjs+++ b/app/assets/javascripts/discourse/app/components/plugin-outlet.gjs@@@ -1,67 -1,138 +1,206 @@@+ import Component from "@glimmer/component";+ import { cached } from "@glimmer/tracking";+ import ClassicComponent from "@ember/component";+ import { get } from "@ember/object";+ import { getOwner } from "@ember/owner";+ import { service } from "@ember/service";+ import { bind } from "discourse/lib/decorators";+ import deprecated from "discourse/lib/deprecated";+ import { helperContext } from "discourse/lib/helpers";+ import {+ buildArgsWithDeprecations,+ connectorsExist,+ renderedConnectorsFor,+ } from "discourse/lib/plugin-connectors";++ const GET_DEPRECATION_MSG =+ "Plugin outlet context is no longer an EmberObject - using `get()` is deprecated.";+ const TAG_NAME_DEPRECATION_MSG =+ "The `tagName` argument to PluginOutlet is deprecated. If a wrapper element is required, define it manually around the outlet call. Using tagName will prevent wrapper PluginOutlets from functioning correctly.";+ const ARGS_DEPRECATION_MSG =+ "PluginOutlet arguments should now be passed using `@outletArgs=` instead of `@args=`";++ /**+ A plugin outlet is an extension point for templates where other templates can+ be inserted by plugins.++ ## Usage++ If your handlebars template has:++ ```handlebars+ <PluginOutlet @name="evil-trout" />+ ```++ Then any handlebars files you create in the `connectors/evil-trout` directory+ will automatically be appended. For example:++ plugins/hello/assets/javascripts/discourse/templates/connectors/evil-trout/hello.hbs++ With the contents:++ ```handlebars+ <b>Hello World</b>+ ```++ Will insert <b>Hello World</b> at that point in the template.++ **/++ export default class PluginOutletComponent extends Component {+ @service clientErrorHandler;++ context = {+ ...helperContext(),+ get() {+ deprecated(GET_DEPRECATION_MSG, {+ id: "discourse.plugin-outlet-context-get",+ });+ return get(this, ...arguments);+ },+ };++ constructor() {+ const result = super(...arguments);++ if (this.args.tagName) {+ deprecated(`${TAG_NAME_DEPRECATION_MSG} (outlet: ${this.args.name})`, {+ id: "discourse.plugin-outlet-tag-name",+ });+ }++ if (this.args.args) {+ deprecated(`${ARGS_DEPRECATION_MSG} (outlet: ${this.args.name})`, {+ id: "discourse.plugin-outlet-args",+ });+ }++ return result;+ }++ @bind+ getConnectors({ hasBlock } = {}) {+ const connectors = renderedConnectorsFor(+ this.args.name,+ this.outletArgsWithDeprecations,+ this.context,+ getOwner(this)+ );+ if (connectors.length > 1 && hasBlock) {+ const message = `Multiple connectors were registered for the ${this.args.name} outlet. Using the first.`;+ this.clientErrorHandler.displayErrorNotice(message);+ // eslint-disable-next-line no-console+ console.error(+ message,+ connectors.map((c) => c.humanReadableName)+ );+ return [connectors[0]];+ }+ return connectors;+ }++ @bind+ connectorsExist({ hasBlock } = {}) {+ return (+ connectorsExist(this.args.name) ||+ (hasBlock &&+ (connectorsExist(this.args.name + "__before") ||+ connectorsExist(this.args.name + "__after")))+ );+ }++ // Traditionally, pluginOutlets had an argument named 'args'. However, that name is reserved+ // in recent versions of ember so we need to migrate to outletArgs+ @cached+ get outletArgs() {+ return this.args.outletArgs || this.args.args || {};+ }++ @cached+ get outletArgsWithDeprecations() {+ if (!this.args.deprecatedArgs) {+ return this.outletArgs;+ }++ return buildArgsWithDeprecations(+ this.outletArgs,+ this.args.deprecatedArgs || {},+ { outletName: this.args.name }+ );+ }++ // Older plugin outlets have a `tagName` which we need to preserve for backwards-compatibility+ get wrapperComponent() {+ return PluginOutletWithTagNameWrapper;+ }+ }++ class PluginOutletWithTagNameWrapper extends ClassicComponent {}+++{{~#if @tagName~}}+ {{!+ Older outlets have a wrapper tagName. RFC0389 proposes an interface for dynamic tag names, which we may want to use in future.+ But for now, this classic component wrapper takes care of the tagName.+ }}+ <this.wrapperComponent @tagName={{@tagName}}>+ {{~#each (this.getConnectors) as |c|~}}+ {{~#if c.componentClass~}}+ <c.componentClass @outletArgs={{this.outletArgsWithDeprecations}} />+ {{~else if @defaultGlimmer~}}+ <c.templateOnly @outletArgs={{this.outletArgsWithDeprecations}} />+ {{~else~}}+ <PluginConnector+ @connector={{c}}+ @args={{this.outletArgs}}+ @deprecatedArgs={{@deprecatedArgs}}+ @outletArgs={{this.outletArgsWithDeprecations}}+ @tagName={{or @connectorTagName ""}}+ @layout={{c.template}}+ class={{c.classicClassNames}}+ />+ {{~/if~}}+ {{~/each~}}+ </this.wrapperComponent>+{{~else if (this.connectorsExist hasBlock=(has-block))~}}+ {{~! The modern path: no wrapper element = no classic component ~}}++ {{~#if (has-block)~}}+ <PluginOutlet+ @name={{concat @name "__before"}}+ @outletArgs={{this.outletArgsWithDeprecations}}+ />+ {{~/if~}}++ {{~#each (this.getConnectors hasBlock=(has-block)) as |c|~}}+ {{~#if c.componentClass~}}+ <c.componentClass+ @outletArgs={{this.outletArgsWithDeprecations}}+ >{{yield}}</c.componentClass>+ {{~else if @defaultGlimmer~}}+ <c.templateOnly+ @outletArgs={{this.outletArgsWithDeprecations}}+ >{{yield}}</c.templateOnly>+ {{~else~}}+ <PluginConnector+ @connector={{c}}+ @args={{this.outletArgs}}+ @deprecatedArgs={{@deprecatedArgs}}+ @outletArgs={{this.outletArgsWithDeprecations}}+ @tagName={{or @connectorTagName ""}}+ @layout={{c.template}}+ class={{c.classicClassNames}}+ >{{yield}}</PluginConnector>+ {{~/if~}}+ {{~else~}}+ {{yield}}+ {{~/each~}}++ {{~#if (has-block)~}}+ <PluginOutlet+ @name={{concat @name "__after"}}+ @outletArgs={{this.outletArgsWithDeprecations}}+ />+ {{~/if~}}+{{~else~}}+ {{yield}}+{{~/if~}}diff --cc app/assets/javascripts/discourse/app/components/popup-input-tip.gjsindex 851c22a01cc,4ad362f0233..6a94b24c4f7--- a/app/assets/javascripts/discourse/app/components/popup-input-tip.gjs+++ b/app/assets/javascripts/discourse/app/components/popup-input-tip.gjs@@@ -1,1 -1,62 +1,64 @@@+ import Component from "@ember/component";+ import { not, or, reads } from "@ember/object/computed";+ import { service } from "@ember/service";+ import { htmlSafe } from "@ember/template";+ import {+ attributeBindings,+ classNameBindings,+ tagName,+ } from "@ember-decorators/component";+ import discourseComputed from "discourse/lib/decorators";++ @tagName("a")+ @classNameBindings(":popup-tip", "good", "bad", "lastShownAt::hide")+ @attributeBindings("role", "ariaLabel", "tabindex")+ export default class PopupInputTip extends Component {+ @service composer;++ tipReason = null;+ tabindex = "0";++ @or("shownAt", "validation.lastShownAt") lastShownAt;+ @reads("validation.failed") bad;+ @not("bad") good;++ @discourseComputed("bad")+ role(bad) {+ if (bad) {+ return "alert";+ }+ }++ @discourseComputed("validation.reason")+ ariaLabel(reason) {+ return reason?.replace(/(<([^>]+)>)/gi, "");+ }++ dismiss() {+ this.set("shownAt", null);+ this.composer.clearLastValidatedAt();+ this.element.previousElementSibling?.focus();+ }++ click() {+ this.dismiss();+ }++ keyDown(event) {+ if (event.key === "Enter") {+ this.dismiss();+ }+ }++ didReceiveAttrs() {+ super.didReceiveAttrs(...arguments);+ let reason = this.get("validation.reason");+ if (reason) {+ this.set("tipReason", htmlSafe(`${reason}`));+ } else {+ this.set("tipReason", null);+ }+ }+ }+++{{this.tipReason}} {{d-icon "circle-xmark"}}diff --cc app/assets/javascripts/discourse/app/components/popup-menu.gjsindex f619e1c7f1f,a61673a6b7e..59eec722eee--- a/app/assets/javascripts/discourse/app/components/popup-menu.gjs+++ b/app/assets/javascripts/discourse/app/components/popup-menu.gjs@@@ -1,4 -1,3 +1,8 @@@+ import Component from "@ember/component";++ export default class PopupMenu extends Component {}+++<h3>{{i18n this.title}}</h3>+<ul>+ {{yield}}+</ul>diff --cc app/assets/javascripts/discourse/app/components/reviewable-conversation-post.gjsindex e88695a7a91,84d4d977f2a..da7e055ea2c--- a/app/assets/javascripts/discourse/app/components/reviewable-conversation-post.gjs+++ b/app/assets/javascripts/discourse/app/components/reviewable-conversation-post.gjs@@@ -1,12 -1,6 +1,19 @@@+ import Component from "@ember/component";+ import { gte } from "@ember/object/computed";++ export default class ReviewableConversationPost extends Component {+ @gte("index", 1) showUsername;+ }+++{{#if this.post}}+ <div class="reviewable-conversation-post">+ {{#if this.showUsername}}+ <LinkTo+ @route="user"+ @model={{this.post.user}}+ class="username"+ >@{{this.post.user.username}}</LinkTo>+ {{/if}}+ {{html-safe this.post.excerpt}}+ </div>+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/reviewable-field-editor.gjsindex ab0fa416efa,f14a72c7385..1bc2725b69c--- a/app/assets/javascripts/discourse/app/components/reviewable-field-editor.gjs+++ b/app/assets/javascripts/discourse/app/components/reviewable-field-editor.gjs@@@ -1,1 -1,3 +1,5 @@@+ import Component from "@ember/component";++ export default class ReviewableFieldEditor extends Component {}+++<DEditor @value={{this.value}} @change={{this.valueChanged}} />diff --cc app/assets/javascripts/discourse/app/components/reviewable-field-text.gjsindex 122c20c17ee,38fa568d82c..742279f0a71--- a/app/assets/javascripts/discourse/app/components/reviewable-field-text.gjs+++ b/app/assets/javascripts/discourse/app/components/reviewable-field-text.gjs@@@ -1,5 -1,3 +1,9 @@@+ import Component from "@ember/component";++ export default class ReviewableFieldText extends Component {}+++<Input+ @value={{this.value}}+ class="reviewable-input-text"+ {{on "change" this.valueChanged}}+/>diff --cc app/assets/javascripts/discourse/app/components/reviewable-field-textarea.gjsindex 06afe8a6aed,c86105578b7..28f77543eda--- a/app/assets/javascripts/discourse/app/components/reviewable-field-textarea.gjs+++ b/app/assets/javascripts/discourse/app/components/reviewable-field-textarea.gjs@@@ -1,5 -1,3 +1,9 @@@+ import Component from "@ember/component";++ export default class ReviewableFieldTextarea extends Component {}+++<Textarea+ @value={{this.value}}+ {{on "change" this.valueChanged}}+ class="reviewable-input-textarea"+/>diff --cc app/assets/javascripts/discourse/app/components/reviewable-field.gjsindex 31d86a83192,466abaacf80..30aebc5ae36--- a/app/assets/javascripts/discourse/app/components/reviewable-field.gjs+++ b/app/assets/javascripts/discourse/app/components/reviewable-field.gjs@@@ -1,6 -1,3 +1,10 @@@+ import Component from "@ember/component";++ export default class ReviewableField extends Component {}+++{{#if this.value}}+ <div class={{this.classes}}>+ <div class="name">{{this.name}}</div>+ <div class="value">{{this.value}}</div>+ </div>+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/reviewable-flagged-post.gjsindex 0cb394b73b8,2234355e96f..d5e23debded--- a/app/assets/javascripts/discourse/app/components/reviewable-flagged-post.gjs+++ b/app/assets/javascripts/discourse/app/components/reviewable-flagged-post.gjs@@@ -1,42 -1,39 +1,82 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { bind } from "discourse/lib/decorators";++ export default class ReviewableFlaggedPost extends Component {+ @tracked isCollapsed = false;+ @tracked isLongPost = false;+ maxPostHeight = 300;++ @action+ toggleContent() {+ this.isCollapsed = !this.isCollapsed;+ }++ @bind+ calculatePostBodySize(element) {+ if (element?.offsetHeight > this.maxPostHeight) {+ this.isCollapsed = true;+ this.isLongPost = true;+ } else {+ this.isCollapsed = false;+ this.isLongPost = false;+ }+ }++ get collapseButtonProps() {+ if (this.isCollapsed) {+ return {+ label: "review.show_more",+ icon: "chevron-down",+ };+ }+ return {+ label: "review.show_less",+ icon: "chevron-up",+ };+ }+ }+++<div class="flagged-post-header">+ <ReviewableTopicLink @reviewable={{@reviewable}} @tagName="" />+ <ReviewablePostEdits @reviewable={{@reviewable}} @tagName="" />+</div>++<div class="post-contents-wrapper">+ <ReviewableCreatedBy @user={{@reviewable.target_created_by}} />+ <div class="post-contents">+ <ReviewablePostHeader+ @reviewable={{@reviewable}}+ @createdBy={{@reviewable.target_created_by}}+ @tagName=""+ />+ <div+ class="post-body {{if this.isCollapsed 'is-collapsed'}}"+ {{did-insert this.calculatePostBodySize @reviewable}}+ >+ {{#if @reviewable.blank_post}}+ <p>{{i18n "review.deleted_post"}}</p>+ {{else}}+ {{html-safe @reviewable.cooked}}+ {{/if}}+ </div>++ {{#if this.isLongPost}}+ <DButton+ @action={{this.toggleContent}}+ @label={{this.collapseButtonProps.label}}+ @icon={{this.collapseButtonProps.icon}}+ class="btn-default btn-icon post-body__toggle-btn"+ />+ {{/if}}+ <span>+ <PluginOutlet+ @name="after-reviewable-flagged-post-body"+ @connectorTagName="div"+ @outletArgs={{hash model=@reviewable}}+ />+ </span>+ {{yield}}+ </div>+</div>diff --cc app/assets/javascripts/discourse/app/components/reviewable-histories.gjsindex b5c6f41581b,b51fe7fab4a..988178123a4--- a/app/assets/javascripts/discourse/app/components/reviewable-histories.gjs+++ b/app/assets/javascripts/discourse/app/components/reviewable-histories.gjs@@@ -1,27 -1,6 +1,34 @@@+ import Component from "@ember/component";+ import { filterBy } from "@ember/object/computed";++ export default class ReviewableHistories extends Component {+ @filterBy("histories", "created", false) filteredHistories;+ }+++{{#if this.filteredHistories}}+ <table class="reviewable-histories">+ <thead>+ <tr>+ <th colspan="3">{{i18n "review.history.title"}}</th>+ </tr>+ </thead>+ <tbody>+ {{#each this.filteredHistories as |rh|}}+ {{#unless rh.created}}+ <tr>+ <td>+ {{reviewable-history-description rh}}+ </td>+ <td>+ <UserLink @user={{this.rs.user}}>+ {{avatar rh.created_by imageSize="tiny"}}+ {{rh.created_by.username}}+ </UserLink>+ </td>+ <td>{{format-date rh.created_at format="medium"}}</td>+ </tr>+ {{/unless}}+ {{/each}}+ </tbody>+ </table>+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/reviewable-post-edits.gjsindex 2bdce30f2ed,af7558a0861..2fd058c3852--- a/app/assets/javascripts/discourse/app/components/reviewable-post-edits.gjs+++ b/app/assets/javascripts/discourse/app/components/reviewable-post-edits.gjs@@@ -1,10 -1,40 +1,51 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { gt } from "@ember/object/computed";+ import { service } from "@ember/service";+ import HistoryModal from "discourse/components/modal/history";+ import discourseComputed from "discourse/lib/decorators";+ import { longDate } from "discourse/lib/formatter";+ import { historyHeat } from "discourse/widgets/post-edits-indicator";++ export default class ReviewablePostEdits extends Component {+ @service modal;++ @gt("reviewable.post_version", 1) hasEdits;++ @discourseComputed("reviewable.post_updated_at")+ historyClass(updatedAt) {+ return historyHeat(this.siteSettings, new Date(updatedAt));+ }++ @discourseComputed("reviewable.post_updated_at")+ editedDate(updatedAt) {+ return longDate(updatedAt);+ }++ @action+ showEditHistory(event) {+ event?.preventDefault();+ let postId = this.get("reviewable.post_id");+ this.store.find("post", postId).then((post) => {+ this.modal.show(HistoryModal, {+ model: {+ post,+ postId,+ postVersion: "latest",+ topicController: null,+ },+ });+ });+ }+ }+++{{#if this.hasEdits}}+ <a+ href+ {{on "click" this.showEditHistory}}+ class="has-edits {{this.historyClass}}"+ title={{i18n "post.last_edited_on" dateTime=this.editedDate}}+ >+ {{d-icon "pencil"}}+ </a>+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/reviewable-post-header.gjsindex fb74062c881,003976726f3..adffcee27dd--- a/app/assets/javascripts/discourse/app/components/reviewable-post-header.gjs+++ b/app/assets/javascripts/discourse/app/components/reviewable-post-header.gjs@@@ -1,16 -1,3 +1,20 @@@+ import Component from "@ember/component";++ export default class ReviewablePostHeader extends Component {}+++<div class="reviewable-post-header">+ <ReviewableCreatedByName @user={{this.createdBy}} />+ {{#if this.reviewable.reply_to_post_number}}+ <a+ href={{concat+ this.reviewable.topic_url+ "/"+ this.reviewable.reply_to_post_number+ }}+ class="reviewable-reply-to"+ >+ {{d-icon "share"}}+ <span>{{i18n "review.in_reply_to"}}</span>+ </a>+ {{/if}}+</div>diff --cc app/assets/javascripts/discourse/app/components/reviewable-post.gjsindex d335aa849f8,1bbf7468675..fc7b578b23c--- a/app/assets/javascripts/discourse/app/components/reviewable-post.gjs+++ b/app/assets/javascripts/discourse/app/components/reviewable-post.gjs@@@ -1,23 -1,3 +1,27 @@@+ import Component from "@ember/component";++ export default class ReviewablePost extends Component {}+++<div class="flagged-post-header">+ <ReviewableTopicLink @reviewable={{this.reviewable}} @tagName="" />+ <ReviewablePostEdits @reviewable={{this.reviewable}} @tagName="" />+</div>++<div class="post-contents-wrapper">+ <ReviewableCreatedBy @user={{this.reviewable.target_created_by}} />+ <div class="post-contents">+ <ReviewablePostHeader+ @reviewable={{this.reviewable}}+ @createdBy={{this.reviewable.target_created_by}}+ @tagName=""+ />+ <div class="post-body">+ {{#if this.reviewable.blank_post}}+ <p>{{i18n "review.deleted_post"}}</p>+ {{else}}+ {{html-safe this.reviewable.cooked}}+ {{/if}}+ </div>+ {{yield}}+ </div>+</div>diff --cc app/assets/javascripts/discourse/app/components/reviewable-queued-post.gjsindex 24a107150bb,2def42545a1..92c9a44b367--- a/app/assets/javascripts/discourse/app/components/reviewable-queued-post.gjs+++ b/app/assets/javascripts/discourse/app/components/reviewable-queued-post.gjs@@@ -1,46 -1,55 +1,102 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import RawEmailModal from "discourse/components/modal/raw-email";++ export default class ReviewableQueuedPost extends Component {+ @service modal;++ @tracked isCollapsed = false;+ @tracked isLongPost = false;+ @tracked postBodyHeight = 0;+ maxPostHeight = 300;++ @action+ showRawEmail(event) {+ event?.preventDefault();+ this.modal.show(RawEmailModal, {+ model: {+ rawEmail: this.args.reviewable.payload.raw_email,+ },+ });+ }++ @action+ toggleContent() {+ this.isCollapsed = !this.isCollapsed;+ }++ get collapseButtonProps() {+ if (this.isCollapsed) {+ return {+ label: "review.show_more",+ icon: "chevron-down",+ };+ }+ return {+ label: "review.show_less",+ icon: "chevron-up",+ };+ }++ @action+ setPostBodyHeight(offsetHeight) {+ this.postBodyHeight = offsetHeight;++ if (this.postBodyHeight > this.maxPostHeight) {+ this.isCollapsed = true;+ this.isLongPost = true;+ } else {+ this.isCollapsed = false;+ this.isLongPost = false;+ }+ }+ }+++<ReviewableTopicLink @reviewable={{@reviewable}} @tagName="">+ <div class="title-text">+ {{d-icon "square-plus" title="review.new_topic"}}+ {{@reviewable.payload.title}}+ </div>+ {{category-badge @reviewable.category}}+ <ReviewableTags @tags={{@reviewable.payload.tags}} @tagName="" />+ {{#if @reviewable.payload.via_email}}+ <a href {{on "click" this.showRawEmail}} class="show-raw-email">+ {{d-icon "envelope" title="post.via_email"}}+ </a>+ {{/if}}+</ReviewableTopicLink>++<div class="post-contents-wrapper">+ <ReviewableCreatedBy @user={{@reviewable.target_created_by}} />++ <div class="post-contents">+ <ReviewablePostHeader+ @reviewable={{@reviewable}}+ @createdBy={{@reviewable.target_created_by}}+ @tagName=""+ />++ <CookText+ class="post-body {{if this.isCollapsed 'is-collapsed'}}"+ @rawText={{@reviewable.payload.raw}}+ @categoryId={{@reviewable.category_id}}+ @topicId={{@reviewable.topic_id}}+ @paintOneboxes={{true}}+ @opts={{hash removeMissing=true}}+ @onOffsetHeightCalculated={{this.setPostBodyHeight}}+ />++ {{#if this.isLongPost}}+ <DButton+ @action={{this.toggleContent}}+ @label={{this.collapseButtonProps.label}}+ @icon={{this.collapseButtonProps.icon}}+ class="btn-default btn-icon post-body__toggle-btn"+ />+ {{/if}}++ {{yield}}+ </div>+</div>diff --cc app/assets/javascripts/discourse/app/components/reviewable-score.gjsindex 49407ecb2e6,26b3bd18bd5..ad4834f3c18--- a/app/assets/javascripts/discourse/app/components/reviewable-score.gjs+++ b/app/assets/javascripts/discourse/app/components/reviewable-score.gjs@@@ -1,43 -1,21 +1,65 @@@+ import Component from "@ember/component";+ import { gt } from "@ember/object/computed";+ import { tagName } from "@ember-decorators/component";+ import discourseComputed from "discourse/lib/decorators";++ @tagName("")+ export default class ReviewableScore extends Component {+ @gt("rs.status", 0) showStatus;++ @discourseComputed("rs.score_type.title", "reviewable.target_created_by")+ title(title, targetCreatedBy) {+ if (title && targetCreatedBy) {+ return title.replace(+ /{{username}}|%{username}/,+ targetCreatedBy.username+ );+ }++ return title;+ }+ }+++<tr class="reviewable-score">+ <td class="user">+ <UserLink @user={{this.rs.user}}>+ {{avatar this.rs.user imageSize="tiny"}}+ {{this.rs.user.username}}+ </UserLink>+ </td>++ <td>+ {{format-date this.rs.created_at format="tiny"}}+ </td>++ <td>+ {{d-icon this.rs.score_type.icon}}+ {{this.title}}+ </td>++ {{#if this.showStatus}}+ <td class="reviewed-by">+ {{#if this.rs.reviewed_by}}+ <UserLink @user={{this.rs.reviewed_by}}>+ {{avatar this.rs.reviewed_by imageSize="tiny"}}+ {{this.rs.reviewed_by.username}}+ </UserLink>+ {{else}}+ —+ {{/if}}+ </td>++ <td>+ {{#if this.rs.reviewed_by}}+ {{format-date this.rs.reviewed_at format="tiny"}}+ {{/if}}+ </td>++ <td>+ {{reviewable-status this.rs.status this.reviewable.type}}+ </td>++ {{else}}+ <td colspan="4"></td>+ {{/if}}+</tr>diff --cc app/assets/javascripts/discourse/app/components/reviewable-scores.gjsindex 462acc3d6ce,a5e66c61fd3..940f408db03--- a/app/assets/javascripts/discourse/app/components/reviewable-scores.gjs+++ b/app/assets/javascripts/discourse/app/components/reviewable-scores.gjs@@@ -1,47 -1,3 +1,51 @@@+ import Component from "@ember/component";++ export default class ReviewableScores extends Component {}+++{{#if this.reviewable.reviewable_scores}}+ <div class="reviewable-scores__table-wrapper">+ <table class="reviewable-scores">+ <thead>+ <tr>+ <th>{{i18n "review.scores.submitted_by"}}</th>+ <th>{{i18n "review.scores.date"}}</th>+ <th>{{i18n "review.scores.type"}}</th>+ <th>{{i18n "review.scores.reviewed_by"}}</th>+ <th>{{i18n "review.scores.reviewed_timestamp"}}</th>+ <th>{{i18n "review.scores.status"}}</th>+ </tr>+ </thead>+ <tbody>+ {{#each this.reviewable.reviewable_scores as |rs|}}+ <ReviewableScore @rs={{rs}} @reviewable={{this.reviewable}} />+ {{/each}}+ </tbody>+ </table>+ </div>++ {{#each this.reviewable.reviewable_scores as |rs|}}+ {{#if rs.reason}}+ <div class="reviewable-score-reason">{{html-safe rs.reason}}</div>+ {{/if}}+ {{#if rs.context}}+ <div class="reviewable-score-context">{{html-safe rs.context}}</div>+ {{/if}}++ {{#if rs.reviewable_conversation}}+ <div class="reviewable-conversation">+ {{#each rs.reviewable_conversation.conversation_posts as |p index|}}+ <ReviewableConversationPost @post={{p}} @index={{index}} />+ {{/each}}+ <div class="controls">+ <a+ href={{rs.reviewable_conversation.permalink}}+ class="btn btn-small"+ >+ {{i18n "review.conversation.view_full"}}+ </a>+ </div>+ </div>+ {{/if}}+ {{/each}}++{{/if}}diff --cc app/assets/javascripts/discourse/app/components/reviewable-tags.gjsindex 57f5b9761aa,12dc40dc4be..26b22e660e0--- a/app/assets/javascripts/discourse/app/components/reviewable-tags.gjs+++ b/app/assets/javascripts/discourse/app/components/reviewable-tags.gjs@@@ -1,5 -1,3 +1,9 @@@+ import Component from "@ember/component";++ export default class ReviewableTags extends Component {}+++{{#if this.tags}}+ <div class="list-tags">+ {{#each this.tags as |t|}}{{discourse-tag t}}{{/each}}+ </div>+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/reviewable-topic-link.gjsindex 57c672bdde2,0eb6a54282e..ac6be71ab65--- a/app/assets/javascripts/discourse/app/components/reviewable-topic-link.gjs+++ b/app/assets/javascripts/discourse/app/components/reviewable-topic-link.gjs@@@ -1,23 -1,3 +1,27 @@@+ import Component from "@ember/component";++ export default class ReviewableTopicLink extends Component {}+++<div class="post-topic">+ {{#if this.reviewable.topic}}+ <TopicStatus+ @topic={{this.reviewable.topic}}+ @showPrivateMessageIcon={{true}}+ />+ <a href={{this.reviewable.target_url}} class="title-text">{{html-safe+ this.reviewable.topic.fancyTitle+ }}</a>+ {{category-badge this.reviewable.category}}+ <ReviewableTags @tags={{this.reviewable.topic_tags}} @tagName="" />+ {{else if (has-block)}}+ {{yield}}+ {{else}}+ <span class="title-text">+ {{i18n "review.topics.deleted"}}+ <LinkTo+ @route="topic"+ @models={{array "-" this.reviewable.removed_topic_id}}+ >{{i18n "review.topics.original"}}</LinkTo>+ </span>+ {{/if}}+</div>diff --cc app/assets/javascripts/discourse/app/components/reviewable-user.gjsindex 1db4f3c67a8,e028341ceb4..fa77ad72f7b--- a/app/assets/javascripts/discourse/app/components/reviewable-user.gjs+++ b/app/assets/javascripts/discourse/app/components/reviewable-user.gjs@@@ -1,73 -1,9 +1,83 @@@+ import Component from "@ember/component";+ import discourseComputed from "discourse/lib/decorators";++ export default class ReviewableUser extends Component {+ @discourseComputed("reviewable.user_fields")+ userFields(fields) {+ return this.site.collectUserFields(fields);+ }+ }+++<div class="reviewable-user-info">+ <div class="reviewable-user-fields">+ <div class="reviewable-user-details username">+ <div class="name">{{i18n "review.user.username"}}</div>+ <div class="value">+ {{#if this.reviewable.link_admin}}+ <a+ href={{get-url+ (concat+ "/admin/users/"+ this.reviewable.user_id+ "/"+ this.reviewable.payload.username+ )+ }}+ >+ {{this.reviewable.payload.username}}+ </a>+ {{else}}+ {{this.reviewable.payload.username}}+ {{/if}}+ </div>+ </div>++ <ReviewableField+ @classes="reviewable-user-details name"+ @name={{i18n "review.user.name"}}+ @value={{this.reviewable.payload.name}}+ />++ <ReviewableField+ @classes="reviewable-user-details email"+ @name={{i18n "review.user.email"}}+ @value={{this.reviewable.payload.email}}+ />++ <ReviewableField+ @classes="reviewable-user-details bio"+ @name={{i18n "review.user.bio"}}+ @value={{this.reviewable.payload.bio}}+ />++ {{#if this.reviewable.payload.website}}+ <div class="reviewable-user-details website">+ <div class="name">{{i18n "review.user.website"}}</div>+ <div class="value">+ <a+ href={{this.reviewable.payload.website}}+ target="_blank"+ rel="noopener noreferrer"+ >{{this.reviewable.payload.website}}</a>+ </div>+ </div>+ {{/if}}++ <ReviewableField+ @classes="reviewable-user-details reject-reason"+ @name={{i18n "review.user.reject_reason"}}+ @value={{this.reviewable.reject_reason}}+ />++ {{#each this.userFields as |f|}}+ <ReviewableField+ @classes="reviewable-user-details user-field"+ @name={{f.name}}+ @value={{f.value}}+ @tagName=""+ />+ {{/each}}+ </div>++ {{yield}}+</div>diff --cc app/assets/javascripts/discourse/app/components/save-controls.gjsindex 9d147e76413,3ecc4f73a6f..91e004b03f0--- a/app/assets/javascripts/discourse/app/components/save-controls.gjs+++ b/app/assets/javascripts/discourse/app/components/save-controls.gjs@@@ -1,11 -1,19 +1,31 @@@+ import Component from "@ember/component";+ import { or } from "@ember/object/computed";+ import { classNames } from "@ember-decorators/component";+ import discourseComputed from "discourse/lib/decorators";++ @classNames("controls", "save-button")+ export default class SaveControls extends Component {+ @or("model.isSaving", "saveDisabled") buttonDisabled;++ didInsertElement() {+ super.didInsertElement(...arguments);+ this.set("saved", false);+ }++ @discourseComputed("model.isSaving")+ savingText(saving) {+ return saving ? "saving" : "save";+ }+ }+++<DButton+ @action={{this.action}}+ @disabled={{this.buttonDisabled}}+ @label={{this.savingText}}+ class="btn-primary save-changes"+/>+{{#if this.saved}}+ <span class="saved">{{i18n "saved"}}</span>+{{/if}}++{{yield}}diff --cc app/assets/javascripts/discourse/app/components/search-menu-panel.gjsindex 970f67b0462,1fc5e03290e..9d5180c8f56--- a/app/assets/javascripts/discourse/app/components/search-menu-panel.gjs+++ b/app/assets/javascripts/discourse/app/components/search-menu-panel.gjs@@@ -1,10 -1,12 +1,23 @@@+ import Component from "@glimmer/component";+ import { service } from "@ember/service";++ export default class SearchMenuPanel extends Component {+ @service site;++ get animationClass() {+ return this.site.mobileView || this.site.narrowDesktopView+ ? "slide-in"+ : "drop-down";+ }+ }+++<MenuPanel+ @animationClass={{this.animationClass}}+ @panelClass="search-menu-panel"+>+ <SearchMenu+ @onClose={{@closeSearchMenu}}+ @inlineResults={{true}}+ @autofocusInput={{true}}+ />+</MenuPanel>diff --cc app/assets/javascripts/discourse/app/components/search-menu.gjsindex ba9d259db5a,f152904bc6d..db5c6996dd8--- a/app/assets/javascripts/discourse/app/components/search-menu.gjs+++ b/app/assets/javascripts/discourse/app/components/search-menu.gjs@@@ -1,92 -1,376 +1,469 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { cancel } from "@ember/runloop";+ import { service } from "@ember/service";+ import { Promise } from "rsvp";+ import { popupAjaxError } from "discourse/lib/ajax-error";+ import { CANCELLED_STATUS } from "discourse/lib/autocomplete";+ import { search as searchCategoryTag } from "discourse/lib/category-tag-search";+ import discourseDebounce from "discourse/lib/debounce";+ import { bind } from "discourse/lib/decorators";+ import getURL from "discourse/lib/get-url";+ import {+ isValidSearchTerm,+ searchForTerm,+ updateRecentSearches,+ } from "discourse/lib/search";+ import DiscourseURL from "discourse/lib/url";+ import userSearch from "discourse/lib/user-search";++ const CATEGORY_SLUG_REGEXP = /(\#[a-zA-Z0-9\-:]*)$/gi;+ const USERNAME_REGEXP = /(\@[a-zA-Z0-9\-\_]*)$/gi;+ const SUGGESTIONS_REGEXP = /(in:|status:|order:|:)([a-zA-Z]*)$/gi;+ export const SEARCH_INPUT_ID = "search-term";+ export const MODIFIER_REGEXP = /.*(\#|\@|:).*$/gi;+ export const DEFAULT_TYPE_FILTER = "exclude_topics";++ export function focusSearchInput() {+ document.getElementById(SEARCH_INPUT_ID).focus();+ }++ export default class SearchMenu extends Component {+ @service search;+ @service currentUser;+ @service siteSettings;+ @service appEvents;++ @tracked loading = false;+ @tracked+ inPMInboxContext = this.search.searchContext?.type === "private_messages";+ @tracked typeFilter = DEFAULT_TYPE_FILTER;+ @tracked suggestionKeyword = false;+ @tracked suggestionResults = [];+ @tracked invalidTerm = false;+ @tracked menuPanelOpen = false;++ _debouncer = null;+ _activeSearch = null;++ willDestroy() {+ if (!this.args.inlineResults) {+ document.removeEventListener("mousedown", this.onDocumentPress);+ document.removeEventListener("touchend", this.onDocumentPress);+ }+ super.willDestroy(...arguments);+ }++ @bind+ setupEventListeners() {+ // We only need to register click events when the search menu is rendered outside of the header.+ // The header handles clicking outside.+ if (!this.args.inlineResults) {+ document.addEventListener("mousedown", this.onDocumentPress);+ document.addEventListener("touchend", this.onDocumentPress);+ }+ }++ @bind+ onDocumentPress(event) {+ if (!this.menuPanelOpen) {+ return;+ }++ if (!event.target.closest(".search-menu-container.menu-panel-results")) {+ this.close();+ }+ }++ get classNames() {+ const classes = ["search-menu-container"];++ if (!this.args.inlineResults) {+ classes.push("menu-panel-results");+ }++ if (this.loading) {+ classes.push("loading");+ }++ return classes.join(" ");+ }++ get includesTopics() {+ return (+ !!this.search.results?.topics?.length ||+ this.typeFilter !== DEFAULT_TYPE_FILTER+ );+ }++ get searchContext() {+ if (this.search.inTopicContext || this.inPMInboxContext) {+ return this.search.searchContext;+ }++ return false;+ }++ @action+ onKeydown(event) {+ if (event.key === "Escape") {+ this.close();+ }+ }++ @action+ close() {+ if (this.args?.onClose) {+ return this.args.onClose();+ }++ // We want to blur the search input when in stand-alone mode+ // so that when we focus on the search input again, the menu panel pops up+ document.getElementById(SEARCH_INPUT_ID)?.blur();+ this.menuPanelOpen = false;+ }++ @action+ open() {+ this.menuPanelOpen = true;+ }++ @bind+ fullSearchUrl(opts) {+ let url = "/search";+ let params = new URLSearchParams();++ if (this.search.activeGlobalSearchTerm) {+ let q = this.search.activeGlobalSearchTerm;++ if (this.searchContext?.type === "topic") {+ q += ` topic:${this.searchContext.id}`;+ } else if (this.searchContext?.type === "private_messages") {+ q += " in:messages";+ }+ params.set("q", q);+ }+ if (opts?.expanded) {+ params.set("expanded", "true");+ }+ if (params.toString() !== "") {+ url = `${url}?${params}`;+ }+ return getURL(url);+ }++ @action+ openAdvancedSearch() {+ this.fullSearch();+ this.close();+ }++ get displayMenuPanelResults() {+ if (this.args.inlineResults) {+ return false;+ }++ return this.menuPanelOpen;+ }++ @bind+ clearSearch(e) {+ e.stopPropagation();+ e.preventDefault();+ this.search.activeGlobalSearchTerm = "";+ focusSearchInput();+ this.triggerSearch();+ }++ @action+ searchTermChanged(term, opts = {}) {+ this.typeFilter = opts.searchTopics ? null : DEFAULT_TYPE_FILTER;+ if (opts.setTopicContext) {+ this.search.inTopicContext = true;+ }+ this.search.activeGlobalSearchTerm = term;+ this.triggerSearch();+ }++ @action+ fullSearch() {+ this.loading = false;+ const url = this.fullSearchUrl();+ if (url) {+ DiscourseURL.routeTo(url);+ }+ }++ @action+ updateTypeFilter(value) {+ this.typeFilter = value;+ }++ @action+ clearPMInboxContext() {+ this.inPMInboxContext = false;+ }++ @action+ clearTopicContext() {+ this.search.inTopicContext = false;+ }++ // for cancelling debounced search+ cancel() {+ if (this._activeSearch) {+ this._activeSearch.abort();+ this._activeSearch = null;+ }+ }++ async perform() {+ this.cancel();++ const matchSuggestions = this.matchesSuggestions();+ if (matchSuggestions) {+ this.search.noResults = true;+ this.search.results = {};+ this.loading = false;+ this.suggestionResults = [];++ if (matchSuggestions.type === "category") {+ const categorySearchTerm = matchSuggestions.categoriesMatch[0].replace(+ "#",+ ""+ );++ const categoryTagSearch = searchCategoryTag(+ categorySearchTerm,+ this.siteSettings+ );+ Promise.resolve(categoryTagSearch).then((results) => {+ if (results !== CANCELLED_STATUS) {+ this.suggestionResults = results;+ this.suggestionKeyword = "#";+ }+ });+ } else if (matchSuggestions.type === "username") {+ const userSearchTerm = matchSuggestions.usernamesMatch[0].replace(+ "@",+ ""+ );+ const opts = { includeGroups: true, limit: 6 };+ if (userSearchTerm.length > 0) {+ opts.term = userSearchTerm;+ } else {+ opts.lastSeenUsers = true;+ }++ userSearch(opts).then((result) => {+ if (result?.users?.length > 0) {+ this.suggestionResults = result.users;+ this.suggestionKeyword = "@";+ } else {+ this.search.noResults = true;+ this.suggestionKeyword = false;+ }+ });+ } else {+ this.suggestionKeyword = matchSuggestions[0];+ }+ return;+ }++ this.suggestionKeyword = false;++ if (!this.search.activeGlobalSearchTerm) {+ this.search.noResults = false;+ this.search.results = {};+ this.loading = false;+ this.invalidTerm = false;+ } else if (+ !isValidSearchTerm(this.search.activeGlobalSearchTerm, this.siteSettings)+ ) {+ this.search.noResults = true;+ this.search.results = {};+ this.loading = false;+ this.invalidTerm = true;+ } else {+ this.loading = true;+ this.invalidTerm = false;++ this._activeSearch = searchForTerm(this.search.activeGlobalSearchTerm, {+ typeFilter: this.typeFilter,+ fullSearchUrl: this.fullSearchUrl,+ searchContext: this.searchContext,+ });++ this._activeSearch+ .then((results) => {+ // we ensure the current search term is the one used+ // when starting the query+ if (results) {+ if (this.searchContext) {+ this.appEvents.trigger("post-stream:refresh", {+ force: true,+ });+ }++ this.search.noResults = results.resultTypes.length === 0;+ this.search.results = results;+ }+ })+ .catch(popupAjaxError)+ .finally(() => {+ this.loading = false;+ this.appEvents.trigger("search:search_result_view", {+ searchMenu: true, // delineate between search menu and full page search+ });+ });+ }+ }++ matchesSuggestions() {+ if (+ this.search.activeGlobalSearchTerm === undefined ||+ this.includesTopics+ ) {+ return false;+ }++ const term = this.search.activeGlobalSearchTerm.trim();+ const categoriesMatch = term.match(CATEGORY_SLUG_REGEXP);++ if (categoriesMatch) {+ return { type: "category", categoriesMatch };+ }++ const usernamesMatch = term.match(USERNAME_REGEXP);+ if (usernamesMatch) {+ return { type: "username", usernamesMatch };+ }++ const suggestionsMatch = term.match(SUGGESTIONS_REGEXP);+ if (suggestionsMatch) {+ return suggestionsMatch;+ }++ return false;+ }++ @action+ triggerSearch() {+ this.search.noResults = false;++ if (this.includesTopics) {+ if (this.search.contextType === "topic") {+ this.search.highlightTerm = this.search.activeGlobalSearchTerm;+ }+ this.loading = true;+ cancel(this._debouncer);+ this.perform();++ if (this.currentUser) {+ updateRecentSearches(+ this.currentUser,+ this.search.activeGlobalSearchTerm+ );+ }+ } else {+ this.loading = false;+ if (!this.search.inTopicContext) {+ this._debouncer = discourseDebounce(this, this.perform, 400);+ }+ }+ }+ }+++<div+ class={{this.classNames}}+ {{did-insert this.setupEventListeners}}+ {{! template-lint-disable no-invalid-interactive }}+ {{on "keydown" this.onKeydown}}+>+ <div class="search-input">+ {{#if this.search.inTopicContext}}+ <DButton+ @icon="xmark"+ @label="search.in_this_topic"+ @title="search.in_this_topic_tooltip"+ @action={{this.clearTopicContext}}+ class="btn-small search-context"+ />+ {{else if this.inPMInboxContext}}+ <DButton+ @icon="xmark"+ @label="search.in_messages"+ @title="search.in_messages_tooltip"+ @action={{this.clearPMInboxContext}}+ class="btn-small search-context"+ />+ {{/if}}++ <PluginOutlet+ @name="search-menu-before-term-input"+ @outletArgs={{hash openSearchMenu=this.open}}+ />++ <SearchMenu::SearchTerm+ @searchTermChanged={{this.searchTermChanged}}+ @typeFilter={{this.typeFilter}}+ @updateTypeFilter={{this.updateTypeFilter}}+ @triggerSearch={{this.triggerSearch}}+ @fullSearch={{this.fullSearch}}+ @clearPMInboxContext={{this.clearPMInboxContext}}+ @clearTopicContext={{this.clearTopicContext}}+ @closeSearchMenu={{this.close}}+ @openSearchMenu={{this.open}}+ @autofocus={{@autofocusInput}}+ />++ {{#if this.loading}}+ <div class="searching">+ {{loading-spinner}}+ </div>+ {{else}}+ <div class="searching">+ <PluginOutlet @name="search-menu-before-advanced-search" />+ {{#if this.search.activeGlobalSearchTerm}}+ <SearchMenu::ClearButton @clearSearch={{this.clearSearch}} />+ {{/if}}+ <SearchMenu::AdvancedButton+ @openAdvancedSearch={{this.openAdvancedSearch}}+ />+ </div>+ {{/if}}+ </div>++ {{#if @inlineResults}}+ <SearchMenu::Results+ @loading={{this.loading}}+ @invalidTerm={{this.invalidTerm}}+ @suggestionKeyword={{this.suggestionKeyword}}+ @suggestionResults={{this.suggestionResults}}+ @searchTopics={{this.includesTopics}}+ @inPMInboxContext={{this.inPMInboxContext}}+ @triggerSearch={{this.triggerSearch}}+ @updateTypeFilter={{this.updateTypeFilter}}+ @closeSearchMenu={{this.close}}+ @searchTermChanged={{this.searchTermChanged}}+ @clearSearch={{this.clearSearch}}+ />+ {{else if this.displayMenuPanelResults}}+ <MenuPanel @panelClass="search-menu-panel">+ <SearchMenu::Results+ @loading={{this.loading}}+ @invalidTerm={{this.invalidTerm}}+ @suggestionKeyword={{this.suggestionKeyword}}+ @suggestionResults={{this.suggestionResults}}+ @searchTopics={{this.includesTopics}}+ @inPMInboxContext={{this.inPMInboxContext}}+ @triggerSearch={{this.triggerSearch}}+ @updateTypeFilter={{this.updateTypeFilter}}+ @closeSearchMenu={{this.close}}+ @searchTermChanged={{this.searchTermChanged}}+ @clearSearch={{this.clearSearch}}+ />+ </MenuPanel>+ {{/if}}+</div>diff --cc app/assets/javascripts/discourse/app/components/search-menu/browser-search-tip.gjsindex 4b470452ec4,36fffa34ad4..f35d5ce8cb7--- a/app/assets/javascripts/discourse/app/components/search-menu/browser-search-tip.gjs+++ b/app/assets/javascripts/discourse/app/components/search-menu/browser-search-tip.gjs@@@ -1,8 -1,9 +1,18 @@@+ import Component from "@glimmer/component";+ import { translateModKey } from "discourse/lib/utilities";+ import { i18n } from "discourse-i18n";++ export default class BrowserSearchTip extends Component {+ get translatedLabel() {+ return i18n("search.browser_tip", { modifier: translateModKey("Meta+") });+ }+ }+++<div class="browser-search-tip">+ <span class="tip-label">+ {{this.translatedLabel}}+ </span>+ <span class="tip-description">+ {{i18n "search.browser_tip_description"}}+ </span>+</div>diff --cc app/assets/javascripts/discourse/app/components/search-menu/highlighted-search.gjsindex e205ba46aea,33b6f44111a..e1adb48b965--- a/app/assets/javascripts/discourse/app/components/search-menu/highlighted-search.gjs+++ b/app/assets/javascripts/discourse/app/components/search-menu/highlighted-search.gjs@@@ -1,3 -1,13 +1,17 @@@+ import Component from "@glimmer/component";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import highlightSearch from "discourse/lib/highlight-search";++ export default class HighlightedSearch extends Component {+ @service search;++ @action+ highlight(element) {+ highlightSearch(element, this.search.activeGlobalSearchTerm);+ }+ }+++<span {{did-insert this.highlight}}>+ {{html-safe @string}}+</span>diff --cc app/assets/javascripts/discourse/app/components/search-menu/results.gjsindex 2a7de0c8399,4c8be480c06..55562e1c056--- a/app/assets/javascripts/discourse/app/components/search-menu/results.gjs+++ b/app/assets/javascripts/discourse/app/components/search-menu/results.gjs@@@ -1,86 -1,57 +1,144 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import CategoryViewComponent from "./results/type/category";+ import GroupViewComponent from "./results/type/group";+ import PostViewComponent from "./results/type/post";+ import TagViewComponent from "./results/type/tag";+ import TopicViewComponent from "./results/type/topic";+ import UserViewComponent from "./results/type/user";++ const SEARCH_RESULTS_COMPONENT_TYPE = {+ "search-result-category": CategoryViewComponent,+ "search-result-topic": TopicViewComponent,+ "search-result-post": PostViewComponent,+ "search-result-user": UserViewComponent,+ "search-result-tag": TagViewComponent,+ "search-result-group": GroupViewComponent,+ };++ export default class Results extends Component {+ @service search;++ @tracked searchTopics = this.args.searchTopics;++ get renderInitialOptions() {+ return !this.search.activeGlobalSearchTerm && !this.args.inPMInboxContext;+ }++ get noTopicResults() {+ return this.args.searchTopics && this.search.noResults;+ }++ get termTooShort() {+ return this.args.searchTopics && this.args.invalidTerm;+ }++ get resultTypesWithComponent() {+ let content = [];+ this.search.results.resultTypes?.map((resultType) => {+ content.push({+ ...resultType,+ component: SEARCH_RESULTS_COMPONENT_TYPE[resultType.componentName],+ });+ });+ return content;+ }++ get searchLogId() {+ return this.search.results.grouped_search_result?.search_log_id;+ }++ @action+ updateSearchTopics(value) {+ this.searchTopics = value;+ }+ }+++{{#if (and this.search.inTopicContext (not @searchTopics))}}+ <SearchMenu::BrowserSearchTip />+{{else}}+ <ConditionalLoadingSection @isLoading={{this.loading}}>+ <div class="results">+ <PluginOutlet+ @name="search-menu-results-top"+ @outletArgs={{hash+ closeSearchMenu=@closeSearchMenu+ searchTerm=this.search.activeGlobalSearchTerm+ inTopicContext=this.search.inTopicContext+ searchTopics=@searchTopics+ }}+ />+ {{#if @suggestionKeyword}}+ <SearchMenu::Results::Assistant+ @suggestionKeyword={{@suggestionKeyword}}+ @results={{@suggestionResults}}+ @closeSearchMenu={{@closeSearchMenu}}+ @searchTermChanged={{@searchTermChanged}}+ />+ {{else if this.termTooShort}}+ <div class="no-results">{{i18n "search.too_short"}}</div>+ {{else if this.noTopicResults}}+ <div class="no-results">{{i18n "search.no_results"}}</div>+ {{else if this.renderInitialOptions}}+ <SearchMenu::Results::InitialOptions+ @closeSearchMenu={{@closeSearchMenu}}+ @searchTermChanged={{@searchTermChanged}}+ />+ {{else}}+ {{#if (and (not @searchTopics) (not @inPMInboxContext))}}+ {{! render the first couple suggestions before a search has been performed}}+ <SearchMenu::Results::InitialOptions+ @closeSearchMenu={{@closeSearchMenu}}+ @searchTermChanged={{@searchTermChanged}}+ />+ {{/if}}++ {{#if (and @searchTopics this.resultTypesWithComponent)}}+ {{! render results after a search has been performed }}+ <SearchMenu::Results::Types+ @resultTypes={{this.resultTypesWithComponent}}+ @topicResultsOnly={{true}}+ @closeSearchMenu={{@closeSearchMenu}}+ @searchLogId={{this.searchLogId}}+ />+ <SearchMenu::Results::MoreLink+ @updateTypeFilter={{@updateTypeFilter}}+ @triggerSearch={{@triggerSearch}}+ @resultTypes={{this.resultTypesWithComponent}}+ @closeSearchMenu={{@closeSearchMenu}}+ @searchTermChanged={{@searchTermChanged}}+ />+ {{else if+ (and+ (not @inPMInboxContext)+ (not @searchTopics)+ this.resultTypesWithComponent+ )+ }}+ <SearchMenu::Results::Types+ @resultTypes={{this.resultTypesWithComponent}}+ @closeSearchMenu={{@closeSearchMenu}}+ @searchTermChanged={{@searchTermChanged}}+ @displayNameWithUser={{true}}+ @searchLogId={{this.searchLogId}}+ />+ {{/if}}+ <PluginOutlet+ @name="search-menu-with-results-bottom"+ @outletArgs={{hash resultTypes=this.resultTypesWithComponent}}+ />+ {{/if}}+ <PluginOutlet+ @name="search-menu-results-bottom"+ @outletArgs={{hash+ inTopicContext=this.search.inTopicContext+ searchTermChanged=@searchTermChanged+ searchTopics=@searchTopics+ closeSearchMenu=@closeSearchMenu+ }}+ />+ </div>+ </ConditionalLoadingSection>+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/search-menu/results/assistant-item.gjsindex 8b3962c7398,558d567a6cb..d8ee1668596--- a/app/assets/javascripts/discourse/app/components/search-menu/results/assistant-item.gjs+++ b/app/assets/javascripts/discourse/app/components/search-menu/results/assistant-item.gjs@@@ -1,57 -1,125 +1,183 @@@+ import Component from "@glimmer/component";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import { focusSearchInput } from "discourse/components/search-menu";+ import { debounce } from "discourse/lib/decorators";+ import getURL from "discourse/lib/get-url";++ const _itemSelectCallbacks = [];+ export function addItemSelectCallback(fn) {+ _itemSelectCallbacks.push(fn);+ }++ export function resetItemSelectCallbacks() {+ _itemSelectCallbacks.length = 0;+ }++ export default class AssistantItem extends Component {+ @service search;+ @service appEvents;++ icon = this.args.icon || "magnifying-glass";++ get href() {+ let href = "#";+ if (this.args.category) {+ href = this.args.category.url;++ if (this.args.tags && this.args.isIntersection) {+ href = getURL(`/tag/${this.args.tag}`);+ }+ } else if (+ this.args.tags &&+ this.args.isIntersection &&+ this.args.additionalTags?.length+ ) {+ href = getURL(`/tag/${this.args.tag}`);+ }++ return href;+ }++ get prefix() {+ let prefix = "";+ if (this.args.suggestionKeyword !== "+") {+ prefix =+ this.search.activeGlobalSearchTerm+ ?.split(this.args.suggestionKeyword)[0]+ .trim() || "";+ if (prefix.length) {+ prefix = `${prefix} `;+ }+ } else {+ prefix = this.search.activeGlobalSearchTerm;+ }+ return prefix;+ }++ get tagsSlug() {+ if (!this.args.tag || !this.args.additionalTags) {+ return;+ }++ return `tags:${[this.args.tag, ...this.args.additionalTags].join("+")}`;+ }++ @action+ onKeydown(e) {+ // don't capture tab key+ if (e.key === "Tab") {+ return;+ }++ if (e.key === "Enter") {+ this.itemSelected();+ }++ if (e.key === "ArrowUp" || e.key === "ArrowDown") {+ this.search.handleArrowUpOrDown(e);+ }+ }++ @action+ onClick(e) {+ this.itemSelected();+ e.preventDefault();+ return false;+ }++ @debounce(100)+ itemSelected() {+ let updatedTerm = "";+ if (+ this.args.slug &&+ (this.args.suggestionKeyword || this.args.concatSlug)+ ) {+ updatedTerm = this.prefix.concat(this.args.slug);+ } else {+ updatedTerm = this.prefix.trim();+ }++ const inTopicContext = this.search.searchContext?.type === "topic";+ const searchTopics = !inTopicContext || this.search.activeGlobalSearchTerm;++ if (+ _itemSelectCallbacks.length &&+ !_itemSelectCallbacks.some((fn) =>+ fn({+ updatedTerm,+ searchTermChanged: this.args.searchTermChanged,+ usage: this.args.usage,+ })+ )+ ) {+ // Return early if any callbacks return false+ return;+ }++ this.args.searchTermChanged(updatedTerm, {+ searchTopics,+ ...(inTopicContext &&+ !this.args.searchAllTopics && { setTopicContext: true }),+ });+ focusSearchInput();+ }+ }+++{{! template-lint-disable no-pointer-down-event-binding }}+{{! template-lint-disable no-invalid-interactive }}+<li+ class={{concat-class @typeClass "search-menu-assistant-item"}}+ {{on "keydown" this.onKeydown}}+ {{on "click" this.onClick}}+ data-usage={{@usage}}+>+ <a class="search-link" href={{this.href}}>+ <span aria-label={{i18n "search.title"}}>+ {{d-icon (or @icon "magnifying-glass")}}+ </span>++ {{#if this.prefix}}+ <span class="search-item-prefix">+ {{this.prefix}}+ </span>+ {{/if}}++ {{#if @withInLabel}}+ <span class="label-suffix">{{i18n "search.in"}}</span>+ {{/if}}++ {{#if @category}}+ <SearchMenu::Results::Type::Category @result={{@category}} />+ {{#if (and @tag @isIntersection)}}+ <span class="search-item-tag">+ {{d-icon "tag"}}{{@tag}}+ </span>+ {{/if}}+ {{else if @tag}}+ {{#if (and @isIntersection @additionalTags.length)}}+ <span class="search-item-tag">{{this.tagsSlug}}</span>+ {{else}}+ <span class="search-item-tag">+ <SearchMenu::Results::Type::Tag @result={{@tag}} />+ </span>+ {{/if}}+ {{else if @user}}+ <span class="search-item-user">+ <SearchMenu::Results::Type::User @result={{@user}} />+ </span>+ {{/if}}++ <span class="search-item-slug">+ {{#if @suffix}}+ <span class="label-suffix">{{@suffix}}</span>+ {{/if}}+ {{@label}}+ </span>+ {{#if @extraHint}}+ <span class="extra-hint">+ {{i18n "search.enter_hint"}}+ </span>+ {{/if}}+ </a>+</li>diff --cc app/assets/javascripts/discourse/app/components/search-menu/results/assistant.gjsindex 29de87a014e,8ed297982ea..26e14c4002f--- a/app/assets/javascripts/discourse/app/components/search-menu/results/assistant.gjs+++ b/app/assets/javascripts/discourse/app/components/search-menu/results/assistant.gjs@@@ -1,97 -1,128 +1,226 @@@+ import Component from "@glimmer/component";+ import { service } from "@ember/service";++ const suggestionShortcuts = [+ "in:title",+ "in:pinned",+ "status:open",+ "status:closed",+ "status:public",+ "status:noreplies",+ "order:latest",+ "order:views",+ "order:likes",+ "order:latest_topic",+ ];++ const SUGGESTION_KEYWORD_MAP = {+ "+": "tagIntersection",+ "#": "categoryOrTag",+ "@": "user",+ };++ export default class Assistant extends Component {+ @service router;+ @service currentUser;+ @service siteSettings;+ @service search;++ constructor() {+ super(...arguments);++ if (this.currentUser) {+ addSearchSuggestion("in:likes");+ addSearchSuggestion("in:bookmarks");+ addSearchSuggestion("in:mine");+ addSearchSuggestion("in:messages");+ addSearchSuggestion("in:seen");+ addSearchSuggestion("in:tracking");+ addSearchSuggestion("in:unseen");+ addSearchSuggestion("in:watching");+ }++ if (this.siteSettings.tagging_enabled) {+ addSearchSuggestion("in:tagged");+ addSearchSuggestion("in:untagged");+ }+ }++ get suggestionShortcuts() {+ const shortcut = this.search.activeGlobalSearchTerm.split(" ").slice(-1);+ const suggestions = suggestionShortcuts.filter((suggestion) =>+ suggestion.includes(shortcut)+ );+ return suggestions.slice(0, 8);+ }++ get userMatchesInTopic() {+ return (+ this.args.results.length === 1 &&+ this.router.currentRouteName.startsWith("topic.")+ );+ }++ get suggestionType() {+ switch (this.args.suggestionKeyword) {+ case "+":+ return SUGGESTION_KEYWORD_MAP[this.args.suggestionKeyword];+ case "#":+ return SUGGESTION_KEYWORD_MAP[this.args.suggestionKeyword];+ case "@":+ return SUGGESTION_KEYWORD_MAP[this.args.suggestionKeyword];+ }+ }++ get prefix() {+ let prefix = "";+ if (this.args.suggestionKeyword !== "+") {+ prefix =+ this.args.slug?.split(this.args.suggestionKeyword)[0].trim() || "";+ if (prefix.length) {+ prefix = `${prefix} `;+ }+ } else {+ this.args.results.forEach((result) => {+ if (result.additionalTags) {+ prefix =+ this.args.slug?.split(" ").slice(0, -1).join(" ").trim() || "";+ } else {+ prefix = this.args.slug?.split("#")[0].trim() || "";+ }+ if (prefix.length) {+ prefix = `${prefix} `;+ }+ });+ }+ return prefix;+ }++ // For all results that are a category we need to assign+ // a 'fullSlug' for each object. It would place too much logic+ // to do this on the fly within the view so instead we build+ // a 'fullSlugForCategoryMap' which we can then+ // access in the view by 'category.id'+ get fullSlugForCategoryMap() {+ const categoryMap = {};+ this.args.results.forEach((result) => {+ if (result.model) {+ const fullSlug = result.model.parentCategory+ ? `#${result.model.parentCategory.slug}:${result.model.slug}`+ : `#${result.model.slug}`;+ categoryMap[result.model.id] = `${this.prefix}${fullSlug}`;+ }+ });+ return categoryMap;+ }++ get user() {+ // when only one user matches while in topic+ // quick suggest user search in the topic or globally+ return this.args.results[0];+ }+ }++ export function addSearchSuggestion(value) {+ if (!suggestionShortcuts.includes(value)) {+ suggestionShortcuts.push(value);+ }+ }+++<ul class="search-menu-assistant">+ {{! suggestion type keywords are mapped to SUGGESTION_KEYWORD_MAP }}+ {{#if (eq this.suggestionType "tagIntersection")}}+ <PluginOutlet @name="search-menu-results-assistant-tag-intersection-top" />+ {{#each @results as |result|}}+ <SearchMenu::Results::AssistantItem+ @tag={{result.tagName}}+ @additionalTags={{result.additionalTags}}+ @category={{result.category}}+ @slug={{@slug}}+ @withInLabel={{@withInLabel}}+ @isIntersection={{true}}+ @searchAllTopics={{true}}+ @searchTermChanged={{@searchTermChanged}}+ @suggestionKeyword={{@suggestionKeyword}}+ @typeClass="tag-intersection"+ />+ {{/each}}+ {{else if (eq this.suggestionType "categoryOrTag")}}+ <PluginOutlet @name="search-menu-results-assistant-category-or-tag-top" />+ {{#each @results as |result|}}+ {{#if result.model}}+ {{! render category }}+ <SearchMenu::Results::AssistantItem+ @category={{result.model}}+ @slug={{get this.fullSlugForCategoryMap result.model.id}}+ @withInLabel={{@withInLabel}}+ @searchAllTopics={{true}}+ @searchTermChanged={{@searchTermChanged}}+ @suggestionKeyword={{@suggestionKeyword}}+ @typeClass="category"+ />+ {{else}}+ {{! render tag }}+ <SearchMenu::Results::AssistantItem+ @tag={{result.name}}+ @slug={{concat this.prefix "#" result.name}}+ @withInLabel={{@withInLabel}}+ @searchAllTopics={{true}}+ @searchTermChanged={{@searchTermChanged}}+ @suggestionKeyword={{@suggestionKeyword}}+ @typeClass="tag"+ />+ {{/if}}+ {{/each}}+ {{else if (eq this.suggestionType "user")}}+ <PluginOutlet @name="search-menu-results-assistant-user-top" />+ {{#if this.userMatchesInTopic}}+ <SearchMenu::Results::AssistantItem+ @extraHint={{true}}+ @user={{this.user}}+ @slug={{concat this.prefix "@" this.user.username}}+ @suffix={{i18n "search.in_topics_posts"}}+ @searchAllTopics={{true}}+ @searchTermChanged={{@searchTermChanged}}+ @suggestionKeyword={{@suggestionKeyword}}+ @typeClass="user"+ />++ <SearchMenu::Results::AssistantItem+ @user={{this.user}}+ @slug={{concat this.prefix "@" this.user.username}}+ @suffix={{i18n "search.in_this_topic"}}+ @searchTermChanged={{@searchTermChanged}}+ @suggestionKeyword={{@suggestionKeyword}}+ @typeClass="user"+ />+ {{else}}+ {{#each @results as |result|}}+ <SearchMenu::Results::AssistantItem+ @user={{result}}+ @slug={{concat this.prefix "@" result.username}}+ @searchAllTopics={{true}}+ @searchTermChanged={{@searchTermChanged}}+ @suggestionKeyword={{@suggestionKeyword}}+ @typeClass="user"+ />+ {{/each}}+ {{/if}}+ {{else}}+ <PluginOutlet+ @name="search-menu-results-assistant-shortcut-top"+ @outletArgs={{hash suggestionShortcuts=this.suggestionShortcuts}}+ />+ {{#each this.suggestionShortcuts as |item|}}+ <SearchMenu::Results::AssistantItem+ @slug={{concat this.prefix item}}+ @label={{item}}+ @searchAllTopics={{true}}+ @searchTermChanged={{@searchTermChanged}}+ @suggestionKeyword={{@suggestionKeyword}}+ @typeClass="shortcut"+ />+ {{/each}}+ {{/if}}+ <PluginOutlet @name="search-menu-assistant-bottom" />+</ul>diff --cc app/assets/javascripts/discourse/app/components/search-menu/results/blurb.gjsindex 5558a2cb8e1,9fbd8c3b36b..228b4846d8f--- a/app/assets/javascripts/discourse/app/components/search-menu/results/blurb.gjs+++ b/app/assets/javascripts/discourse/app/components/search-menu/results/blurb.gjs@@@ -1,11 -1,7 +1,19 @@@+ import Component from "@glimmer/component";+ import { service } from "@ember/service";++ export default class Blurb extends Component {+ @service siteSettings;+ @service site;+ }+++<span class="blurb">+ {{format-age @result.created_at}}+ <span class="blurb__separator"> - </span>+ {{#if this.siteSettings.use_pg_headlines_for_excerpt}}+ <span>{{html-safe @result.blurb}}</span>+ {{else}}+ <span class="blurb__text">+ <SearchMenu::HighlightedSearch @string={{@result.blurb}} />+ </span>+ {{/if}}+</span>diff --cc app/assets/javascripts/discourse/app/components/search-menu/results/initial-options.gjsindex b4e611b2e06,5fa4c315634..8a528806651--- a/app/assets/javascripts/discourse/app/components/search-menu/results/initial-options.gjs+++ b/app/assets/javascripts/discourse/app/components/search-menu/results/initial-options.gjs@@@ -1,76 -1,144 +1,221 @@@+ import Component from "@glimmer/component";+ import { service } from "@ember/service";+ import { MODIFIER_REGEXP } from "discourse/components/search-menu";+ import { i18n } from "discourse-i18n";+ import Assistant from "./assistant";+ import AssistantItem from "./assistant-item";++ const SEARCH_CONTEXT_TYPE_COMPONENTS = {+ topic: AssistantItem,+ private_messages: AssistantItem,+ category: Assistant,+ tag: Assistant,+ tagIntersection: Assistant,+ user: AssistantItem,+ };++ const DISPLAY_INITIAL_OPTIONS_FOR_CONTEXT_TYPES = [+ "topic",+ "category",+ "tag",+ "tagIntersection",+ "user",+ ];++ export default class InitialOptions extends Component {+ @service search;+ @service siteSettings;+ @service currentUser;++ constructor() {+ super(...arguments);++ if (this.search.activeGlobalSearchTerm || this.search.searchContext) {+ if (this.search.searchContext) {+ // set the component we will be using to display results+ this.contextTypeComponent =+ SEARCH_CONTEXT_TYPE_COMPONENTS[this.search.searchContext.type];+ // set attributes for the component+ this.setAttributesForSearchContextType(this.search.searchContext.type);+ }+ }+ }++ get termMatchesContextTypeKeyword() {+ return this.search.activeGlobalSearchTerm?.match(MODIFIER_REGEXP);+ }++ get displayInitialOptions() {+ if (this.search.activeGlobalSearchTerm) {+ return false;+ }+ return DISPLAY_INITIAL_OPTIONS_FOR_CONTEXT_TYPES.includes(+ this.search.searchContext?.type+ );+ }++ setAttributesForSearchContextType(type) {+ switch (type) {+ case "topic":+ this.topicContextType();+ break;+ case "private_messages":+ this.privateMessageContextType();+ break;+ case "category":+ this.categoryContextType();+ break;+ case "tag":+ this.tagContextType();+ break;+ case "tagIntersection":+ this.tagIntersectionContextType();+ break;+ case "user":+ this.userContextType();+ break;+ }+ }++ topicContextType() {+ this.suffix = i18n("search.in_this_topic");+ }++ privateMessageContextType() {+ this.slug = "in:messages";+ this.label = "in:messages";+ }++ categoryContextType() {+ const searchContextCategory = this.search.searchContext.category;+ const fullSlug = searchContextCategory.parentCategory+ ? `#${searchContextCategory.parentCategory.slug}:${searchContextCategory.slug}`+ : `#${searchContextCategory.slug}`;++ this.slug = fullSlug;+ this.contextTypeKeyword = "#";+ this.initialResults = [{ model: this.search.searchContext.category }];+ this.withInLabel = true;+ }++ tagContextType() {+ this.slug = `#${this.search.searchContext.name}`;+ this.contextTypeKeyword = "#";+ this.initialResults = [{ name: this.search.searchContext.name }];+ this.withInLabel = true;+ }++ tagIntersectionContextType() {+ const searchContext = this.search.searchContext;++ let tagTerm;+ if (searchContext.additionalTags) {+ const tags = [searchContext.tagId, ...searchContext.additionalTags];+ tagTerm = `tags:${tags.join("+")}`;+ } else {+ tagTerm = `#${searchContext.tagId}`;+ }+ let suggestionOptions = {+ tagName: searchContext.tagId,+ additionalTags: searchContext.additionalTags,+ };+ if (searchContext.category) {+ const categorySlug = searchContext.category.parentCategory+ ? `#${searchContext.category.parentCategory.slug}:${searchContext.category.slug}`+ : `#${searchContext.category.slug}`;+ suggestionOptions.categoryName = categorySlug;+ suggestionOptions.category = searchContext.category;+ tagTerm = tagTerm + ` ${categorySlug}`;+ }++ this.slug = tagTerm;+ this.contextTypeKeyword = "+";+ this.initialResults = [suggestionOptions];+ this.withInLabel = true;+ }++ userContextType() {+ this.contextTypeKeyword = "@";+ this.slug = `@${this.search.searchContext.user.username}`;+ this.suffix = i18n("search.in_posts_by", {+ username: this.search.searchContext.user.username,+ });+ }+ }+++<ul class="search-menu-initial-options">+ <PluginOutlet+ @name="search-menu-initial-options"+ @outletArgs={{hash+ termMatchesContextTypeKeyword=this.termMatchesContextTypeKeyword+ contextTypeComponent=this.contextTypeComponent+ slug=this.slug+ suggestionKeyword=this.contextTypeKeyword+ results=this.initialResults+ withInLabel=this.withInLabel+ suffix=this.suffix+ label=this.label+ closeSearchMenu=@closeSearchMenu+ searchTermChanged=@searchTermChanged+ }}+ >+ {{#if this.termMatchesContextTypeKeyword}}+ <SearchMenu::Results::AssistantItem+ @slug={{this.slug}}+ @extraHint={{true}}+ @closeSearchMenu={{@closeSearchMenu}}+ @searchTermChanged={{@searchTermChanged}}+ @suggestionKeyword={{this.contextTypeKeyword}}+ />+ {{else}}+ {{#if (or this.search.activeGlobalSearchTerm this.search.searchContext)}}+ {{#if this.search.activeGlobalSearchTerm}}+ <SearchMenu::Results::AssistantItem+ @suffix={{i18n "search.in_topics_posts"}}+ @closeSearchMenu={{@closeSearchMenu}}+ @searchAllTopics={{true}}+ @extraHint={{true}}+ @searchTermChanged={{@searchTermChanged}}+ @suggestionKeyword={{this.contextTypeKeyword}}+ />+ {{/if}}++ {{#if this.search.searchContext}}+ <this.contextTypeComponent+ @slug={{this.slug}}+ @suggestionKeyword={{this.contextTypeKeyword}}+ @results={{this.initialResults}}+ @withInLabel={{this.withInLabel}}+ @suffix={{this.suffix}}+ @label={{this.label}}+ @closeSearchMenu={{@closeSearchMenu}}+ @searchTermChanged={{@searchTermChanged}}+ />++ {{#if+ (and+ this.currentUser+ this.siteSettings.log_search_queries+ this.displayInitialOptions+ )+ }}+ <SearchMenu::Results::RecentSearches+ @closeSearchMenu={{@closeSearchMenu}}+ @searchTermChanged={{@searchTermChanged}}+ />+ {{/if}}+ {{/if}}+ {{else}}+ <SearchMenu::Results::RandomQuickTip+ @searchTermChanged={{@searchTermChanged}}+ />+ {{#if (and this.currentUser this.siteSettings.log_search_queries)}}+ <SearchMenu::Results::RecentSearches+ @closeSearchMenu={{@closeSearchMenu}}+ @searchTermChanged={{@searchTermChanged}}+ />+ {{/if}}+ {{/if}}+ {{/if}}+ </PluginOutlet>+</ul>diff --cc app/assets/javascripts/discourse/app/components/search-menu/results/more-link.gjsindex 72cccafbc1d,8b806058d74..7ea44b57298--- a/app/assets/javascripts/discourse/app/components/search-menu/results/more-link.gjs+++ b/app/assets/javascripts/discourse/app/components/search-menu/results/more-link.gjs@@@ -1,21 -1,45 +1,67 @@@+ import Component from "@glimmer/component";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import DiscourseURL from "discourse/lib/url";++ export default class MoreLink extends Component {+ @service search;++ get topicResults() {+ const topicResults = this.args.resultTypes.filter(+ (resultType) => resultType.type === "topic"+ );+ return topicResults[0];+ }++ get moreUrl() {+ return this.topicResults.moreUrl && this.topicResults.moreUrl();+ }++ @action+ transitionToMoreUrl(event) {+ event.preventDefault();+ this.args.closeSearchMenu();+ DiscourseURL.routeTo(this.moreUrl);+ return false;+ }++ @action+ moreOfType(type) {+ this.args.updateTypeFilter(type);+ this.args.triggerSearch();+ this.args.closeSearchMenu();+ }++ @action+ onKeyup(e) {+ if (e.key === "Escape") {+ this.args.closeSearchMenu();+ e.preventDefault();+ return false;+ }++ this.search.handleArrowUpOrDown(e);+ }+ }+++{{#if this.topicResults}}+ {{! template-lint-disable no-invalid-interactive }}+ <div class="search-menu__show-more" {{on "keyup" this.onKeyup}}>+ {{#if this.moreUrl}}+ <a+ href={{this.moreUrl}}+ {{on "click" this.transitionToMoreUrl}}+ class="filter search-link"+ >+ {{i18n "more"}}...+ </a>+ {{else if this.topicResults.more}}+ <a+ {{on "click" (fn this.moreOfType this.topicResults.type)}}+ class="filter search-link"+ >+ {{i18n "more"}}...+ </a>+ {{/if}}+ </div>+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/search-menu/results/random-quick-tip.gjsindex c9da7348637,f72cd95343f..7c59f8b2263--- a/app/assets/javascripts/discourse/app/components/search-menu/results/random-quick-tip.gjs+++ b/app/assets/javascripts/discourse/app/components/search-menu/results/random-quick-tip.gjs@@@ -1,16 -1,74 +1,91 @@@+ import Component from "@glimmer/component";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import { focusSearchInput } from "discourse/components/search-menu";+ import { i18n } from "discourse-i18n";++ const DEFAULT_QUICK_TIPS = [+ {+ label: "#",+ description: i18n("search.tips.category_tag"),+ clickable: true,+ },+ {+ label: "@",+ description: i18n("search.tips.author"),+ clickable: true,+ },+ {+ label: "in:",+ description: i18n("search.tips.in"),+ clickable: true,+ },+ {+ label: "status:",+ description: i18n("search.tips.status"),+ clickable: true,+ },+ {+ label: i18n("search.tips.full_search_key", { modifier: "Ctrl" }),+ description: i18n("search.tips.full_search"),+ },+ {+ label: "@me",+ description: i18n("search.tips.me"),+ },+ ];++ let QUICK_TIPS = [];++ export function addQuickSearchRandomTip(tip) {+ if (!QUICK_TIPS.includes(tip)) {+ QUICK_TIPS.push(tip);+ }+ }++ export function resetQuickSearchRandomTips() {+ QUICK_TIPS = [].concat(DEFAULT_QUICK_TIPS);+ }++ export function removeDefaultQuickSearchRandomTips() {+ QUICK_TIPS = QUICK_TIPS.filter((tip) => !DEFAULT_QUICK_TIPS.includes(tip));+ }++ resetQuickSearchRandomTips();++ export default class RandomQuickTip extends Component {+ @service search;++ constructor() {+ super(...arguments);+ this.randomTip = QUICK_TIPS[Math.floor(Math.random() * QUICK_TIPS.length)];+ }++ @action+ tipSelected(e) {+ if (e.target.classList.contains("tip-clickable")) {+ this.args.searchTermChanged(this.randomTip.label);+ focusSearchInput();++ e.stopPropagation();+ e.preventDefault();+ }+ }+ }+++<li class="search-random-quick-tip">+ <button+ class={{concat-class+ "tip-label"+ (if this.randomTip.clickable "tip-clickable")+ }}+ {{on "click" this.tipSelected}}+ aria-describedby="tip-description"+ >+ {{this.randomTip.label}}+ </button>++ <span id="tip-description">+ {{this.randomTip.description}}+ </span>+</li>diff --cc app/assets/javascripts/discourse/app/components/search-menu/results/recent-searches.gjsindex bb0381202af,3c596adfcb0..771eeb9f76a--- a/app/assets/javascripts/discourse/app/components/search-menu/results/recent-searches.gjs+++ b/app/assets/javascripts/discourse/app/components/search-menu/results/recent-searches.gjs@@@ -1,25 -1,47 +1,73 @@@+ import Component from "@glimmer/component";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import User from "discourse/models/user";++ export default class RecentSearches extends Component {+ @service currentUser;+ @service siteSettings;++ constructor() {+ super(...arguments);++ if (+ this.currentUser &&+ this.siteSettings.log_search_queries &&+ !this.currentUser.recent_searches?.length+ ) {+ this.loadRecentSearches();+ }+ }++ @action+ async clearRecent() {+ const result = await User.resetRecentSearches();+ if (result.success) {+ this.currentUser.recent_searches.clear();+ }+ }++ @action+ onKeyup(e) {+ if (e.key === "Escape") {+ this.args.closeSearchMenu();+ e.preventDefault();+ return false;+ }++ this.search.handleArrowUpOrDown(e);+ }++ async loadRecentSearches() {+ const result = await User.loadRecentSearches();+ if (result.success && result.recent_searches?.length) {+ this.currentUser.set("recent_searches", result.recent_searches);+ }+ }+ }+++{{#if this.currentUser.recent_searches}}+ <div class="search-menu-recent">+ <div class="heading">+ <h4>{{i18n "search.recent"}}</h4>+ <FlatButton+ @title="search.clear_recent"+ @icon="xmark"+ @action={{this.clearRecent}}+ class="clear-recent-searches"+ />+ </div>++ {{#each this.currentUser.recent_searches as |slug|}}+ <SearchMenu::Results::AssistantItem+ @icon="clock-rotate-left"+ @label={{slug}}+ @slug={{slug}}+ @closeSearchMenu={{@closeSearchMenu}}+ @searchTermChanged={{@searchTermChanged}}+ @usage="recent-search"+ @concatSlug={{true}}+ />+ {{/each}}+ </div>+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/search-menu/results/type/topic.gjsindex f5c9e681cdd,e8e79e4594b..10ff6ed35ee--- a/app/assets/javascripts/discourse/app/components/search-menu/results/type/topic.gjs+++ b/app/assets/javascripts/discourse/app/components/search-menu/results/type/topic.gjs@@@ -1,36 -1,6 +1,43 @@@+ import Component from "@glimmer/component";+ import { service } from "@ember/service";++ export default class Results extends Component {+ @service siteSettings;+ }+++<span class="topic">+ <span class="first-line">+ <TopicStatus+ @topic={{@result.topic}}+ @disableActions={{true}}+ @context="topic-view-title"+ />+ <span class="topic-title" data-topic-id={{@result.topic.id}}>+ {{#if+ (and+ this.siteSettings.use_pg_headlines_for_excerpt+ @result.topic_title_headline+ )+ }}+ <a href={{if @withTopicUrl @result.url}}>+ {{replace-emoji (html-safe @result.topic_title_headline)}}+ </a>+ {{else}}+ <a href={{if @withTopicUrl @result.url}}>+ <SearchMenu::HighlightedSearch @string={{@result.topic.fancyTitle}} />+ </a>+ {{/if}}+ <PluginOutlet+ @name="search-menu-results-topic-title-suffix"+ @outletArgs={{hash [email protected]}}+ />+ </span>+ </span>+ <span class="second-line">+ {{category-link @result.topic.category link=(if @withTopicUrl true false)}}+ {{#if this.siteSettings.tagging_enabled}}+ {{discourse-tags @result.topic tagName="span"}}+ {{/if}}+ </span>+</span>+<SearchMenu::Results::Blurb @result={{@result}} />diff --cc app/assets/javascripts/discourse/app/components/search-menu/results/types.gjsindex 11cf81ebb71,1f4edc87f59..e468bab3e80--- a/app/assets/javascripts/discourse/app/components/search-menu/results/types.gjs+++ b/app/assets/javascripts/discourse/app/components/search-menu/results/types.gjs@@@ -1,38 -1,68 +1,107 @@@+ import Component from "@glimmer/component";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import { wantsNewWindow } from "discourse/lib/intercept-click";+ import { logSearchLinkClick } from "discourse/lib/search";+ import DiscourseURL from "discourse/lib/url";++ export default class Types extends Component {+ @service search;++ get filteredResultTypes() {+ // return only topic result types+ if (this.args.topicResultsOnly) {+ return this.args.resultTypes.filter(+ (resultType) => resultType.type === "topic"+ );+ }++ // return all result types minus topics+ return this.args.resultTypes.filter(+ (resultType) => resultType.type !== "topic"+ );+ }++ @action+ onClick({ resultType, result }, event) {+ logSearchLinkClick({+ searchLogId: this.args.searchLogId,+ searchResultId: result.id,+ searchResultType: resultType.type,+ });++ if (wantsNewWindow(event)) {+ return;+ }++ event.preventDefault();+ this.routeToSearchResult(event.currentTarget.href);+ }++ @action+ onKeydown({ resultType, result }, event) {+ if (event.key === "Escape") {+ this.args.closeSearchMenu();+ event.preventDefault();+ return false;+ } else if (event.key === "Enter") {+ event.preventDefault();+ event.stopPropagation();+ logSearchLinkClick({+ searchLogId: this.args.searchLogId,+ searchResultId: result.id,+ searchResultType: resultType.type,+ });+ this.routeToSearchResult(event.target.href);+ return false;+ }++ this.search.handleResultInsertion(event);+ this.search.handleArrowUpOrDown(event);+ }++ @action+ routeToSearchResult(href) {+ DiscourseURL.routeTo(href);+ this.args.closeSearchMenu();+ }+ }+++{{#each this.filteredResultTypes as |resultType|}}+ <div class={{resultType.componentName}}>+ <PluginOutlet+ @name="search-menu-results-type-top"+ @outletArgs={{hash resultType=resultType}}+ />+ <ul+ class="list"+ aria-label={{concat (i18n "search.results") " " resultType.type}}+ >+ {{#each resultType.results as |result|}}+ {{! template-lint-disable no-pointer-down-event-binding }}+ {{! template-lint-disable no-invalid-interactive }}+ <li+ class="item"+ {{on+ "keydown"+ (fn this.onKeydown (hash resultType=resultType result=result))+ }}+ >+ <a+ href={{or result.url result.path}}+ {{on+ "click"+ (fn this.onClick (hash resultType=resultType result=result))+ }}+ class="search-link"+ >+ <resultType.component+ @result={{result}}+ @displayNameWithUser={{@displayNameWithUser}}+ />+ </a>+ </li>+ {{/each}}+ </ul>+ </div>+{{/each}}diff --cc app/assets/javascripts/discourse/app/components/search-menu/search-term.gjsindex d34c37136a6,7a399221eb6..c91f8b7ed72--- a/app/assets/javascripts/discourse/app/components/search-menu/search-term.gjs+++ b/app/assets/javascripts/discourse/app/components/search-menu/search-term.gjs@@@ -1,14 -1,117 +1,132 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import {+ DEFAULT_TYPE_FILTER,+ SEARCH_INPUT_ID,+ } from "discourse/components/search-menu";+ import { isiPad } from "discourse/lib/utilities";++ const SECOND_ENTER_MAX_DELAY = 15000;++ const onKeyUpCallbacks = [];++ export function addOnKeyUpCallback(fn) {+ onKeyUpCallbacks.push(fn);+ }+ export function resetOnKeyUpCallbacks() {+ onKeyUpCallbacks.clear();+ }++ export default class SearchTerm extends Component {+ @service search;+ @service appEvents;++ @tracked lastEnterTimestamp = null;+ @tracked searchCleared = !this.search.activeGlobalSearchTerm;++ // make constant available in template+ get inputId() {+ return SEARCH_INPUT_ID;+ }++ @action+ updateSearchTerm(input) {+ this.parseAndUpdateSearchTerm(+ this.search.activeGlobalSearchTerm,+ input.target.value+ );++ this.searchCleared = this.search.activeGlobalSearchTerm ? false : true;+ }++ @action+ focus(element) {+ if (this.args.autofocus) {+ element.focus();+ element.select();+ }+ }++ @action+ onKeydown(e) {+ if (e.key === "Escape") {+ this.args.closeSearchMenu();+ e.preventDefault();+ e.stopPropagation();+ }+ }++ @action+ onKeyup(e) {+ if (+ onKeyUpCallbacks.length &&+ !onKeyUpCallbacks.some((fn) => fn(this, e))+ ) {+ // Return early if any callbacks return false+ return;+ }++ this.args.openSearchMenu();++ this.search.handleArrowUpOrDown(e);++ if (e.key === "Enter") {+ const recentEnterHit =+ this.lastEnterTimestamp &&+ Date.now() - this.lastEnterTimestamp < SECOND_ENTER_MAX_DELAY;++ if (+ e.ctrlKey ||+ e.metaKey ||+ (isiPad() && e.altKey) ||+ (this.args.typeFilter !== DEFAULT_TYPE_FILTER && recentEnterHit)+ ) {+ this.args.fullSearch();+ this.args.closeSearchMenu();+ } else {+ this.args.updateTypeFilter(null);+ this.args.triggerSearch();+ }+ this.lastEnterTimestamp = Date.now();+ }++ if (e.key === "Backspace") {+ if (!e.target.value) {+ // only clear context if we're not in the middle of a search+ if (this.searchCleared) {+ this.args.clearTopicContext();+ this.args.clearPMInboxContext();+ this.focus(e.target);+ }+ this.searchCleared = true;+ }+ }++ e.preventDefault();+ }++ parseAndUpdateSearchTerm(originalVal, newVal) {+ // remove zero-width chars+ const parsedVal = newVal.replace(/[\u200B-\u200D\uFEFF]/, "");+ if (parsedVal !== originalVal) {+ this.args.searchTermChanged(parsedVal);+ }+ }+ }+++<input+ id={{this.inputId}}+ type="search"+ autocomplete="off"+ enterkeyhint="search"+ value={{this.search.activeGlobalSearchTerm}}+ placeholder={{i18n "search.title"}}+ aria-label={{i18n "search.title"}}+ {{on "keyup" this.onKeyup}}+ {{on "keydown" this.onKeydown}}+ {{on "input" this.updateSearchTerm}}+ {{on "focus" @openSearchMenu}}+ {{did-insert this.focus}}+/>diff --cc app/assets/javascripts/discourse/app/components/search-result-entries.gjsindex ddbf9ad4539,b11dbe5a61a..ae002c3d8db--- a/app/assets/javascripts/discourse/app/components/search-result-entries.gjs+++ b/app/assets/javascripts/discourse/app/components/search-result-entries.gjs@@@ -1,11 -1,5 +1,17 @@@+ import Component from "@ember/component";+ import { tagName } from "@ember-decorators/component";++ @tagName("")+ export default class SearchResultEntries extends Component {}+++<div class="fps-result-entries" role="list">+ {{#each this.posts as |post|}}+ <SearchResultEntry+ @post={{post}}+ @bulkSelectEnabled={{this.bulkSelectEnabled}}+ @selected={{this.selected}}+ @highlightQuery={{this.highlightQuery}}+ @searchLogId={{this.searchLogId}}+ />+ {{/each}}+</div>diff --cc app/assets/javascripts/discourse/app/components/search-result-entry.gjsindex af53b82109d,86aa22c7631..ed204d39af5--- a/app/assets/javascripts/discourse/app/components/search-result-entry.gjs+++ b/app/assets/javascripts/discourse/app/components/search-result-entry.gjs@@@ -1,104 -1,34 +1,139 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import {+ attributeBindings,+ classNameBindings,+ classNames,+ tagName,+ } from "@ember-decorators/component";+ import { wantsNewWindow } from "discourse/lib/intercept-click";+ import { logSearchLinkClick } from "discourse/lib/search";++ @tagName("div")+ @classNames("fps-result")+ @classNameBindings("bulkSelectEnabled")+ @attributeBindings("role")+ export default class SearchResultEntry extends Component {+ role = "listitem";++ @action+ logClick(topicId, event) {+ // Avoid click logging when any modifier keys are pressed.+ if (wantsNewWindow(event)) {+ return;+ }++ if (this.searchLogId && topicId) {+ logSearchLinkClick({+ searchLogId: this.searchLogId,+ searchResultId: topicId,+ searchResultType: "topic",+ });+ }+ }+ }+++<PluginOutlet+ @name="search-results-topic-avatar-wrapper"+ @outletArgs={{hash post=this.post}}+>+ <div class="author">+ <a href={{this.post.userPath}} data-user-card={{this.post.username}}>+ {{avatar this.post imageSize="large"}}+ </a>+ </div>++</PluginOutlet>++<div class="fps-topic" data-topic-id={{this.post.topic.id}}>+ <div class="topic">++ {{#if this.bulkSelectEnabled}}+ <TrackSelected+ @selectedList={{this.selected}}+ @selectedId={{this.post.topic}}+ class="bulk-select"+ />+ {{/if}}++ <a+ href={{this.post.url}}+ {{on "click" (fn this.logClick this.post.topic_id)}}+ class="search-link{{if this.post.topic.visited ' visited'}}"+ role="heading"+ aria-level="2"+ >+ {{raw "topic-status" topic=this.post.topic showPrivateMessageIcon=true}}+ <span class="topic-title">+ {{#if this.post.useTopicTitleHeadline}}+ {{html-safe this.post.topicTitleHeadline}}+ {{else}}+ <HighlightSearch @highlight={{this.highlightQuery}}>+ {{html-safe this.post.topic.fancyTitle}}+ </HighlightSearch>+ {{/if}}+ </span>+ <PluginOutlet+ @name="search-results-topic-title-suffix"+ @outletArgs={{hash topic=this.post.topic}}+ />+ </a>++ <div class="search-category">+ {{#if this.post.topic.category.parentCategory}}+ {{category-link this.post.topic.category.parentCategory}}+ {{/if}}+ {{category-link this.post.topic.category hideParent=true}}+ {{#if this.post.topic}}+ {{discourse-tags this.post.topic}}+ {{/if}}+ <span>+ <PluginOutlet+ @name="full-page-search-category"+ @connectorTagName="div"+ @outletArgs={{hash post=this.post}}+ />+ </span>+ </div>+ </div>++ <PluginOutlet+ @name="search-result-entry-blurb-wrapper"+ @outletArgs={{hash post=this.post logClick=this.logClick}}+ >+ <div class="blurb container">+ <span class="date">+ {{format-date this.post.created_at format="tiny"}}+ {{#if this.post.blurb}}+ <span class="separator">-</span>+ {{/if}}+ </span>++ {{#if this.post.blurb}}+ {{#if this.siteSettings.use_pg_headlines_for_excerpt}}+ {{html-safe this.post.blurb}}+ {{else}}+ <HighlightSearch @highlight={{this.highlightQuery}}>+ {{html-safe this.post.blurb}}+ </HighlightSearch>+ {{/if}}+ {{/if}}+ </div>+ </PluginOutlet>++ <PluginOutlet+ @name="search-result-entry-stats-wrapper"+ @outletArgs={{hash post=this.post}}+ >+ {{#if this.showLikeCount}}+ {{#if this.post.like_count}}+ <span class="like-count">+ <span class="value">{{this.post.like_count}}</span>+ {{d-icon "heart"}}+ </span>+ {{/if}}+ {{/if}}+ </PluginOutlet>+</div>++<PluginOutlet @name="after-search-result-entry" />diff --cc app/assets/javascripts/discourse/app/components/second-factor-form.gjsindex 766245d8ef3,9e1122965b8..2f6924b4db7--- a/app/assets/javascripts/discourse/app/components/second-factor-form.gjs+++ b/app/assets/javascripts/discourse/app/components/second-factor-form.gjs@@@ -1,21 -1,65 +1,87 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import discourseComputed from "discourse/lib/decorators";+ import { SECOND_FACTOR_METHODS } from "discourse/models/user";+ import { i18n } from "discourse-i18n";++ export default class SecondFactorForm extends Component {+ @discourseComputed("secondFactorMethod")+ secondFactorTitle(secondFactorMethod) {+ switch (secondFactorMethod) {+ case SECOND_FACTOR_METHODS.TOTP:+ return i18n("login.second_factor_title");+ case SECOND_FACTOR_METHODS.SECURITY_KEY:+ return i18n("login.second_factor_title");+ case SECOND_FACTOR_METHODS.BACKUP_CODE:+ return i18n("login.second_factor_backup_title");+ }+ }++ @discourseComputed("secondFactorMethod")+ secondFactorDescription(secondFactorMethod) {+ switch (secondFactorMethod) {+ case SECOND_FACTOR_METHODS.TOTP:+ return i18n("login.second_factor_description");+ case SECOND_FACTOR_METHODS.SECURITY_KEY:+ return i18n("login.security_key_description");+ case SECOND_FACTOR_METHODS.BACKUP_CODE:+ return i18n("login.second_factor_backup_description");+ }+ }++ @discourseComputed("secondFactorMethod", "isLogin")+ linkText(secondFactorMethod, isLogin) {+ if (isLogin) {+ return secondFactorMethod === SECOND_FACTOR_METHODS.TOTP+ ? "login.second_factor_backup"+ : "login.second_factor";+ } else {+ return secondFactorMethod === SECOND_FACTOR_METHODS.TOTP+ ? "user.second_factor_backup.use"+ : "user.second_factor.use";+ }+ }++ @discourseComputed("backupEnabled", "totpEnabled", "secondFactorMethod")+ showToggleMethodLink(backupEnabled, totpEnabled, secondFactorMethod) {+ return (+ backupEnabled &&+ totpEnabled &&+ secondFactorMethod !== SECOND_FACTOR_METHODS.SECURITY_KEY+ );+ }++ @action+ toggleSecondFactorMethod(event) {+ event?.preventDefault();+ const secondFactorMethod = this.secondFactorMethod;+ this.set("secondFactorToken", "");+ if (secondFactorMethod === SECOND_FACTOR_METHODS.TOTP) {+ this.set("secondFactorMethod", SECOND_FACTOR_METHODS.BACKUP_CODE);+ } else {+ this.set("secondFactorMethod", SECOND_FACTOR_METHODS.TOTP);+ }+ }+ }+++<div id="second-factor">+ <h3>{{this.secondFactorTitle}}</h3>++ {{#if this.optionalText}}+ <p>{{html-safe this.optionalText}}</p>+ {{/if}}++ <p class="second-factor__description">{{this.secondFactorDescription}}</p>++ {{yield}}++ {{#if this.showToggleMethodLink}}+ <p>+ <a+ href+ class="toggle-second-factor-method"+ {{on "click" this.toggleSecondFactorMethod}}+ >{{i18n this.linkText}}</a>+ </p>+ {{/if}}+</div>diff --cc app/assets/javascripts/discourse/app/components/selected-posts.gjsindex 04d92e1f323,d722fe78e7f..061fd729ba0--- a/app/assets/javascripts/discourse/app/components/selected-posts.gjs+++ b/app/assets/javascripts/discourse/app/components/selected-posts.gjs@@@ -1,64 -1,3 +1,68 @@@+ import Component from "@ember/component";++ export default class SelectedPosts extends Component {}+++<p>+ <CountI18n+ @key="topic.multi_select.description"+ @count={{this.selectedPostsCount}}+ />+</p>++{{#if this.canSelectAll}}+ <p>+ <a class="select-all" href {{on "click" this.selectAll}}>+ {{i18n "topic.multi_select.select_all"}}+ </a>+ </p>+{{/if}}++{{#if this.canDeselectAll}}+ <p>+ <a href {{on "click" this.deselectAll}}>+ {{i18n "topic.multi_select.deselect_all"}}+ </a>+ </p>+{{/if}}++{{#if this.canDeleteSelected}}+ <DButton+ @action={{this.deleteSelected}}+ @icon="trash-can"+ @label="topic.multi_select.delete"+ class="btn-danger"+ />+{{/if}}++{{#if this.canMergeTopic}}+ <DButton+ @action={{route-action "moveToTopic"}}+ @icon="right-from-bracket"+ @label="topic.move_to.action"+ class="btn-primary move-to-topic"+ />+{{/if}}++{{#if this.canChangeOwner}}+ <DButton+ @action={{route-action "changeOwner"}}+ @icon="user"+ @label="topic.change_owner.action"+ class="btn-primary"+ />+{{/if}}++{{#if this.canMergePosts}}+ <DButton+ @action={{this.mergePosts}}+ @icon="up-down"+ @label="topic.merge_posts.action"+ class="btn-primary"+ />+{{/if}}++<p class="cancel">+ <a href {{on "click" this.toggleMultiSelect}}>+ {{i18n "topic.multi_select.cancel"}}+ </a>+</p>diff --cc app/assets/javascripts/discourse/app/components/share-panel.gjsindex 0f024c13ccf,d2f99ff3867..5ab5dfe19eb--- a/app/assets/javascripts/discourse/app/components/share-panel.gjs+++ b/app/assets/javascripts/discourse/app/components/share-panel.gjs@@@ -1,17 -1,70 +1,88 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { alias } from "@ember/object/computed";+ import { isEmpty } from "@ember/utils";+ import discourseComputed from "discourse/lib/decorators";+ import discourseLater from "discourse/lib/later";+ import Sharing from "discourse/lib/sharing";+ import { escapeExpression } from "discourse/lib/utilities";+ import { i18n } from "discourse-i18n";++ export default class SharePanel extends Component {+ tagName = null;++ @alias("panel.model.type") type;+ @alias("panel.model.topic") topic;+ @alias("panel.model.topic.category.read_restricted") privateCategory;++ @discourseComputed("topic.{isPrivateMessage,invisible,category}")+ sources(topic) {+ const privateContext =+ this.siteSettings.login_required ||+ (topic && topic.isPrivateMessage) ||+ (topic && topic.invisible) ||+ this.privateCategory;+ return Sharing.activeSources(this.siteSettings.share_links, privateContext);+ }++ @discourseComputed("type", "topic.title")+ shareTitle(type, topicTitle) {+ topicTitle = escapeExpression(topicTitle);+ return i18n("share.topic_html", { topicTitle });+ }++ @discourseComputed("panel.model.shareUrl", "topic.shareUrl")+ shareUrl(forcedShareUrl, shareUrl) {+ shareUrl = forcedShareUrl || shareUrl;++ if (isEmpty(shareUrl)) {+ return;+ }++ // Relative urls+ if (shareUrl.startsWith("/")) {+ const location = window.location;+ shareUrl = `${location.protocol}//${location.host}${shareUrl}`;+ }++ return encodeURI(shareUrl);+ }++ didInsertElement() {+ super.didInsertElement(...arguments);+ discourseLater(() => {+ if (this.element) {+ const textArea = this.element.querySelector(".topic-share-url");+ textArea.style.height = textArea.scrollHeight + "px";+ textArea.focus();+ textArea.setSelectionRange(0, this.shareUrl.length);+ }+ }, 200);+ }++ @action+ share(source) {+ Sharing.shareSource(source, {+ url: this.shareUrl,+ title: this.topic.get("title"),+ });+ }+ }+++<div class="header">+ <h3 class="title">{{html-safe this.shareTitle}}</h3>+</div>++<div class="body">+ <DTextarea+ @value={{this.shareUrl}}+ @aria-label={{i18n "share.url"}}+ class="topic-share-url"+ />++ <div class="sources">+ {{#each this.sources as |source|}}+ <ShareSource @source={{source}} @action={{this.share}} />+ {{/each}}+ </div>+</div>diff --cc app/assets/javascripts/discourse/app/components/sidebar.gjsindex 918457ed914,437db621637..d78a2310e16--- a/app/assets/javascripts/discourse/app/components/sidebar.gjs+++ b/app/assets/javascripts/discourse/app/components/sidebar.gjs@@@ -1,30 -1,65 +1,96 @@@+ import Component from "@glimmer/component";+ import { service } from "@ember/service";+ import { bind } from "discourse/lib/decorators";++ export default class Sidebar extends Component {+ @service appEvents;+ @service site;+ @service siteSettings;+ @service currentUser;+ @service sidebarState;++ constructor() {+ super(...arguments);++ if (this.site.mobileView) {+ document.addEventListener("click", this.collapseSidebar);+ }+ }++ willDestroy() {+ super.willDestroy(...arguments);+ if (this.site.mobileView) {+ document.removeEventListener("click", this.collapseSidebar);+ }+ }++ get showSwitchPanelButtonsOnTop() {+ return this.siteSettings.default_sidebar_switch_panel_position === "top";+ }++ get switchPanelButtons() {+ if (+ !this.sidebarState.displaySwitchPanelButtons ||+ this.sidebarState.panels.length === 1 ||+ !this.currentUser+ ) {+ return [];+ }++ return this.sidebarState.panels.filter(+ (panel) => panel !== this.sidebarState.currentPanel && !panel.hidden+ );+ }++ @bind+ collapseSidebar(event) {+ let shouldCollapseSidebar = false;++ const isClickWithinSidebar = event.composedPath().some((element) => {+ if (+ element?.className !== "sidebar-section-header-caret" &&+ ["A", "BUTTON"].includes(element.nodeName)+ ) {+ shouldCollapseSidebar = true;+ return true;+ }++ return element.className && element.className === "sidebar-wrapper";+ });++ if (shouldCollapseSidebar || !isClickWithinSidebar) {+ this.args.toggleSidebar();+ }+ }+ }+++{{body-class "has-sidebar-page"}}++<section id="d-sidebar" class="sidebar-container">+ {{#if this.showSwitchPanelButtonsOnTop}}+ <Sidebar::SwitchPanelButtons @buttons={{this.switchPanelButtons}} />+ {{/if}}++ <PluginOutlet @name="before-sidebar-sections" />++ {{#if this.sidebarState.showMainPanel}}+ <Sidebar::Sections+ @currentUser={{this.currentUser}}+ @collapsableSections={{true}}+ @panel={{this.sidebarState.currentPanel}}+ />+ {{else}}+ <Sidebar::ApiPanels+ @currentUser={{this.currentUser}}+ @collapsableSections={{true}}+ />+ {{/if}}++ <PluginOutlet @name="after-sidebar-sections" />++ {{#unless this.showSwitchPanelButtonsOnTop}}+ <Sidebar::SwitchPanelButtons @buttons={{this.switchPanelButtons}} />+ {{/unless}}++ <Sidebar::Footer />+</section>diff --cc app/assets/javascripts/discourse/app/components/signup-cta.gjsindex b3da7b60ed0,5a78cc4ffeb..aa7030b738d--- a/app/assets/javascripts/discourse/app/components/signup-cta.gjs+++ b/app/assets/javascripts/discourse/app/components/signup-cta.gjs@@@ -1,27 -1,29 +1,57 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { on } from "@ember-decorators/object";+ import discourseLater from "discourse/lib/later";++ export default class SignupCta extends Component {+ action = "showCreateAccount";++ @action+ neverShow(event) {+ event?.preventDefault();+ this.keyValueStore.setItem("anon-cta-never", "t");+ this.session.set("showSignupCta", false);+ }++ @action+ hideForSession() {+ this.session.set("hideSignupCta", true);+ this.keyValueStore.setItem("anon-cta-hidden", Date.now());+ discourseLater(() => this.session.set("showSignupCta", false), 20 * 1000);+ }++ @on("willDestroyElement")+ _turnOffIfHidden() {+ if (this.session.get("hideSignupCta")) {+ this.session.set("showSignupCta", false);+ }+ }+ }+++<div class="signup-cta alert alert-info">+ {{#if this.session.hideSignupCta}}+ <h3>+ {{i18n "signup_cta.hidden_for_session"}}+ </h3>+ {{else}}+ <h3>{{replace-emoji (i18n "signup_cta.intro")}}</h3>+ <p>{{replace-emoji (i18n "signup_cta.value_prop")}}</p>++ <div class="buttons">+ <DButton+ @action={{route-action "showCreateAccount"}}+ @label="signup_cta.sign_up"+ @icon="user"+ class="btn-primary"+ />+ <DButton+ @action={{action "hideForSession"}}+ @label="signup_cta.hide_session"+ class="no-icon"+ />+ <a href {{on "click" this.neverShow}}>{{i18n+ "signup_cta.hide_forever"+ }}</a>+ </div>+ {{/if}}+</div>diff --cc app/assets/javascripts/discourse/app/components/slow-mode-info.gjsindex 84106da8ae1,998b7feecf1..87a68ede17a--- a/app/assets/javascripts/discourse/app/components/slow-mode-info.gjs+++ b/app/assets/javascripts/discourse/app/components/slow-mode-info.gjs@@@ -1,18 -1,25 +1,44 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { durationTextFromSeconds } from "discourse/helpers/slow-mode";+ import { popupAjaxError } from "discourse/lib/ajax-error";+ import discourseComputed from "discourse/lib/decorators";+ import Topic from "discourse/models/topic";++ export default class SlowModeInfo extends Component {+ @discourseComputed("topic.slow_mode_seconds")+ durationText(seconds) {+ return durationTextFromSeconds(seconds);+ }++ @discourseComputed("topic.slow_mode_seconds", "topic.closed")+ showSlowModeNotice(seconds, closed) {+ return seconds > 0 && !closed;+ }++ @action+ disableSlowMode() {+ Topic.setSlowMode(this.topic.id, 0)+ .catch(popupAjaxError)+ .then(() => this.set("topic.slow_mode_seconds", 0));+ }+ }+++{{#if this.showSlowModeNotice}}+ <div class="topic-status-info">+ <h3 class="slow-mode-heading">+ <span>+ {{d-icon "hourglass-start"}}+ {{i18n "topic.slow_mode_notice.duration" duration=this.durationText}}+ </span>++ {{#if this.user.canManageTopic}}+ <DButton+ @action={{this.disableSlowMode}}+ @icon="trash-can"+ class="slow-mode-remove"+ />+ {{/if}}+ </h3>+ </div>+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/sub-category-item.gjsindex 26437f539eb,888c2d17242..dccc3796e29--- a/app/assets/javascripts/discourse/app/components/sub-category-item.gjs+++ b/app/assets/javascripts/discourse/app/components/sub-category-item.gjs@@@ -1,17 -1,3 +1,21 @@@+ import CategoryListItem from "discourse/components/category-list-item";++ export default class SubCategoryItem extends CategoryListItem {}+++{{#unless this.isMuted}}+ {{#if this.site.mobileView}}+ {{category-link this.category}}+ {{else}}+ <span class="subcategory">+ <CategoryTitleBefore @category={{this.category}} />+ {{category-link this.category hideParent="true"}}+ {{#unless this.hideUnread}}+ <CategoryUnread+ @category={{this.category}}+ @unreadTopicsCount={{this.unreadTopicsCount}}+ @newTopicsCount={{this.newTopicsCount}}+ />+ {{/unless}}+ </span>+ {{/if}}+{{/unless}}diff --cc app/assets/javascripts/discourse/app/components/sub-category-row.gjsindex 68e1f3bc83a,c9be1502e14..f0da753d608--- a/app/assets/javascripts/discourse/app/components/sub-category-row.gjs+++ b/app/assets/javascripts/discourse/app/components/sub-category-row.gjs@@@ -1,59 -1,3 +1,63 @@@+ import CategoryListItem from "discourse/components/category-list-item";++ export default class SubCategoryRow extends CategoryListItem {}+++{{#unless this.isHidden}}+ {{#if this.site.mobileView}}+ <tr+ data-category-id={{this.category.id}}+ style={{border-color this.category.color}}+ class="subcategory-list-item category {{if this.isMuted 'muted'}}"+ >+ <td>+ <CategoryTitleLink @tagName="h4" @category={{this.category}} />+ <div class="subcategories-list">+ {{#if this.category.subcategories}}+ <div class="subcategories">+ {{#each this.category.subcategories as |subcategory|}}+ <SubCategoryItem+ @category={{subcategory}}+ @listType={{this.listType}}+ />+ {{/each}}+ </div>+ {{/if}}+ </div>+ </td>+ </tr>+ {{else}}+ <tr+ data-category-id={{this.category.id}}+ data-notification-level={{this.category.notificationLevelString}}+ class="{{if+ this.category.description_excerpt+ 'has-description'+ 'no-description'+ }}+ {{if this.category.uploaded_logo.url 'has-logo' 'no-logo'}}"+ >+ <td+ class="category {{if this.isMuted 'muted'}}"+ style={{border-color this.category.color}}+ >+ <CategoryTitleLink @tagName="h4" @category={{this.category}} />+ {{#if this.category.description_excerpt}}+ <div class="category-description subcategory-description">+ {{dir-span this.category.description_excerpt htmlSafe="true"}}+ </div>+ {{/if}}+ {{#if this.category.subcategories}}+ <div class="subcategories">+ {{#each this.category.subcategories as |subsubcategory|}}+ <SubCategoryItem+ @category={{subsubcategory}}+ @hideUnread="true"+ @listType={{this.listType}}+ />+ {{/each}}+ </div>+ {{/if}}+ </td>+ </tr>+ {{/if}}+{{/unless}}diff --cc app/assets/javascripts/discourse/app/components/subcategories-with-featured-topics.gjsindex b8ef0f7917c,0cdcac41b2b..37a9aee460d--- a/app/assets/javascripts/discourse/app/components/subcategories-with-featured-topics.gjs+++ b/app/assets/javascripts/discourse/app/components/subcategories-with-featured-topics.gjs@@@ -1,53 -1,3 +1,57 @@@+ import Component from "@ember/component";++ export default class SubcategoriesWithFeaturedTopics extends Component {}+++{{#each this.categories as |category|}}+ {{#if this.site.mobileView}}+ <PluginOutlet+ @name="mobile-subcategories-with-featured-topics-list"+ @outletArgs={{hash category=category}}+ >+ <div class="category-list subcategory-list with-topics">+ <div class="parent-category">+ <CategoryTitleLink @category={{category}} />+ <span class="stat" title={{category.statTitle}}>{{html-safe+ category.stat+ }}</span>+ </div>+ <div class="subcategories">+ {{#each category.serializedSubcategories as |subCategory|}}+ <ParentCategoryRow @category={{subCategory}} @showTopics={{true}} />+ {{else}}+ {{! No subcategories... so just show the parent to avoid confusion }}+ <ParentCategoryRow @category={{category}} @showTopics={{true}} />+ {{/each}}+ </div>+ </div>+ </PluginOutlet>+ {{else}}+ <PluginOutlet+ @name="subcategories-with-featured-topics-list"+ @outletArgs={{hash category=category}}+ >+ <table class="category-list subcategory-list with-topics">+ <thead>+ <tr>+ <th class="parent-category">+ <CategoryTitleLink @category={{category}} />+ <span class="stat" title={{category.statTitle}}>{{html-safe+ category.stat+ }}</span>+ </th>+ <th class="topics">{{i18n "categories.topics"}}</th>+ <th class="latest">{{i18n "categories.latest"}}</th>+ </tr>+ </thead>+ <tbody aria-labelledby="categories-only-category">+ {{#each category.serializedSubcategories as |subCategory|}}+ <ParentCategoryRow @category={{subCategory}} @showTopics={{true}} />+ {{else}}+ {{! No subcategories... so just show the parent to avoid confusion }}+ <ParentCategoryRow @category={{category}} @showTopics={{true}} />+ {{/each}}+ </tbody>+ </table>+ </PluginOutlet>+ {{/if}}+{{/each}}diff --cc app/assets/javascripts/discourse/app/components/tag-list.gjsindex 19668461028,4f63bab143f..0d260b3f8ed--- a/app/assets/javascripts/discourse/app/components/tag-list.gjs+++ b/app/assets/javascripts/discourse/app/components/tag-list.gjs@@@ -1,30 -1,44 +1,75 @@@+ import Component from "@ember/component";+ import { sort } from "@ember/object/computed";+ import { classNameBindings } from "@ember-decorators/component";+ import discourseComputed from "discourse/lib/decorators";+ import Category from "discourse/models/category";+ import { i18n } from "discourse-i18n";++ @classNameBindings(+ ":tags-list",+ ":tag-list",+ "categoryClass",+ "tagGroupNameClass"+ )+ export default class TagList extends Component {+ isPrivateMessage = false;++ @sort("tags", "sortProperties") sortedTags;++ @discourseComputed("titleKey")+ title(titleKey) {+ return titleKey && i18n(titleKey);+ }++ @discourseComputed("categoryId")+ category(categoryId) {+ return categoryId && Category.findById(categoryId);+ }++ @discourseComputed("category.fullSlug")+ categoryClass(slug) {+ return slug && `tag-list-${slug}`;+ }++ @discourseComputed("tagGroupName")+ tagGroupNameClass(groupName) {+ if (groupName) {+ groupName = groupName+ .replace(/\s+/g, "-")+ .replace(/[!\"#$%&'\(\)\*\+,\.\/:;<=>\?\@\[\\\]\^`\{\|\}~]/g, "")+ .toLowerCase();+ return groupName && `tag-group-${groupName}`;+ }+ }+ }+++{{#if this.title}}+ <h3>{{this.title}}</h3>+{{/if}}+{{#if this.category}}+ <CategoryTitleLink @category={{this.category}} />+{{/if}}+{{#if this.tagGroupName}}+ <h3>{{this.tagGroupName}}</h3>+{{/if}}+{{#each this.sortedTags as |tag|}}+ <div class="tag-box">+ {{discourse-tag+ tag.id+ description=tag.description+ isPrivateMessage=this.isPrivateMessage+ pmOnly=tag.pmOnly+ tagsForUser=this.tagsForUser+ }}+ {{#if tag.pmOnly}}+ {{d-icon "envelope"}}+ {{/if}}+ {{#if tag.totalCount}}+ <span class="tag-count">+ x+ {{tag.totalCount}}+ </span>+ {{/if}}+ </div>+{{/each}}+<div class="clearfix"></div>diff --cc app/assets/javascripts/discourse/app/components/tap-tile-grid.gjsindex 271812f5e2a,dc643685bd3..3921a118344--- a/app/assets/javascripts/discourse/app/components/tap-tile-grid.gjs+++ b/app/assets/javascripts/discourse/app/components/tap-tile-grid.gjs@@@ -1,1 -1,7 +1,9 @@@+ import Component from "@ember/component";+ import { classNames } from "@ember-decorators/component";++ @classNames("tap-tile-grid")+ export default class TapTileGrid extends Component {+ activeTile = null;+ }+++{{yield (hash activeTile=this.activeTile)}}diff --cc app/assets/javascripts/discourse/app/components/tap-tile.gjsindex c620b1c322e,04a484d6803..771ee0d1346--- a/app/assets/javascripts/discourse/app/components/tap-tile.gjs+++ b/app/assets/javascripts/discourse/app/components/tap-tile.gjs@@@ -1,4 -1,35 +1,40 @@@+ import Component from "@ember/component";+ import { reads } from "@ember/object/computed";+ import {+ attributeBindings,+ classNameBindings,+ classNames,+ } from "@ember-decorators/component";+ import { propertyEqual } from "discourse/lib/computed";++ @classNames("tap-tile")+ @classNameBindings("active")+ @attributeBindings("role", "ariaPressed", "tabIndex")+ export default class TapTile extends Component {+ role = "button";+ tabIndex = 0;++ @reads("active") ariaPressed;+ @propertyEqual("activeTile", "tileId") active;++ init() {+ super.init(...arguments);+ this.set("elementId", `tap_tile_${this.tileId}`);+ }++ click() {+ this.onChange(this.tileId);+ }++ keyDown(e) {+ if (e.key === "Enter") {+ e.stopPropagation();+ this.onChange(this.tileId);+ }+ }+ }+++{{#if this.icon}}+ {{d-icon this.icon}}+{{/if}}+{{yield}}diff --cc app/assets/javascripts/discourse/app/components/time-shortcut-picker.gjsindex f44b04490af,295a6380088..a35de08bb81--- a/app/assets/javascripts/discourse/app/components/time-shortcut-picker.gjs+++ b/app/assets/javascripts/discourse/app/components/time-shortcut-picker.gjs@@@ -1,51 -1,282 +1,334 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { and, equal } from "@ember/object/computed";+ import { tagName } from "@ember-decorators/component";+ import { observes, on } from "@ember-decorators/object";+ import discourseComputed from "discourse/lib/decorators";+ import {+ defaultTimeShortcuts,+ formatTime,+ hideDynamicTimeShortcuts,+ specialShortcutOptions,+ TIME_SHORTCUT_TYPES,+ } from "discourse/lib/time-shortcut";+ import { laterToday, now, parseCustomDatetime } from "discourse/lib/time-utils";+ import { i18n } from "discourse-i18n";++ const BINDINGS = {+ "l t": {+ handler: "selectShortcut",+ args: [TIME_SHORTCUT_TYPES.LATER_TODAY],+ },+ "l w": {+ handler: "selectShortcut",+ args: [TIME_SHORTCUT_TYPES.LATER_THIS_WEEK],+ },+ "n d": {+ handler: "selectShortcut",+ args: [TIME_SHORTCUT_TYPES.TOMORROW],+ },+ "n b w": {+ handler: "selectShortcut",+ args: [TIME_SHORTCUT_TYPES.START_OF_NEXT_BUSINESS_WEEK],+ },+ "n m": {+ handler: "selectShortcut",+ args: [TIME_SHORTCUT_TYPES.NEXT_MONTH],+ },+ "c r": { handler: "selectShortcut", args: [TIME_SHORTCUT_TYPES.CUSTOM] },+ "n r": { handler: "selectShortcut", args: [TIME_SHORTCUT_TYPES.NONE] },+ };++ @tagName("")+ export default class TimeShortcutPicker extends Component {+ @equal("selectedShortcut", TIME_SHORTCUT_TYPES.CUSTOM) customDatetimeSelected;+ @equal("selectedShortcut", TIME_SHORTCUT_TYPES.RELATIVE)+ relativeTimeSelected;+ @and("customDate", "customTime") customDatetimeFilled;++ userTimezone = null;++ onTimeSelected = null;++ selectedShortcut = null;+ selectedTime = null;+ selectedDate = null;+ selectedDatetime = null;+ prefilledDatetime = null;+ selectedDurationMins = null;++ hiddenOptions = null;+ customOptions = null;++ lastCustomDate = null;+ lastCustomTime = null;+ parsedLastCustomDatetime = null;+ customDate = null;+ customTime = null;++ _itsatrap = null;++ @on("init")+ _setupPicker() {+ this.setProperties({+ userTimezone: this.currentUser.user_option.timezone,+ hiddenOptions: this.hiddenOptions || [],+ customOptions: this.customOptions || [],+ customLabels: this.customLabels || {},+ });++ if (this.prefilledDatetime) {+ this.parsePrefilledDatetime();+ }++ this._bindKeyboardShortcuts();+ }++ @observes("prefilledDatetime")+ prefilledDatetimeChanged() {+ if (this.prefilledDatetime) {+ this.parsePrefilledDatetime();+ } else {+ this.setProperties({+ customDate: null,+ customTime: null,+ selectedShortcut: null,+ });+ }+ }++ willDestroyElement() {+ super.willDestroyElement(...arguments);++ this._itsatrap.unbind(Object.keys(BINDINGS));+ }++ parsePrefilledDatetime() {+ let parsedDatetime = parseCustomDatetime(+ this.prefilledDatetime,+ null,+ this.userTimezone+ );++ if (parsedDatetime.isSame(laterToday())) {+ return this.set("selectedShortcut", TIME_SHORTCUT_TYPES.LATER_TODAY);+ }++ this.setProperties({+ customDate: parsedDatetime.format("YYYY-MM-DD"),+ customTime: parsedDatetime.format("HH:mm"),+ selectedShortcut: TIME_SHORTCUT_TYPES.CUSTOM,+ });+ }++ _loadLastUsedCustomDatetime() {+ const lastTime = this.keyValueStore.lastCustomTime;+ const lastDate = this.keyValueStore.lastCustomDate;++ if (lastTime && lastDate) {+ let parsed = parseCustomDatetime(lastDate, lastTime, this.userTimezone);++ if (!parsed.isValid() || parsed < now(this.userTimezone)) {+ return;+ }++ this.setProperties({+ lastCustomDate: lastDate,+ lastCustomTime: lastTime,+ parsedLastCustomDatetime: parsed,+ });+ }+ }++ _bindKeyboardShortcuts() {+ Object.keys(BINDINGS).forEach((shortcut) => {+ this._itsatrap.bind(shortcut, () => {+ let binding = BINDINGS[shortcut];+ this.send(binding.handler, ...binding.args);+ return false;+ });+ });+ }++ @observes("customDate", "customTime")+ customDatetimeChanged() {+ if (!this.customDatetimeFilled) {+ return;+ }+ this.selectShortcut(TIME_SHORTCUT_TYPES.CUSTOM);+ }++ @discourseComputed(+ "timeShortcuts",+ "hiddenOptions",+ "customLabels",+ "userTimezone"+ )+ options(timeShortcuts, hiddenOptions, customLabels, userTimezone) {+ this._loadLastUsedCustomDatetime();++ let options;+ if (timeShortcuts && timeShortcuts.length) {+ options = timeShortcuts;+ } else {+ options = defaultTimeShortcuts(userTimezone);+ }+ options = hideDynamicTimeShortcuts(+ options,+ userTimezone,+ this.siteSettings+ );++ let specialOptions = specialShortcutOptions();+ if (this.lastCustomDate && this.lastCustomTime) {+ let lastCustom = specialOptions.findBy(+ "id",+ TIME_SHORTCUT_TYPES.LAST_CUSTOM+ );+ lastCustom.time = this.parsedLastCustomDatetime;+ lastCustom.timeFormatKey = "dates.long_no_year";+ lastCustom.hidden = false;+ }+ options = options.concat(specialOptions);++ if (hiddenOptions.length > 0) {+ options.forEach((opt) => {+ if (hiddenOptions.includes(opt.id)) {+ opt.hidden = true;+ }+ });+ }++ this._applyCustomLabels(options, customLabels);+ options.forEach((o) => (o.timeFormatted = formatTime(o)));+ return options;+ }++ @action+ relativeTimeChanged(relativeTimeMins) {+ const dateTime = now(this.userTimezone).add(relativeTimeMins, "minutes");++ this.setProperties({+ selectedDurationMins: relativeTimeMins,+ selectedDatetime: dateTime,+ });++ this.onTimeSelected?.(TIME_SHORTCUT_TYPES.RELATIVE, dateTime);+ }++ @action+ selectShortcut(type) {+ if (this.options.filterBy("hidden").mapBy("id").includes(type)) {+ return;+ }++ let dateTime = null;+ if (type === TIME_SHORTCUT_TYPES.CUSTOM) {+ const defaultCustomDateTime = this._defaultCustomDateTime();+ this.set(+ "customDate",+ this.customDate || defaultCustomDateTime.format("YYYY-MM-DD")+ );+ this.set(+ "customTime",+ this.customTime || defaultCustomDateTime.format("HH:mm")+ );++ const customDatetime = parseCustomDatetime(+ this.customDate,+ this.customTime,+ this.userTimezone+ );++ if (customDatetime.isValid() && this.customDate) {+ dateTime = customDatetime;++ this.keyValueStore.lastCustomTime = this.customTime;+ this.keyValueStore.lastCustomDate = this.customDate;+ }+ } else {+ dateTime = this.options.findBy("id", type).time;+ }++ this.setProperties({+ selectedShortcut: type,+ selectedDatetime: dateTime,+ });++ if (this.onTimeSelected) {+ this.onTimeSelected(type, dateTime);+ }+ }++ _applyCustomLabels(options, customLabels) {+ options.forEach((option) => {+ if (customLabels[option.id]) {+ option.label = customLabels[option.id];+ }+ });+ }++ _formatTime(options) {+ options.forEach((option) => {+ if (option.time && option.timeFormatKey) {+ option.timeFormatted = option.time.format(i18n(option.timeFormatKey));+ }+ });+ }++ _defaultCustomDateTime() {+ return moment.tz(this.userTimezone).add(1, "hour");+ }+ }+++<TapTileGrid @activeTile={{this.selectedShortcut}} as |grid|>+ {{#each this.options key="id" as |option|}}+ {{#unless option.hidden}}+ <TapTile+ @tileId={{option.id}}+ @activeTile={{grid.activeTile}}+ @onChange={{action "selectShortcut"}}+ >++ <div class="tap-tile-title">{{i18n option.label}}</div>+ <div class="tap-tile-date">{{option.timeFormatted}}</div>+ </TapTile>+ {{/unless}}++ {{#if option.isCustomTimeShortcut}}+ {{#if this.customDatetimeSelected}}+ <div class="control-group custom-date-time-wrap custom-input-wrap">+ <div class="tap-tile-date-input">+ {{d-icon "calendar-days"}}+ <DatePickerFuture+ @value={{this.customDate}}+ @defaultDate={{this.defaultCustomDate}}+ @onSelect={{fn (mut this.customDate)}}+ @id="custom-date"+ />+ </div>+ <div class="tap-tile-time-input">+ {{d-icon "far-clock"}}+ <Input+ placeholder="--:--"+ id="custom-time"+ @type="time"+ class="time-input"+ @value={{this.customTime}}+ />+ </div>+ </div>+ <div class="control-group custom-date-time-wrap custom-relative-wrap">+ <label class="control-label" for="bookmark-relative-time-picker">+ {{i18n "relative_time_picker.relative"}}+ </label>+ <RelativeTimePicker+ @durationMinutes={{this.selectedDurationMins}}+ @onChange={{this.relativeTimeChanged}}+ id="bookmark-relative-time-picker"+ />+ </div>+ {{/if}}+ {{/if}}+ {{/each}}+</TapTileGrid>diff --cc app/assets/javascripts/discourse/app/components/top-period-buttons.gjsindex 5ce99b5a02e,da8fb2e56d9..8fe2500bfb6--- a/app/assets/javascripts/discourse/app/components/top-period-buttons.gjs+++ b/app/assets/javascripts/discourse/app/components/top-period-buttons.gjs@@@ -1,7 -1,17 +1,25 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { classNames } from "@ember-decorators/component";+ import discourseComputed from "discourse/lib/decorators";++ @classNames("top-title-buttons")+ export default class TopPeriodButtons extends Component {+ @discourseComputed("period")+ periods(period) {+ return this.site.get("periods").filter((p) => p !== period);+ }++ @action+ changePeriod(p) {+ this.action(p);+ }+ }+++{{#each this.periods as |p|}}+ <DButton+ @action={{fn this.changePeriod p}}+ @translatedLabel={{period-title p}}+ class="btn-default"+ />+{{/each}}diff --cc app/assets/javascripts/discourse/app/components/topic-category.gjsindex f052e6bdb92,1985ed434b3..332e8179ae3--- a/app/assets/javascripts/discourse/app/components/topic-category.gjs+++ b/app/assets/javascripts/discourse/app/components/topic-category.gjs@@@ -1,25 -1,4 +1,30 @@@+ import Component from "@ember/component";++ // Injections don't occur without a class+ export default class TopicCategory extends Component {}+++{{#unless this.topic.isPrivateMessage}}+ {{bound-category-link+ this.topic.category+ ancestors=this.topic.category.predecessors+ hideParent=true+ }}+{{/unless}}+<div class="topic-header-extra">+ {{#if this.siteSettings.tagging_enabled}}+ <div class="list-tags">+ {{discourse-tags this.topic mode="list" tags=this.topic.tags}}+ </div>+ {{/if}}+ {{#if this.siteSettings.topic_featured_link_enabled}}+ {{topic-featured-link this.topic}}+ {{/if}}+</div>++<span>+ <PluginOutlet+ @name="topic-category"+ @connectorTagName="div"+ @outletArgs={{hash topic=this.topic category=this.topic.category}}+ />+</span>diff --cc app/assets/javascripts/discourse/app/components/topic-entrance.gjsindex f8f06588f13,5e0c35860c9..cf535b1f93e--- a/app/assets/javascripts/discourse/app/components/topic-entrance.gjs+++ b/app/assets/javascripts/discourse/app/components/topic-entrance.gjs@@@ -1,25 -1,202 +1,228 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { scheduleOnce } from "@ember/runloop";+ import { service } from "@ember/service";+ import { classNameBindings } from "@ember-decorators/component";+ import { on } from "@ember-decorators/object";+ import $ from "jquery";+ import discourseComputed, { bind } from "discourse/lib/decorators";+ import DiscourseURL from "discourse/lib/url";+ import { i18n } from "discourse-i18n";++ function entranceDate(dt, showTime) {+ const today = new Date();++ if (dt.toDateString() === today.toDateString()) {+ return moment(dt).format(i18n("dates.time"));+ }++ if (dt.getYear() === today.getYear()) {+ // No year+ return moment(dt).format(+ showTime+ ? i18n("dates.long_date_without_year_with_linebreak")+ : i18n("dates.long_no_year_no_time")+ );+ }++ return moment(dt).format(+ showTime+ ? i18n("dates.long_date_with_year_with_linebreak")+ : i18n("dates.long_date_with_year_without_time")+ );+ }++ @classNameBindings("visible::hidden")+ export default class TopicEntrance extends Component {+ @service router;+ @service session;+ @service historyStore;++ elementId = "topic-entrance";+ topic = null;+ visible = null;+ _position = null;+ _originalActiveElement = null;+ _activeButton = null;++ @discourseComputed("topic.created_at")+ createdDate(createdAt) {+ return new Date(createdAt);+ }++ @discourseComputed("topic.bumped_at")+ bumpedDate(bumpedAt) {+ return new Date(bumpedAt);+ }++ @discourseComputed("createdDate", "bumpedDate")+ showTime(createdDate, bumpedDate) {+ return (+ bumpedDate.getTime() - createdDate.getTime() < 1000 * 60 * 60 * 24 * 2+ );+ }++ @discourseComputed("createdDate", "showTime")+ topDate(createdDate, showTime) {+ return entranceDate(createdDate, showTime);+ }++ @discourseComputed("bumpedDate", "showTime")+ bottomDate(bumpedDate, showTime) {+ return entranceDate(bumpedDate, showTime);+ }++ @on("didInsertElement")+ _inserted() {+ this.appEvents.on("topic-entrance:show", this, "_show");+ this.appEvents.on("dom:clean", this, this.cleanUp);+ }++ @on("didDestroyElement")+ _destroyed() {+ this.appEvents.off("dom:clean", this, this.cleanUp);+ }++ _setCSS() {+ const pos = this._position;+ const $self = $(this.element);+ const width = $self.width();+ const height = $self.height();+ pos.left = parseInt(pos.left, 10) - width / 2;+ pos.top = parseInt(pos.top, 10) - height / 2;++ const windowWidth = $(window).width();+ if (pos.left + width > windowWidth) {+ pos.left = windowWidth - width - 15;+ }+ $self.css(pos);+ }++ @bind+ _escListener(e) {+ if (e.key === "Escape") {+ this.cleanUp();+ } else if (e.key === "Tab") {+ if (this._activeButton === "top") {+ this._jumpBottomButton().focus();+ this._activeButton = "bottom";+ e.preventDefault();+ } else if (this._activeButton === "bottom") {+ this._jumpTopButton().focus();+ this._activeButton = "top";+ e.preventDefault();+ }+ }+ }++ _jumpTopButton() {+ return this.element.querySelector(".jump-top");+ }++ _jumpBottomButton() {+ return this.element.querySelector(".jump-bottom");+ }++ _setupEscListener() {+ document.body.addEventListener("keydown", this._escListener);+ }++ _removeEscListener() {+ document.body.removeEventListener("keydown", this._escListener);+ }++ _trapFocus() {+ this._originalActiveElement = document.activeElement;+ this._jumpTopButton().focus();+ this._activeButton = "top";+ }++ _releaseFocus() {+ if (this._originalActiveElement) {+ this._originalActiveElement.focus();+ this._originalActiveElement = null;+ }+ }++ _applyDomChanges() {+ this._setCSS();+ this._setupEscListener();+ this._trapFocus();+ }++ _show(data) {+ this._position = data.position;++ this.setProperties({ topic: data.topic, visible: true });++ scheduleOnce("afterRender", this, this._applyDomChanges);++ $("html")+ .off("mousedown.topic-entrance")+ .on("mousedown.topic-entrance", (e) => {+ const $target = $(e.target);+ if (+ $target.prop("id") === "topic-entrance" ||+ $(this.element).has($target).length !== 0+ ) {+ return;+ }+ this.cleanUp();+ });+ }++ cleanUp() {+ this.setProperties({ topic: null, visible: false });+ $("html").off("mousedown.topic-entrance");+ this._removeEscListener();+ this._releaseFocus();+ }++ willDestroyElement() {+ super.willDestroyElement(...arguments);+ this.appEvents.off("topic-entrance:show", this, "_show");+ }++ _jumpTo(destination) {+ this.historyStore.set("lastTopicIdViewed", this.topic.id);++ this.cleanUp();+ DiscourseURL.routeTo(destination);+ }++ @action+ enterTop() {+ this._jumpTo(this.get("topic.url"));+ }++ @action+ enterBottom() {+ this._jumpTo(this.get("topic.lastPostUrl"));+ }+ }+++<DButton+ @action={{action "enterTop"}}+ @translatedAriaLabel={{i18n+ "topic_entrance.sr_jump_top_button"+ date=this.topDate+ }}+ title={{i18n "topic_entrance.jump_top_button_title"}}+ class="btn-default full jump-top"+>+ {{d-icon "backward-step"}}+ {{html-safe this.topDate}}+</DButton>++<DButton+ @action={{action "enterBottom"}}+ @translatedAriaLabel={{i18n+ "topic_entrance.sr_jump_bottom_button"+ date=this.bottomDate+ }}+ title={{i18n "topic_entrance.jump_bottom_button_title"}}+ class="btn-default full jump-bottom"+>+ {{html-safe this.bottomDate}}+ {{d-icon "forward-step"}}+</DButton>diff --cc app/assets/javascripts/discourse/app/components/topic-list-item.gjsindex a29b2c90de3,d02d2ae86e1..79ccb08587d--- a/app/assets/javascripts/discourse/app/components/topic-list-item.gjs+++ b/app/assets/javascripts/discourse/app/components/topic-list-item.gjs@@@ -1,5 -1,408 +1,414 @@@+ import Component from "@ember/component";+ import { alias } from "@ember/object/computed";+ import { getOwner } from "@ember/owner";+ import { schedule } from "@ember/runloop";+ import { service } from "@ember/service";+ import { htmlSafe } from "@ember/template";+ import {+ attributeBindings,+ classNameBindings,+ tagName,+ } from "@ember-decorators/component";+ import { observes, on } from "@ember-decorators/object";+ import $ from "jquery";+ import discourseComputed, { bind } from "discourse/lib/decorators";+ import deprecated from "discourse/lib/deprecated";+ import { wantsNewWindow } from "discourse/lib/intercept-click";+ import { RAW_TOPIC_LIST_DEPRECATION_OPTIONS } from "discourse/lib/plugin-api";+ import { RUNTIME_OPTIONS } from "discourse/lib/raw-handlebars-helpers";+ import { findRawTemplate } from "discourse/lib/raw-templates";+ import { applyValueTransformer } from "discourse/lib/transformer";+ import DiscourseURL, { groupPath } from "discourse/lib/url";+ import { i18n } from "discourse-i18n";++ export function showEntrance(e) {+ let target = $(e.target);++ if (target.hasClass("posts-map") || target.parents(".posts-map").length > 0) {+ if (target.prop("tagName") !== "A") {+ target = target.find("a");+ if (target.length === 0) {+ target = target.end();+ }+ }++ this.appEvents.trigger("topic-entrance:show", {+ topic: this.topic,+ position: target.offset(),+ });+ return false;+ }+ }++ export function navigateToTopic(topic, href) {+ const historyStore = getOwner(this).lookup("service:history-store");+ historyStore.set("lastTopicIdViewed", topic.id);++ DiscourseURL.routeTo(href || topic.get("url"));+ return false;+ }++ @tagName("tr")+ @classNameBindings(":topic-list-item", "unboundClassNames", "topic.visited")+ @attributeBindings("dataTopicId:data-topic-id", "role", "ariaLevel:aria-level")+ export default class TopicListItem extends Component {+ static reopen() {+ deprecated(+ "Modifying topic-list-item with `reopen` is deprecated. Use the value transformer `topic-list-columns` and other new topic-list plugin APIs instead.",+ RAW_TOPIC_LIST_DEPRECATION_OPTIONS+ );++ return super.reopen(...arguments);+ }++ static reopenClass() {+ deprecated(+ "Modifying topic-list-item with `reopenClass` is deprecated. Use the value transformer `topic-list-columns` and other new topic-list plugin APIs instead.",+ RAW_TOPIC_LIST_DEPRECATION_OPTIONS+ );++ return super.reopenClass(...arguments);+ }++ @service router;+ @service historyStore;++ @alias("topic.id") dataTopicId;++ didReceiveAttrs() {+ super.didReceiveAttrs(...arguments);+ this.renderTopicListItem();+ }++ // Already-rendered topic is marked as highlighted+ // Ideally this should be a modifier... but we can't do that+ // until this component has its tagName removed.+ @observes("topic.highlight")+ topicHighlightChanged() {+ if (this.topic.highlight) {+ this._highlightIfNeeded();+ }+ }++ @observes("topic.pinned", "expandGloballyPinned", "expandAllPinned")+ renderTopicListItem() {+ const template = findRawTemplate("list/topic-list-item");+ if (template) {+ this.set(+ "topicListItemContents",+ htmlSafe(template(this, RUNTIME_OPTIONS))+ );+ schedule("afterRender", () => {+ if (this.isDestroyed || this.isDestroying) {+ return;+ }+ if (this.selected && this.selected.includes(this.topic)) {+ this.element.querySelector("input.bulk-select").checked = true;+ }+ if (this._shouldFocusLastVisited()) {+ const title = this._titleElement();+ if (title) {+ title.addEventListener("focus", this._onTitleFocus);+ title.addEventListener("blur", this._onTitleBlur);+ }+ }+ });+ }+ }++ didInsertElement() {+ super.didInsertElement(...arguments);++ if (this.includeUnreadIndicator) {+ this.messageBus.subscribe(this.unreadIndicatorChannel, this.onMessage);+ }+ }++ willDestroyElement() {+ super.willDestroyElement(...arguments);++ this.messageBus.unsubscribe(this.unreadIndicatorChannel, this.onMessage);++ if (this._shouldFocusLastVisited()) {+ const title = this._titleElement();+ if (title) {+ title.removeEventListener("focus", this._onTitleFocus);+ title.removeEventListener("blur", this._onTitleBlur);+ }+ }+ }++ @bind+ onMessage(data) {+ const nodeClassList = document.querySelector(+ `.indicator-topic-${data.topic_id}`+ ).classList;++ nodeClassList.toggle("read", !data.show_indicator);+ }++ @discourseComputed("topic.participant_groups")+ participantGroups(groupNames) {+ if (!groupNames) {+ return [];+ }++ return groupNames.map((name) => {+ return { name, url: groupPath(name) };+ });+ }++ @discourseComputed("topic.id")+ unreadIndicatorChannel(topicId) {+ return `/private-messages/unread-indicator/${topicId}`;+ }++ @discourseComputed("topic.unread_by_group_member")+ unreadClass(unreadByGroupMember) {+ return unreadByGroupMember ? "" : "read";+ }++ @discourseComputed("topic.unread_by_group_member")+ includeUnreadIndicator(unreadByGroupMember) {+ return typeof unreadByGroupMember !== "undefined";+ }++ @discourseComputed+ newDotText() {+ return this.currentUser && this.currentUser.trust_level > 0+ ? ""+ : i18n("filters.new.lower_title");+ }++ @discourseComputed("topic", "lastVisitedTopic")+ unboundClassNames(topic, lastVisitedTopic) {+ let classes = [];++ if (topic.get("category")) {+ classes.push("category-" + topic.get("category.fullSlug"));+ }++ if (topic.get("tags")) {+ topic.get("tags").forEach((tag) => classes.push("tag-" + tag));+ }++ if (topic.get("hasExcerpt")) {+ classes.push("has-excerpt");+ }++ if (topic.get("unseen")) {+ classes.push("unseen-topic");+ }++ if (topic.unread_posts) {+ classes.push("unread-posts");+ }++ ["liked", "archived", "bookmarked", "pinned", "closed"].forEach((name) => {+ if (topic.get(name)) {+ classes.push(name);+ }+ });++ if (topic === lastVisitedTopic) {+ classes.push("last-visit");+ }++ return classes.join(" ");+ }++ hasLikes() {+ return this.get("topic.like_count") > 0;+ }++ hasOpLikes() {+ return this.get("topic.op_like_count") > 0;+ }++ @discourseComputed+ expandPinned() {+ return applyValueTransformer(+ "topic-list-item-expand-pinned",+ this._expandPinned,+ {+ topic: this.topic,+ mobileView: this.site.mobileView,+ }+ );+ }++ get _expandPinned() {+ const pinned = this.get("topic.pinned");+ if (!pinned) {+ return false;+ }++ if (this.site.mobileView) {+ if (!this.siteSettings.show_pinned_excerpt_mobile) {+ return false;+ }+ } else {+ if (!this.siteSettings.show_pinned_excerpt_desktop) {+ return false;+ }+ }++ if (this.expandGloballyPinned && this.get("topic.pinned_globally")) {+ return true;+ }++ if (this.expandAllPinned) {+ return true;+ }++ return false;+ }++ showEntrance() {+ return showEntrance.call(this, ...arguments);+ }++ click(e) {+ const result = this.showEntrance(e);+ if (result === false) {+ return result;+ }++ const topic = this.topic;+ const target = e.target;+ const classList = target.classList;+ if (classList.contains("bulk-select")) {+ const selected = this.selected;++ if (target.checked) {+ selected.addObject(topic);++ if (this.lastChecked && e.shiftKey) {+ const bulkSelects = Array.from(+ document.querySelectorAll("input.bulk-select")+ ),+ from = bulkSelects.indexOf(target),+ to = bulkSelects.findIndex((el) => el.id === this.lastChecked.id),+ start = Math.min(from, to),+ end = Math.max(from, to);++ bulkSelects+ .slice(start, end)+ .filter((el) => el.checked !== true)+ .forEach((checkbox) => {+ checkbox.click();+ });+ }++ this.set("lastChecked", target);+ } else {+ selected.removeObject(topic);+ this.set("lastChecked", null);+ }+ }++ if (+ classList.contains("raw-topic-link") ||+ classList.contains("post-activity")+ ) {+ if (wantsNewWindow(e)) {+ return true;+ }+ e.preventDefault();+ return this.navigateToTopic(topic, target.getAttribute("href"));+ }++ // make full row click target on mobile, due to size constraints+ if (+ this.site.mobileView &&+ e.target.matches(+ ".topic-list-data, .main-link, .right, .topic-item-stats, .topic-item-stats__category-tags, .discourse-tags"+ )+ ) {+ if (wantsNewWindow(e)) {+ return true;+ }+ e.preventDefault();+ return this.navigateToTopic(topic, topic.lastUnreadUrl);+ }++ return this.unhandledRowClick(e, topic);+ }++ unhandledRowClick() {}++ keyDown(e) {+ if (e.key === "Enter" && e.target.classList.contains("post-activity")) {+ e.preventDefault();+ return this.navigateToTopic(this.topic, e.target.getAttribute("href"));+ }+ }++ navigateToTopic() {+ return navigateToTopic.call(this, ...arguments);+ }++ highlight(opts = { isLastViewedTopic: false }) {+ schedule("afterRender", () => {+ if (!this.element || this.isDestroying || this.isDestroyed) {+ return;+ }++ this.element.classList.add("highlighted");+ this.element.setAttribute(+ "data-is-last-viewed-topic",+ opts.isLastViewedTopic+ );+ this.element.addEventListener("animationend", () => {+ this.element.classList.remove("highlighted");+ });+ if (opts.isLastViewedTopic && this._shouldFocusLastVisited()) {+ this._titleElement()?.focus();+ }+ });+ }++ @on("didInsertElement")+ _highlightIfNeeded() {+ // highlight the last topic viewed+ const lastViewedTopicId = this.historyStore.get("lastTopicIdViewed");+ const isLastViewedTopic = lastViewedTopicId === this.topic.id;++ if (isLastViewedTopic) {+ this.historyStore.delete("lastTopicIdViewed");+ this.highlight({ isLastViewedTopic: true });+ } else if (this.get("topic.highlight")) {+ // highlight new topics that have been loaded from the server or the one we just created+ this.set("topic.highlight", false);+ this.highlight();+ }+ }++ @bind+ _onTitleFocus() {+ if (this.element && !this.isDestroying && !this.isDestroyed) {+ this.element.classList.add("selected");+ }+ }++ @bind+ _onTitleBlur() {+ if (this.element && !this.isDestroying && !this.isDestroyed) {+ this.element.classList.remove("selected");+ }+ }++ _shouldFocusLastVisited() {+ return this.site.desktopView && this.focusLastVisitedTopic;+ }++ _titleElement() {+ return this.element.querySelector(".main-link .title");+ }+ }+++<PluginOutlet+ @name="above-topic-list-item"+ @outletArgs={{hash topic=this.topic}}+/>+{{this.topicListItemContents}}diff --cc app/assets/javascripts/discourse/app/components/topic-list.gjsindex ae89d49c9d2,331258e9a60..eca6255cfe7--- a/app/assets/javascripts/discourse/app/components/topic-list.gjs+++ b/app/assets/javascripts/discourse/app/components/topic-list.gjs@@@ -1,80 -1,251 +1,332 @@@+ import Component from "@ember/component";+ import { dependentKeyCompat } from "@ember/object/compat";+ import { alias } from "@ember/object/computed";+ import { service } from "@ember/service";+ import {+ classNameBindings,+ classNames,+ tagName,+ } from "@ember-decorators/component";+ import { observes, on } from "@ember-decorators/object";+ import discourseComputed from "discourse/lib/decorators";+ import deprecated from "discourse/lib/deprecated";+ import { RAW_TOPIC_LIST_DEPRECATION_OPTIONS } from "discourse/lib/plugin-api";+ import LoadMore from "discourse/mixins/load-more";++ @tagName("table")+ @classNames("topic-list")+ @classNameBindings("bulkSelectEnabled:sticky-header")+ export default class TopicList extends Component.extend(LoadMore) {+ static reopen() {+ deprecated(+ "Modifying topic-list with `reopen` is deprecated. Use the value transformer `topic-list-columns` and other new topic-list plugin APIs instead.",+ RAW_TOPIC_LIST_DEPRECATION_OPTIONS+ );++ return super.reopen(...arguments);+ }++ static reopenClass() {+ deprecated(+ "Modifying topic-list with `reopenClass` is deprecated. Use the value transformer `topic-list-columns` and other new topic-list plugin APIs instead.",+ RAW_TOPIC_LIST_DEPRECATION_OPTIONS+ );++ return super.reopenClass(...arguments);+ }++ @service modal;+ @service router;+ @service siteSettings;++ showTopicPostBadges = true;+ listTitle = "topic.title";+ lastCheckedElementId = null;++ // Overwrite this to perform client side filtering of topics, if desired+ @alias("topics") filteredTopics;++ get canDoBulkActions() {+ return (+ this.currentUser?.canManageTopic && this.bulkSelectHelper?.selected.length+ );+ }++ @on("init")+ _init() {+ this.addObserver("hideCategory", this.rerender);+ this.addObserver("order", this.rerender);+ this.addObserver("ascending", this.rerender);+ this.refreshLastVisited();+ }++ get selected() {+ return this.bulkSelectHelper?.selected;+ }++ // for the classNameBindings+ @dependentKeyCompat+ get bulkSelectEnabled() {+ return (+ this.get("canBulkSelect") && this.bulkSelectHelper?.bulkSelectEnabled+ );+ }++ get toggleInTitle() {+ return (+ !this.bulkSelectHelper?.bulkSelectEnabled && this.get("canBulkSelect")+ );+ }++ @discourseComputed+ sortable() {+ return !!this.changeSort;+ }++ @discourseComputed("order")+ showLikes(order) {+ return order === "likes";+ }++ @discourseComputed("order")+ showOpLikes(order) {+ return order === "op_likes";+ }++ @observes("topics.[]")+ topicsAdded() {+ // special case so we don't keep scanning huge lists+ if (!this.lastVisitedTopic) {+ this.refreshLastVisited();+ }+ }++ @observes("topics", "order", "ascending", "category", "top", "hot")+ lastVisitedTopicChanged() {+ this.refreshLastVisited();+ }++ scrolled() {+ super.scrolled(...arguments);+ let onScroll = this.onScroll;+ if (!onScroll) {+ return;+ }++ onScroll.call(this);+ }++ _updateLastVisitedTopic(topics, order, ascending, top, hot) {+ this.set("lastVisitedTopic", null);++ if (!this.highlightLastVisited) {+ return;+ }++ if (order && order !== "activity") {+ return;+ }++ if (top || hot) {+ return;+ }++ if (!topics || topics.length === 1) {+ return;+ }++ if (ascending) {+ return;+ }++ let user = this.currentUser;+ if (!user || !user.previous_visit_at) {+ return;+ }++ let lastVisitedTopic, topic;++ let prevVisit = user.get("previousVisitAt");++ // this is more efficient cause we keep appending to list+ // work backwards+ let start = 0;+ while (topics[start] && topics[start].get("pinned")) {+ start++;+ }++ let i;+ for (i = topics.length - 1; i >= start; i--) {+ if (topics[i].get("bumpedAt") > prevVisit) {+ lastVisitedTopic = topics[i];+ break;+ }+ topic = topics[i];+ }++ if (!lastVisitedTopic || !topic) {+ return;+ }++ // end of list that was scanned+ if (topic.get("bumpedAt") > prevVisit) {+ return;+ }++ this.set("lastVisitedTopic", lastVisitedTopic);+ }++ refreshLastVisited() {+ this._updateLastVisitedTopic(+ this.topics,+ this.order,+ this.ascending,+ this.top,+ this.hot+ );+ }++ click(e) {+ const onClick = (sel, callback) => {+ let target = e.target.closest(sel);++ if (target) {+ callback(target);+ }+ };++ onClick("button.bulk-select", () => {+ this.bulkSelectHelper.toggleBulkSelect();+ this.rerender();+ });++ onClick("button.bulk-select-all", () => {+ this.bulkSelectHelper.autoAddTopicsToBulkSelect = true;+ document+ .querySelectorAll("input.bulk-select:not(:checked)")+ .forEach((el) => el.click());+ });++ onClick("button.bulk-clear-all", () => {+ this.bulkSelectHelper.autoAddTopicsToBulkSelect = false;+ document+ .querySelectorAll("input.bulk-select:checked")+ .forEach((el) => el.click());+ });++ onClick("th.sortable", (element) => {+ this.changeSort(element.dataset.sortOrder);+ this.rerender();+ });++ onClick("button.topics-replies-toggle", (element) => {+ if (element.classList.contains("--all")) {+ this.changeNewListSubset(null);+ } else if (element.classList.contains("--topics")) {+ this.changeNewListSubset("topics");+ } else if (element.classList.contains("--replies")) {+ this.changeNewListSubset("replies");+ }+ this.rerender();+ });+ }++ keyDown(e) {+ if (e.key === "Enter" || e.key === " ") {+ let onKeyDown = (sel, callback) => {+ let target = e.target.closest(sel);++ if (target) {+ callback.call(this, target);+ }+ };++ onKeyDown("th.sortable", (element) => {+ e.preventDefault();+ this.changeSort(element.dataset.sortOrder);+ this.rerender();+ });+ }+ }+ }+++<caption class="sr-only">{{i18n "sr_topic_list_caption"}}</caption>++<thead class="topic-list-header">+ {{raw+ "topic-list-header"+ canBulkSelect=this.canBulkSelect+ toggleInTitle=this.toggleInTitle+ hideCategory=this.hideCategory+ showPosters=this.showPosters+ showLikes=this.showLikes+ showOpLikes=this.showOpLikes+ order=this.order+ ascending=this.ascending+ sortable=this.sortable+ listTitle=this.listTitle+ bulkSelectEnabled=this.bulkSelectEnabled+ bulkSelectHelper=this.bulkSelectHelper+ canDoBulkActions=this.canDoBulkActions+ showTopicsAndRepliesToggle=this.showTopicsAndRepliesToggle+ newListSubset=this.newListSubset+ newRepliesCount=this.newRepliesCount+ newTopicsCount=this.newTopicsCount+ }}+</thead>++<PluginOutlet+ @name="before-topic-list-body"+ @outletArgs={{hash+ topics=this.topics+ selected=this.selected+ bulkSelectEnabled=this.bulkSelectEnabled+ lastVisitedTopic=this.lastVisitedTopic+ discoveryList=this.discoveryList+ hideCategory=this.hideCategory+ }}+/>++<tbody class="topic-list-body">+ {{#each this.filteredTopics as |topic index|}}+ <TopicListItem+ @topic={{topic}}+ @bulkSelectEnabled={{this.bulkSelectEnabled}}+ @showTopicPostBadges={{this.showTopicPostBadges}}+ @hideCategory={{this.hideCategory}}+ @showPosters={{this.showPosters}}+ @showLikes={{this.showLikes}}+ @showOpLikes={{this.showOpLikes}}+ @expandGloballyPinned={{this.expandGloballyPinned}}+ @expandAllPinned={{this.expandAllPinned}}+ @lastVisitedTopic={{this.lastVisitedTopic}}+ @selected={{this.selected}}+ @lastChecked={{this.lastChecked}}+ @tagsForUser={{this.tagsForUser}}+ @focusLastVisitedTopic={{this.focusLastVisitedTopic}}+ @index={{index}}+ />+ {{raw+ "list/visited-line"+ lastVisitedTopic=this.lastVisitedTopic+ topic=topic+ }}+ <PluginOutlet+ @name="after-topic-list-item"+ @outletArgs={{hash topic=topic index=index}}+ @connectorTagName="tr"+ />+ {{/each}}+</tbody>++<PluginOutlet+ @name="after-topic-list-body"+ @outletArgs={{hash+ topics=this.topics+ selected=this.selected+ bulkSelectEnabled=this.bulkSelectEnabled+ lastVisitedTopic=this.lastVisitedTopic+ discoveryList=this.discoveryList+ hideCategory=this.hideCategory+ }}+/>diff --cc app/assets/javascripts/discourse/app/components/topic-navigation.gjsindex 79e8d8a0876,eae88cf9913..9879c5aa19b--- a/app/assets/javascripts/discourse/app/components/topic-navigation.gjs+++ b/app/assets/javascripts/discourse/app/components/topic-navigation.gjs@@@ -1,3 -1,280 +1,284 @@@+ import Component from "@ember/component";+ import EmberObject from "@ember/object";+ import { next } from "@ember/runloop";+ import { service } from "@ember/service";+ import { classNameBindings } from "@ember-decorators/component";+ import { observes } from "@ember-decorators/object";+ import $ from "jquery";+ import discourseDebounce from "discourse/lib/debounce";+ import { bind } from "discourse/lib/decorators";+ import discourseLater from "discourse/lib/later";+ import { headerOffset } from "discourse/lib/offset-calculator";+ import SwipeEvents from "discourse/lib/swipe-events";+ import JumpToPost from "./modal/jump-to-post";++ const MIN_WIDTH_TIMELINE = 925;+ const MIN_HEIGHT_TIMELINE = 325;++ @classNameBindings(+ "info.topicProgressExpanded:topic-progress-expanded",+ "info.renderTimeline:with-timeline",+ "info.withTopicProgress:with-topic-progress"+ )+ export default class TopicNavigation extends Component {+ @service modal;+ @service composer;++ composerOpen = null;+ info = EmberObject.create();+ canRender = true;+ _lastTopicId = null;+ _swipeEvents = null;++ didUpdateAttrs() {+ super.didUpdateAttrs(...arguments);+ if (this._lastTopicId !== this.topic.id) {+ this._lastTopicId = this.topic.id;+ this.set("canRender", false);+ next(() => {+ this.set("canRender", true);+ this._performCheckSize();+ });+ }+ }++ _performCheckSize() {+ if (!this.element || this.isDestroying || this.isDestroyed) {+ return;+ }++ if (this.info.topicProgressExpanded) {+ this.info.set("renderTimeline", true);+ } else if (this.site.mobileView) {+ this.info.set("renderTimeline", false);+ } else {+ const composerHeight =+ document.querySelector("#reply-control")?.offsetHeight || 0;+ const verticalSpace =+ window.innerHeight - composerHeight - headerOffset();++ if (this.composer.isPreviewVisible) {+ this.info.set(+ "renderTimeline",+ this.mediaQuery.matches && verticalSpace > MIN_HEIGHT_TIMELINE+ );+ } else {+ this.info.set("renderTimeline", this.mediaQuery.matches);+ }+ }++ this.info.set(+ "withTopicProgress",+ !this.info.renderTimeline && this.topic.posts_count > 1+ );+ }++ @bind+ _checkSize() {+ discourseDebounce(this, this._performCheckSize, 200, true);+ }++ // we need to store this so topic progress has something to init with+ _topicScrolled(event) {+ this.set("info.prevEvent", event);+ }++ @observes("info.topicProgressExpanded")+ _expanded() {+ if (this.get("info.topicProgressExpanded")) {+ $(window).on("click.hide-fullscreen", (e) => {+ let $target = $(e.target);+ let $parents = $target.parents();+ if (+ !$target.is(".widget-button") &&+ !$parents.is(".widget-button") &&+ !$parents.is("#discourse-modal") &&+ !$target.is("#discourse-modal") &&+ ($target.is(".topic-timeline") ||+ !$parents.is("#topic-progress-wrapper")) &&+ !$parents.is(".timeline-open-jump-to-post-prompt-btn") &&+ !$target.is(".timeline-open-jump-to-post-prompt-btn")+ ) {+ this._collapseFullscreen();+ }+ });+ } else {+ $(window).off("click.hide-fullscreen");+ }+ this._checkSize();+ }++ composerOpened() {+ this.set("composerOpen", true);+ this._checkSize();+ }++ composerClosed() {+ this.set("composerOpen", false);+ this._checkSize();+ }++ _collapseFullscreen(postId, delay = 500) {+ if (this.get("info.topicProgressExpanded")) {+ $(".timeline-fullscreen").removeClass("show");+ discourseLater(() => {+ if (!this.element || this.isDestroying || this.isDestroyed) {+ return;+ }++ this.set("info.topicProgressExpanded", false);+ this._checkSize();+ }, delay);+ }+ }++ keyboardTrigger(e) {+ if (e.type === "jump") {+ this.modal.show(JumpToPost, {+ model: {+ topic: this.topic,+ jumpToIndex: this.jumpToIndex,+ jumpToDate: this.jumpToDate,+ },+ });+ }+ }++ @bind+ onSwipeStart(event) {+ const e = event.detail;+ const target = e.originalEvent.target;++ if (+ target.classList.contains("docked") ||+ !target.closest(".timeline-container")+ ) {+ event.preventDefault();+ return;+ }++ e.originalEvent.preventDefault();+ const centeredElement = document.elementFromPoint(e.center.x, e.center.y);+ if (centeredElement.closest(".timeline-scrollarea-wrapper")) {+ event.preventDefault();+ } else if (e.direction === "up" || e.direction === "down") {+ this.movingElement = document.querySelector(".timeline-container");+ }+ }++ @bind+ onSwipeCancel() {+ let durationMs = this._swipeEvents.getMaxAnimationTimeMs();+ const timelineContainer = document.querySelector(".timeline-container");+ timelineContainer.animate([{ transform: `translate3d(0, 0, 0)` }], {+ duration: durationMs,+ fill: "forwards",+ easing: "ease-out",+ });+ }++ @bind+ onSwipeEnd(event) {+ const e = event.detail;+ const timelineContainer = document.querySelector(".timeline-container");+ const maxOffset = timelineContainer.offsetHeight;++ let durationMs = this._swipeEvents.getMaxAnimationTimeMs();+ if (this._swipeEvents.shouldCloseMenu(e, "bottom")) {+ const distancePx = maxOffset - this.pxClosed;+ durationMs = this._swipeEvents.getMaxAnimationTimeMs(+ distancePx / Math.abs(e.velocityY)+ );+ timelineContainer+ .animate([{ transform: `translate3d(0, ${maxOffset}px, 0)` }], {+ duration: durationMs,+ fill: "forwards",+ })+ .finished.then(() => this._collapseFullscreen(null, 0));+ } else {+ const distancePx = this.pxClosed;+ durationMs = this._swipeEvents.getMaxAnimationTimeMs(+ distancePx / Math.abs(e.velocityY)+ );+ timelineContainer.animate([{ transform: `translate3d(0, 0, 0)` }], {+ duration: durationMs,+ fill: "forwards",+ easing: "ease-out",+ });+ }+ }++ @bind+ onSwipe(event) {+ const e = event.detail;+ e.originalEvent.preventDefault();+ this.pxClosed = Math.max(0, e.deltaY);++ this.movingElement.animate(+ [{ transform: `translate3d(0, ${this.pxClosed}px, 0)` }],+ { fill: "forwards" }+ );+ }++ didInsertElement() {+ super.didInsertElement(...arguments);++ this._lastTopicId = this.topic.id;++ this.appEvents+ .on("topic:current-post-scrolled", this, this._topicScrolled)+ .on("topic:jump-to-post", this, this._collapseFullscreen)+ .on("topic:keyboard-trigger", this, this.keyboardTrigger);++ if (this.site.desktopView) {+ this.mediaQuery = matchMedia(`(min-width: ${MIN_WIDTH_TIMELINE}px)`);+ this.mediaQuery.addEventListener("change", this._checkSize);+ this.appEvents.on("composer:opened", this, this.composerOpened);+ this.appEvents.on("composer:resize-ended", this, this.composerOpened);+ this.appEvents.on("composer:closed", this, this.composerClosed);+ this.appEvents.on("composer:preview-toggled", this._checkSize);+ $("#reply-control").on("div-resized", this._checkSize);+ }++ this._checkSize();+ this._swipeEvents = new SwipeEvents(this.element);+ if (this.site.mobileView) {+ this._swipeEvents.addTouchListeners();+ this.element.addEventListener("swipestart", this.onSwipeStart);+ this.element.addEventListener("swipeend", this.onSwipeEnd);+ this.element.addEventListener("swipecancel", this.onSwipeCancel);+ this.element.addEventListener("swipe", this.onSwipe);+ }+ }++ willDestroyElement() {+ super.willDestroyElement(...arguments);++ this.appEvents+ .off("topic:current-post-scrolled", this, this._topicScrolled)+ .off("topic:jump-to-post", this, this._collapseFullscreen)+ .off("topic:keyboard-trigger", this, this.keyboardTrigger);++ $(window).off("click.hide-fullscreen");++ if (this.site.desktopView) {+ this.mediaQuery.removeEventListener("change", this._checkSize);+ this.appEvents.off("composer:opened", this, this.composerOpened);+ this.appEvents.off("composer:resize-ended", this, this.composerOpened);+ this.appEvents.off("composer:closed", this, this.composerClosed);+ this.appEvents.off("composer:preview-toggled", this._checkSize);+ $("#reply-control").off("div-resized", this._checkSize);+ }+ if (this.site.mobileView) {+ this.element.removeEventListener("swipestart", this.onSwipeStart);+ this.element.removeEventListener("swipeend", this.onSwipeEnd);+ this.element.removeEventListener("swipecancel", this.onSwipeCancel);+ this.element.removeEventListener("swipe", this.onSwipe);+ this._swipeEvents.removeTouchListeners();+ }+ }+ }+++{{#if this.canRender}}+ {{yield this.info}}+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/topic-progress.gjsindex 14f9438b222,500102462d7..ebfa5ae2a68--- a/app/assets/javascripts/discourse/app/components/topic-progress.gjs+++ b/app/assets/javascripts/discourse/app/components/topic-progress.gjs@@@ -1,33 -1,95 +1,129 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { alias } from "@ember/object/computed";+ import { scheduleOnce } from "@ember/runloop";+ import { classNameBindings } from "@ember-decorators/component";+ import discourseComputed from "discourse/lib/decorators";++ @classNameBindings("docked")+ export default class TopicProgress extends Component {+ elementId = "topic-progress-wrapper";+ docked = false;+ progressPosition = null;++ @alias("topic.postStream") postStream;++ _streamPercentage = null;++ @discourseComputed(+ "postStream.loaded",+ "topic.currentPost",+ "postStream.filteredPostsCount"+ )+ hideProgress(loaded, currentPost, filteredPostsCount) {+ const hideOnShortStream = this.site.desktopView && filteredPostsCount < 2;+ return !loaded || !currentPost || hideOnShortStream;+ }++ @discourseComputed("postStream.filteredPostsCount")+ hugeNumberOfPosts(filteredPostsCount) {+ return (+ filteredPostsCount >= this.siteSettings.short_progress_text_threshold+ );+ }++ @discourseComputed("progressPosition", "topic.last_read_post_id")+ showBackButton(position, lastReadId) {+ if (!lastReadId) {+ return;+ }++ const stream = this.get("postStream.stream");+ const readPos = stream.indexOf(lastReadId) || 0;++ return readPos < stream.length - 1 && readPos > position;+ }++ _topicScrolled(event) {+ if (this.docked) {+ this.setProperties({+ progressPosition: this.get("postStream.filteredPostsCount"),+ _streamPercentage: 100,+ });+ } else {+ this.setProperties({+ progressPosition: event.postIndex,+ _streamPercentage: (event.percent * 100).toFixed(2),+ });+ }+ }++ @discourseComputed("_streamPercentage")+ progressStyle(_streamPercentage) {+ return `--progress-bg-width: ${_streamPercentage || 0}%`;+ }++ didInsertElement() {+ super.didInsertElement(...arguments);++ this.appEvents.on("topic:current-post-scrolled", this, this._topicScrolled);++ if (this.prevEvent) {+ scheduleOnce("afterRender", this, this._topicScrolled, this.prevEvent);+ }+ }++ willDestroyElement() {+ super.willDestroyElement(...arguments);+ this.appEvents.off(+ "topic:current-post-scrolled",+ this,+ this._topicScrolled+ );+ }++ click(e) {+ if (e.target.closest("#topic-progress")) {+ this.toggleProperty("expanded");+ }+ }++ @action+ goBack() {+ this.jumpToPost(this.get("topic.last_read_post_number"));+ }+ }+++{{#unless this.hideProgress}}+ {{yield}}+{{/unless}}++{{#if this.showBackButton}}+ <div class="progress-back-container">+ <DButton+ @label="topic.timeline.back"+ @action={{this.goBack}}+ @icon="arrow-down"+ class="btn-primary btn-small progress-back"+ />+ </div>+{{/if}}++<nav+ title={{i18n "topic.progress.title"}}+ aria-label={{i18n "topic.progress.title"}}+ class={{if this.hideProgress "hidden"}}+ id="topic-progress"+ style={{html-safe this.progressStyle}}+>+ <div class="nums">+ <span>{{this.progressPosition}}</span>+ <span class={{if this.hugeNumberOfPosts "hidden"}}>/</span>+ <span+ class={{if this.hugeNumberOfPosts "hidden"}}+ >{{this.postStream.filteredPostsCount}}</span>+ </div>+ <div class="bg"></div>+</nav>++<PluginOutlet @name="after-topic-progress" @connectorTagName="div" />diff --cc app/assets/javascripts/discourse/app/components/topic-timer-info.gjsindex bc7000fd324,333eebff38b..a21bca03fdb--- a/app/assets/javascripts/discourse/app/components/topic-timer-info.gjs+++ b/app/assets/javascripts/discourse/app/components/topic-timer-info.gjs@@@ -1,26 -1,163 +1,190 @@@+ import Component from "@ember/component";+ import { cancel, next } from "@ember/runloop";+ import { htmlSafe } from "@ember/template";+ import { classNames } from "@ember-decorators/component";+ import { on } from "@ember-decorators/object";+ import { DELETE_REPLIES_TYPE } from "discourse/components/modal/edit-topic-timer";+ import discourseComputed from "discourse/lib/decorators";+ import { isTesting } from "discourse/lib/environment";+ import { iconHTML } from "discourse/lib/icon-library";+ import discourseLater from "discourse/lib/later";+ import Category from "discourse/models/category";+ import { i18n } from "discourse-i18n";++ @classNames("topic-timer-info")+ export default class TopicTimerInfo extends Component {+ clockIcon = htmlSafe(`${iconHTML("far-clock")}`);+ trashLabel = i18n("post.controls.remove_timer");++ title = null;+ notice = null;+ showTopicTimer = null;+ showTopicTimerModal = null;+ removeTopicTimer = null;+ _delayedRerender = null;++ @on("didReceiveAttrs")+ setupRenderer() {+ this.renderTopicTimer();+ }++ @on("willDestroyElement")+ cancelDelayedRenderer() {+ if (this._delayedRerender) {+ cancel(this._delayedRerender);+ }+ }++ @discourseComputed+ canModifyTimer() {+ return this.currentUser && this.currentUser.get("canManageTopic");+ }++ @discourseComputed("canModifyTimer", "removeTopicTimer")+ showTrashCan(canModifyTimer, removeTopicTimer) {+ return canModifyTimer && removeTopicTimer;+ }++ @discourseComputed("canModifyTimer", "showTopicTimerModal")+ showEdit(canModifyTimer, showTopicTimerModal) {+ return canModifyTimer && showTopicTimerModal;+ }++ additionalOpts() {+ return {};+ }++ renderTopicTimer() {+ const isDeleteRepliesType = this.statusType === DELETE_REPLIES_TYPE;++ if (+ !isDeleteRepliesType &&+ !this.basedOnLastPost &&+ (!this.executeAt || this.executeAt < moment())+ ) {+ this.set("showTopicTimer", null);+ return;+ }++ if (this.isDestroyed) {+ return;+ }++ const topicStatus = this.topicClosed ? "close" : "open";+ const topicStatusKnown = this.topicClosed !== undefined;+ const topicStatusUpdate = this.statusUpdate !== undefined;+ if (topicStatusKnown && topicStatus === this.statusType) {+ if (!topicStatusUpdate) {+ return;+ }++ // The topic status has just been toggled, so we can hide the timer info.+ this.set("showTopicTimer", null);+ // The timer has already been removed on the back end. The front end is not aware of the change yet.+ // TODO: next() is a hack, to-be-removed+ next(() => this.set("executeAt", null));+ return;+ }++ const statusUpdateAt = moment(this.executeAt);+ const duration = moment.duration(statusUpdateAt - moment());+ const minutesLeft = duration.asMinutes();+ if (minutesLeft > 0 || isDeleteRepliesType || this.basedOnLastPost) {+ // We don't want to display a notice before a topic timer time has been set+ if (!this.executeAt) {+ return;+ }++ let durationMinutes = parseInt(this.durationMinutes, 10) || 0;++ let options = {+ timeLeft: duration.humanize(true),+ duration: moment+ .duration(durationMinutes, "minutes")+ .humanize({ s: 60, m: 60, h: 24 }),+ };++ const categoryId = this.categoryId;+ if (categoryId) {+ const category = Category.findById(categoryId);++ options = Object.assign(+ {+ categoryName: category.get("slug"),+ categoryUrl: category.get("url"),+ },+ options+ );+ }++ options = Object.assign(options, this.additionalOpts());+ this.setProperties({+ title: htmlSafe(`${moment(this.executeAt).format("LLLL")}`),+ notice: htmlSafe(`${i18n(this._noticeKey(), options)}`),+ showTopicTimer: true,+ });++ // TODO Sam: concerned this can cause a heavy rerender loop+ if (!isTesting()) {+ this._delayedRerender = discourseLater(() => {+ this.renderTopicTimer();+ }, this.rerenderDelay(minutesLeft));+ }+ } else {+ this.set("showTopicTimer", null);+ }+ }++ rerenderDelay(minutesLeft) {+ if (minutesLeft > 2160) {+ return 12 * 60 * 60000;+ } else if (minutesLeft > 1410) {+ return 60 * 60000;+ } else if (minutesLeft > 90) {+ return 30 * 60000;+ } else if (minutesLeft > 2) {+ return 60000;+ }++ return 1000;+ }++ _noticeKey() {+ let statusType = this.statusType;+ if (statusType === "silent_close") {+ statusType = "close";+ }+ if (this.basedOnLastPost && statusType === "close") {+ statusType = "close_after_last_post";+ }++ return `topic.status_update_notice.auto_${statusType}`;+ }+ }+++{{#if this.showTopicTimer}}+ <h3 class="topic-timer-heading">+ <span title={{this.title}}>+ {{this.clockIcon}}+ {{this.notice}}+ </span>+ <div class="topic-timer-modify">+ {{#if this.showEdit}}+ <DButton+ @title="post.controls.edit_timer"+ @icon="pencil"+ @action={{this.showTopicTimerModal}}+ class="topic-timer-edit no-text"+ />+ {{/if}}+ {{#if this.showTrashCan}}+ <DButton+ @title="post.controls.remove_timer"+ @icon="trash-can"+ @action={{this.removeTopicTimer}}+ class="topic-timer-remove no-text"+ />+ {{/if}}+ </div>+ </h3>+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/user-avatar-flair.gjsindex ce9f0575ce0,1ba93ac92aa..51f68838a0e--- a/app/assets/javascripts/discourse/app/components/user-avatar-flair.gjs+++ b/app/assets/javascripts/discourse/app/components/user-avatar-flair.gjs@@@ -1,8 -1,33 +1,42 @@@+ import Component from "@ember/component";+ import { tagName } from "@ember-decorators/component";+ import autoGroupFlairForUser from "discourse/lib/avatar-flair";+ import discourseComputed from "discourse/lib/decorators";++ @tagName("")+ export default class UserAvatarFlair extends Component {+ @discourseComputed("user")+ flair(user) {+ if (!user || !user.flair_group_id) {+ return;+ }++ if (user.flair_url || user.flair_bg_color) {+ return {+ flairName: user.flair_name,+ flairUrl: user.flair_url,+ flairBgColor: user.flair_bg_color,+ flairColor: user.flair_color,+ };+ }++ const autoFlairAttrs = autoGroupFlairForUser(this.site, user);+ if (autoFlairAttrs) {+ return {+ flairName: autoFlairAttrs.flair_name,+ flairUrl: autoFlairAttrs.flair_url,+ flairBgColor: autoFlairAttrs.flair_bg_color,+ flairColor: autoFlairAttrs.flair_color,+ };+ }+ }+ }+++{{#if this.flair}}+ <AvatarFlair+ @flairName={{this.flair.flairName}}+ @flairUrl={{this.flair.flairUrl}}+ @flairBgColor={{this.flair.flairBgColor}}+ @flairColor={{this.flair.flairColor}}+ />+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/user-card-contents.gjsindex d51a9c01b31,902c2d0f64d..8e3c806fa48--- a/app/assets/javascripts/discourse/app/components/user-card-contents.gjs+++ b/app/assets/javascripts/discourse/app/components/user-card-contents.gjs@@@ -1,426 -1,319 +1,746 @@@+ import EmberObject, { action, computed, set } from "@ember/object";+ import { alias, and, gt, gte, not, or } from "@ember/object/computed";+ import { dasherize } from "@ember/string";+ import { isEmpty } from "@ember/utils";+ import {+ attributeBindings,+ classNameBindings,+ classNames,+ } from "@ember-decorators/component";+ import { observes, on } from "@ember-decorators/object";+ import CardContentsBase from "discourse/components/card-contents-base";+ import CanCheckEmailsHelper from "discourse/lib/can-check-emails-helper";+ import { setting } from "discourse/lib/computed";+ import discourseComputed from "discourse/lib/decorators";+ import { durationTiny } from "discourse/lib/formatter";+ import { getURLWithCDN } from "discourse/lib/get-url";+ import { wantsNewWindow } from "discourse/lib/intercept-click";+ import { prioritizeNameInUx } from "discourse/lib/settings";+ import { emojiUnescape } from "discourse/lib/text";+ import { escapeExpression } from "discourse/lib/utilities";+ import User from "discourse/models/user";+ import { i18n } from "discourse-i18n";++ @classNames("user-card")+ @classNameBindings(+ "visible:show",+ "showBadges",+ "user.card_background_upload_url::no-bg",+ "isFixed:fixed",+ "usernameClass",+ "primaryGroup"+ )+ @attributeBindings("ariaLabel:aria-label")+ export default class UserCardContents extends CardContentsBase {+ elementId = "user-card";+ avatarSelector = "[data-user-card]";+ avatarDataAttrKey = "userCard";+ mentionSelector = "a.mention";+ ariaLabel = i18n("user.card");++ @setting("allow_profile_backgrounds") allowBackgrounds;+ @setting("enable_badges") showBadges;+ @setting("display_local_time_in_user_card") showUserLocalTime;+ @setting("moderators_view_emails") canModeratorsViewEmails;++ @alias("topic.postStream") postStream;++ @gte("topicPostCount", 2) enoughPostsForFiltering;++ @and("viewingTopic", "postStream.hasNoFilters", "enoughPostsForFiltering")+ showFilter;++ @gt("postStream.userFilters.length", 0) hasUserFilters;+ @gt("moreBadgesCount", 0) showMoreBadges;+ @and("viewingAdmin", "showName", "user.canBeDeleted") showDelete;+ @not("user.isBasic") linkWebsite;+ @or("user.suspend_reason", "user.bio_excerpt") isSuspendedOrHasBio;+ @and("user.staged", "canCheckEmails") showCheckEmail;++ user = null;++ // If inside a topic+ topicPostCount = null;++ @and(+ "user.featured_topic",+ "siteSettings.allow_featured_topic_on_user_profiles"+ )+ showFeaturedTopic;++ @computed("user.name", "user.username")+ get showName() {+ return this.user.name !== this.user.username;+ }++ @computed("model.id", "currentUser.id")+ get canCheckEmails() {+ return new CanCheckEmailsHelper(+ this.model,+ this.canModeratorsViewEmails,+ this.currentUser+ ).canCheckEmails;+ }++ @discourseComputed("user")+ hasLocaleOrWebsite(user) {+ return user.location || user.website_name || this.userTimezone;+ }++ @discourseComputed("user.status")+ hasStatus() {+ return this.siteSettings.enable_user_status && this.user.status;+ }++ @discourseComputed("user.status.emoji")+ userStatusEmoji(emoji) {+ return emojiUnescape(escapeExpression(`:${emoji}:`));+ }++ @discourseComputed("user.staff")+ staff(isStaff) {+ return isStaff ? "staff" : "";+ }++ @discourseComputed("user.trust_level")+ newUser(trustLevel) {+ return trustLevel === 0 ? "new-user" : "";+ }++ @discourseComputed("user.name")+ nameFirst(name) {+ return prioritizeNameInUx(name);+ }++ @discourseComputed("user")+ userTimezone(user) {+ if (!this.showUserLocalTime) {+ return;+ }+ return user.get("user_option.timezone");+ }++ @discourseComputed("userTimezone")+ formattedUserLocalTime(timezone) {+ return moment.tz(timezone).format(i18n("dates.time"));+ }++ @discourseComputed("username")+ usernameClass(username) {+ return username ? `user-card-${username}` : "";+ }++ @discourseComputed("username", "topicPostCount")+ filterPostsLabel(username, count) {+ return i18n("topic.filter_to", { username, count });+ }++ @discourseComputed("[email protected]")+ publicUserFields() {+ const siteUserFields = this.site.get("user_fields");+ if (!isEmpty(siteUserFields)) {+ const userFields = this.get("user.user_fields");+ return siteUserFields+ .filterBy("show_on_user_card", true)+ .sortBy("position")+ .map((field) => {+ set(field, "dasherized_name", dasherize(field.get("name")));+ const value = userFields ? userFields[field.get("id")] : null;+ return isEmpty(value) ? null : EmberObject.create({ value, field });+ })+ .compact();+ }+ }++ @discourseComputed("user.trust_level")+ removeNoFollow(trustLevel) {+ return trustLevel > 2 && !this.siteSettings.tl3_links_no_follow;+ }++ @discourseComputed("user.badge_count", "user.featured_user_badges.length")+ moreBadgesCount(badgeCount, badgeLength) {+ return badgeCount - badgeLength;+ }++ @discourseComputed("user.time_read", "user.recent_time_read")+ showRecentTimeRead(timeRead, recentTimeRead) {+ return timeRead !== recentTimeRead && recentTimeRead !== 0;+ }++ @discourseComputed("user.recent_time_read")+ recentTimeRead(recentTimeReadSeconds) {+ return durationTiny(recentTimeReadSeconds);+ }++ @discourseComputed("showRecentTimeRead", "user.time_read", "recentTimeRead")+ timeReadTooltip(showRecent, timeRead, recentTimeRead) {+ if (showRecent) {+ return i18n("time_read_recently_tooltip", {+ time_read: durationTiny(timeRead),+ recent_time_read: recentTimeRead,+ });+ } else {+ return i18n("time_read_tooltip", {+ time_read: durationTiny(timeRead),+ });+ }+ }++ @observes("user.card_background_upload_url")+ addBackground() {+ if (!this.allowBackgrounds) {+ return;+ }++ if (!this.element) {+ return;+ }++ const url = this.get("user.card_background_upload_url");+ const bg = isEmpty(url) ? "" : `url(${getURLWithCDN(url)})`;+ this.element.style.backgroundImage = bg;+ }++ @discourseComputed("user.primary_group_name")+ primaryGroup(primaryGroup) {+ return `group-${primaryGroup}`;+ }++ @discourseComputed("user.profile_hidden", "user.inactive")+ contentHidden(profileHidden, inactive) {+ return profileHidden || inactive;+ }++ @on("didInsertElement")+ _inserted() {+ this.appEvents.on("dom:clean", this, this.cleanUp);+ }++ @on("didDestroyElement")+ _destroyed() {+ this.appEvents.off("dom:clean", this, this.cleanUp);+ }++ async _showCallback(username) {+ this.setProperties({ visible: true, loading: true });++ const args = {+ forCard: true,+ include_post_count_for: this.get("topic.id"),+ };++ try {+ const user = await User.findByUsername(username, args);++ if (user.topic_post_count) {+ this.set(+ "topicPostCount",+ user.topic_post_count[args.include_post_count_for]+ );+ }+ this.setProperties({ user });+ this.user.statusManager.trackStatus();++ return user;+ } catch {+ this._close();+ } finally {+ this.set("loading", null);+ }+ }++ _close() {+ this.user?.statusManager.stopTrackingStatus();++ this.setProperties({+ user: null,+ topicPostCount: null,+ });++ super._close(...arguments);+ }++ cleanUp() {+ this._close();+ }++ @action+ refreshRoute(value) {+ this.router.transitionTo({ queryParams: { name: value } });+ }++ @action+ handleShowUser(event) {+ if (wantsNewWindow(event)) {+ return;+ }++ event.preventDefault();+ // Invokes `showUser` argument. Convert to `this.args.showUser` when+ // refactoring this to a glimmer component.+ this.showUser(this.user);+ this._close();+ }++ @action+ close() {+ this._close();+ }++ @action+ composePM(user, post) {+ this._close();+ this.composePrivateMessage(user, post);+ }++ @action+ cancelFilter() {+ this.postStream.cancelFilter();+ this.postStream.refresh();+ this._close();+ }++ @action+ handleFilterPosts() {+ this.filterPosts(this.user);+ this._close();+ }++ @action+ deleteUser() {+ this.user.delete();+ this._close();+ }++ @action+ checkEmail(user) {+ user.checkEmail();+ }+ }+++{{#if this.visible}}+ <PluginOutlet+ @name="before-user-card-content"+ @outletArgs={{hash user=this.user}}+ />+ <div class="card-content">+ {{#if this.loading}}+ <div class="card-row first-row">+ <div class="user-card-avatar">+ <div+ class="card-avatar-placeholder animated-placeholder placeholder-animation"+ ></div>+ </div>+ </div>++ <div class="card-row second-row">+ <div class="animated-placeholder placeholder-animation"></div>+ </div>+ <div class="card-row">+ <div class="animated-placeholder placeholder-animation"></div>+ </div>+ <div class="card-row">+ <div class="animated-placeholder placeholder-animation"></div>+ </div>+ <div class="card-row">+ <div class="animated-placeholder placeholder-animation"></div>+ </div>+ {{else}}+ <div class="card-row first-row">+ <PluginOutlet+ @name="user-card-main-info"+ @outletArgs={{hash+ user=this.user+ post=this.post+ contentHidden=this.contentHidden+ handleShowUser=this.handleShowUser+ }}+ >+ <div class="user-card-avatar" aria-hidden="true">+ {{#if this.contentHidden}}+ <span class="card-huge-avatar">{{bound-avatar+ this.user+ "huge"+ }}</span>+ {{else}}+ <a+ {{on "click" this.handleShowUser}}+ href={{this.user.path}}+ class="card-huge-avatar"+ tabindex="-1"+ >{{bound-avatar this.user "huge"}}</a>+ {{/if}}++ <UserAvatarFlair @user={{this.user}} />++ <div>+ <PluginOutlet+ @name="user-card-avatar-flair"+ @connectorTagName="div"+ @outletArgs={{hash user=this.user}}+ />+ </div>+ </div>+ <div class="names">+ <div+ class="names__primary+ {{this.staff}}+ {{this.newUser}}+ {{if this.nameFirst 'full-name' 'username'}}"+ >+ {{#if this.contentHidden}}+ <span class="name-username-wrapper">+ {{if+ this.nameFirst+ this.user.name+ (format-username this.user.username)+ }}+ </span>+ {{else}}+ <a+ {{on "click" this.handleShowUser}}+ href={{this.user.path}}+ class="user-profile-link"+ aria-label={{i18n+ "user.profile_link"+ username=this.user.username+ }}+ >+ <span class="name-username-wrapper">+ {{if+ this.nameFirst+ this.user.name+ (format-username this.user.username)+ }}+ </span>+ {{user-status this.user currentUser=this.currentUser}}+ </a>+ {{/if}}+ </div>+ <PluginOutlet+ @name="user-card-after-username"+ @connectorTagName="div"+ @outletArgs={{hash user=this.user showUser=this.handleShowUser}}+ />+ {{#if this.nameFirst}}+ <div+ class="names__secondary username"+ >{{this.user.username}}</div>+ {{else}}+ {{#if this.user.name}}+ <div class="names__secondary full-name">{{this.user.name}}</div>+ {{/if}}+ {{/if}}+ {{#if this.user.title}}+ <div class="names__secondary">{{this.user.title}}</div>+ {{/if}}+ {{#if this.user.staged}}+ <div class="names__secondary staged">{{i18n "user.staged"}}</div>+ {{/if}}+ {{#if this.hasStatus}}+ <div class="user-status">+ {{html-safe this.userStatusEmoji}}+ <span class="user-status__description">+ {{this.user.status.description}}+ </span>+ {{format-date this.user.status.ends_at format="tiny"}}+ </div>+ {{/if}}+ <div>+ <PluginOutlet+ @name="user-card-post-names"+ @connectorTagName="div"+ @outletArgs={{hash user=this.user}}+ />+ </div>+ </div>+ </PluginOutlet>+ <ul class="usercard-controls">+ {{#if this.user.can_send_private_message_to_user}}+ <li class="compose-pm">+ <DButton+ @action={{fn (action "composePM") this.user this.post}}+ @icon="envelope"+ @label="user.private_message"+ class="btn-primary"+ />+ </li>+ {{/if}}+ <PluginOutlet+ @name="user-card-below-message-button"+ @connectorTagName="li"+ @outletArgs={{hash user=this.user close=(action "close")}}+ />+ {{#if this.showFilter}}+ <li>+ <DButton+ @action={{fn this.handleFilterPosts this.user}}+ @icon="filter"+ @translatedLabel={{this.filterPostsLabel}}+ class="btn-default"+ />+ </li>+ {{/if}}+ {{#if this.hasUserFilters}}+ <li>+ <DButton+ @action={{action "cancelFilter"}}+ @icon="xmark"+ @label="topic.filters.cancel"+ />+ </li>+ {{/if}}+ {{#if this.showDelete}}+ <li>+ <DButton+ @action={{fn (action "deleteUser") this.user}}+ @icon="triangle-exclamation"+ @label="admin.user.delete"+ class="btn-danger"+ />+ </li>+ {{/if}}+ <PluginOutlet+ @name="user-card-additional-buttons"+ @connectorTagName="li"+ @outletArgs={{hash user=this.user close=(action "close")}}+ />+ </ul>+ <PluginOutlet+ @name="user-card-additional-controls"+ @connectorTagName="div"+ @outletArgs={{hash user=this.user close=(action "close")}}+ />+ </div>++ {{#if this.user.profile_hidden}}+ <div class="card-row second-row">+ <div class="profile-hidden">+ <span role="alert">{{i18n "user.profile_hidden"}}</span>+ </div>+ </div>+ {{else if this.user.inactive}}+ <div class="card-row second-row">+ <div class="inactive-user">+ <span role="alert">{{i18n "user.inactive_user"}}</span>+ </div>+ </div>+ {{/if}}++ {{#if this.isSuspendedOrHasBio}}+ <div class="card-row second-row">+ {{#if this.user.suspend_reason}}+ <div class="suspended">+ <div class="suspension-date">+ {{d-icon "ban"}}+ {{#if this.user.suspendedForever}}+ {{i18n "user.suspended_permanently"}}+ {{else}}+ {{i18n+ "user.suspended_notice"+ date=this.user.suspendedTillDate+ }}+ {{/if}}+ </div>+ <div class="suspension-reason">+ <span class="suspension-reason-title">{{i18n+ "user.suspended_reason"+ }}</span>+ <span+ class="suspension-reason-description"+ >{{this.user.suspend_reason}}</span>+ </div>+ </div>+ {{else}}+ {{#if this.user.bio_excerpt}}+ <div class="bio">+ <HtmlWithLinks>+ {{html-safe this.user.bio_excerpt}}+ </HtmlWithLinks>+ </div>+ {{/if}}+ {{/if}}+ </div>+ {{/if}}++ {{#if this.showFeaturedTopic}}+ <div class="card-row">+ <div class="featured-topic">+ <span class="desc">{{i18n "user.featured_topic"}}</span>+ <LinkTo+ @route="topic"+ @models={{array+ this.user.featured_topic.slug+ this.user.featured_topic.id+ }}+ >{{replace-emoji+ (html-safe this.user.featured_topic.fancy_title)+ }}</LinkTo>+ </div>+ </div>+ {{/if}}++ {{#if this.hasLocaleOrWebsite}}+ <div class="card-row">+ <div class="location-and-website">+ {{#if this.user.website_name}}+ <span class="website-name">+ {{d-icon "globe"}}+ {{#if this.linkWebsite}}+ {{! template-lint-disable link-rel-noopener }}+ <a+ href={{this.user.website}}+ rel="noopener {{unless this.removeNoFollow 'nofollow ugc'}}"+ target="_blank"+ >{{this.user.website_name}}</a>+ {{! template-lint-enable link-rel-noopener }}+ {{else}}+ <span+ title={{this.user.website}}+ >{{this.user.website_name}}</span>+ {{/if}}+ </span>+ {{/if}}+ {{#if this.user.location}}+ <span class="location">+ {{d-icon "location-dot"}}+ <span>{{this.user.location}}</span>+ </span>+ {{/if}}+ {{#if this.showUserLocalTime}}+ <span class="local-time" title={{i18n "local_time"}}>+ {{d-icon "far-clock"}}+ <span>{{this.formattedUserLocalTime}}</span>+ </span>+ {{/if}}+ <span>+ <PluginOutlet+ @name="user-card-location-and-website"+ @connectorTagName="div"+ @outletArgs={{hash user=this.user}}+ />+ </span>+ </div>+ </div>+ {{/if}}++ <div class="card-row metadata-row">+ {{#unless this.contentHidden}}+ <div class="metadata">+ {{#if this.user.last_posted_at}}+ <div class="metadata__last-posted">+ <span class="desc">{{i18n "last_post"}}</span>+ {{format-date this.user.last_posted_at leaveAgo="true"}}</div>+ {{/if}}+ <div class="metadata__user-created">+ <span class="desc">{{i18n "joined"}}</span>+ {{format-date this.user.created_at leaveAgo="true"}}</div>+ {{#if this.user.time_read}}+ <div class="metadata__time-read" title={{this.timeReadTooltip}}>+ <span class="desc">{{i18n "time_read"}}</span>+ {{format-duration this.user.time_read}}+ {{#if this.showRecentTimeRead}}+ <span>+ ({{i18n+ "time_read_recently"+ time_read=this.recentTimeRead+ }})+ </span>+ {{/if}}+ </div>+ {{/if}}+ {{#if this.showCheckEmail}}+ <div class="metadata__email">+ {{d-icon "envelope" title="user.email.title"}}+ {{#if this.user.email}}+ {{this.user.email}}+ {{else}}+ <DButton+ @action={{fn (action "checkEmail") this.user}}+ @icon="envelope"+ @label="admin.users.check_email.text"+ class="btn-primary"+ />+ {{/if}}+ </div>+ {{/if}}+ <PluginOutlet+ @name="user-card-metadata"+ @connectorTagName="div"+ @outletArgs={{hash user=this.user}}+ />+ </div>+ {{/unless}}+ <PluginOutlet+ @name="user-card-after-metadata"+ @connectorTagName="div"+ @outletArgs={{hash user=this.user}}+ />+ </div>++ {{#if this.publicUserFields}}+ <div class="card-row">+ <div class="public-user-fields">+ {{#each this.publicUserFields as |uf|}}+ {{#if uf.value}}+ <div+ class="public-user-field public-user-field__{{uf.field.dasherized_name}}"+ >+ <span class="user-field-name">{{uf.field.name}}:</span>+ <span class="user-field-value">+ {{#each uf.value as |v|}}+ {{! some values are arrays }}+ <span class="user-field-value-list-item">+ {{#if uf.field.searchable}}+ <LinkTo+ @route="users"+ @query={{hash name=v}}+ {{on "click" (fn this.refreshRoute v)}}+ >{{v}}</LinkTo>+ {{else}}+ {{v}}+ {{/if}}+ </span>+ {{else}}+ {{uf.value}}+ {{/each}}+ </span>+ </div>+ {{/if}}+ {{/each}}+ </div>+ </div>+ {{/if}}++ <PluginOutlet+ @name="user-card-before-badges"+ @connectorTagName="div"+ @outletArgs={{hash user=this.user}}+ />++ {{#if this.showBadges}}+ <div class="card-row">+ <PluginOutlet+ @name="user-card-badges"+ @outletArgs={{hash user=this.user post=this.post}}+ >+ {{#if this.user.featured_user_badges}}+ <div class="badge-section">+ {{#each this.user.featured_user_badges as |ub|}}+ <UserBadge @badge={{ub.badge}} @user={{this.user}} />+ {{/each}}+ {{#if this.showMoreBadges}}+ <span class="more-user-badges">+ <LinkTo @route="user.badges" @model={{this.user}}>+ {{i18n "badges.more_badges" count=this.moreBadgesCount}}+ </LinkTo>+ </span>+ {{/if}}+ </div>+ {{/if}}+ </PluginOutlet>+ </div>+ {{/if}}+ {{/if}}+ </div>+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/user-fields/confirm.gjsindex 9737e1fac34,6924c4e9052..cd229747a7c--- a/app/assets/javascripts/discourse/app/components/user-fields/confirm.gjs+++ b/app/assets/javascripts/discourse/app/components/user-fields/confirm.gjs@@@ -1,26 -1,3 +1,30 @@@+ import UserFieldBase from "./base";++ export default class UserFieldConfirm extends UserFieldBase {}+++{{#if this.field.name}}+ <label class="control-label">+ {{this.field.name}}+ {{~#unless this.field.required}} {{i18n "user_fields.optional"}}{{/unless~}}+ </label>+{{/if}}++<div class="controls">+ <label class="control-label checkbox-label">+ <Input+ id={{concat "user-" this.elementId}}+ @checked={{this.value}}+ @type="checkbox"+ />+ <span>+ {{html-safe this.field.description}}+ {{#unless this.field.name}}{{#if this.field.required}}<span+ class="required"+ >*</span>{{/if}}{{/unless}}+ </span>+ </label>+ <InputTip+ @validation={{@validation}}+ class={{unless @validation.reason "hidden"}}+ />+</div>diff --cc app/assets/javascripts/discourse/app/components/user-fields/text.gjsindex ff5fb9d8759,f19667f33e9..ee15ec48bbe--- a/app/assets/javascripts/discourse/app/components/user-fields/text.gjs+++ b/app/assets/javascripts/discourse/app/components/user-fields/text.gjs@@@ -1,21 -1,3 +1,25 @@@+ import UserFieldBase from "./base";++ export default class UserFieldText extends UserFieldBase {}+++<div class="controls">+ <Input+ id={{concat "user-" this.elementId}}+ @value={{this.value}}+ maxlength={{this.site.user_field_max_length}}+ />+ <label+ class="control-label alt-placeholder"+ for={{concat "user-" this.elementId}}+ >+ {{this.field.name}}+ {{~#unless this.field.required}} {{i18n "user_fields.optional"}}{{/unless~}}+ </label>+ <InputTip+ @validation={{this.validation}}+ class={{unless this.validation "hidden"}}+ />+ {{#unless this.validation}}+ <div class="instructions">{{html-safe this.field.description}}</div>+ {{/unless}}+</div>diff --cc app/assets/javascripts/discourse/app/components/user-info.gjsindex 91d1db165a8,ef4863c849a..b0e687bc52d--- a/app/assets/javascripts/discourse/app/components/user-info.gjs+++ b/app/assets/javascripts/discourse/app/components/user-info.gjs@@@ -1,60 -1,39 +1,100 @@@+ import Component from "@ember/component";+ import { alias } from "@ember/object/computed";+ import {+ attributeBindings,+ classNameBindings,+ } from "@ember-decorators/component";+ import discourseComputed from "discourse/lib/decorators";+ import { prioritizeNameInUx } from "discourse/lib/settings";+ import { userPath } from "discourse/lib/url";++ @classNameBindings(":user-info", "size")+ @attributeBindings("dataUsername:data-username")+ export default class UserInfo extends Component {+ size = "small";+ includeLink = true;+ includeAvatar = true;++ @alias("user.username") dataUsername;++ didInsertElement() {+ super.didInsertElement(...arguments);+ this.user?.statusManager?.trackStatus();+ }++ willDestroyElement() {+ super.willDestroyElement(...arguments);+ this.user?.statusManager?.stopTrackingStatus();+ }++ @discourseComputed("user.username")+ userPath(username) {+ return userPath(username);+ }++ @discourseComputed("user.name")+ nameFirst(name) {+ return prioritizeNameInUx(name);+ }+ }+++{{#if this.includeAvatar}}+ <div class="user-image">+ <div class="user-image-inner">+ <a+ href={{this.userPath}}+ data-user-card={{@user.username}}+ aria-hidden="true"+ >{{avatar @user imageSize="large"}}</a>+ <UserAvatarFlair @user={{@user}} />+ </div>+ </div>+{{/if}}+<div class="user-detail">+ <div class="name-line">+ {{#if this.includeLink}}+ <a+ href={{this.userPath}}+ data-user-card={{@user.username}}+ role="heading"+ >+ <span class={{if this.nameFirst "name" "username"}}>+ {{if this.nameFirst @user.name (format-username @user.username)}}+ </span>+ <span class={{if this.nameFirst "username" "name"}}>+ {{if this.nameFirst (format-username @user.username) @user.name}}+ </span>+ </a>+ {{else}}+ <span class={{if this.nameFirst "name" "username"}}>+ {{if this.nameFirst @user.name (format-username @user.username)}}+ </span>+ <span class={{if this.nameFirst "username" "name"}}>+ {{if this.nameFirst (format-username @user.username) @user.name}}+ </span>+ {{/if}}+ {{#if (and @showStatus @user.status)}}+ <UserStatusMessage+ @status={{@user.status}}+ @showDescription={{@showStatusDescription}}+ />+ {{/if}}+ <PluginOutlet+ @name="after-user-name"+ @connectorTagName="span"+ @outletArgs={{hash user=this.user}}+ />+ </div>+ <div class="title">{{@user.title}}</div>+ {{#if (has-block)}}+ <div class="details">+ {{yield}}+ </div>+ {{/if}}+</div>++<PluginOutlet+ @name="after-user-info"+ @connectorTagName="div"+ @outletArgs={{hash user=this.user}}+/>diff --cc app/assets/javascripts/discourse/app/components/user-menu/menu-item.gjsindex f1e7848db94,34c4b8d0845..fbde40cb490--- a/app/assets/javascripts/discourse/app/components/user-menu/menu-item.gjs+++ b/app/assets/javascripts/discourse/app/components/user-menu/menu-item.gjs@@@ -1,33 -1,79 +1,113 @@@+ import Component from "@glimmer/component";+ import { action } from "@ember/object";+ import { htmlSafe } from "@ember/template";+ import { emojiUnescape } from "discourse/lib/text";+ import { escapeExpression } from "discourse/lib/utilities";++ export default class UserMenuItem extends Component {+ get className() {+ return this.#item.className;+ }++ get linkHref() {+ return this.#item.linkHref;+ }++ get linkTitle() {+ return this.#item.linkTitle;+ }++ get icon() {+ return this.#item.icon;+ }++ get label() {+ return this.#item.label;+ }++ get labelClass() {+ return this.#item.labelClass;+ }++ get description() {+ const description = this.#item.description;+ if (description) {+ if (typeof description === "string") {+ // do emoji unescape on all items+ return htmlSafe(emojiUnescape(escapeExpression(description)));+ }+ // it's probably an htmlSafe object, don't try to unescape emojis+ return description;+ }+ }++ get descriptionClass() {+ return this.#item.descriptionClass;+ }++ get topicId() {+ return this.#item.topicId;+ }++ get iconComponent() {+ return this.#item.iconComponent;+ }++ get iconComponentArgs() {+ return this.#item.iconComponentArgs;+ }++ get endComponent() {+ return this.#item.endComponent;+ }++ get endOutletArgs() {+ return this.#item.endOutletArgs;+ }++ get #item() {+ return this.args.item;+ }++ @action+ onClick(event) {+ return this.#item.onClick({+ event,+ closeUserMenu: this.args.closeUserMenu,+ });+ }+ }+++<li class={{this.className}}>+ <a+ href={{this.linkHref}}+ title={{this.linkTitle}}+ {{on "click" this.onClick}}+ >+ {{#if this.iconComponent}}+ <this.iconComponent @data={{this.iconComponentArgs}} />+ {{else}}+ {{d-icon this.icon}}+ {{/if}}+ <div>+ {{#if this.label}}+ <span class={{concat "item-label " this.labelClass}}>+ {{this.label}}+ </span>+ {{/if}}+ {{#if this.description}}+ <span+ class={{concat "item-description " this.descriptionClass}}+ data-topic-id={{this.topicId}}+ >+ {{this.description}}+ </span>+ {{/if}}+ </div>++ {{#if this.endComponent}}+ <this.endComponent />+ {{/if}}+ </a>+ <PluginOutlet @name="menu-item-end" @outletArgs={{this.endOutletArgs}} />+</li>diff --cc app/assets/javascripts/discourse/app/components/user-menu/menu-tab.gjsindex 3cd40ca7e63,0e01a83dd88..21f0b9c0623--- a/app/assets/javascripts/discourse/app/components/user-menu/menu-tab.gjs+++ b/app/assets/javascripts/discourse/app/components/user-menu/menu-tab.gjs@@@ -1,20 -1,27 +1,48 @@@+ import Component from "@glimmer/component";++ export default class UserMenuTab extends Component {+ get isActive() {+ return this.args.tab.id === this.args.currentTabId;+ }++ get classNames() {+ const list = ["btn", "btn-flat", "btn-icon", "no-text", "user-menu-tab"];+ if (this.isActive) {+ list.push("active");+ }+ return list.join(" ");+ }++ get id() {+ return `user-menu-button-${this.args.tab.id}`;+ }++ get tabIndex() {+ return this.isActive ? "0" : "-1";+ }++ get ariaControls() {+ return `quick-access-${this.args.tab.id}`;+ }+ }+++<a+ role="tab"+ class={{this.classNames}}+ id={{this.id}}+ tabindex={{this.tabIndex}}+ title={{@tab.title}}+ aria-label={{@tab.title}}+ aria-selected={{if this.isActive "true" "false"}}+ aria-controls={{this.ariaControls}}+ data-tab-number={{@tab.position}}+ href={{@tab.linkWhenActive}}+ {{on "click" @onTabClick}}+ {{on "keydown" @onTabClick}}+>+ {{d-icon @tab.icon}}+ {{#if @tab.count}}+ <span aria-hidden="true" class="badge-notification">{{@tab.count}}</span>+ {{/if}}+ {{yield}}+</a>diff --cc app/assets/javascripts/discourse/app/components/user-menu/menu.gjsindex 45fc22a8614,348edbb18e9..dc2a84b2c02--- a/app/assets/javascripts/discourse/app/components/user-menu/menu.gjs+++ b/app/assets/javascripts/discourse/app/components/user-menu/menu.gjs@@@ -1,51 -1,326 +1,378 @@@+ import Component from "@glimmer/component";+ import { cached, tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { getOwner } from "@ember/owner";+ import { service } from "@ember/service";+ import { bind } from "discourse/lib/decorators";+ import deprecated from "discourse/lib/deprecated";+ import getUrl from "discourse/lib/get-url";+ import { wantsNewWindow } from "discourse/lib/intercept-click";+ import UserMenuTab, { CUSTOM_TABS_CLASSES } from "discourse/lib/user-menu/tab";+ import { NO_REMINDER_ICON } from "discourse/models/bookmark";+ import UserMenuBookmarksList from "./bookmarks-list";+ import UserMenuLikesNotificationsList from "./likes-notifications-list";+ import UserMenuMessagesList from "./messages-list";+ import UserMenuNotificationsList from "./notifications-list";+ import UserMenuOtherNotificationsList from "./other-notifications-list";+ import UserMenuProfileTabContent from "./profile-tab-content";+ import UserMenuRepliesNotificationsList from "./replies-notifications-list";+ import UserMenuReviewablesList from "./reviewables-list";++ const DEFAULT_TAB_ID = "all-notifications";+ const DEFAULT_PANEL_COMPONENT = UserMenuNotificationsList;++ const REVIEW_QUEUE_TAB_ID = "review-queue";++ const CORE_TOP_TABS = [+ class extends UserMenuTab {+ id = DEFAULT_TAB_ID;+ icon = "bell";+ panelComponent = DEFAULT_PANEL_COMPONENT;++ get linkWhenActive() {+ return `${this.currentUser.path}/notifications`;+ }+ },++ class extends UserMenuTab {+ id = "replies";+ icon = "user_menu.replies";+ panelComponent = UserMenuRepliesNotificationsList;+ notificationTypes = [+ "mentioned",+ "group_mentioned",+ "posted",+ "quoted",+ "replied",+ ];++ get count() {+ return (+ this.getUnreadCountForType("mentioned") ++ this.getUnreadCountForType("group_mentioned") ++ this.getUnreadCountForType("posted") ++ this.getUnreadCountForType("quoted") ++ this.getUnreadCountForType("replied")+ );+ }++ get linkWhenActive() {+ return `${this.currentUser.path}/notifications/responses`;+ }+ },++ class extends UserMenuTab {+ id = "likes";+ icon = "heart";+ panelComponent = UserMenuLikesNotificationsList;++ get shouldDisplay() {+ return !this.currentUser.user_option.likes_notifications_disabled;+ }++ get count() {+ return (+ this.getUnreadCountForType("liked") ++ this.getUnreadCountForType("liked_consolidated") ++ this.getUnreadCountForType("reaction")+ );+ }++ // TODO(osama): reaction is a type used by the reactions plugin, but it's+ // added here temporarily until we add a plugin API for extending+ // filterByTypes in lists+ get notificationTypes() {+ return ["liked", "liked_consolidated", "reaction"];+ }++ get linkWhenActive() {+ return `${this.currentUser.path}/notifications/likes-received`;+ }+ },++ class extends UserMenuTab {+ id = "messages";+ icon = "notification.private_message";+ panelComponent = UserMenuMessagesList;+ notificationTypes = ["private_message", "group_message_summary"];++ get count() {+ return this.getUnreadCountForType("private_message");+ }++ get shouldDisplay() {+ return this.currentUser?.can_send_private_messages;+ }++ get linkWhenActive() {+ return `${this.currentUser.path}/messages`;+ }+ },++ class extends UserMenuTab {+ id = "bookmarks";+ icon = NO_REMINDER_ICON;+ panelComponent = UserMenuBookmarksList;+ notificationTypes = ["bookmark_reminder"];++ get count() {+ return this.getUnreadCountForType("bookmark_reminder");+ }++ get linkWhenActive() {+ return `${this.currentUser.path}/activity/bookmarks`;+ }+ },++ class extends UserMenuTab {+ id = REVIEW_QUEUE_TAB_ID;+ icon = "flag";+ panelComponent = UserMenuReviewablesList;+ linkWhenActive = getUrl("/review");++ get shouldDisplay() {+ return (+ this.currentUser.can_review && this.currentUser.get("reviewable_count")+ );+ }++ get count() {+ return this.currentUser.get("reviewable_count");+ }+ },+ ];++ const CORE_BOTTOM_TABS = [+ class extends UserMenuTab {+ id = "profile";+ icon = "user";+ panelComponent = UserMenuProfileTabContent;++ get linkWhenActive() {+ return `${this.currentUser.path}/summary`;+ }+ },+ ];++ const CORE_OTHER_NOTIFICATIONS_TAB = class extends UserMenuTab {+ id = "other-notifications";+ icon = "discourse-other-tab";+ panelComponent = UserMenuOtherNotificationsList;++ constructor(currentUser, siteSettings, site, otherNotificationTypes) {+ super(...arguments);+ this.otherNotificationTypes = otherNotificationTypes;+ }++ get count() {+ return this.otherNotificationTypes.reduce((sum, notificationType) => {+ return sum + this.getUnreadCountForType(notificationType);+ }, 0);+ }++ get notificationTypes() {+ return this.otherNotificationTypes;+ }+ };++ function resolvePanelComponent(owner, panelComponent) {+ if (typeof panelComponent === "string") {+ const nameForConsole = JSON.stringify(panelComponent);+ deprecated(+ `user-menu tab panelComponent must be passed as a component class (passed ${nameForConsole})`,+ { id: "discourse.user-menu.panel-component-class" }+ );+ return owner.resolveRegistration(`component:${panelComponent}`);+ }+ return panelComponent;+ }++ export default class UserMenu extends Component {+ @service appEvents;+ @service currentUser;+ @service router;+ @service site;+ @service siteSettings;++ @tracked currentTabId = DEFAULT_TAB_ID;+ @tracked currentPanelComponent = DEFAULT_PANEL_COMPONENT;+ @tracked currentNotificationTypes;++ constructor() {+ super(...arguments);+ this.router.on("routeDidChange", this.onRouteChange);+ }++ willDestroy() {+ super.willDestroy(...arguments);+ this.router.off("routeDidChange", this.onRouteChange);+ }++ @bind+ onRouteChange() {+ this.args.closeUserMenu();+ }++ get classNames() {+ let classes = ["user-menu", "revamped", "menu-panel", "drop-down"];+ if (this.siteSettings.show_user_menu_avatars) {+ classes.push("show-avatars");+ }+ return classes.join(" ");+ }++ @cached+ get topTabs() {+ const tabs = [];++ CORE_TOP_TABS.forEach((tabClass) => {+ const tab = new tabClass(this.currentUser, this.siteSettings, this.site);+ if (tab.shouldDisplay) {+ tabs.push(tab);+ }+ });++ let reviewQueueTabIndex = tabs.findIndex(+ (tab) => tab.id === REVIEW_QUEUE_TAB_ID+ );++ CUSTOM_TABS_CLASSES.forEach((tabClass) => {+ const tab = new tabClass(this.currentUser, this.siteSettings, this.site);+ if (tab.shouldDisplay) {+ if (reviewQueueTabIndex === -1) {+ tabs.push(tab);+ } else {+ tabs.insertAt(reviewQueueTabIndex, tab);+ reviewQueueTabIndex++;+ }+ }+ });++ tabs.push(+ new CORE_OTHER_NOTIFICATIONS_TAB(+ this.currentUser,+ this.siteSettings,+ this.site,+ this.#notificationTypesForTheOtherTab(tabs)+ )+ );++ return tabs.map((tab, index) => {+ tab.position = index;+ return tab;+ });+ }++ @cached+ get bottomTabs() {+ const tabs = [];++ CORE_BOTTOM_TABS.forEach((tabClass) => {+ const tab = new tabClass(this.currentUser, this.siteSettings, this.site);+ if (tab.shouldDisplay) {+ tabs.push(tab);+ }+ });++ const topTabsLength = this.topTabs.length;+ return tabs.map((tab, index) => {+ tab.position = index + topTabsLength;+ return tab;+ });+ }++ #notificationTypesForTheOtherTab(tabs) {+ const usedNotificationTypes = tabs+ .filter((tab) => tab.notificationTypes)+ .map((tab) => tab.notificationTypes)+ .flat();+ return Object.keys(this.site.notification_types).filter(+ (notificationType) => !usedNotificationTypes.includes(notificationType)+ );+ }++ @action+ handleTabClick(tab, event) {+ if (wantsNewWindow(event) || this.currentTabId === tab.id) {+ // Allow normal navigation to href+ return;+ }++ if (event.type === "keydown" && event.keyCode !== 13) {+ return;+ }++ event.preventDefault();++ this.currentTabId = tab.id;+ this.currentPanelComponent = resolvePanelComponent(+ getOwner(this),+ tab.panelComponent+ );++ this.appEvents.trigger("user-menu:tab-click", tab.id);+ this.currentNotificationTypes = tab.notificationTypes;+ }++ @action+ triggerRenderedAppEvent() {+ this.appEvents.trigger("user-menu:rendered");+ }++ @action+ focusFirstTab(topTabsContainerElement) {+ topTabsContainerElement.querySelector(".btn.active")?.focus();+ }+ }+++<div+ class={{this.classNames}}+ data-tab-id={{this.currentTabId}}+ data-max-width="320"+ {{did-insert this.triggerRenderedAppEvent}}+>+ <div class="panel-body">+ <div class="panel-body-contents">+ <div+ class="menu-tabs-container"+ role="tablist"+ aria-orientation="vertical"+ aria-label={{i18n "user_menu.sr_menu_tabs"}}+ >+ <div class="top-tabs tabs-list" {{did-insert this.focusFirstTab}}>+ {{#each this.topTabs as |tab|}}+ <UserMenu::MenuTab+ @tab={{tab}}+ @currentTabId={{this.currentTabId}}+ @onTabClick={{fn this.handleTabClick tab}}+ />+ {{/each}}+ </div>+ <div class="bottom-tabs tabs-list">+ {{#each this.bottomTabs as |tab|}}+ <UserMenu::MenuTab+ @tab={{tab}}+ @currentTabId={{this.currentTabId}}+ @onTabClick={{fn this.handleTabClick tab}}+ />+ {{/each}}+ </div>++ <PluginOutlet+ @name="user-menu-tabs-list__after"+ @outletArgs={{hash user=this.currentUser}}+ />+ </div>+ <div+ id={{concat "quick-access-" this.currentTabId}}+ class="quick-access-panel"+ >+ <this.currentPanelComponent+ @closeUserMenu={{@closeUserMenu}}+ @filterByTypes={{this.currentNotificationTypes}}+ @ariaLabelledby={{concat "user-menu-button-" this.currentTabId}}+ />+ </div>+ </div>+ </div>+</div>diff --cc app/assets/javascripts/discourse/app/components/user-menu/profile-tab-content.gjsindex 1754c594c45,a4fd7ce1603..178ca285b90--- a/app/assets/javascripts/discourse/app/components/user-menu/profile-tab-content.gjs+++ b/app/assets/javascripts/discourse/app/components/user-menu/profile-tab-content.gjs@@@ -1,167 -1,110 +1,278 @@@+ import Component from "@glimmer/component";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import DoNotDisturbModal from "discourse/components/modal/do-not-disturb";+ import UserStatusModal from "discourse/components/modal/user-status";+ import { ajax } from "discourse/lib/ajax";+ import DoNotDisturb from "discourse/lib/do-not-disturb";+ import { userPath } from "discourse/lib/url";++ const _extraItems = [];++ export function addUserMenuProfileTabItem(item) {+ _extraItems.push(item);+ }++ export function resetUserMenuProfileTabItems() {+ _extraItems.clear();+ }++ export default class UserMenuProfileTabContent extends Component {+ @service currentUser;+ @service siteSettings;+ @service userStatus;+ @service modal;++ saving = false;++ get showToggleAnonymousButton() {+ return (+ this.currentUser.can_post_anonymously || this.currentUser.is_anonymous+ );+ }++ get isInDoNotDisturb() {+ return !!this.#doNotDisturbUntilDate;+ }++ get doNotDisturbDateTime() {+ return this.#doNotDisturbUntilDate.getTime();+ }++ get showDoNotDisturbEndDate() {+ return !DoNotDisturb.isEternal(+ this.currentUser.get("do_not_disturb_until")+ );+ }++ get extraItems() {+ return _extraItems;+ }++ get #doNotDisturbUntilDate() {+ if (!this.currentUser.get("do_not_disturb_until")) {+ return;+ }+ const date = new Date(this.currentUser.get("do_not_disturb_until"));+ if (date < new Date()) {+ return;+ }+ return date;+ }++ get isPresenceHidden() {+ return this.currentUser.get("user_option.hide_presence");+ }++ @action+ doNotDisturbClick() {+ if (this.saving) {+ return;+ }+ this.saving = true;+ if (this.currentUser.do_not_disturb_until) {+ return this.currentUser.leaveDoNotDisturb().finally(() => {+ this.saving = false;+ });+ } else {+ this.saving = false;+ this.args.closeUserMenu();+ this.modal.show(DoNotDisturbModal);+ }+ }++ @action+ togglePresence() {+ this.currentUser.set("user_option.hide_presence", !this.isPresenceHidden);+ this.currentUser.save(["hide_presence"]);+ }++ @action+ setUserStatusClick() {+ this.args.closeUserMenu();++ this.modal.show(UserStatusModal, {+ model: {+ status: this.currentUser.status,+ pauseNotifications: this.currentUser.isInDoNotDisturb(),+ saveAction: (status, pauseNotifications) =>+ this.userStatus.set(status, pauseNotifications),+ deleteAction: () => this.userStatus.clear(),+ },+ });+ }++ @action+ async toggleAnonymous() {+ await ajax(userPath("toggle-anon"), { type: "POST" });+ window.location.reload();+ }+ }+++<ul aria-labelledby={{@ariaLabelledby}}>+ {{#if this.siteSettings.enable_user_status}}+ <li class="set-user-status">+ <DButton+ @action={{this.setUserStatusClick}}+ class="btn-flat profile-tab-btn"+ >+ {{#if this.currentUser.status}}+ {{emoji this.currentUser.status.emoji}}+ <span class="item-label">+ {{this.currentUser.status.description}}+ {{#if this.currentUser.status.ends_at}}+ {{format-age this.currentUser.status.ends_at}}+ {{/if}}+ </span>+ {{else}}+ {{d-icon "circle-plus"}}+ <span class="item-label">+ {{i18n "user_status.set_custom_status"}}+ </span>+ {{/if}}+ </DButton>+ </li>+ {{/if}}++ <li+ class={{concat-class+ "presence-toggle"+ (unless this.isPresenceHidden "enabled")+ }}+ title={{i18n "presence_toggle.title"}}+ >+ <DButton @action={{this.togglePresence}} class="btn-flat profile-tab-btn">+ {{d-icon (if this.isPresenceHidden "toggle-off" "toggle-on")}}+ <span class="item-label">+ {{#if this.isPresenceHidden}}+ {{i18n "presence_toggle.offline"}}+ {{else}}+ {{i18n "presence_toggle.online"}}+ {{/if}}+ </span>+ </DButton>+ </li>++ <li+ class={{concat-class "do-not-disturb" (if this.isInDoNotDisturb "enabled")}}+ >+ <DButton+ @action={{this.doNotDisturbClick}}+ class="btn-flat profile-tab-btn"+ >+ {{d-icon (if this.isInDoNotDisturb "toggle-on" "toggle-off")}}+ <span class="item-label">+ {{#if this.isInDoNotDisturb}}+ <span>{{i18n "pause_notifications.label"}}</span>+ {{#if this.showDoNotDisturbEndDate}}+ {{format-age this.doNotDisturbDateTime}}+ {{/if}}+ {{else}}+ {{i18n "pause_notifications.label"}}+ {{/if}}+ </span>+ </DButton>+ </li>++ <hr />++ <li class="summary">+ <LinkTo @route="user.summary" @model={{this.currentUser}}>+ {{d-icon "user"}}+ <span class="item-label">+ {{i18n "user.summary.title"}}+ </span>+ </LinkTo>+ </li>++ <li class="activity">+ <LinkTo @route="userActivity" @model={{this.currentUser}}>+ {{d-icon "bars-staggered"}}+ <span class="item-label">+ {{i18n "user.activity_stream"}}+ </span>+ </LinkTo>+ </li>++ {{#if this.currentUser.can_invite_to_forum}}+ <li class="invites">+ <LinkTo @route="userInvited" @model={{this.currentUser}}>+ {{d-icon "user-plus"}}+ <span class="item-label">+ {{i18n "user.invited.title"}}+ </span>+ </LinkTo>+ </li>+ {{/if}}++ <li class="drafts">+ <LinkTo @route="userActivity.drafts" @model={{this.currentUser}}>+ {{d-icon "user_menu.drafts"}}+ <span class="item-label">+ {{#if this.currentUser.draft_count}}+ {{i18n "drafts.label_with_count" count=this.currentUser.draft_count}}+ {{else}}+ {{i18n "drafts.label"}}+ {{/if}}+ </span>+ </LinkTo>+ </li>++ <li class="preferences">+ <LinkTo @route="preferences" @model={{this.currentUser}}>+ {{d-icon "gear"}}+ <span class="item-label">+ {{i18n "user.preferences.title"}}+ </span>+ </LinkTo>+ </li>++ {{#if this.showToggleAnonymousButton}}+ <li+ class={{if+ this.currentUser.is_anonymous+ "disable-anonymous"+ "enable-anonymous"+ }}+ >+ <DButton+ @action={{this.toggleAnonymous}}+ class="btn-flat profile-tab-btn"+ >+ {{#if this.currentUser.is_anonymous}}+ {{d-icon "ban"}}+ <span class="item-label">+ {{i18n "switch_from_anon"}}+ </span>+ {{else}}+ {{d-icon "user-secret"}}+ <span class="item-label">+ {{i18n "switch_to_anon"}}+ </span>+ {{/if}}+ </DButton>+ </li>+ {{/if}}++ {{#each this.extraItems as |item|}}+ <li class={{item.className}}>+ <a href={{item.href}}>+ {{#if item.icon}}+ {{d-icon item.icon}}+ {{/if}}+ <span class="item-label">+ {{item.content}}+ </span>+ </a>+ </li>+ {{/each}}++ <li class="logout">+ <DButton @action={{route-action "logout"}} class="btn-flat profile-tab-btn">+ {{d-icon "right-from-bracket"}}+ <span class="item-label">+ {{i18n "user.log_out"}}+ </span>+ </DButton>+ </li>+</ul>diff --cc app/assets/javascripts/discourse/app/components/user-notification-schedule.gjsindex 8b08f2ada1c,8a7f98bf119..85177ccbb8e--- a/app/assets/javascripts/discourse/app/components/user-notification-schedule.gjs+++ b/app/assets/javascripts/discourse/app/components/user-notification-schedule.gjs@@@ -1,32 -1,139 +1,172 @@@+ import Component from "@ember/component";+ import EmberObject, { action } from "@ember/object";+ import discourseComputed from "discourse/lib/decorators";+ import { i18n } from "discourse-i18n";++ const DAYS = [+ "monday",+ "tuesday",+ "wednesday",+ "thursday",+ "friday",+ "saturday",+ "sunday",+ ];++ class Day extends EmberObject {+ id = null;+ startTimeOptions = null;+ model = null;++ @action+ onChangeStartTime(val) {+ this.startingTimeChangedForDay(val);+ }++ @action+ onChangeEndTime(val) {+ this.set(`model.user_notification_schedule.day_${this.id}_end_time`, val);+ }++ @discourseComputed(+ "model.user_notification_schedule.day_{0,1,2,3,4,5,6}_start_time"+ )+ startTimeValue(schedule) {+ return schedule[`day_${this.id}_start_time`];+ }++ @discourseComputed(+ "model.user_notification_schedule.day_{0,1,2,3,4,5,6}_start_time"+ )+ endTimeOptions(schedule) {+ return this.buildEndTimeOptionsFor(schedule[`day_${this.id}_start_time`]);+ }++ @discourseComputed(+ "model.user_notification_schedule.day_{0,1,2,3,4,5,6}_end_time"+ )+ endTimeValue(schedule) {+ return schedule[`day_${this.id}_end_time`];+ }++ startingTimeChangedForDay(val) {+ val = parseInt(val, 10);+ this.model.set(`user_notification_schedule.day_${this.id}_start_time`, val);+ if (+ val !== "-1" &&+ this.model.user_notification_schedule[`day_${this.id}_end_time`] <= val+ ) {+ this.model.set(+ `user_notification_schedule.day_${this.id}_end_time`,+ val + 30+ );+ }+ }++ buildEndTimeOptionsFor(startTime) {+ startTime = parseInt(startTime, 10);+ if (startTime === -1) {+ return null;+ }+ return this.buildTimeOptions(startTime + 30, {+ includeNone: false,+ showMidnight: true,+ });+ }+ }++ export default class UserNotificationSchedule extends Component {+ days = null;++ didInsertElement() {+ super.didInsertElement(...arguments);+ this.set(+ "startTimeOptions",+ this.buildTimeOptions(0, {+ includeNone: true,+ showMidnight: false,+ })+ );++ this.set("days", []);++ DAYS.forEach((day, index) => {+ this.days.pushObject(+ Day.create({+ id: index,+ day,+ model: this.model,+ buildTimeOptions: this.buildTimeOptions,+ startTimeOptions: this.startTimeOptions,+ })+ );+ });+ }++ buildTimeOptions(startAt, opts = { includeNone: false, showMidnight: true }) {+ let timeOptions = [];++ if (opts.includeNone) {+ timeOptions.push({+ name: i18n("user.notification_schedule.none"),+ value: -1,+ });+ }++ for (let timeInMin = startAt; timeInMin <= 1440; timeInMin += 30) {+ let hours = Math.floor(timeInMin / 60);+ let minutes = timeInMin % 60;++ if (minutes === 0) {+ minutes = "00";+ }+ if (hours === 24) {+ if (opts.showMidnight) {+ timeOptions.push({+ name: i18n("user.notification_schedule.midnight"),+ value: 1440,+ });+ }+ break;+ }+ timeOptions.push({+ name: moment().set("hour", hours).set("minute", minutes).format("LT"),+ value: timeInMin,+ });+ }+ return timeOptions;+ }+ }+++<div+ class="control-group notification-schedule"+ data-setting-name="user-notification-schedule"+>+ <label class="control-label">{{i18n+ "user.notification_schedule.title"+ }}</label>+ <PreferenceCheckbox+ @labelKey="user.notification_schedule.label"+ @checked={{this.model.user_notification_schedule.enabled}}+ />++ {{#if this.model.user_notification_schedule.enabled}}+ <div class="instruction">{{i18n "user.notification_schedule.tip"}}</div>++ <table class="notification-schedule-table">+ <tbody class="notification-schedule-tbody">+ {{#each this.days as |day|}}+ <UserNotificationScheduleDay+ @day={{day.day}}+ @startTimeOptions={{day.startTimeOptions}}+ @startTimeValue={{day.startTimeValue}}+ @onChangeStartTime={{day.onChangeStartTime}}+ @endTimeOptions={{day.endTimeOptions}}+ @endTimeValue={{day.endTimeValue}}+ @onChangeEndTime={{day.onChangeEndTime}}+ />+ {{/each}}+ </tbody>+ </table>+ {{/if}}+</div>diff --cc app/assets/javascripts/discourse/app/components/user-profile-avatar.gjsindex 5d86e1763fc,60747884307..2eb9efefe27--- a/app/assets/javascripts/discourse/app/components/user-profile-avatar.gjs+++ b/app/assets/javascripts/discourse/app/components/user-profile-avatar.gjs@@@ -1,21 -1,3 +1,25 @@@+ import Component from "@ember/component";++ export default class UserProfileAvatar extends Component {}+++<PluginOutlet+ @name="user-profile-avatar-wrapper"+ @outletArgs={{hash user=@user}}+>+ <div class="user-profile-avatar">+ <PluginOutlet+ @name="user-profile-avatar-img-wrapper"+ @outletArgs={{hash user=@user}}+ >+ {{bound-avatar @user "huge"}}+ </PluginOutlet>++ <UserAvatarFlair @user={{@user}} />+ <div>+ <PluginOutlet+ @name="user-profile-avatar-flair"+ @outletArgs={{hash model=@user}}+ />+ </div>+ </div>+</PluginOutlet>diff --cc app/assets/javascripts/discourse/app/components/user-stream-item.gjsindex ed250df6de8,9cb77527ec3..d417140e6c7--- a/app/assets/javascripts/discourse/app/components/user-stream-item.gjs+++ b/app/assets/javascripts/discourse/app/components/user-stream-item.gjs@@@ -1,121 -1,53 +1,175 @@@+ import Component from "@ember/component";+ import { computed } from "@ember/object";+ import { classNameBindings, tagName } from "@ember-decorators/component";+ import { propertyEqual } from "discourse/lib/computed";+ import discourseComputed from "discourse/lib/decorators";+ import deprecated from "discourse/lib/deprecated";+ import { userPath } from "discourse/lib/url";+ import { actionDescription } from "discourse/widgets/post-small-action";++ @tagName("li")+ @classNameBindings(+ ":user-stream-item",+ ":item", // DEPRECATED: 'item' class+ "hidden",+ "item.deleted:deleted",+ "moderatorAction"+ )+ export default class UserStreamItem extends Component {+ @propertyEqual("item.post_type", "site.post_types.moderator_action")+ moderatorAction;++ @actionDescription(+ "item.action_code",+ "item.created_at",+ "item.action_code_who",+ "item.action_code_path"+ )+ actionDescription;++ constructor() {+ super(...arguments);+ deprecated(+ `<UserStreamItem /> component is deprecated. Use <PostList /> or <UserStream /> component to render a post list instead.`,+ {+ since: "3.4.0.beta4",+ dropFrom: "3.5.0.beta1",+ id: "discourse.user-stream-item",+ }+ );+ }++ @computed("item.hidden")+ get hidden() {+ return (+ this.get("item.hidden") && !(this.currentUser && this.currentUser.staff)+ );+ }++ @discourseComputed("item.draft_username", "item.username")+ userUrl(draftUsername, username) {+ return userPath((draftUsername || username).toLowerCase());+ }+ }+++<PluginOutlet @name="user-stream-item-above" @outletArgs={{hash item=@item}} />++<div class="user-stream-item__header info">+ <a+ href={{this.userUrl}}+ data-user-card={{or @item.draft_username @item.username}}+ class="avatar-link"+ >+ <div class="avatar-wrapper">+ {{avatar @item imageSize="large" extraClasses="actor" ignoreTitle="true"}}+ </div>+ </a>++ <div class="user-stream-item__details">+ <div class="stream-topic-title">+ <TopicStatus @topic={{@item}} @disableActions={{true}} />+ <span class="title">+ {{#if @item.postUrl}}+ <a href={{@item.postUrl}}>{{replace-emoji @item.title}}</a>+ {{else}}+ {{replace-emoji @item.title}}+ {{/if}}+ </span>+ </div>+ <div class="category">{{category-link @item.category}}</div>+ </div>++ {{#if @item.draftType}}+ <span class="draft-type">{{html-safe @item.draftType}}</span>+ {{else}}+ <ExpandPost @item={{@item}} />+ {{/if}}++ <div class="user-stream-item__metadata">+ <span class="time">{{format-date @item.created_at}}</span>++ {{#if @item.deleted_by}}+ <span class="delete-info">+ {{d-icon "trash-can"}}+ {{avatar+ @item.deleted_by+ imageSize="tiny"+ extraClasses="actor"+ ignoreTitle="true"+ }}+ {{format-date @item.deleted_at leaveAgo="true"}}+ </span>+ {{/if}}+ </div>++ <span>+ <PluginOutlet+ @name="user-stream-item-header"+ @connectorTagName="div"+ @outletArgs={{hash item=@item}}+ />+ </span>+</div>++{{#if this.actionDescription}}+ <p class="excerpt">{{this.actionDescription}}</p>+{{/if}}++<p+ data-topic-id={{@item.topic_id}}+ data-post-id={{@item.post_id}}+ data-user-id={{@item.user_id}}+ class="excerpt"+>+ {{~#if @item.expandedExcerpt}}+ {{~html-safe @item.expandedExcerpt~}}+ {{else}}+ {{~html-safe @item.excerpt~}}+ {{/if~}}+</p>++{{#each @item.children as |child|}}+ {{! DEPRECATED: 'child-actions' class }}+ <div class="user-stream-item-actions child-actions">+ {{d-icon child.icon class="icon"}}+ {{#each child.items as |grandChild|}}+ <a+ href={{grandChild.userUrl}}+ data-user-card={{grandChild.username}}+ class="avatar-link"+ >+ <div class="avatar-wrapper">+ {{avatar+ grandChild+ imageSize="tiny"+ extraClasses="actor"+ ignoreTitle="true"+ avatarTemplatePath="acting_avatar_template"+ }}+ </div>+ </a>+ {{#if grandChild.edit_reason}}+ —+ <span class="edit-reason">{{grandChild.edit_reason}}</span>{{/if}}+ {{/each}}+ </div>+{{/each}}++{{#if @item.editableDraft}}+ <div class="user-stream-item-draft-actions">+ <DButton+ @action={{fn @resumeDraft @item}}+ @icon="pencil"+ @label="drafts.resume"+ class="btn-default resume-draft"+ />+ <DButton+ @action={{fn @removeDraft @item}}+ @icon="trash-can"+ @title="drafts.remove"+ class="btn-danger remove-draft"+ />+ </div>+{{/if}}++{{yield to="bottom"}}diff --cc app/assets/javascripts/discourse/app/components/user-summary-category-search.gjsindex 12660d9b789,d4305c9c00a..ba8b90161bb--- a/app/assets/javascripts/discourse/app/components/user-summary-category-search.gjs+++ b/app/assets/javascripts/discourse/app/components/user-summary-category-search.gjs@@@ -1,7 -1,15 +1,23 @@@+ import Component from "@ember/component";+ import { tagName } from "@ember-decorators/component";+ import discourseComputed from "discourse/lib/decorators";++ @tagName("")+ export default class UserSummaryCategorySearch extends Component {+ @discourseComputed("user", "category")+ searchParams() {+ let query = `@${this.get("user.username")} #${this.get("category.slug")}`;+ if (this.searchOnlyFirstPosts) {+ query += " in:first";+ }+ return query;+ }+ }+++{{#if @count}}+ <LinkTo @route="full-page-search" @query={{hash q=this.searchParams}}>+ {{@count}}+ </LinkTo>+{{else}}+ –+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/user-summary-topic.gjsindex 3132f60ecc2,27a932f1579..ebfa8624e36--- a/app/assets/javascripts/discourse/app/components/user-summary-topic.gjs+++ b/app/assets/javascripts/discourse/app/components/user-summary-topic.gjs@@@ -1,14 -1,5 +1,20 @@@+ import Component from "@ember/component";+ import { tagName } from "@ember-decorators/component";++ @tagName("li")+ export default class UserSummaryTopic extends Component {}+++<PluginOutlet+ @name="user-summary-topic-wrapper"+ @outletArgs={{hash topic=@topic url=@url}}+>+ <span class="topic-info">+ {{format-date @createdAt format="tiny" noTitle="true"}}+ {{#if @likes}}+ ·+ {{d-icon "heart"}} <span class="like-count">{{number @likes}}</span>+ {{/if}}+ </span>+ <br />+ <a href={{@url}}>{{html-safe @topic.fancyTitle}}</a>+</PluginOutlet>diff --cc app/assets/javascripts/discourse/app/components/user-summary-topics-list.gjsindex dde46c3d610,7a10500d14b..6e3319050c8--- a/app/assets/javascripts/discourse/app/components/user-summary-topics-list.gjs+++ b/app/assets/javascripts/discourse/app/components/user-summary-topics-list.gjs@@@ -1,20 -1,14 +1,35 @@@+ import Component from "@ember/component";+ import { tagName } from "@ember-decorators/component";+ import discourseComputed from "discourse/lib/decorators";++ // should be kept in sync with 'UserSummary::MAX_SUMMARY_RESULTS'+ const MAX_SUMMARY_RESULTS = 6;++ @tagName("")+ export default class UserSummaryTopicsList extends Component {+ @discourseComputed("items.length")+ hasMore(length) {+ return length >= MAX_SUMMARY_RESULTS;+ }+ }+++{{#if @items}}+ <ul>+ {{#each @items as |item|}}+ {{yield item}}+ {{/each}}+ </ul>+ {{#if this.hasMore}}+ <p>+ <LinkTo+ @route={{concat "userActivity." @type}}+ @model={{@user}}+ class="more"+ >+ {{i18n (concat "user.summary.more_" @type)}}+ </LinkTo>+ </p>+ {{/if}}+{{else}}+ <p>{{i18n (concat "user.summary.no_" @type)}}</p>+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/user-summary-user.gjsindex f7237988540,ae818c434ae..b8263842e3c--- a/app/assets/javascripts/discourse/app/components/user-summary-user.gjs+++ b/app/assets/javascripts/discourse/app/components/user-summary-user.gjs@@@ -1,4 -1,5 +1,10 @@@+ import Component from "@ember/component";+ import { tagName } from "@ember-decorators/component";++ @tagName("li")+ export default class UserSummaryUser extends Component {}+++<UserInfo @user={{@user}}>+ {{d-icon @icon}}+ <span class={{@countClass}}>{{number @user.count}}</span>+</UserInfo>diff --cc app/assets/javascripts/discourse/app/components/user-summary-users-list.gjsindex 1b7636d652d,95ebd1bdad8..f0db0ed5404--- a/app/assets/javascripts/discourse/app/components/user-summary-users-list.gjs+++ b/app/assets/javascripts/discourse/app/components/user-summary-users-list.gjs@@@ -1,9 -1,3 +1,13 @@@+ import Component from "@ember/component";++ export default class UserSummaryUsersList extends Component {}+++{{#if this.users}}+ <ul>+ {{#each this.users as |user|}}+ {{yield user}}+ {{/each}}+ </ul>+{{else}}+ <p>{{i18n (concat "user.summary." this.none)}}</p>+{{/if}}