A platform for community discussion. Free, open, simple.
DEV: [gjs-codemod] merge js and hbs
David Taylorf049f775c7b2
diff --cc app/assets/javascripts/discourse/app/components/badge-title.gjsindex 40fb6e51425,916d36f13a2..d32f25ccefc--- a/app/assets/javascripts/discourse/app/components/badge-title.gjs+++ b/app/assets/javascripts/discourse/app/components/badge-title.gjs@@@ -1,38 -1,59 +1,98 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import { tagName } from "@ember-decorators/component";+ import { ajax } from "discourse/lib/ajax";+ import { i18n } from "discourse-i18n";++ @tagName("")+ export default class BadgeTitle extends Component {+ @service dialog;++ selectableUserBadges = null;+ _selectedUserBadgeId = null;+ _isSaved = false;+ _isSaving = false;++ init() {+ super.init(...arguments);++ const badge = this._findBadgeByTitle(+ this.selectableUserBadges,+ this.currentUser.title+ );+ this.set("_selectedUserBadgeId", badge?.id || 0);+ }++ @action+ saveBadgeTitle() {+ this.setProperties({ _isSaved: false, _isSaving: true });++ const selectedUserBadge = this._findBadgeById(+ this.selectableUserBadges,+ this._selectedUserBadgeId+ );++ return ajax(`${this.currentUser.path}/preferences/badge_title`, {+ type: "PUT",+ data: { user_badge_id: selectedUserBadge?.id || 0 },+ })+ .then(+ () => {+ this.set("_isSaved", true);+ this.currentUser.set("title", selectedUserBadge?.badge?.name || "");+ },+ () => {+ this.dialog.alert(i18n("generic_error"));+ }+ )+ .finally(() => this.set("_isSaving", false));+ }++ _findBadgeById(badges, id) {+ return (badges || []).findBy("id", id);+ }++ _findBadgeByTitle(badges, title) {+ return (badges || []).findBy("badge.name", title);+ }+ }+++<div class="badge-title">+ <form class="form-horizontal">++ <h3>{{i18n "badges.select_badge_for_title"}}</h3>++ <div class="control-group">+ <div class="controls">+ <ComboBox+ @value={{this._selectedUserBadgeId}}+ @nameProperty="badge.name"+ @content={{this.selectableUserBadges}}+ @onChange={{fn (mut this._selectedUserBadgeId)}}+ />+ </div>+ </div>++ <div class="control-group">+ <div class="controls">+ <DButton+ @action={{this.saveBadgeTitle}}+ @disabled={{this._isSaving}}+ @label={{if this._isSaving "saving" "save"}}+ class="btn-primary"+ />+ {{#if this.closeAction}}+ <DButton+ @action={{this.closeAction}}+ @label="close"+ class="btn-default close-btn"+ />+ {{/if}}+ {{#if this._isSaved}}+ <span role="status" class="badge-title__saved">{{i18n "saved"}}</span>+ {{/if}}+ </div>+ </div>+ </form>+</div>diff --cc app/assets/javascripts/discourse/app/components/bookmark-list.gjsindex 1a1ba76ead1,e56c7d92246..f31e65f430c--- a/app/assets/javascripts/discourse/app/components/bookmark-list.gjs+++ b/app/assets/javascripts/discourse/app/components/bookmark-list.gjs@@@ -1,210 -1,185 +1,396 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { dependentKeyCompat } from "@ember/object/compat";+ import { service } from "@ember/service";+ import { classNames } from "@ember-decorators/component";+ import { Promise } from "rsvp";+ import BookmarkModal from "discourse/components/modal/bookmark";+ import { ajax } from "discourse/lib/ajax";+ import { BookmarkFormData } from "discourse/lib/bookmark-form-data";+ import {+ openLinkInNewTab,+ shouldOpenInNewTab,+ } from "discourse/lib/click-track";+ import { i18n } from "discourse-i18n";++ @classNames("bookmark-list-wrapper")+ export default class BookmarkList extends Component {+ @service dialog;+ @service modal;++ get canDoBulkActions() {+ return this.bulkSelectHelper?.selected.length;+ }++ get selected() {+ return this.bulkSelectHelper?.selected;+ }++ get selectedCount() {+ return this.selected?.length || 0;+ }++ @action+ removeBookmark(bookmark) {+ return new Promise((resolve, reject) => {+ const deleteBookmark = () => {+ bookmark+ .destroy()+ .then(() => {+ this.appEvents.trigger(+ "bookmarks:changed",+ null,+ bookmark.attachedTo()+ );+ this._removeBookmarkFromList(bookmark);+ resolve(true);+ })+ .catch((error) => {+ reject(error);+ });+ };+ if (!bookmark.reminder_at) {+ return deleteBookmark();+ }+ this.dialog.deleteConfirm({+ message: i18n("bookmarks.confirm_delete"),+ didConfirm: () => deleteBookmark(),+ didCancel: () => resolve(false),+ });+ });+ }++ @action+ screenExcerptForExternalLink(event) {+ if (event?.target?.tagName === "A") {+ if (shouldOpenInNewTab(event.target.href)) {+ openLinkInNewTab(event, event.target);+ }+ }+ }++ @action+ editBookmark(bookmark) {+ this.modal.show(BookmarkModal, {+ model: {+ bookmark: new BookmarkFormData(bookmark),+ afterSave: (savedData) => {+ this.appEvents.trigger(+ "bookmarks:changed",+ savedData,+ bookmark.attachedTo()+ );+ this.reload();+ },+ afterDelete: () => {+ this.reload();+ },+ },+ });+ }++ @action+ clearBookmarkReminder(bookmark) {+ return ajax(`/bookmarks/${bookmark.id}`, {+ type: "PUT",+ data: { reminder_at: null },+ }).then(() => {+ bookmark.set("reminder_at", null);+ });+ }++ @action+ togglePinBookmark(bookmark) {+ bookmark.togglePin().then(this.reload);+ }++ @action+ toggleBulkSelect() {+ this.bulkSelectHelper?.toggleBulkSelect();+ this.rerender();+ }++ @action+ selectAll() {+ this.bulkSelectHelper.autoAddBookmarksToBulkSelect = true;+ document+ .querySelectorAll("input.bulk-select:not(:checked)")+ .forEach((el) => el.click());+ }++ @action+ clearAll() {+ this.bulkSelectHelper.autoAddBookmarksToBulkSelect = false;+ document+ .querySelectorAll("input.bulk-select:checked")+ .forEach((el) => el.click());+ }++ @dependentKeyCompat // for the classNameBindings+ get bulkSelectEnabled() {+ return this.bulkSelectHelper?.bulkSelectEnabled;+ }++ _removeBookmarkFromList(bookmark) {+ this.content.removeObject(bookmark);+ }++ _toggleSelection(target, bookmark, isSelectingRange) {+ const selected = this.selected;++ if (target.checked) {+ selected.addObject(bookmark);++ if (isSelectingRange) {+ 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(bookmark);+ this.set("lastChecked", null);+ }+ }++ click(e) {+ const onClick = (sel, callback) => {+ let target = e.target.closest(sel);++ if (target) {+ callback(target);+ }+ };++ onClick("input.bulk-select", () => {+ const target = e.target;+ const bookmarkId = target.dataset.id;+ const bookmark = this.content.find(+ (item) => item.id.toString() === bookmarkId+ );+ this._toggleSelection(target, bookmark, this.lastChecked && e.shiftKey);+ });+ }+ }+++<ConditionalLoadingSpinner @condition={{this.loading}}>+ <LoadMore+ @selector=".bookmark-list .bookmark-list-item"+ @action={{this.loadMore}}+ >+ <table class="topic-list bookmark-list">+ <thead class="topic-list-header">+ {{#if this.site.desktopView}}+ <PluginOutlet @name="bookmark-list-table-header">+ {{#if this.bulkSelectEnabled}}+ <th class="bulk-select topic-list-data">+ <FlatButton+ @action={{this.toggleBulkSelect}}+ @class="bulk-select"+ @icon="list-check"+ @title="bookmarks.bulk.toggle"+ />+ </th>+ {{/if}}+ <th class="topic-list-data">++ {{#if this.bulkSelectEnabled}}+ <span class="bulk-select-topics">+ {{~#if this.canDoBulkActions}}+ <div class="bulk-select-bookmarks-dropdown">+ <span class="bulk-select-bookmark-dropdown__count">+ {{i18n+ "bookmarks.bulk.selected_count"+ count=this.selectedCount+ }}+ </span>+ <BulkSelectBookmarksDropdown+ @bulkSelectHelper={{this.bulkSelectHelper}}+ />+ </div>++ {{/if~}}+ <DButton+ @action={{this.selectAll}}+ class="btn btn-default bulk-select-all"+ @label="bookmarks.bulk.select_all"+ />+ <DButton+ @action={{this.clearAll}}+ class="btn btn-default bulk-clear-all"+ @label="bookmarks.bulk.clear_all"+ />+ </span>+ {{else}}+ <FlatButton+ @action={{this.toggleBulkSelect}}+ @class="bulk-select"+ @icon="list-check"+ @title="bookmarks.bulk.toggle"+ />+ {{i18n "topic.title"}}+ {{/if~}}+ </th>+ <th class="topic-list-data"> </th>+ <th class="post-metadata topic-list-data">{{i18n+ "post.bookmarks.updated"+ }}</th>+ <th class="post-metadata topic-list-data">{{i18n "activity"}}</th>+ <th> </th>+ </PluginOutlet>+ {{/if}}+ </thead>+ <tbody class="topic-list-body">+ {{#each this.content as |bookmark|}}+ <tr class="topic-list-item bookmark-list-item">+ {{#if this.bulkSelectEnabled}}+ <td class="bulk-select bookmark-list-data">+ <label for="bulk-select-{{bookmark.id}}">+ <input+ type="checkbox"+ class="bulk-select"+ id="bulk-select-{{bookmark.id}}"+ data-id={{bookmark.id}}+ />+ </label>+ </td>+ {{/if}}+ <td class="main-link topic-list-data">+ <PluginOutlet+ @name="bookmark-list-before-link"+ @outletArgs={{hash bookmark=bookmark}}+ />++ <span class="link-top-line">+ <div class="bookmark-metadata">+ {{#if bookmark.reminder_at}}+ <span+ class="bookmark-metadata-item bookmark-reminder+ {{if+ bookmark.reminderAtExpired+ 'bookmark-expired-reminder'+ }}"+ >+ {{d-icon "far-clock"}}{{bookmark.formattedReminder}}+ </span>+ {{/if}}+ {{#if bookmark.name}}+ <span class="bookmark-metadata-item">+ {{d-icon "circle-info"}}<span>{{bookmark.name}}</span>+ </span>+ {{/if}}+ </div>+ <div class="bookmark-status-with-link">+ {{#if bookmark.pinned}}+ {{d-icon "thumbtack" class="bookmark-pinned"}}+ {{/if}}+ {{#if bookmark.bookmarkableTopicAlike}}+ <TopicStatus @topic={{bookmark.topicStatus}} />+ {{topic-link bookmark.topicForList}}+ {{else}}+ <a+ href={{bookmark.bookmarkable_url}}+ role="heading"+ aria-level="2"+ class="title"+ data-topic-id="${topic.id}"+ >+ {{bookmark.fancy_title}}+ </a>+ {{/if}}+ </div>+ </span>+ {{#if bookmark.bookmarkableTopicAlike}}+ <div class="link-bottom-line">+ {{category-link bookmark.category}}+ {{discourse-tags+ bookmark+ mode="list"+ tagsForUser=this.tagsForUser+ }}+ </div>+ {{/if}}+ {{#if+ (and+ this.site.mobileView+ bookmark.excerpt+ bookmark.user.avatar_template+ )+ }}+ <a+ href={{bookmark.bookmarkableUser.path}}+ data-user-card={{bookmark.user.username}}+ class="avatar"+ >+ {{avatar+ bookmark.bookmarkableUser+ avatarTemplatePath="avatar_template"+ usernamePath="username"+ namePath="name"+ imageSize="small"+ }}+ </a>+ {{/if}}++ {{! template-lint-disable no-invalid-interactive }}+ <p+ class="post-excerpt"+ {{on "click" this.screenExcerptForExternalLink}}+ >{{html-safe bookmark.excerpt}}</p>+ </td>+ {{#if this.site.desktopView}}+ <td class="author-avatar topic-list-data">+ {{#if bookmark.user.avatar_template}}+ <a+ href={{bookmark.user.path}}+ data-user-card={{bookmark.user.username}}+ class="avatar"+ >+ {{avatar+ bookmark.user+ avatarTemplatePath="avatar_template"+ usernamePath="username"+ namePath="name"+ imageSize="small"+ }}+ </a>+ {{/if}}+ </td>+ <td class="post-metadata topic-list-data updated-at">{{format-date+ bookmark.updated_at+ format="tiny"+ }}</td>+ {{raw+ "list/activity-column"+ topic=bookmark+ class="num post-metadata"+ tagName="td"+ }}+ {{/if}}+ <td class="topic-list-data">+ <BookmarkActionsDropdown+ @bookmark={{bookmark}}+ @removeBookmark={{action "removeBookmark"}}+ @editBookmark={{action "editBookmark"}}+ @clearBookmarkReminder={{action "clearBookmarkReminder"}}+ @togglePinBookmark={{action "togglePinBookmark"}}+ />+ </td>+ </tr>+ {{/each}}+ </tbody>+ </table>+ <ConditionalLoadingSpinner @condition={{this.loadingMore}} />+ </LoadMore>+</ConditionalLoadingSpinner>diff --cc app/assets/javascripts/discourse/app/components/bread-crumbs.gjsindex 0562ed9eb97,ee6b2d511f2..18b7adfdb9a--- a/app/assets/javascripts/discourse/app/components/bread-crumbs.gjs+++ b/app/assets/javascripts/discourse/app/components/bread-crumbs.gjs@@@ -1,72 -1,126 +1,199 @@@+ import Component from "@ember/component";+ import { filter } from "@ember/object/computed";+ import { classNameBindings, tagName } from "@ember-decorators/component";+ import discourseComputed from "discourse/lib/decorators";+ import deprecated from "discourse/lib/deprecated";++ // A breadcrumb including category drop downs+ @tagName("ol")+ @classNameBindings("hidden:hidden", ":category-breadcrumb")+ export default class BreadCrumbs extends Component {+ editingCategory = false;+ editingCategoryTab = null;++ @filter("categories", function (c) {+ deprecated(+ "The parentCategories property of the bread-crumbs component is deprecated",+ { id: "discourse.breadcrumbs.parentCategories" }+ );+ if (+ c.id === this.site.get("uncategorized_category_id") &&+ !this.siteSettings.allow_uncategorized_topics+ ) {+ // Don't show "uncategorized" if allow_uncategorized_topics setting is false.+ return false;+ }++ return !c.get("parentCategory");+ })+ parentCategories;++ @discourseComputed("category", "categories", "noSubcategories")+ categoryBreadcrumbs(category, filteredCategories, noSubcategories) {+ const ancestors = category?.ancestors || [];+ const parentCategories = [undefined, ...ancestors];+ const categories = [...ancestors, undefined];++ return parentCategories+ .map((x, i) => [x, categories[i]])+ .map((record) => {+ const [parentCategory, subCategory] = record;++ const options = filteredCategories.filter(+ (c) =>+ c.get("parentCategory.id") === (parentCategory && parentCategory.id)+ );++ return {+ category: subCategory,+ parentCategory,+ options,+ isSubcategory: !!parentCategory,+ noSubcategories: !subCategory && noSubcategories,+ hasOptions: !parentCategory || parentCategory.has_children,+ };+ });+ }++ @discourseComputed("siteSettings.tagging_enabled", "editingCategory")+ showTagsSection(taggingEnabled, editingCategory) {+ return taggingEnabled && !editingCategory;+ }++ @discourseComputed("category")+ parentCategory(category) {+ deprecated(+ "The parentCategory property of the bread-crumbs component is deprecated",+ { id: "discourse.breadcrumbs.parentCategory" }+ );+ return category && category.parentCategory;+ }++ @discourseComputed("parentCategories")+ parentCategoriesSorted(parentCategories) {+ deprecated(+ "The parentCategoriesSorted property of the bread-crumbs component is deprecated",+ { id: "discourse.breadcrumbs.parentCategoriesSorted" }+ );+ if (this.siteSettings.fixed_category_positions) {+ return parentCategories;+ }++ return parentCategories.sortBy("totalTopicCount").reverse();+ }++ @discourseComputed("category")+ hidden(category) {+ return this.site.mobileView && !category;+ }++ @discourseComputed("category", "parentCategory")+ firstCategory(category, parentCategory) {+ deprecated(+ "The firstCategory property of the bread-crumbs component is deprecated",+ { id: "discourse.breadcrumbs.firstCategory" }+ );+ return parentCategory || category;+ }++ @discourseComputed("category", "parentCategory")+ secondCategory(category, parentCategory) {+ deprecated(+ "The secondCategory property of the bread-crumbs component is deprecated",+ { id: "discourse.breadcrumbs.secondCategory" }+ );+ return parentCategory && category;+ }++ @discourseComputed("firstCategory", "hideSubcategories")+ childCategories(firstCategory, hideSubcategories) {+ deprecated(+ "The childCategories property of the bread-crumbs component is deprecated",+ { id: "discourse.breadcrumbs.childCategories" }+ );+ if (hideSubcategories) {+ return [];+ }++ if (!firstCategory) {+ return [];+ }++ return this.categories.filter(+ (c) => c.get("parentCategory") === firstCategory+ );+ }+ }+++<PluginOutlet+ @name="bread-crumbs-left"+ @connectorTagName="li"+ @outletArgs={{hash+ tagId=this.tag.id+ additionalTags=this.additionalTags+ noSubcategories=this.noSubcategories+ showTagsSection=this.showTagsSection+ currentCategory=this.category+ categoryBreadcrumbs=this.categoryBreadcrumbs+ editingCategory=this.editingCategory+ editingCategoryTab=this.editingCategoryTab+ }}+/>++{{#each this.categoryBreadcrumbs as |breadcrumb|}}+ {{#if breadcrumb.hasOptions}}+ <li+ style={{if breadcrumb.category (category-variables breadcrumb.category)}}+ >+ <CategoryDrop+ @category={{breadcrumb.category}}+ @categories={{breadcrumb.options}}+ @tagId={{this.tag.id}}+ @editingCategory={{this.editingCategory}}+ @editingCategoryTab={{this.editingCategoryTab}}+ @options={{hash+ parentCategory=breadcrumb.parentCategory+ subCategory=breadcrumb.isSubcategory+ noSubcategories=breadcrumb.noSubcategories+ autoFilterable=true+ }}+ />+ </li>+ {{/if}}+{{/each}}++{{#if this.showTagsSection}}+ {{#if this.additionalTags}}+ <li>+ <TagsIntersectionChooser+ @currentCategory={{this.category}}+ @mainTag={{this.tag.id}}+ @additionalTags={{this.additionalTags}}+ @options={{hash categoryId=this.category.id}}+ />+ </li>+ {{else}}+ <li>+ <TagDrop+ @currentCategory={{this.category}}+ @noSubcategories={{this.noSubcategories}}+ @tagId={{this.tag.id}}+ />+ </li>+ {{/if}}+{{/if}}++<PluginOutlet+ @name="bread-crumbs-right"+ @connectorTagName="li"+ @outletArgs={{hash+ tagId=this.tag.id+ additionalTags=this.additionalTags+ noSubcategories=this.noSubcategories+ showTagsSection=this.showTagsSection+ currentCategory=this.category+ categoryBreadcrumbs=this.categoryBreadcrumbs+ editingCategory=this.editingCategory+ editingCategoryTab=this.editingCategoryTab+ }}+/>diff --cc app/assets/javascripts/discourse/app/components/bulk-actions/append-tags.gjsindex 7d512a85cc5,6b66d271026..ab426c69f64--- a/app/assets/javascripts/discourse/app/components/bulk-actions/append-tags.gjs+++ b/app/assets/javascripts/discourse/app/components/bulk-actions/append-tags.gjs@@@ -1,10 -1,6 +1,17 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";++ export default class AppendTags extends Component {+ @tracked tags = [];+ }+++<p>{{i18n "topics.bulk.choose_append_tags"}}</p>++<p><TagChooser @tags={{this.tags}} @categoryId={{@categoryId}} /></p>++<DButton+ @action={{fn @performAndRefresh (hash type="append_tags" tags=this.tags)}}+ @disabled={{not this.tags}}+ @label="topics.bulk.append_tags"+ class="topic-bulk-actions__append-tags"+/>diff --cc app/assets/javascripts/discourse/app/components/bulk-actions/change-category.gjsindex 09ed88a1231,61c10614f4e..0cb7ddeea5a--- a/app/assets/javascripts/discourse/app/components/bulk-actions/change-category.gjs+++ b/app/assets/javascripts/discourse/app/components/bulk-actions/change-category.gjs@@@ -1,15 -1,17 +1,33 @@@+ import Component from "@glimmer/component";+ import { action } from "@ember/object";++ export default class ChangeCategory extends Component {+ categoryId = 0;++ @action+ async changeCategory() {+ await this.args.forEachPerformed(+ {+ type: "change_category",+ category_id: this.categoryId,+ },+ (t) => t.set("category_id", this.categoryId)+ );+ }+ }+++<p>{{i18n "topics.bulk.choose_new_category"}}</p>++<p>+ <CategoryChooser+ @value={{this.categoryId}}+ @onChange={{fn (mut this.categoryId)}}+ />+</p>++<ConditionalLoadingSpinner @condition={{@loading}}>+ <DButton+ @action={{this.changeCategory}}+ @label="topics.bulk.change_category"+ />+</ConditionalLoadingSpinner>diff --cc app/assets/javascripts/discourse/app/components/bulk-actions/change-tags.gjsindex 4e46d9ff96a,eb80adf4565..e3716f37672--- a/app/assets/javascripts/discourse/app/components/bulk-actions/change-tags.gjs+++ b/app/assets/javascripts/discourse/app/components/bulk-actions/change-tags.gjs@@@ -1,9 -1,6 +1,16 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";++ export default class ChangeTags extends Component {+ @tracked tags = [];+ }+++<p>{{i18n "topics.bulk.choose_new_tags"}}</p>++<p><TagChooser @tags={{this.tags}} @categoryId={{@categoryId}} /></p>++<DButton+ @action={{fn @performAndRefresh (hash type="change_tags" tags=this.tags)}}+ @disabled={{not this.tags}}+ @label="topics.bulk.change_tags"+/>diff --cc app/assets/javascripts/discourse/app/components/composer-action-title.gjsindex 556d2be7c3c,a5edc9c2ac8..83dc9429304--- a/app/assets/javascripts/discourse/app/components/composer-action-title.gjs+++ b/app/assets/javascripts/discourse/app/components/composer-action-title.gjs@@@ -1,16 -1,95 +1,112 @@@+ import Component from "@ember/component";+ import { alias } from "@ember/object/computed";+ import { htmlSafe } from "@ember/template";+ import { classNames } from "@ember-decorators/component";+ import discourseComputed from "discourse/lib/decorators";+ import escape from "discourse/lib/escape";+ import { iconHTML } from "discourse/lib/icon-library";+ import {+ CREATE_SHARED_DRAFT,+ CREATE_TOPIC,+ EDIT,+ EDIT_SHARED_DRAFT,+ PRIVATE_MESSAGE,+ REPLY,+ } from "discourse/models/composer";+ import { i18n } from "discourse-i18n";++ const TITLES = {+ [PRIVATE_MESSAGE]: "topic.private_message",+ [CREATE_TOPIC]: "topic.create_long",+ [CREATE_SHARED_DRAFT]: "composer.create_shared_draft",+ [EDIT_SHARED_DRAFT]: "composer.edit_shared_draft",+ };++ @classNames("composer-action-title")+ export default class ComposerActionTitle extends Component {+ @alias("model.replyOptions") options;+ @alias("model.action") action;++ // Note we update when some other attributes like tag/category change to allow+ // text customizations to use those.+ @discourseComputed("options", "action", "model.tags", "model.category")+ actionTitle(opts, action) {+ const result = this.model.customizationFor("actionTitle");+ if (result) {+ return result;+ }++ if (TITLES[action]) {+ return i18n(TITLES[action]);+ }++ if (action === REPLY) {+ if (opts.userAvatar && opts.userLink) {+ return this._formatReplyToUserPost(opts.userAvatar, opts.userLink);+ } else if (opts.topicLink) {+ return this._formatReplyToTopic(opts.topicLink);+ }+ }++ if (action === EDIT) {+ if (opts.userAvatar && opts.userLink && opts.postLink) {+ return this._formatEditUserPost(+ opts.userAvatar,+ opts.userLink,+ opts.postLink,+ opts.originalUser+ );+ }+ }+ }++ _formatEditUserPost(userAvatar, userLink, postLink, originalUser) {+ let editTitle = `+ <a class="post-link" href="${postLink.href}">${postLink.anchor}</a>+ ${userAvatar}+ <span class="username">${userLink.anchor}</span>+ `;++ if (originalUser) {+ editTitle += `+ ${iconHTML("share", { class: "reply-to-glyph" })}+ ${originalUser.avatar}+ <span class="original-username">${originalUser.username}</span>+ `;+ }++ return htmlSafe(editTitle);+ }++ _formatReplyToTopic(link) {+ return htmlSafe(+ `<a class="topic-link" href="${link.href}" data-topic-id="${this.get(+ "model.topic.id"+ )}">${link.anchor}</a>`+ );+ }++ _formatReplyToUserPost(avatar, link) {+ const htmlLink = `<a class="user-link" href="${link.href}">${escape(+ link.anchor+ )}</a>`;+ return htmlSafe(`${avatar}${htmlLink}`);+ }+ }+++<ComposerActions+ @composerModel={{this.model}}+ @replyOptions={{this.model.replyOptions}}+ @canWhisper={{this.canWhisper}}+ @action={{this.model.action}}+ @tabindex={{this.tabindex}}+ @topic={{this.model.topic}}+ @post={{this.model.post}}+ @whisper={{this.model.whisper}}+ @noBump={{this.model.noBump}}+ @options={{hash mobilePlacementStrategy="fixed"}}+/>++<span class="action-title" role="heading" aria-level="1">+ {{this.actionTitle}}+</span>diff --cc app/assets/javascripts/discourse/app/components/composer-container.gjsindex 8995737599f,ecbf8ecc993..3cc9438cc7f--- a/app/assets/javascripts/discourse/app/components/composer-container.gjs+++ b/app/assets/javascripts/discourse/app/components/composer-container.gjs@@@ -1,416 -1,7 +1,424 @@@+ import Component from "@glimmer/component";+ import { service } from "@ember/service";++ export default class ComposerContainer extends Component {+ @service composer;+ @service site;+ }+++<ComposerBody+ @composer={{this.composer.model}}+ @showPreview={{this.composer.isPreviewVisible}}+ @openIfDraft={{this.composer.openIfDraft}}+ @typed={{this.composer.typed}}+ @cancelled={{this.composer.cancelled}}+ @save={{this.composer.saveAction}}+>+ <div class="grippie"></div>+ {{#if this.composer.visible}}+ {{html-class (if this.composer.isPreviewVisible "composer-has-preview")}}+ <ComposerMessages+ @composer={{this.composer.model}}+ @messageCount={{this.composer.messageCount}}+ @addLinkLookup={{this.composer.addLinkLookup}}+ />++ {{#if this.composer.showFullScreenPrompt}}+ <ComposerFullscreenPrompt+ @removeFullScreenExitPrompt={{this.composer.removeFullScreenExitPrompt}}+ />+ {{/if}}++ {{#if this.composer.model.viewOpenOrFullscreen}}+ <div+ role="dialog"+ aria-label={{this.composer.ariaLabel}}+ class="reply-area+ {{if this.composer.canEditTags 'with-tags' 'without-tags'}}+ {{if+ this.composer.hasFormTemplate+ 'with-form-template'+ 'without-form-template'+ }}+ {{if+ this.composer.model.showCategoryChooser+ 'with-category'+ 'without-category'+ }}"+ >+ <span class="composer-open-plugin-outlet-container">+ <PluginOutlet+ @name="composer-open"+ @connectorTagName="div"+ @outletArgs={{hash model=this.composer.model}}+ />+ </span>++ <div class="reply-to">+ {{#unless this.composer.model.viewFullscreen}}+ <div class="reply-details">+ <ComposerActionTitle+ @model={{this.composer.model}}+ @canWhisper={{this.composer.canWhisper}}+ />++ <PluginOutlet+ @name="composer-action-after"+ @outletArgs={{hash model=this.composer.model}}+ />++ {{#if this.site.desktopView}}+ {{#if this.composer.model.unlistTopic}}+ <span class="unlist">({{i18n "composer.unlist"}})</span>+ {{/if}}+ {{#if this.composer.isWhispering}}+ {{#if this.composer.model.noBump}}+ <span class="no-bump">{{d-icon "anchor"}}</span>+ {{/if}}+ {{/if}}+ {{/if}}++ {{#if this.composer.canEdit}}+ <LinkToInput+ @onClick={{this.composer.displayEditReason}}+ @showInput={{this.composer.showEditReason}}+ @icon="circle-info"+ class="display-edit-reason"+ >+ <TextField+ @value={{this.composer.editReason}}+ @id="edit-reason"+ @maxlength="255"+ @placeholderKey="composer.edit_reason_placeholder"+ />+ </LinkToInput>+ {{/if}}+ </div>+ {{/unless}}++ <PluginOutlet+ @name="before-composer-controls"+ @outletArgs={{hash model=this.composer.model}}+ />++ <ComposerToggles+ @composeState={{this.composer.model.composeState}}+ @showToolbar={{this.composer.showToolbar}}+ @toggleComposer={{this.composer.toggle}}+ @toggleToolbar={{this.composer.toggleToolbar}}+ @toggleFullscreen={{this.composer.fullscreenComposer}}+ @disableTextarea={{this.composer.disableTextarea}}+ />+ </div>++ <ComposerEditor>+ <div class="composer-fields">+ <PluginOutlet+ @name="before-composer-fields"+ @outletArgs={{hash model=this.composer.model}}+ />+ {{#unless this.composer.model.viewFullscreen}}+ {{#if this.composer.model.canEditTitle}}+ {{#if this.composer.model.creatingPrivateMessage}}+ <div class="user-selector">+ <ComposerUserSelector+ @topicId={{this.composer.topicModel.id}}+ @recipients={{this.composer.model.targetRecipients}}+ @hasGroups={{this.composer.model.hasTargetGroups}}+ @focusTarget={{this.composer.focusTarget}}+ class={{concat-class+ "users-input"+ (if this.composer.showWarning "can-warn")+ }}+ />+ {{#if this.composer.showWarning}}+ <label class="add-warning">+ <Input+ @type="checkbox"+ @checked={{this.composer.model.isWarning}}+ />+ <span>{{i18n "composer.add_warning"}}</span>+ </label>+ {{/if}}+ </div>+ {{/if}}++ <div+ class="title-and-category+ {{if this.composer.isPreviewVisible 'with-preview'}}"+ >+ <ComposerTitle+ @composer={{this.composer.model}}+ @lastValidatedAt={{this.composer.lastValidatedAt}}+ @focusTarget={{this.composer.focusTarget}}+ />++ {{#if this.composer.model.showCategoryChooser}}+ <div class="category-input">+ <CategoryChooser+ @value={{this.composer.model.categoryId}}+ @onChange={{this.composer.updateCategory}}+ @options={{hash+ disabled=this.composer.disableCategoryChooser+ scopedCategoryId=this.composer.scopedCategoryId+ prioritizedCategoryId=this.composer.prioritizedCategoryId+ }}+ />+ <PluginOutlet+ @name="after-composer-category-input"+ @outletArgs={{hash composer=this.composer.model}}+ />+ <PopupInputTip+ @validation={{this.composer.categoryValidation}}+ />+ </div>+ {{/if}}++ {{#if this.composer.canEditTags}}+ <div class="tags-input">+ <MiniTagChooser+ @value={{this.composer.model.tags}}+ @onChange={{fn (mut this.composer.model.tags)}}+ @options={{hash+ disabled=this.composer.disableTagsChooser+ categoryId=this.composer.model.categoryId+ minimum=this.composer.model.minimumRequiredTags+ }}+ />+ <PluginOutlet+ @name="after-composer-tag-input"+ @outletArgs={{hash composer=this.composer.model}}+ />+ <PopupInputTip+ @validation={{this.composer.tagValidation}}+ />+ </div>+ {{/if}}++ <PluginOutlet+ @name="after-title-and-category"+ @outletArgs={{hash+ model=this.composer.model+ tagValidation=this.composer.tagValidation+ canEditTags=this.composer.canEditTags+ disabled=this.composer.disableTagsChooser+ }}+ />+ </div>+ {{/if}}++ <span>+ <PluginOutlet+ @name="composer-fields"+ @connectorTagName="div"+ @outletArgs={{hash+ model=this.composer.model+ showPreview=this.composer.isPreviewVisible+ }}+ />+ </span>+ {{/unless}}+ </div>+ </ComposerEditor>++ <span>+ <PluginOutlet+ @name="composer-after-composer-editor"+ @outletArgs={{hash model=this.composer.model}}+ />+ </span>++ <div class="submit-panel">+ <span>+ <PluginOutlet+ @name="composer-fields-below"+ @connectorTagName="div"+ @outletArgs={{hash model=this.composer.model}}+ />+ </span>++ <div class="save-or-cancel">+ <ComposerSaveButton+ @action={{this.composer.saveAction}}+ @icon={{this.composer.saveIcon}}+ @label={{this.composer.saveLabel}}+ @forwardEvent={{true}}+ @disableSubmit={{this.composer.disableSubmit}}+ />++ {{#if this.site.mobileView}}+ <DButton+ @action={{this.composer.cancel}}+ class="cancel btn-transparent"+ @icon={{if this.composer.canEdit "xmark" "trash-can"}}+ @preventFocus={{true}}+ @title="close"+ />+ {{else}}+ <DButton+ @action={{this.composer.cancel}}+ class="cancel btn-transparent"+ @preventFocus={{true}}+ @title="close"+ @label="close"+ />+ {{/if}}++ {{#if this.site.mobileView}}+ {{#if this.composer.whisperOrUnlistTopic}}+ <span class="whisper">+ {{d-icon "far-eye-slash"}}+ </span>+ {{/if}}++ {{#if this.composer.model.noBump}}+ <span class="no-bump">{{d-icon "anchor"}}</span>+ {{/if}}+ {{/if}}++ <span>+ <PluginOutlet+ @name="composer-after-save-or-cancel"+ @outletArgs={{hash model=this.composer.model}}+ />+ </span>+ </div>++ {{#if this.site.mobileView}}+ <span>+ <PluginOutlet+ @name="composer-mobile-buttons-bottom"+ @outletArgs={{hash model=this.composer.model}}+ />+ </span>++ {{#if this.composer.allowUpload}}+ <a+ id="mobile-file-upload"+ class="btn btn-default no-text mobile-file-upload+ {{if this.composer.isUploading 'hidden'}}"+ aria-label={{i18n "composer.upload_title"}}+ >+ {{d-icon this.composer.uploadIcon}}+ </a>+ {{/if}}++ {{#if this.composer.allowPreview}}+ <a+ href+ class="btn btn-default no-text mobile-preview"+ title={{i18n "composer.show_preview"}}+ {{on "click" this.composer.togglePreview}}+ aria-label={{i18n "composer.show_preview"}}+ >+ {{d-icon "desktop"}}+ </a>+ {{/if}}++ {{#if this.composer.isPreviewVisible}}+ <DButton+ @action={{this.composer.togglePreview}}+ @title="composer.hide_preview"+ @ariaLabel="composer.hide_preview"+ @icon="pencil"+ class="hide-preview"+ />+ {{/if}}+ {{/if}}++ {{#if+ (or this.composer.isUploading this.composer.isProcessingUpload)+ }}+ <div id="file-uploading">+ {{#if this.composer.isProcessingUpload}}+ {{loading-spinner size="small"}}<span>{{i18n+ "upload_selector.processing"+ }}</span>+ {{else}}+ {{loading-spinner size="small"}}<span>{{i18n+ "upload_selector.uploading"+ }}+ {{this.composer.uploadProgress}}%</span>+ {{/if}}++ {{#if this.composer.isCancellable}}+ <a+ href+ id="cancel-file-upload"+ {{on "click" this.composer.cancelUpload}}+ >{{d-icon "xmark"}}</a>+ {{/if}}+ </div>+ {{/if}}++ <div+ class={{if this.composer.isUploading "hidden"}}+ id="draft-status"+ >+ {{#if this.composer.model.draftStatus}}+ <span+ class="draft-error"+ title={{this.composer.model.draftStatus}}+ >+ {{#if this.composer.model.draftConflictUser}}+ {{avatar+ this.composer.model.draftConflictUser+ imageSize="small"+ }}+ {{d-icon "user-pen"}}+ {{else}}+ {{d-icon "triangle-exclamation"}}+ {{/if}}+ {{#if this.site.desktopView}}+ {{this.composer.model.draftStatus}}+ {{/if}}+ </span>+ {{/if}}+ </div>++ {{#if (and this.composer.allowPreview this.site.desktopView)}}+ <DButton+ @action={{this.composer.togglePreview}}+ @translatedTitle={{this.composer.toggleText}}+ @icon="angles-left"+ class={{concat-class+ "btn-transparent btn-mini-toggle toggle-preview"+ (unless this.composer.isPreviewVisible "active")+ }}+ />+ {{/if}}+ </div>+ </div>+ {{else}}+ <div class="saving-text">+ {{#if this.composer.model.createdPost}}+ {{i18n "composer.saved"}}+ <a+ href={{this.composer.createdPost.url}}+ {{on "click" this.composer.viewNewReply}}+ class="permalink"+ >{{i18n "composer.view_new_post"}}</a>+ {{else}}+ {{i18n "composer.saving"}}+ {{loading-spinner size="small"}}+ {{/if}}+ </div>++ <div class="draft-text">+ {{#if this.composer.model.topic}}+ {{d-icon "share"}}+ {{html-safe this.composer.draftTitle}}+ {{else}}+ {{i18n "composer.saved_draft"}}+ {{/if}}+ </div>++ <ComposerToggles+ @composeState={{this.composer.model.composeState}}+ @toggleFullscreen={{this.composer.openIfDraft}}+ @toggleComposer={{this.composer.toggle}}+ @toggleToolbar={{this.composer.toggleToolbar}}+ />+ {{/if}}+ {{/if}}+</ComposerBody>diff --cc app/assets/javascripts/discourse/app/components/composer-editor.gjsindex 8a19b4c5397,5bb3c40179f..0395d415ed6--- a/app/assets/javascripts/discourse/app/components/composer-editor.gjs+++ b/app/assets/javascripts/discourse/app/components/composer-editor.gjs@@@ -1,58 -1,956 +1,1015 @@@+ import Component from "@ember/component";+ import EmberObject, { action, computed } from "@ember/object";+ import { getOwner } from "@ember/owner";+ import { schedule, throttle } from "@ember/runloop";+ import { service } from "@ember/service";+ import { classNameBindings } from "@ember-decorators/component";+ import { observes, on } from "@ember-decorators/object";+ import { BasePlugin } from "@uppy/core";+ import $ from "jquery";+ import { resolveAllShortUrls } from "pretty-text/upload-short-url";+ import { ajax } from "discourse/lib/ajax";+ import { tinyAvatar } from "discourse/lib/avatar-utils";+ import { setupComposerPosition } from "discourse/lib/composer/composer-position";+ import discourseComputed, { bind, debounce } from "discourse/lib/decorators";+ import {+ fetchUnseenHashtagsInContext,+ linkSeenHashtagsInContext,+ } from "discourse/lib/hashtag-decorator";+ import { iconHTML } from "discourse/lib/icon-library";+ import discourseLater from "discourse/lib/later";+ import {+ fetchUnseenMentions,+ linkSeenMentions,+ } from "discourse/lib/link-mentions";+ import { loadOneboxes } from "discourse/lib/load-oneboxes";+ import {+ authorizesOneOrMoreImageExtensions,+ IMAGE_MARKDOWN_REGEX,+ } from "discourse/lib/uploads";+ import UppyComposerUpload from "discourse/lib/uppy/composer-upload";+ import { formatUsername } from "discourse/lib/utilities";+ import Composer from "discourse/models/composer";+ import { i18n } from "discourse-i18n";++ let uploadHandlers = [];+ export function addComposerUploadHandler(extensions, method) {+ uploadHandlers.push({+ extensions,+ method,+ });+ }+ export function cleanUpComposerUploadHandler() {+ // we cannot set this to uploadHandlers = [] because that messes with+ // the references to the original array that the component has. this only+ // really affects tests, but without doing this you could addComposerUploadHandler+ // in a beforeEach function in a test but then it's not adding to the+ // existing reference that the component has, because an earlier test ran+ // cleanUpComposerUploadHandler and lost it. setting the length to 0 empties+ // the array but keeps the reference+ uploadHandlers.length = 0;+ }++ let uploadPreProcessors = [];+ export function addComposerUploadPreProcessor(pluginClass, optionsResolverFn) {+ if (!(pluginClass.prototype instanceof BasePlugin)) {+ throw new Error(+ "Composer upload preprocessors must inherit from the Uppy BasePlugin class."+ );+ }++ uploadPreProcessors.push({+ pluginClass,+ optionsResolverFn,+ });+ }+ export function cleanUpComposerUploadPreProcessor() {+ uploadPreProcessors = [];+ }++ let uploadMarkdownResolvers = [];+ export function addComposerUploadMarkdownResolver(resolver) {+ uploadMarkdownResolvers.push(resolver);+ }+ export function cleanUpComposerUploadMarkdownResolver() {+ uploadMarkdownResolvers = [];+ }++ let apiImageWrapperBtnEvents = [];+ export function addApiImageWrapperButtonClickEvent(fn) {+ apiImageWrapperBtnEvents.push(fn);+ }++ const DEBOUNCE_FETCH_MS = 450;+ const DEBOUNCE_JIT_MS = 2000;++ @classNameBindings("composer.showToolbar:toolbar-visible", ":wmd-controls")+ export default class ComposerEditor extends Component {+ @service composer;++ composerEventPrefix = "composer";+ shouldBuildScrollMap = true;+ scrollMap = null;++ fileUploadElementId = "file-uploader";++ init() {+ super.init(...arguments);+ this.warnedCannotSeeMentions = [];+ this.warnedGroupMentions = [];++ this.uppyComposerUpload = new UppyComposerUpload(getOwner(this), {+ composerEventPrefix: this.composerEventPrefix,+ composerModel: this.composer.model,+ uploadMarkdownResolvers,+ uploadPreProcessors,+ uploadHandlers,+ fileUploadElementId: this.fileUploadElementId,+ });+ }++ get topic() {+ return this.composer.get("model.topic");+ }++ @discourseComputed("composer.model.requiredCategoryMissing")+ replyPlaceholder(requiredCategoryMissing) {+ if (requiredCategoryMissing) {+ return "composer.reply_placeholder_choose_category";+ } else {+ const key = authorizesOneOrMoreImageExtensions(+ this.currentUser.staff,+ this.siteSettings+ )+ ? "reply_placeholder"+ : "reply_placeholder_no_images";+ return `composer.${key}`;+ }+ }++ @discourseComputed+ showLink() {+ return this.currentUser && this.currentUser.link_posting_access !== "none";+ }++ @observes("composer.focusTarget")+ setFocus() {+ if (this.composer.focusTarget === "editor") {+ this.textManipulation.putCursorAtEnd();+ }+ }++ @discourseComputed+ markdownOptions() {+ return {+ previewing: true,++ formatUsername,++ lookupAvatarByPostNumber: (postNumber, topicId) => {+ const topic = this.topic;+ if (!topic) {+ return;+ }++ const posts = topic.get("postStream.posts");+ if (posts && topicId === topic.get("id")) {+ const quotedPost = posts.findBy("post_number", postNumber);+ if (quotedPost) {+ return tinyAvatar(quotedPost.get("avatar_template"));+ }+ }+ },++ lookupPrimaryUserGroupByPostNumber: (postNumber, topicId) => {+ const topic = this.topic;+ if (!topic) {+ return;+ }++ const posts = topic.get("postStream.posts");+ if (posts && topicId === topic.get("id")) {+ const quotedPost = posts.findBy("post_number", postNumber);+ if (quotedPost) {+ return quotedPost.primary_group_name;+ }+ }+ },++ hashtagTypesInPriorityOrder:+ this.site.hashtag_configurations["topic-composer"],+ hashtagIcons: this.site.hashtag_icons,+ };+ }++ @on("didInsertElement")+ _composerEditorInit() {+ const preview = this.element.querySelector(".d-editor-preview-wrapper");+ this._registerImageAltTextButtonClick(preview);++ if (this.composer.allowUpload) {+ this.uppyComposerUpload.setup(this.element);+ }++ this.appEvents.trigger(`${this.composerEventPrefix}:will-open`);+ }++ /**+ * Sets up the editor with the given text manipulation instance+ *+ * @param {TextManipulation} textManipulation The text manipulation instance+ * @returns {(() => void)} destructor function+ */+ @bind+ setupEditor(textManipulation) {+ this.textManipulation = textManipulation;+ this.uppyComposerUpload.placeholderHandler = textManipulation.placeholder;++ const input = this.element.querySelector(".d-editor-input");++ input.addEventListener("scroll", this._throttledSyncEditorAndPreviewScroll);++ this.composer.set("allowPreview", this.textManipulation.allowPreview);++ if (+ // Focus on the editor unless we have a title+ !this.get("composer.model.canEditTitle") ||+ // Or focus is in the body (e.g. when the editor is destroyed)+ document.activeElement.tagName === "BODY"+ ) {+ this.textManipulation.putCursorAtEnd();+ }++ const destroyComposerPosition = setupComposerPosition(input);++ return () => {+ destroyComposerPosition();++ input.removeEventListener(+ "scroll",+ this._throttledSyncEditorAndPreviewScroll+ );+ };+ }++ @discourseComputed(+ "composer.model.reply",+ "composer.model.replyLength",+ "composer.model.missingReplyCharacters",+ "composer.model.minimumPostLength",+ "composer.lastValidatedAt"+ )+ validation(+ reply,+ replyLength,+ missingReplyCharacters,+ minimumPostLength,+ lastValidatedAt+ ) {+ const postType = this.get("composer.post.post_type");+ if (postType === this.site.get("post_types.small_action")) {+ return;+ }++ let reason;+ if (replyLength < 1) {+ reason = i18n("composer.error.post_missing");+ } else if (missingReplyCharacters > 0) {+ reason = i18n("composer.error.post_length", {+ count: minimumPostLength,+ });+ const tl = this.get("currentUser.trust_level");+ if ((tl === 0 || tl === 1) && !this._isNewTopic) {+ reason +=+ "<br/>" ++ i18n("composer.error.try_like", {+ heart: iconHTML("heart", {+ label: i18n("likes_lowercase", { count: 1 }),+ }),+ });+ }+ }++ if (reason) {+ return EmberObject.create({+ failed: true,+ reason,+ lastShownAt: lastValidatedAt,+ });+ }+ }++ @computed("composer.{creatingTopic,editingFirstPost,creatingSharedDraft}")+ get _isNewTopic() {+ return (+ this.composer.model.creatingTopic ||+ this.composer.model.editingFirstPost ||+ this.composer.model.creatingSharedDraft+ );+ }++ _resetShouldBuildScrollMap() {+ this.set("shouldBuildScrollMap", true);+ }++ @bind+ _handleInputInteraction(event) {+ const preview = this.element.querySelector(".d-editor-preview-wrapper");++ if (!$(preview).is(":visible")) {+ return;+ }++ preview.removeEventListener("scroll", this._handleInputOrPreviewScroll);+ event.target.addEventListener("scroll", this._handleInputOrPreviewScroll);+ }++ @bind+ _handleInputOrPreviewScroll(event) {+ this._syncScroll(+ this._syncEditorAndPreviewScroll,+ $(event.target),+ $(this.element.querySelector(".d-editor-preview-wrapper"))+ );+ }++ @bind+ _handlePreviewInteraction(event) {+ this.element+ .querySelector(".d-editor-input")+ ?.removeEventListener("scroll", this._handleInputOrPreviewScroll);++ event.target?.addEventListener("scroll", this._handleInputOrPreviewScroll);+ }++ _syncScroll($callback, $input, $preview) {+ if (!this.scrollMap || this.shouldBuildScrollMap) {+ this.set("scrollMap", this._buildScrollMap($input, $preview));+ this.set("shouldBuildScrollMap", false);+ }++ throttle(this, $callback, $input, $preview, this.scrollMap, 20);+ }++ // Adapted from https://github.com/markdown-it/markdown-it.github.io+ _buildScrollMap($input, $preview) {+ let sourceLikeDiv = $("<div />")+ .css({+ position: "absolute",+ height: "auto",+ visibility: "hidden",+ width: $input[0].clientWidth,+ "font-size": $input.css("font-size"),+ "font-family": $input.css("font-family"),+ "line-height": $input.css("line-height"),+ "white-space": $input.css("white-space"),+ })+ .appendTo("body");++ const linesMap = [];+ let numberOfLines = 0;++ $input+ .val()+ .split("\n")+ .forEach((text) => {+ linesMap.push(numberOfLines);++ if (text.length === 0) {+ numberOfLines++;+ } else {+ sourceLikeDiv.text(text);++ let height;+ let lineHeight;+ height = parseFloat(sourceLikeDiv.css("height"));+ lineHeight = parseFloat(sourceLikeDiv.css("line-height"));+ numberOfLines += Math.round(height / lineHeight);+ }+ });++ linesMap.push(numberOfLines);+ sourceLikeDiv.remove();++ const previewOffsetTop = $preview.offset().top;+ const offset =+ $preview.scrollTop() -+ previewOffsetTop -+ ($input.offset().top - previewOffsetTop);+ const nonEmptyList = [];+ const scrollMap = [];+ for (let i = 0; i < numberOfLines; i++) {+ scrollMap.push(-1);+ }++ nonEmptyList.push(0);+ scrollMap[0] = 0;++ $preview.find(".preview-sync-line").each((_, element) => {+ let $element = $(element);+ let lineNumber = $element.data("line-number");+ let linesToTop = linesMap[lineNumber];+ if (linesToTop !== 0) {+ nonEmptyList.push(linesToTop);+ }+ scrollMap[linesToTop] = Math.round($element.offset().top + offset);+ });++ nonEmptyList.push(numberOfLines);+ scrollMap[numberOfLines] = $preview[0].scrollHeight;++ let position = 0;++ for (let i = 1; i < numberOfLines; i++) {+ if (scrollMap[i] !== -1) {+ position++;+ continue;+ }++ let top = nonEmptyList[position];+ let bottom = nonEmptyList[position + 1];++ scrollMap[i] = (+ (scrollMap[bottom] * (i - top) + scrollMap[top] * (bottom - i)) /+ (bottom - top)+ ).toFixed(2);+ }++ return scrollMap;+ }++ @bind+ _throttledSyncEditorAndPreviewScroll(event) {+ const $preview = $(this.element.querySelector(".d-editor-preview-wrapper"));++ throttle(+ this,+ this._syncEditorAndPreviewScroll,+ $(event.target),+ $preview,+ 20+ );+ }++ _syncEditorAndPreviewScroll($input, $preview) {+ if (!$input) {+ return;+ }++ if ($input.scrollTop() === 0) {+ $preview.scrollTop(0);+ return;+ }++ const inputHeight = $input[0].scrollHeight;+ const previewHeight = $preview[0].scrollHeight;++ if ($input.height() + $input.scrollTop() + 100 > inputHeight) {+ // cheat, special case for bottom+ $preview.scrollTop(previewHeight);+ return;+ }++ const scrollPosition = $input.scrollTop();+ const factor = previewHeight / inputHeight;+ const desired = scrollPosition * factor;+ $preview.scrollTop(desired + 50);+ }++ _renderMentions(preview) {+ const unseen = linkSeenMentions(preview, this.siteSettings);+ if (unseen.length > 0) {+ this._renderUnseenMentions(preview, unseen);+ } else {+ this._warnMentionedGroups(preview);+ this._warnCannotSeeMention(preview);+ }+ }++ @debounce(DEBOUNCE_FETCH_MS)+ _renderUnseenMentions(preview, unseen) {+ fetchUnseenMentions({+ names: unseen,+ topicId: this.get("composer.model.topic.id"),+ allowedNames: this.get("composer.model.targetRecipients")?.split(","),+ }).then((response) => {+ linkSeenMentions(preview, this.siteSettings);+ this._warnMentionedGroups(preview);+ this._warnCannotSeeMention(preview);+ this._warnHereMention(response.here_count);+ });+ }++ _renderHashtags(preview) {+ const context = this.site.hashtag_configurations["topic-composer"];+ const unseen = linkSeenHashtagsInContext(context, preview);+ if (unseen.length > 0) {+ this._renderUnseenHashtags(preview, unseen, context);+ }+ }++ @debounce(DEBOUNCE_FETCH_MS)+ _renderUnseenHashtags(preview, unseen, context) {+ fetchUnseenHashtagsInContext(context, unseen).then(() =>+ linkSeenHashtagsInContext(context, preview)+ );+ }++ @debounce(DEBOUNCE_FETCH_MS)+ _refreshOneboxes(preview) {+ const post = this.get("composer.post");+ // If we are editing a post, we'll refresh its contents once.+ const refresh = post && !post.get("refreshedPost");++ const loaded = loadOneboxes(+ preview,+ ajax,+ this.get("composer.topic.id"),+ this.get("composer.category.id"),+ this.siteSettings.max_oneboxes_per_post,+ refresh+ );++ if (refresh && loaded > 0) {+ post.set("refreshedPost", true);+ }+ }++ _expandShortUrls(preview) {+ resolveAllShortUrls(ajax, this.siteSettings, preview);+ }++ _decorateCookedElement(preview, helper) {+ this.appEvents.trigger(+ "decorate-non-stream-cooked-element",+ preview,+ helper+ );+ }++ @debounce(DEBOUNCE_JIT_MS)+ _warnMentionedGroups(preview) {+ schedule("afterRender", () => {+ preview+ .querySelectorAll(".mention-group[data-mentionable-user-count]")+ .forEach((mention) => {+ const { name } = mention.dataset;+ if (+ this.warnedGroupMentions.includes(name) ||+ this._isInQuote(mention)+ ) {+ return;+ }++ this.warnedGroupMentions.push(name);+ this.composer.groupsMentioned({+ name,+ userCount: mention.dataset.mentionableUserCount,+ maxMentions: mention.dataset.maxMentions,+ });+ });+ });+ }++ // add a delay to allow for typing, so you don't open the warning right away+ // previously we would warn after @bob even if you were about to mention @bob2+ @debounce(DEBOUNCE_JIT_MS)+ _warnCannotSeeMention(preview) {+ if (this.composer.model?.draftKey === Composer.NEW_PRIVATE_MESSAGE_KEY) {+ return;+ }++ preview.querySelectorAll(".mention[data-reason]").forEach((mention) => {+ const { name } = mention.dataset;+ if (this.warnedCannotSeeMentions.includes(name)) {+ return;+ }++ this.warnedCannotSeeMentions.push(name);+ this.composer.cannotSeeMention({+ name,+ reason: mention.dataset.reason,+ });+ });++ preview+ .querySelectorAll(".mention-group[data-reason]")+ .forEach((mention) => {+ const { name } = mention.dataset;+ if (this.warnedCannotSeeMentions.includes(name)) {+ return;+ }++ this.warnedCannotSeeMentions.push(name);+ this.composer.cannotSeeMention({+ name,+ reason: mention.dataset.reason,+ notifiedCount: mention.dataset.notifiedUserCount,+ isGroup: true,+ });+ });+ }++ _warnHereMention(hereCount) {+ if (!hereCount || hereCount === 0) {+ return;+ }++ this.composer.hereMention(hereCount);+ }++ @bind+ _handleImageScaleButtonClick(event) {+ if (!event.target.classList.contains("scale-btn")) {+ return;+ }++ const index = parseInt(+ event.target.closest(".button-wrapper").dataset.imageIndex,+ 10+ );++ const scale = event.target.dataset.scale;+ const matchingPlaceholder = this.get("composer.model.reply").match(+ IMAGE_MARKDOWN_REGEX+ );++ if (matchingPlaceholder) {+ const match = matchingPlaceholder[index];++ if (match) {+ const replacement = match.replace(+ IMAGE_MARKDOWN_REGEX,+ ``+ );++ this.appEvents.trigger(+ `${this.composerEventPrefix}:replace-text`,+ matchingPlaceholder[index],+ replacement,+ { regex: IMAGE_MARKDOWN_REGEX, index }+ );+ }+ }++ event.preventDefault();+ return;+ }++ resetImageControls(buttonWrapper) {+ const imageResize = buttonWrapper.querySelector(".scale-btn-container");+ const imageDelete = buttonWrapper.querySelector(".delete-image-button");++ const readonlyContainer = buttonWrapper.querySelector(+ ".alt-text-readonly-container"+ );+ const editContainer = buttonWrapper.querySelector(+ ".alt-text-edit-container"+ );++ imageResize.removeAttribute("hidden");+ imageDelete.removeAttribute("hidden");++ readonlyContainer.removeAttribute("hidden");+ buttonWrapper.removeAttribute("editing");+ editContainer.setAttribute("hidden", "true");+ }++ commitAltText(buttonWrapper) {+ const index = parseInt(buttonWrapper.getAttribute("data-image-index"), 10);+ const matchingPlaceholder = this.get("composer.model.reply").match(+ IMAGE_MARKDOWN_REGEX+ );+ const match = matchingPlaceholder[index];+ const input = buttonWrapper.querySelector("input.alt-text-input");+ const replacement = match.replace(+ IMAGE_MARKDOWN_REGEX,+ ``+ );++ this.appEvents.trigger(+ `${this.composerEventPrefix}:replace-text`,+ match,+ replacement+ );++ this.resetImageControls(buttonWrapper);+ }++ @bind+ _handleAltTextInputKeypress(event) {+ if (!event.target.classList.contains("alt-text-input")) {+ return;+ }++ if (event.key === "[" || event.key === "]") {+ event.preventDefault();+ }++ if (event.key === "Enter") {+ const buttonWrapper = event.target.closest(".button-wrapper");+ this.commitAltText(buttonWrapper);+ }+ }++ @bind+ _handleAltTextEditButtonClick(event) {+ if (!event.target.classList.contains("alt-text-edit-btn")) {+ return;+ }++ const buttonWrapper = event.target.closest(".button-wrapper");+ const imageResize = buttonWrapper.querySelector(".scale-btn-container");+ const imageDelete = buttonWrapper.querySelector(".delete-image-button");++ const readonlyContainer = buttonWrapper.querySelector(+ ".alt-text-readonly-container"+ );+ const altText = readonlyContainer.querySelector(".alt-text");++ const editContainer = buttonWrapper.querySelector(+ ".alt-text-edit-container"+ );+ const editContainerInput = editContainer.querySelector(".alt-text-input");++ buttonWrapper.setAttribute("editing", "true");+ imageResize.setAttribute("hidden", "true");+ imageDelete.setAttribute("hidden", "true");+ readonlyContainer.setAttribute("hidden", "true");+ editContainerInput.value = altText.textContent;+ editContainer.removeAttribute("hidden");+ editContainerInput.focus();+ event.preventDefault();+ }++ @bind+ _handleAltTextOkButtonClick(event) {+ if (!event.target.classList.contains("alt-text-edit-ok")) {+ return;+ }++ const buttonWrapper = event.target.closest(".button-wrapper");+ this.commitAltText(buttonWrapper);+ }++ @bind+ _handleAltTextCancelButtonClick(event) {+ if (!event.target.classList.contains("alt-text-edit-cancel")) {+ return;+ }++ const buttonWrapper = event.target.closest(".button-wrapper");+ this.resetImageControls(buttonWrapper);+ }++ @bind+ _handleImageDeleteButtonClick(event) {+ if (!event.target.classList.contains("delete-image-button")) {+ return;+ }+ const index = parseInt(+ event.target.closest(".button-wrapper").dataset.imageIndex,+ 10+ );+ const matchingPlaceholder = this.get("composer.model.reply").match(+ IMAGE_MARKDOWN_REGEX+ );+ this.appEvents.trigger(+ `${this.composerEventPrefix}:replace-text`,+ matchingPlaceholder[index],+ "",+ { regex: IMAGE_MARKDOWN_REGEX, index }+ );+ }++ @bind+ _handleImageGridButtonClick(event) {+ if (!event.target.classList.contains("wrap-image-grid-button")) {+ return;+ }++ const index = parseInt(+ event.target.closest(".button-wrapper").dataset.imageIndex,+ 10+ );+ const reply = this.get("composer.model.reply");+ const matches = reply.match(IMAGE_MARKDOWN_REGEX);+ const closingIndex =+ index + parseInt(event.target.dataset.imageCount, 10) - 1;++ const textArea = this.element.querySelector(".d-editor-input");+ textArea.selectionStart = reply.indexOf(matches[index]);+ textArea.selectionEnd =+ reply.indexOf(matches[closingIndex]) + matches[closingIndex].length;++ this.appEvents.trigger(+ `${this.composerEventPrefix}:apply-surround`,+ "[grid]",+ "[/grid]",+ "grid_surround",+ { useBlockMode: true }+ );+ }++ _registerImageAltTextButtonClick(preview) {+ if (!preview) {+ return;+ }++ preview.addEventListener("click", this._handleAltTextCancelButtonClick);+ preview.addEventListener("click", this._handleAltTextEditButtonClick);+ preview.addEventListener("click", this._handleAltTextOkButtonClick);+ preview.addEventListener("click", this._handleImageDeleteButtonClick);+ preview.addEventListener("click", this._handleImageGridButtonClick);+ preview.addEventListener("click", this._handleImageScaleButtonClick);+ preview.addEventListener("keypress", this._handleAltTextInputKeypress);++ apiImageWrapperBtnEvents.forEach((fn) =>+ preview.addEventListener("click", fn)+ );+ }++ @on("willDestroyElement")+ _composerClosed() {+ const preview = this.element.querySelector(".d-editor-preview-wrapper");++ if (this.composer.allowUpload) {+ this.uppyComposerUpload.teardown();+ }++ this.appEvents.trigger(`${this.composerEventPrefix}:will-close`);++ // need to wait a bit for the "slide down" transition of the composer+ discourseLater(+ () => this.appEvents.trigger(`${this.composerEventPrefix}:closed`),+ 400+ );++ preview?.removeEventListener("click", this._handleAltTextCancelButtonClick);+ preview?.removeEventListener("click", this._handleAltTextEditButtonClick);+ preview?.removeEventListener("click", this._handleAltTextOkButtonClick);+ preview?.removeEventListener("click", this._handleImageDeleteButtonClick);+ preview?.removeEventListener("click", this._handleImageGridButtonClick);+ preview?.removeEventListener("click", this._handleImageScaleButtonClick);+ preview?.removeEventListener("keypress", this._handleAltTextInputKeypress);++ apiImageWrapperBtnEvents.forEach((fn) =>+ preview?.removeEventListener("click", fn)+ );+ }++ @action+ onExpandPopupMenuOptions(toolbarEvent) {+ const selected = toolbarEvent.selected;+ toolbarEvent.selectText(selected.start, selected.end - selected.start);+ this.composer.storeToolbarState(toolbarEvent);+ }++ showPreview() {+ this.composer.togglePreview();+ }++ _isInQuote(element) {+ let parent = element.parentElement;+ while (parent && !this._isPreviewRoot(parent)) {+ if (this._isQuote(parent)) {+ return true;+ }++ parent = parent.parentElement;+ }++ return false;+ }++ _isPreviewRoot(element) {+ return (+ element.tagName === "DIV" &&+ element.classList.contains("d-editor-preview")+ );+ }++ _isQuote(element) {+ return element.tagName === "ASIDE" && element.classList.contains("quote");+ }++ @action+ extraButtons(toolbar) {+ toolbar.addButton({+ id: "quote",+ group: "fontStyles",+ icon: "far-comment",+ sendAction: this.composer.importQuote,+ title: "composer.quote_post_title",+ unshift: true,+ });++ if (+ this.composer.allowUpload &&+ this.composer.uploadIcon &&+ this.site.desktopView+ ) {+ toolbar.addButton({+ id: "upload",+ group: "insertions",+ icon: this.composer.uploadIcon,+ title: "upload",+ sendAction: this.showUploadModal,+ });+ }++ toolbar.addButton({+ id: "options",+ group: "extras",+ icon: "gear",+ title: "composer.options",+ sendAction: this.onExpandPopupMenuOptions.bind(this),+ popupMenu: true,+ });+ }++ @action+ previewUpdated(preview, helper) {+ this._renderMentions(preview);+ this._renderHashtags(preview);+ this._refreshOneboxes(preview);+ this._expandShortUrls(preview);++ this._decorateCookedElement(preview, helper);++ this.composer.afterRefresh(preview);+ }++ @computed("composer.formTemplateIds")+ get selectedFormTemplateId() {+ if (this._selectedFormTemplateId) {+ return this._selectedFormTemplateId;+ }++ return (+ this.composer.model.formTemplateId || this.composer.formTemplateIds?.[0]+ );+ }++ set selectedFormTemplateId(value) {+ this._selectedFormTemplateId = value;+ }++ @action+ updateSelectedFormTemplateId(formTemplateId) {+ this.selectedFormTemplateId = formTemplateId;+ }++ @discourseComputed(+ "composer.formTemplateIds",+ "composer.model.replyingToTopic",+ "composer.model.editingPost"+ )+ showFormTemplateForm(formTemplateIds, replyingToTopic, editingPost) {+ return formTemplateIds?.length > 0 && !replyingToTopic && !editingPost;+ }++ @action+ showUploadModal() {+ document.getElementById(this.fileUploadElementId).click();+ }+ }+++{{#if this.showFormTemplateForm}}+ <div class="d-editor">+ <div class="d-editor-container">+ <div class="d-editor-textarea-column">+ {{yield}}++ {{#if (gt this.composer.formTemplateIds.length 1)}}+ <FormTemplateChooser+ @filteredIds={{this.composer.formTemplateIds}}+ @value={{this.selectedFormTemplateId}}+ @onChange={{this.updateSelectedFormTemplateId}}+ @options={{hash maximum=1}}+ class="composer-select-form-template"+ />+ {{/if}}+ <form id="form-template-form">+ <FormTemplateField::Wrapper+ @id={{this.selectedFormTemplateId}}+ @initialValues={{this.composer.formTemplateInitialValues}}+ @onSelectFormTemplate={{this.composer.onSelectFormTemplate}}+ />+ </form>+ </div>+ </div>+ </div>+{{else}}+ <DEditor+ @value={{this.composer.model.reply}}+ @placeholder={{this.replyPlaceholder}}+ @previewUpdated={{action "previewUpdated"}}+ @markdownOptions={{this.markdownOptions}}+ @extraButtons={{action "extraButtons"}}+ @processPreview={{this.composer.isPreviewVisible}}+ @validation={{this.validation}}+ @loading={{this.composer.loading}}+ @forcePreview={{this.forcePreview}}+ @showLink={{this.showLink}}+ @composerEvents={{true}}+ @onPopupMenuAction={{this.composer.onPopupMenuAction}}+ @popupMenuOptions={{this.composer.popupMenuOptions}}+ @disabled={{this.composer.disableTextarea}}+ @outletArgs={{hash composer=this.composer.model editorType="composer"}}+ @topicId={{this.composer.model.topic.id}}+ @categoryId={{this.composer.model.category.id}}+ @onSetup={{this.setupEditor}}+ @disableSubmit={{this.composer.disableSubmit}}+ >+ {{yield}}+ </DEditor>+{{/if}}++{{#if this.composer.allowUpload}}+ <PickFilesButton+ @fileInputId={{this.fileUploadElementId}}+ @allowMultiple={{true}}+ name="file-uploader"+ />+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/composer-user-selector.gjsindex 6559932fc64,86c0ec9d8b4..25d782f5ef4--- a/app/assets/javascripts/discourse/app/components/composer-user-selector.gjs+++ b/app/assets/javascripts/discourse/app/components/composer-user-selector.gjs@@@ -1,12 -1,48 +1,61 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import discourseComputed from "discourse/lib/decorators";++ export default class ComposerUserSelector extends Component {+ _groups = [];++ didInsertElement() {+ super.didInsertElement(...arguments);++ if (this.focusTarget === "usernames") {+ this.element.querySelector(".select-kit .select-kit-header").focus();+ }+ }++ @discourseComputed("recipients")+ splitRecipients(recipients) {+ if (Array.isArray(recipients)) {+ return recipients;+ }+ return recipients ? recipients.split(",").filter(Boolean) : [];+ }++ _updateGroups(selected, newGroups) {+ const groups = [];+ this._groups.forEach((existing) => {+ if (selected.includes(existing)) {+ groups.addObject(existing);+ }+ });+ newGroups.forEach((newGroup) => {+ if (!groups.includes(newGroup)) {+ groups.addObject(newGroup);+ }+ });+ this.setProperties({+ _groups: groups,+ hasGroups: groups.length > 0,+ });+ }++ @action+ updateRecipients(selected, content) {+ const newGroups = content.filterBy("isGroup").mapBy("id");+ this._updateGroups(selected, newGroups);+ this.set("recipients", selected.join(","));+ }+ }+++<EmailGroupUserChooser+ @id="private-message-users"+ @value={{this.splitRecipients}}+ @onChange={{action "updateRecipients"}}+ @options={{hash+ topicId=this.topicId+ none="composer.users_placeholder"+ includeMessageableGroups=true+ allowEmails=this.currentUser.can_send_private_email_messages+ autoWrap=true+ }}+/>diff --cc app/assets/javascripts/discourse/app/components/d-editor.gjsindex fdffb1ebdb3,f290430aa87..da643f05eef--- a/app/assets/javascripts/discourse/app/components/d-editor.gjs+++ b/app/assets/javascripts/discourse/app/components/d-editor.gjs@@@ -1,93 -1,702 +1,796 @@@+ import { tracked } from "@glimmer/tracking";+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { getOwner } from "@ember/owner";+ import { schedule, scheduleOnce } from "@ember/runloop";+ import { service } from "@ember/service";+ import { classNames } from "@ember-decorators/component";+ import { observes, on } from "@ember-decorators/object";+ import { emojiSearch, isSkinTonableEmoji } from "pretty-text/emoji";+ import { translations } from "pretty-text/emoji/data";+ import { Promise } from "rsvp";+ import TextareaEditor from "discourse/components/composer/textarea-editor";+ import EmojiPickerDetached from "discourse/components/emoji-picker/detached";+ import InsertHyperlink from "discourse/components/modal/insert-hyperlink";+ import { SKIP } from "discourse/lib/autocomplete";+ import Toolbar from "discourse/lib/composer/toolbar";+ import discourseDebounce from "discourse/lib/debounce";+ import discourseComputed from "discourse/lib/decorators";+ import deprecated from "discourse/lib/deprecated";+ import { isTesting } from "discourse/lib/environment";+ import { getRegister } from "discourse/lib/get-owner";+ import { hashtagAutocompleteOptions } from "discourse/lib/hashtag-autocomplete";+ import { wantsNewWindow } from "discourse/lib/intercept-click";+ import { PLATFORM_KEY_MODIFIER } from "discourse/lib/keyboard-shortcuts";+ import loadEmojiSearchAliases from "discourse/lib/load-emoji-search-aliases";+ import loadRichEditor from "discourse/lib/load-rich-editor";+ import { findRawTemplate } from "discourse/lib/raw-templates";+ import { emojiUrlFor, generateCookFunction } from "discourse/lib/text";+ import userSearch from "discourse/lib/user-search";+ import {+ destroyUserStatuses,+ initUserStatusHtml,+ renderUserStatusHtml,+ } from "discourse/lib/user-status-on-autocomplete";+ import virtualElementFromTextRange from "discourse/lib/virtual-element-from-text-range";+ import { i18n } from "discourse-i18n";++ let _createCallbacks = [];++ export function addToolbarCallback(func) {+ _createCallbacks.push(func);+ }+ export function clearToolbarCallbacks() {+ _createCallbacks = [];+ }++ export function onToolbarCreate(func) {+ deprecated("`onToolbarCreate` is deprecated, use the plugin api instead.", {+ id: "discourse.d-editor.on-toolbar-create",+ });+ addToolbarCallback(func);+ }++ @classNames("d-editor")+ export default class DEditor extends Component {+ @service emojiStore;+ @service modal;+ @service menu;++ @tracked editorComponent;+ /** @type {TextManipulation} */+ @tracked textManipulation;++ @tracked preview;++ ready = false;+ lastSel = null;+ showLink = true;+ isEditorFocused = false;+ processPreview = true;+ morphingOptions = {+ beforeAttributeUpdated: (element, attributeName) => {+ // Don't morph the open attribute of <details> elements+ return !(element.tagName === "DETAILS" && attributeName === "open");+ },+ };++ async init() {+ super.init(...arguments);++ this.register = getRegister(this);++ if (+ this.siteSettings.rich_editor &&+ this.keyValueStore.get("d-editor-prefers-rich-editor") === "true"+ ) {+ this.editorComponent = await loadRichEditor();+ } else {+ this.editorComponent = TextareaEditor;+ }+ }++ @discourseComputed("placeholder")+ placeholderTranslated(placeholder) {+ if (placeholder) {+ return i18n(placeholder);+ }+ return null;+ }++ _readyNow() {+ this.set("ready", true);++ if (this.autofocus) {+ this.textManipulation.focus();+ }+ }++ didInsertElement() {+ super.didInsertElement(...arguments);+ this._previewMutationObserver = this._disablePreviewTabIndex();+ }++ get keymap() {+ const keymap = {};++ const shortcuts = this.get("toolbar.shortcuts");++ Object.keys(shortcuts).forEach((sc) => {+ const button = shortcuts[sc];+ keymap[sc] = () => {+ const customAction = shortcuts[sc].shortcutAction;++ if (customAction) {+ const toolbarEvent = this.newToolbarEvent();+ customAction(toolbarEvent);+ } else {+ button.action(button);+ }+ return false;+ };+ });++ if (this.popupMenuOptions && this.onPopupMenuAction) {+ this.popupMenuOptions.forEach((popupButton) => {+ if (popupButton.shortcut && popupButton.condition) {+ const shortcut =+ `${PLATFORM_KEY_MODIFIER}+${popupButton.shortcut}`.toLowerCase();+ keymap[shortcut] = () => {+ this.onPopupMenuAction(popupButton, this.newToolbarEvent());+ return false;+ };+ }+ });+ }++ keymap["tab"] = () => this.textManipulation.indentSelection("right");+ keymap["shift+tab"] = () => this.textManipulation.indentSelection("left");++ return keymap;+ }++ @action+ handlePreviewClick(event) {+ if (!event.target.closest(".d-editor-preview")) {+ return;+ }++ if (wantsNewWindow(event)) {+ return;+ }++ if (event.target.tagName === "A") {+ if (event.target.classList.contains("mention")) {+ this.appEvents.trigger(+ "d-editor:preview-click-user-card",+ event.target,+ event+ );+ }++ if (event.target.classList.contains("mention-group")) {+ this.appEvents.trigger(+ "d-editor:preview-click-group-card",+ event.target,+ event+ );+ }++ event.preventDefault();+ return false;+ }+ }++ @on("willDestroyElement")+ _shutDown() {+ this._previewMutationObserver?.disconnect();++ this._cachedCookFunction = null;+ }++ @discourseComputed()+ toolbar() {+ const toolbar = new Toolbar(+ this.getProperties("site", "siteSettings", "showLink", "capabilities")+ );+ toolbar.context = this;++ _createCallbacks.forEach((cb) => cb(toolbar));++ if (this.extraButtons) {+ this.extraButtons(toolbar);+ }++ const firstButton = toolbar.groups.mapBy("buttons").flat().firstObject;+ if (firstButton) {+ firstButton.tabindex = 0;+ }++ return toolbar;+ }++ async cachedCookAsync(text, options) {+ this._cachedCookFunction ||= await generateCookFunction(options || {});+ return await this._cachedCookFunction(text);+ }++ async _updatePreview() {+ if (+ this._state !== "inDOM" ||+ !this.processPreview ||+ this.isDestroying ||+ this.isDestroyed+ ) {+ return;+ }++ const cooked = await this.cachedCookAsync(this.value, this.markdownOptions);++ if (this.preview === cooked || this.isDestroying || this.isDestroyed) {+ return;+ }++ this.preview = cooked;+ }++ @observes("ready", "value", "processPreview")+ async _watchForChanges() {+ if (!this.ready) {+ return;+ }++ // Debouncing in test mode is complicated+ if (isTesting()) {+ await this._updatePreview();+ } else {+ discourseDebounce(this, this._updatePreview, 30);+ }+ }++ _applyHashtagAutocomplete() {+ this.textManipulation.autocomplete(+ hashtagAutocompleteOptions(+ this.site.hashtag_configurations["topic-composer"],+ this.siteSettings,+ {+ afterComplete: () => {+ schedule(+ "afterRender",+ this.textManipulation,+ this.textManipulation.blurAndFocus+ );+ },+ }+ )+ );+ }++ _applyEmojiAutocomplete() {+ if (!this.siteSettings.enable_emoji) {+ return;+ }++ this.textManipulation.autocomplete({+ template: findRawTemplate("emoji-selector-autocomplete"),+ key: ":",+ afterComplete: () => {+ schedule(+ "afterRender",+ this.textManipulation,+ this.textManipulation.blurAndFocus+ );+ },++ onKeyUp: (text, cp) => {+ const matches =+ /(?:^|[\s.\?,@\/#!%&*;:\[\]{}=\-_()])(:(?!:).?[\w-]*:?(?!:)(?:t\d?)?:?) ?$/gi.exec(+ text.substring(0, cp)+ );++ if (matches && matches[1]) {+ return [matches[1]];+ }+ },++ transformComplete: (v) => {+ if (v.code) {+ this.emojiStore.trackEmojiForContext(v.code, "topic");+ return `${v.code}:`;+ } else {+ this.textManipulation.autocomplete({ cancel: true });++ const menuOptions = {+ identifier: "emoji-picker",+ component: EmojiPickerDetached,+ modalForMobile: true,+ data: {+ didSelectEmoji: (emoji) => {+ this.textManipulation.emojiSelected(emoji);+ },+ term: v.term,+ },+ };++ this.menuInstance = this.menu.show(+ virtualElementFromTextRange(),+ menuOptions+ );+ return "";+ }+ },++ dataSource: (term) => {+ return new Promise((resolve) => {+ const full = `:${term}`;+ term = term.toLowerCase();++ if (term.length < this.siteSettings.emoji_autocomplete_min_chars) {+ return resolve(SKIP);+ }++ if (term === "") {+ const favorites = this.emojiStore.favoritesForContext("topic");+ if (favorites.length) {+ return resolve(+ favorites+ .filter((f) => !this.site.denied_emojis?.includes(f))+ .slice(0, 5)+ );+ } else {+ return resolve([+ "slight_smile",+ "smile",+ "wink",+ "sunny",+ "blush",+ ]);+ }+ }++ // note this will only work for emojis starting with :+ // eg: :-)+ const emojiTranslation =+ this.get("site.custom_emoji_translation") || {};+ const allTranslations = Object.assign(+ {},+ translations,+ emojiTranslation+ );+ if (allTranslations[full]) {+ return resolve([allTranslations[full]]);+ }++ const emojiDenied = this.get("site.denied_emojis") || [];+ const match = term.match(/^:?(.*?):t([2-6])?$/);+ if (match) {+ const name = match[1];+ const scale = match[2];++ if (isSkinTonableEmoji(name) && !emojiDenied.includes(name)) {+ if (scale) {+ return resolve([`${name}:t${scale}`]);+ } else {+ return resolve([2, 3, 4, 5, 6].map((x) => `${name}:t${x}`));+ }+ }+ }++ loadEmojiSearchAliases().then((searchAliases) => {+ const options = emojiSearch(term, {+ maxResults: 5,+ diversity: this.emojiStore.diversity,+ exclude: emojiDenied,+ searchAliases,+ });++ resolve(options);+ });+ })+ .then((list) => {+ if (list === SKIP) {+ return [];+ }++ return list.map((code) => {+ return { code, src: emojiUrlFor(code) };+ });+ })+ .then((list) => {+ if (list.length) {+ list.push({ label: i18n("composer.more_emoji"), term });+ }+ return list;+ });+ },++ triggerRule: async () => !(await this.textManipulation.inCodeBlock()),+ });+ }++ _applyMentionAutocomplete() {+ if (!this.siteSettings.enable_mentions) {+ return;+ }++ this.textManipulation.autocomplete({+ template: findRawTemplate("user-selector-autocomplete"),+ dataSource: (term) => {+ destroyUserStatuses();+ return userSearch({+ term,+ topicId: this.topicId,+ categoryId: this.categoryId,+ includeGroups: true,+ }).then((result) => {+ initUserStatusHtml(getOwner(this), result.users);+ return result;+ });+ },+ onRender: (options) => renderUserStatusHtml(options),+ key: "@",+ transformComplete: (v) => v.username || v.name,+ afterComplete: () => {+ schedule(+ "afterRender",+ this.textManipulation,+ this.textManipulation.blurAndFocus+ );+ },+ triggerRule: async () => !(await this.textManipulation.inCodeBlock()),+ onClose: destroyUserStatuses,+ });+ }++ @action+ rovingButtonBar(event) {+ let target = event.target;+ let siblingFinder;+ if (event.code === "ArrowRight") {+ siblingFinder = "nextElementSibling";+ } else if (event.code === "ArrowLeft") {+ siblingFinder = "previousElementSibling";+ } else {+ return true;+ }++ while (+ target.parentNode &&+ !target.parentNode.classList.contains("d-editor-button-bar")+ ) {+ target = target.parentNode;+ }++ let focusable = target[siblingFinder];+ if (focusable) {+ while (+ (focusable.tagName !== "BUTTON" &&+ !focusable.classList.contains("select-kit")) ||+ focusable.classList.contains("hidden")+ ) {+ focusable = focusable[siblingFinder];+ }++ if (focusable?.tagName === "DETAILS") {+ focusable = focusable.querySelector("summary");+ }++ focusable?.focus();+ }++ return true;+ }++ /**+ * Represents a toolbar event object passed to toolbar buttons.+ *+ * @typedef {Object} ToolbarEvent+ * @property {function} applySurround - Applies surrounding text+ * @property {function} formatCode - Formats as code+ * @property {function} replaceText - Replaces text+ * @property {function} selectText - Selects a range of text+ * @property {function} toggleDirection - Toggles text direction+ * @property {function} getText - Gets the text+ * @property {function} addText - Adds text+ * @property {function} applyList - Applies a list format+ * @property {*} selected - The current selection+ */++ /**+ * Creates a new toolbar event object+ *+ * @param {boolean} trimLeading - Whether to trim leading whitespace+ * @returns {ToolbarEvent} An object with toolbar event actions+ */+ newToolbarEvent(trimLeading) {+ const selected = this.textManipulation.getSelected(trimLeading);+ return {+ selected,+ selectText: (from, length) =>+ this.textManipulation.selectText(from, length, { scroll: false }),+ applySurround: (head, tail, exampleKey, opts) =>+ this.textManipulation.applySurround(+ selected,+ head,+ tail,+ exampleKey,+ opts+ ),+ applyList: (head, exampleKey, opts) =>+ this.textManipulation.applyList(selected, head, exampleKey, opts),+ formatCode: () => this.textManipulation.formatCode(),+ addText: (text) => this.textManipulation.addText(selected, text),+ getText: () => this.value,+ toggleDirection: () => this.textManipulation.toggleDirection(),+ replaceText: (oldVal, newVal, opts) =>+ this.textManipulation.replaceText(oldVal, newVal, opts),+ };+ }++ @action+ toolbarButton(button) {+ if (this.disabled) {+ return;+ }++ const toolbarEvent = this.newToolbarEvent(button.trimLeading);+ if (button.sendAction) {+ return button.sendAction(toolbarEvent);+ } else {+ button.perform(toolbarEvent);+ }+ }++ @action+ showLinkModal(toolbarEvent) {+ if (this.disabled) {+ return;+ }++ let linkText = "";+ this._lastSel = toolbarEvent.selected;++ if (this._lastSel) {+ linkText = this._lastSel.value;+ }++ this.modal.show(InsertHyperlink, {+ model: {+ linkText,+ toolbarEvent,+ },+ });+ }++ @action+ handleFocusIn() {+ this.set("isEditorFocused", true);+ }++ @action+ handleFocusOut() {+ this.set("isEditorFocused", false);+ }++ /**+ * Sets up the editor with the given text manipulation instance+ *+ * @param {TextManipulation} textManipulation The text manipulation instance+ * @returns {(() => void)} destructor function+ */+ @action+ setupEditor(textManipulation) {+ this.textManipulation = textManipulation;++ const destroyEvents = this.setupEvents();++ this.element.addEventListener("paste", textManipulation.paste);++ this._applyEmojiAutocomplete();+ this._applyHashtagAutocomplete();+ this._applyMentionAutocomplete();++ const destroyEditor = this.onSetup?.(textManipulation);++ scheduleOnce("afterRender", this, this._readyNow);++ return () => {+ destroyEvents?.();++ this.element?.removeEventListener("paste", textManipulation.paste);++ textManipulation.autocomplete("destroy");++ destroyEditor?.();+ };+ }++ @action+ async toggleRichEditor() {+ this.editorComponent = this.isRichEditorEnabled+ ? TextareaEditor+ : await loadRichEditor();++ this.keyValueStore.set({+ key: "d-editor-prefers-rich-editor",+ value: this.isRichEditorEnabled,+ });+ }++ @action+ onChange(event) {+ this.set("value", event?.target?.value);+ this.change?.(event);+ }++ get isRichEditorEnabled() {+ return this.editorComponent !== TextareaEditor;+ }++ setupEvents() {+ const textManipulation = this.textManipulation;++ if (this.composerEvents) {+ this.appEvents.on(+ "composer:insert-block",+ textManipulation,+ "insertBlock"+ );+ this.appEvents.on("composer:insert-text", textManipulation, "insertText");+ this.appEvents.on(+ "composer:replace-text",+ textManipulation,+ "replaceText"+ );+ this.appEvents.on(+ "composer:apply-surround",+ textManipulation,+ "applySurroundSelection"+ );+ this.appEvents.on(+ "composer:indent-selected-text",+ textManipulation,+ "indentSelection"+ );++ return () => {+ this.appEvents.off(+ "composer:insert-block",+ textManipulation,+ "insertBlock"+ );+ this.appEvents.off(+ "composer:insert-text",+ textManipulation,+ "insertText"+ );+ this.appEvents.off(+ "composer:replace-text",+ textManipulation,+ "replaceText"+ );+ this.appEvents.off(+ "composer:apply-surround",+ textManipulation,+ "applySurroundSelection"+ );+ this.appEvents.off(+ "composer:indent-selected-text",+ textManipulation,+ "indentSelection"+ );+ };+ }+ }++ _disablePreviewTabIndex() {+ const observer = new MutationObserver(function () {+ document.querySelectorAll(".d-editor-preview a").forEach((anchor) => {+ anchor.setAttribute("tabindex", "-1");+ });+ });++ observer.observe(document.querySelector(".d-editor-preview-wrapper"), {+ childList: true,+ subtree: true,+ attributes: false,+ characterData: true,+ });++ return observer;+ }+ }+++<div class="d-editor-container">+ <div class="d-editor-textarea-column">+ {{yield}}++ <div+ class="d-editor-textarea-wrapper+ {{if this.disabled 'disabled'}}+ {{if this.isEditorFocused 'in-focus'}}"+ >+ <div class="d-editor-button-bar" role="toolbar">+ {{#if this.siteSettings.rich_editor}}+ <Composer::ToggleSwitch+ @preventFocus={{true}}+ @disabled={{@disableSubmit}}+ @state={{this.isRichEditorEnabled}}+ {{on "click" this.toggleRichEditor}}+ />+ {{/if}}++ {{#each this.toolbar.groups as |group|}}+ {{#each group.buttons as |b|}}+ {{#if (b.condition this)}}+ {{#if b.popupMenu}}+ <ToolbarPopupMenuOptions+ @content={{this.popupMenuOptions}}+ @onChange={{this.onPopupMenuAction}}+ @onOpen={{action b.action b}}+ @tabindex={{-1}}+ @onKeydown={{this.rovingButtonBar}}+ @options={{hash icon=b.icon focusAfterOnChange=false}}+ class={{b.className}}+ />+ {{else}}+ <DButton+ @action={{fn (action b.action) b}}+ @translatedTitle={{b.title}}+ @label={{b.label}}+ @icon={{b.icon}}+ @preventFocus={{b.preventFocus}}+ @onKeyDown={{this.rovingButtonBar}}+ tabindex={{b.tabindex}}+ class={{b.className}}+ />+ {{/if}}+ {{/if}}+ {{/each}}+ {{/each}}+ </div>++ <ConditionalLoadingSpinner @condition={{this.loading}} />+ <this.editorComponent+ @class="d-editor-input"+ @onSetup={{this.setupEditor}}+ @markdownOptions={{this.markdownOptions}}+ @keymap={{this.keymap}}+ @value={{this.value}}+ @placeholder={{this.placeholderTranslated}}+ @disabled={{this.disabled}}+ @change={{this.onChange}}+ @focusIn={{this.handleFocusIn}}+ @focusOut={{this.handleFocusOut}}+ @categoryId={{@categoryId}}+ @topicId={{@topicId}}+ @id={{this.textAreaId}}+ />+ <PopupInputTip @validation={{this.validation}} />+ <PluginOutlet+ @name="after-d-editor"+ @connectorTagName="div"+ @outletArgs={{this.outletArgs}}+ />+ </div>+ </div>++ {{! template-lint-disable no-invalid-interactive }}+ <div+ class="d-editor-preview-wrapper {{if this.forcePreview 'force-preview'}}"+ {{on "click" this.handlePreviewClick}}+ >+ <DecoratedHtml+ @className="d-editor-preview"+ @html={{html-safe this.preview}}+ @decorate={{this.previewUpdated}}+ />+ <span class="d-editor-plugin">+ <PluginOutlet+ @name="editor-preview"+ @connectorTagName="div"+ @outletArgs={{this.outletArgs}}+ />+ </span>+ </div>+</div>diff --cc app/assets/javascripts/discourse/app/components/d-navigation.gjsindex e9722541f30,0c572be82a0..a02826ffaf5--- a/app/assets/javascripts/discourse/app/components/d-navigation.gjs+++ b/app/assets/javascripts/discourse/app/components/d-navigation.gjs@@@ -1,146 -1,215 +1,362 @@@+ import { tracked } from "@glimmer/tracking";+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { dependentKeyCompat } from "@ember/object/compat";+ import { service } from "@ember/service";+ import { htmlSafe } from "@ember/template";+ import { tagName } from "@ember-decorators/component";+ import { setting } from "discourse/lib/computed";+ import discourseComputed from "discourse/lib/decorators";+ import { filterTypeForMode } from "discourse/lib/filter-mode";+ import { NotificationLevels } from "discourse/lib/notification-levels";+ import { applyValueTransformer } from "discourse/lib/transformer";+ import NavItem from "discourse/models/nav-item";++ @tagName("")+ export default class DNavigation extends Component {+ @service router;+ @service dialog;+ @service site;++ @tracked filterMode;++ @setting("fixed_category_positions") fixedCategoryPositions;++ get createTopicLabel() {+ return this.site.desktopView ? "topic.create" : "";+ }++ get showBulkSelectInNavControls() {+ const enableOnDesktop = applyValueTransformer(+ "bulk-select-in-nav-controls",+ false,+ { site: this.site }+ );++ return (+ (this.site.mobileView || enableOnDesktop) &&+ this.notCategoriesRoute &&+ this.canBulkSelect+ );+ }++ @dependentKeyCompat+ get filterType() {+ return filterTypeForMode(this.filterMode);+ }++ // Should be a `readOnly` instead but some themes/plugins still pass+ // the `categories` property into this component+ @discourseComputed()+ categories() {+ let categories = this.site.categoriesList;++ if (!this.siteSettings.allow_uncategorized_topics) {+ categories = categories.filter(+ (category) => category.id !== this.site.uncategorized_category_id+ );+ }++ if (this.currentUser?.indirectly_muted_category_ids) {+ categories = categories.filter(+ (category) =>+ !this.currentUser.indirectly_muted_category_ids.includes(category.id)+ );+ }++ return categories;+ }++ @discourseComputed("category")+ showCategoryNotifications(category) {+ return category && this.currentUser;+ }++ @discourseComputed("category.notification_level")+ categoryNotificationLevel(notificationLevel) {+ if (+ this.currentUser?.indirectly_muted_category_ids?.includes(+ this.category.id+ )+ ) {+ return NotificationLevels.MUTED;+ } else {+ return notificationLevel;+ }+ }++ // don't show tag notification menu on tag intersections+ @discourseComputed("tagNotification", "additionalTags")+ showTagNotifications(tagNotification, additionalTags) {+ return tagNotification && !additionalTags;+ }++ @discourseComputed("category", "createTopicDisabled")+ categoryReadOnlyBanner(category, createTopicDisabled) {+ if (category && this.currentUser && createTopicDisabled) {+ return category.read_only_banner;+ }+ }++ @discourseComputed(+ "createTopicDisabled",+ "categoryReadOnlyBanner",+ "canCreateTopicOnTag",+ "tag.id"+ )+ createTopicButtonDisabled(+ createTopicDisabled,+ categoryReadOnlyBanner,+ canCreateTopicOnTag,+ tagId+ ) {+ if (tagId && !canCreateTopicOnTag) {+ return true;+ } else if (categoryReadOnlyBanner) {+ return false;+ }+ return createTopicDisabled;+ }++ @discourseComputed("categoryReadOnlyBanner")+ createTopicClass(categoryReadOnlyBanner) {+ let classNames = ["btn-default"];+ if (categoryReadOnlyBanner) {+ classNames.push("disabled");+ }+ return classNames.join(" ");+ }++ @discourseComputed("category.can_edit")+ showCategoryEdit(canEdit) {+ return canEdit;+ }++ @discourseComputed("additionalTags", "category", "tag.id")+ showToggleInfo(additionalTags, category, tagId) {+ return !additionalTags && !category && tagId !== "none";+ }++ @discourseComputed(+ "filterType",+ "category",+ "noSubcategories",+ "tag.id",+ "router.currentRoute.queryParams",+ "skipCategoriesNavItem"+ )+ navItems(+ filterType,+ category,+ noSubcategories,+ tagId,+ currentRouteQueryParams,+ skipCategoriesNavItem+ ) {+ return NavItem.buildList(category, {+ filterType,+ noSubcategories,+ currentRouteQueryParams,+ tagId,+ siteSettings: this.siteSettings,+ skipCategoriesNavItem,+ });+ }++ @discourseComputed("filterType")+ notCategoriesRoute(filterType) {+ return filterType !== "categories";+ }++ @action+ async changeTagNotificationLevel(notificationLevel) {+ const response = await this.tagNotification.update({+ notification_level: notificationLevel,+ });++ const payload = response.responseJson;++ this.tagNotification.set("notification_level", notificationLevel);++ this.currentUser.setProperties({+ watched_tags: payload.watched_tags,+ watching_first_post_tags: payload.watching_first_post_tags,+ tracked_tags: payload.tracked_tags,+ muted_tags: payload.muted_tags,+ regular_tags: payload.regular_tags,+ });+ }++ @action+ changeCategoryNotificationLevel(notificationLevel) {+ this.category.setNotification(notificationLevel);+ }++ @action+ selectCategoryAdminDropdownAction(actionId) {+ switch (actionId) {+ case "create":+ this.createCategory();+ break;+ case "reorder":+ this.reorderCategories();+ break;+ }+ }++ @action+ clickCreateTopicButton() {+ if (this.categoryReadOnlyBanner) {+ this.dialog.alert({ message: htmlSafe(this.categoryReadOnlyBanner) });+ } else {+ this.createTopic();+ }+ }+ }+++<BreadCrumbs+ @categories={{this.categories}}+ @category={{this.category}}+ @noSubcategories={{this.noSubcategories}}+ @tag={{this.tag}}+ @additionalTags={{this.additionalTags}}+/>++<PluginOutlet+ @name="after-breadcrumbs"+ @outletArgs={{hash+ categories=this.categories+ category=this.category+ tag=this.tag+ additionalTags=this.additionalTags+ }}+/>++{{#unless this.additionalTags}}+ {{! nav bar doesn't work with tag intersections }}+ <NavigationBar+ @navItems={{this.navItems}}+ @filterMode={{this.filterMode}}+ @category={{this.category}}+ @tag={{this.tag}}+ />+{{/unless}}++<div class="navigation-controls">+ {{#if this.showBulkSelectInNavControls}}+ <BulkSelectToggle @bulkSelectHelper={{@bulkSelectHelper}} />+ {{/if}}++ <TopicDismissButtons+ @position="top"+ @selectedTopics={{@bulkSelectHelper.selected}}+ @model={{@model}}+ @showResetNew={{@showResetNew}}+ @showDismissRead={{@showDismissRead}}+ @resetNew={{@resetNew}}+ @dismissRead={{@dismissRead}}+ />++ {{#if this.showCategoryAdmin}}+ {{#if this.fixedCategoryPositions}}+ <CategoriesAdminDropdown+ @onChange={{action "selectCategoryAdminDropdownAction"}}+ @options={{hash triggerOnChangeOnTab=false}}+ />+ {{else}}+ <DButton+ @action={{this.createCategory}}+ @icon="plus"+ @label={{if+ this.site.mobileView+ "categories.category"+ "category.create"+ }}+ class="btn-default"+ id="create-category"+ />+ {{/if}}+ {{/if}}++ {{#if (and this.category this.showCategoryEdit)}}+ <DButton+ @action={{this.editCategory}}+ @icon="wrench"+ @title="category.edit_title"+ class="btn-default edit-category"+ />+ {{/if}}++ {{#if this.tag}}+ {{#if this.showToggleInfo}}+ <DButton+ @icon={{if this.currentUser.staff "wrench" "circle-info"}}+ @ariaLabel="tagging.info"+ @action={{this.toggleInfo}}+ id="show-tag-info"+ class="btn-default"+ />+ {{/if}}+ {{/if}}++ <PluginOutlet+ @name="before-create-topic-button"+ @outletArgs={{hash+ canCreateTopic=this.canCreateTopic+ createTopicDisabled=this.createTopicDisabled+ createTopicLabel=this.createTopicLabel+ additionalTags=this.additionalTags+ category=this.category+ tag=this.tag+ }}+ />++ <CreateTopicButton+ @canCreateTopic={{this.canCreateTopic}}+ @action={{action "clickCreateTopicButton"}}+ @disabled={{this.createTopicButtonDisabled}}+ @label={{this.createTopicLabel}}+ @btnClass={{this.createTopicClass}}+ @canCreateTopicOnTag={{this.canCreateTopicOnTag}}+ @showDrafts={{if (gt this.draftCount 0) true false}}+ />++ <PluginOutlet+ @name="after-create-topic-button"+ @outletArgs={{hash+ canCreateTopic=this.canCreateTopic+ createTopicDisabled=this.createTopicDisabled+ createTopicLabel=this.createTopicLabel+ category=this.category+ tag=this.tag+ }}+ />++ {{#if this.category}}+ {{#unless this.tag}}+ {{! don't show category notification menu on tag pages }}+ {{#if this.showCategoryNotifications}}+ {{#unless this.category.deleted}}+ <CategoryNotificationsTracking+ @levelId={{this.categoryNotificationLevel}}+ @showFullTitle={{false}}+ @showCaret={{false}}+ @onChange={{this.changeCategoryNotificationLevel}}+ />+ {{/unless}}+ {{/if}}+ {{/unless}}+ {{/if}}++ {{#if this.tag}}+ {{#unless this.category}}+ {{! don't show tag notification menu on category pages }}+ {{#if this.showTagNotifications}}+ <TagNotificationsTracking+ @onChange={{this.changeTagNotificationLevel}}+ @levelId={{this.tagNotification.notification_level}}+ />+ {{/if}}+ {{/unless}}+ {{/if}}+</div>diff --cc app/assets/javascripts/discourse/app/components/discovery/topics.gjsindex 47ada7a5ca1,9fdc1a071a2..51ced9ab56b--- a/app/assets/javascripts/discourse/app/components/discovery/topics.gjs+++ b/app/assets/javascripts/discourse/app/components/discovery/topics.gjs@@@ -1,213 -1,182 +1,396 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import { popupAjaxError } from "discourse/lib/ajax-error";+ import { filterTypeForMode } from "discourse/lib/filter-mode";+ import { userPath } from "discourse/lib/url";+ import { i18n } from "discourse-i18n";++ export default class DiscoveryTopics extends Component {+ @service router;+ @service composer;+ @service modal;+ @service currentUser;+ @service topicTrackingState;+ @service site;++ @tracked loadingNew;++ get redirectedReason() {+ return this.currentUser?.user_option.redirected_to_top?.reason;+ }++ get order() {+ return this.args.model.get("params.order");+ }++ get ascending() {+ return this.args.model.get("params.ascending") === "true";+ }++ get hasTopics() {+ return this.args.model.get("topics.length") > 0;+ }++ get allLoaded() {+ return !this.args.model.get("more_topics_url");+ }++ get latest() {+ return filterTypeForMode(this.args.model.filter) === "latest";+ }++ get top() {+ return filterTypeForMode(this.args.model.filter) === "top";+ }++ get hot() {+ return filterTypeForMode(this.args.model.filter) === "hot";+ }++ get new() {+ return filterTypeForMode(this.args.model.filter) === "new";+ }++ // Show newly inserted topics+ @action+ async showInserted(event) {+ event?.preventDefault();++ if (this.args.model.loadingBefore) {+ return; // Already loading+ }++ const { topicTrackingState } = this;++ try {+ const topicIds = [...topicTrackingState.newIncoming];+ await this.args.model.loadBefore(topicIds, true);+ topicTrackingState.clearIncoming(topicIds);+ } catch (e) {+ popupAjaxError(e);+ }+ }++ get showTopicsAndRepliesToggle() {+ return this.new && this.currentUser?.new_new_view_enabled;+ }++ get newRepliesCount() {+ this.topicTrackingState.get("messageCount"); // Autotrack this++ if (this.currentUser?.new_new_view_enabled) {+ return this.topicTrackingState.countUnread({+ categoryId: this.args.category?.id,+ noSubcategories: this.args.noSubcategories,+ tagId: this.args.tag?.id,+ });+ } else {+ return 0;+ }+ }++ get newTopicsCount() {+ this.topicTrackingState.get("messageCount"); // Autotrack this++ if (this.currentUser?.new_new_view_enabled) {+ return this.topicTrackingState.countNew({+ categoryId: this.args.category?.id,+ noSubcategories: this.args.noSubcategories,+ tagId: this.args.tag?.id,+ });+ } else {+ return 0;+ }+ }++ get showTopicPostBadges() {+ return !this.new || this.currentUser?.new_new_view_enabled;+ }++ get footerMessage() {+ const topicsLength = this.args.model.get("topics.length");+ if (!this.allLoaded) {+ return;+ }++ const { category, tag } = this.args;+ if (category) {+ return i18n("topics.bottom.category", {+ category: category.get("name"),+ });+ } else if (tag) {+ return i18n("topics.bottom.tag", {+ tag: tag.id,+ });+ } else {+ const split = (this.args.model.get("filter") || "").split("/");+ if (topicsLength === 0) {+ return i18n("topics.none." + split[0], {+ category: split[1],+ });+ } else {+ return i18n("topics.bottom." + split[0], {+ category: split[1],+ });+ }+ }+ }++ get footerEducation() {+ const topicsLength = this.args.model.get("topics.length");++ if (!this.allLoaded || topicsLength > 0 || !this.currentUser) {+ return;+ }++ const segments = (this.args.model.get("filter") || "").split("/");++ let tab = segments[segments.length - 1];++ if (tab !== "new" && tab !== "unread") {+ return;+ }++ if (tab === "new" && this.currentUser.new_new_view_enabled) {+ tab = "new_new";+ }++ return i18n("topics.none.educate." + tab, {+ userPrefsUrl: userPath(+ `${this.currentUser.get("username_lower")}/preferences/tracking`+ ),+ });+ }++ get renderNewListHeaderControls() {+ return (+ this.site.mobileView &&+ this.showTopicsAndRepliesToggle &&+ !this.args.bulkSelectEnabled+ );+ }++ get expandGloballyPinned() {+ return !this.expandAllPinned;+ }++ get expandAllPinned() {+ return this.args.tag || this.args.category;+ }+ }+++{{#if @model.canLoadMore}}+ {{hide-application-footer}}+{{/if}}++{{#if this.redirectedReason}}+ <div class="alert alert-info">{{this.redirectedReason}}</div>+{{/if}}++{{#if @model.sharedDrafts}}+ {{#if this.site.useGlimmerTopicList}}+ <TopicList::List+ @listTitle="shared_drafts.title"+ @top={{this.top}}+ @hideCategory="true"+ @category={{@category}}+ @topics={{@model.sharedDrafts}}+ @discoveryList={{true}}+ class="shared-drafts"+ />+ {{else}}+ <TopicList+ @listTitle="shared_drafts.title"+ @top={{this.top}}+ @hideCategory="true"+ @category={{@category}}+ @topics={{@model.sharedDrafts}}+ @discoveryList={{true}}+ class="shared-drafts"+ />+ {{/if}}+{{/if}}++<DiscoveryTopicsList+ @model={{@model}}+ @incomingCount={{this.topicTrackingState.incomingCount}}+ @bulkSelectHelper={{@bulkSelectHelper}}+ @class={{if this.footerEducation "--no-topics-education"}}+>+ {{#if this.top}}+ <div class="top-lists">+ <PeriodChooser+ @period={{@period}}+ @action={{@changePeriod}}+ @fullDay={{false}}+ />+ </div>+ {{else}}+ {{#if (or this.topicTrackingState.hasIncoming @model.loadingBefore)}}+ <div class="show-more {{if this.hasTopics 'has-topics'}}">+ <a+ tabindex="0"+ href+ {{on "click" this.showInserted}}+ class="alert alert-info clickable+ {{if @model.loadingBefore 'loading'}}"+ >+ <CountI18n+ @key="topic_count_"+ @suffix={{this.topicTrackingState.filter}}+ @count={{or+ @model.loadingBefore+ this.topicTrackingState.incomingCount+ }}+ />+ {{#if @model.loadingBefore}}+ {{loading-spinner size="small"}}+ {{/if}}+ </a>+ </div>+ {{/if}}+ {{/if}}++ {{#if this.renderNewListHeaderControls}}+ <NewListHeaderControlsWrapper+ @current={{@model.params.subset}}+ @newRepliesCount={{this.newRepliesCount}}+ @newTopicsCount={{this.newTopicsCount}}+ @changeNewListSubset={{@changeNewListSubset}}+ />+ {{/if}}++ <span>+ <PluginOutlet+ @name="before-topic-list"+ @connectorTagName="div"+ @outletArgs={{hash category=@category tag=@tag}}+ />+ </span>++ {{#if this.hasTopics}}+ {{#if this.site.useGlimmerTopicList}}+ <TopicList::List+ @highlightLastVisited={{true}}+ @top={{this.top}}+ @hot={{this.hot}}+ @showTopicPostBadges={{this.showTopicPostBadges}}+ @showPosters={{true}}+ @canBulkSelect={{@canBulkSelect}}+ @bulkSelectHelper={{@bulkSelectHelper}}+ @changeSort={{@changeSort}}+ @hideCategory={{@model.hideCategory}}+ @order={{this.order}}+ @ascending={{this.ascending}}+ @expandGloballyPinned={{this.expandGloballyPinned}}+ @expandAllPinned={{this.expandAllPinned}}+ @category={{@category}}+ @topics={{@model.topics}}+ @discoveryList={{true}}+ @focusLastVisitedTopic={{true}}+ @showTopicsAndRepliesToggle={{this.showTopicsAndRepliesToggle}}+ @newListSubset={{@model.params.subset}}+ @changeNewListSubset={{@changeNewListSubset}}+ @newRepliesCount={{this.newRepliesCount}}+ @newTopicsCount={{this.newTopicsCount}}+ />+ {{else}}+ <TopicList+ @highlightLastVisited={{true}}+ @top={{this.top}}+ @hot={{this.hot}}+ @showTopicPostBadges={{this.showTopicPostBadges}}+ @showPosters={{true}}+ @canBulkSelect={{@canBulkSelect}}+ @bulkSelectHelper={{@bulkSelectHelper}}+ @changeSort={{@changeSort}}+ @hideCategory={{@model.hideCategory}}+ @order={{this.order}}+ @ascending={{this.ascending}}+ @expandGloballyPinned={{this.expandGloballyPinned}}+ @expandAllPinned={{this.expandAllPinned}}+ @category={{@category}}+ @topics={{@model.topics}}+ @discoveryList={{true}}+ @focusLastVisitedTopic={{true}}+ @showTopicsAndRepliesToggle={{this.showTopicsAndRepliesToggle}}+ @newListSubset={{@model.params.subset}}+ @changeNewListSubset={{@changeNewListSubset}}+ @newRepliesCount={{this.newRepliesCount}}+ @newTopicsCount={{this.newTopicsCount}}+ />+ {{/if}}+ {{/if}}++ <span class="after-topic-list-plugin-outlet-wrapper">+ <PluginOutlet+ @name="after-topic-list"+ @connectorTagName="div"+ @outletArgs={{hash+ category=@category+ tag=@tag+ }}+ />+ </span>+</DiscoveryTopicsList>++<footer class="topic-list-bottom">+ <ConditionalLoadingSpinner @condition={{@model.loadingMore}} />+ {{#if this.allLoaded}}+ <PluginOutlet+ @name="topic-list-bottom"+ @outletArgs={{hash+ category=@category+ tag=@tag+ allLoaded=this.allLoaded+ model=@model+ }}+ >+ <TopicDismissButtons+ @position="bottom"+ @selectedTopics={{@bulkSelectHelper.selected}}+ @model={{@model}}+ @showResetNew={{@showResetNew}}+ @showDismissRead={{@showDismissRead}}+ @resetNew={{@resetNew}}+ @dismissRead={{@dismissRead}}+ />++ <FooterMessage+ @education={{this.footerEducation}}+ @message={{this.footerMessage}}+ >+ {{#if @tag}}+ {{html-safe+ (i18n "topic.browse_all_tags_or_latest" basePath=(base-path))+ }}+ {{else if this.latest}}+ {{#if @category.canCreateTopic}}+ <DiscourseLinkedText+ @action={{fn+ this.composer.openNewTopic+ (hash category=@category)+ }}+ @text="topic.suggest_create_topic"+ />+ {{/if}}+ {{else if this.top}}+ {{html-safe+ (i18n+ "topic.browse_all_categories_latest_or_top" basePath=(base-path)+ )+ }}+ <TopPeriodButtons @period={{@period}} @action={{@changePeriod}} />+ {{else}}+ {{html-safe+ (i18n "topic.browse_all_categories_latest" basePath=(base-path))+ }}+ {{/if}}+ </FooterMessage>+ </PluginOutlet>+ {{/if}}+</footer>diff --cc app/assets/javascripts/discourse/app/components/edit-category-security.gjsindex bee8f3658af,ccb5ff33a03..097b19f4722--- a/app/assets/javascripts/discourse/app/components/edit-category-security.gjs+++ b/app/assets/javascripts/discourse/app/components/edit-category-security.gjs@@@ -1,65 -1,57 +1,123 @@@+ import { action } from "@ember/object";+ import { not } from "@ember/object/computed";+ import { buildCategoryPanel } from "discourse/components/edit-category-panel";+ import discourseComputed from "discourse/lib/decorators";+ import PermissionType from "discourse/models/permission-type";++ export default class EditCategorySecurity extends buildCategoryPanel(+ "security"+ ) {+ selectedGroup = null;++ @not("selectedGroup") noGroupSelected;++ @discourseComputed("[email protected]_type")+ everyonePermission(permissions) {+ return permissions.findBy("group_name", "everyone");+ }++ @discourseComputed("[email protected]_type")+ everyoneGrantedFull() {+ return (+ this.everyonePermission &&+ this.everyonePermission.permission_type === PermissionType.FULL+ );+ }++ @discourseComputed("everyonePermission")+ minimumPermission(everyonePermission) {+ return everyonePermission+ ? everyonePermission.permission_type+ : PermissionType.READONLY;+ }++ @action+ onSelectGroup(group_name) {+ this.category.addPermission({+ group_name,+ permission_type: this.minimumPermission,+ });+ }++ @action+ onChangeEveryonePermission(everyonePermissionType) {+ this.category.permissions.forEach((permission, idx) => {+ if (permission.group_name === "everyone") {+ return;+ }++ if (everyonePermissionType < permission.permission_type) {+ this.category.set(+ `permissions.${idx}.permission_type`,+ everyonePermissionType+ );+ }+ });+ }+ }+++<section class="field">+ {{#if this.category.is_special}}+ {{#if this.category.isUncategorizedCategory}}+ <p class="warning">{{i18n "category.uncategorized_security_warning"}}</p>+ {{else}}+ <p class="warning">{{i18n "category.special_warning"}}</p>+ {{/if}}+ {{/if}}++ {{#unless this.category.is_special}}+ <div class="category-permissions-table">+ <div class="permission-row row-header">+ <span class="group-name">{{i18n "category.permissions.group"}}</span>+ <span class="options">+ <span class="cell">{{i18n "category.permissions.see"}}</span>+ <span class="cell">{{i18n "category.permissions.reply"}}</span>+ <span class="cell">{{i18n "category.permissions.create"}}</span>+ <span class="cell"></span>+ </span>+ </div>+ {{#each this.category.permissions as |p|}}+ <CategoryPermissionRow+ @groupName={{p.group_name}}+ @type={{p.permission_type}}+ @category={{this.category}}+ @everyonePermission={{this.everyonePermission}}+ @onChangeEveryonePermission={{action "onChangeEveryonePermission"}}+ />+ {{/each}}++ {{#unless this.category.permissions}}+ <div class="permission-row row-empty">+ {{i18n "category.permissions.no_groups_selected"}}+ </div>+ {{/unless}}++ {{#if this.category.availableGroups}}+ <div class="add-group">+ <span class="group-name">+ <ComboBox+ @content={{this.category.availableGroups}}+ @onChange={{action "onSelectGroup"}}+ @value={{null}}+ @valueProperty={{null}}+ @nameProperty={{null}}+ @options={{hash none="category.security_add_group"}}+ class="available-groups"+ />+ </span>+ </div>+ {{/if}}+ </div>++ {{#if this.everyoneGrantedFull}}+ <p class="warning">{{i18n "category.permissions.everyone_has_access"}}</p>+ {{/if}}+ {{/unless}}+</section>++<section>+ <PluginOutlet+ @name="category-custom-security"+ @outletArgs={{hash category=this.category}}+ />+</section>diff --cc app/assets/javascripts/discourse/app/components/edit-category-settings.gjsindex 3da62905dca,93a541de08b..7405d8d44b7--- a/app/assets/javascripts/discourse/app/components/edit-category-settings.gjs+++ b/app/assets/javascripts/discourse/app/components/edit-category-settings.gjs@@@ -1,400 -1,161 +1,562 @@@+ import { action } from "@ember/object";+ import { and, empty } from "@ember/object/computed";+ import { buildCategoryPanel } from "discourse/components/edit-category-panel";+ import { setting } from "discourse/lib/computed";+ import { SEARCH_PRIORITIES } from "discourse/lib/constants";+ import discourseComputed from "discourse/lib/decorators";+ import { applyMutableValueTransformer } from "discourse/lib/transformer";+ import { i18n } from "discourse-i18n";++ const categorySortCriteria = [];+ export function addCategorySortCriteria(criteria) {+ categorySortCriteria.push(criteria);+ }++ export default class EditCategorySettings extends buildCategoryPanel(+ "settings"+ ) {+ @setting("email_in") emailInEnabled;+ @setting("fixed_category_positions") showPositionInput;++ @and("category.show_subcategory_list", "isParentCategory")+ showSubcategoryListStyle;+ @empty("category.sort_order") isDefaultSortOrder;++ @discourseComputed("category.isParent", "category.parent_category_id")+ isParentCategory(isParent, parentCategoryId) {+ return isParent || !parentCategoryId;+ }++ @discourseComputed+ availableSubcategoryListStyles() {+ return [+ { name: i18n("category.subcategory_list_styles.rows"), value: "rows" },+ {+ name: i18n(+ "category.subcategory_list_styles.rows_with_featured_topics"+ ),+ value: "rows_with_featured_topics",+ },+ {+ name: i18n("category.subcategory_list_styles.boxes"),+ value: "boxes",+ },+ {+ name: i18n(+ "category.subcategory_list_styles.boxes_with_featured_topics"+ ),+ value: "boxes_with_featured_topics",+ },+ ];+ }++ @discourseComputed("category.id", "category.custom_fields")+ availableViews(categoryId, customFields) {+ const views = [+ { name: i18n("filters.latest.title"), value: "latest" },+ { name: i18n("filters.top.title"), value: "top" },+ ];++ const context = {+ categoryId,+ customFields,+ };++ return applyMutableValueTransformer(+ "category-available-views",+ views,+ context+ );+ }++ @discourseComputed+ availableTopPeriods() {+ return ["all", "yearly", "quarterly", "monthly", "weekly", "daily"].map(+ (p) => {+ return { name: i18n(`filters.top.${p}.title`), value: p };+ }+ );+ }++ @discourseComputed+ availableListFilters() {+ return ["all", "none"].map((p) => {+ return { name: i18n(`category.list_filters.${p}`), value: p };+ });+ }++ @discourseComputed+ searchPrioritiesOptions() {+ const options = [];++ Object.entries(SEARCH_PRIORITIES).forEach((entry) => {+ const [name, value] = entry;++ options.push({+ name: i18n(`category.search_priority.options.${name}`),+ value,+ });+ });++ return options;+ }++ @discourseComputed+ availableSorts() {+ return [+ "likes",+ "op_likes",+ "views",+ "posts",+ "activity",+ "posters",+ "category",+ "created",+ ]+ .concat(categorySortCriteria)+ .map((s) => ({ name: i18n("category.sort_options." + s), value: s }))+ .sort((a, b) => a.name.localeCompare(b.name));+ }++ @discourseComputed("category.sort_ascending")+ sortAscendingOption(sortAscending) {+ if (sortAscending === "false") {+ return false;+ }+ if (sortAscending === "true") {+ return true;+ }+ return sortAscending;+ }++ @discourseComputed+ sortAscendingOptions() {+ return [+ { name: i18n("category.sort_ascending"), value: true },+ { name: i18n("category.sort_descending"), value: false },+ ];+ }++ @discourseComputed+ hiddenRelativeIntervals() {+ return ["mins"];+ }++ @action+ onAutoCloseDurationChange(minutes) {+ let hours = minutes ? minutes / 60 : null;+ this.set("category.auto_close_hours", hours);+ }++ @action+ onDefaultSlowModeDurationChange(minutes) {+ let seconds = minutes ? minutes * 60 : null;+ this.set("category.default_slow_mode_seconds", seconds);+ }++ @action+ onCategoryModeratingGroupsChange(groupIds) {+ this.set("category.moderating_group_ids", groupIds);+ }+ }+++<section>+ {{#if this.showPositionInput}}+ <section class="field position-fields">+ <label for="category-position">+ {{i18n "category.position"}}+ </label>+ <input+ {{on "input" (with-event-value (fn (mut this.category.position)))}}+ value={{this.category.position}}+ type="number"+ min="0"+ id="category-position"+ class="position-input"+ />+ </section>+ {{/if}}++ {{#unless this.showPositionInput}}+ <section class="field position-disabled">+ {{html-safe+ (i18n+ "category.position_disabled"+ url=(get-url+ "/admin/site_settings/category/all_results?filter=fixed_category_positions"+ )+ )+ }}+ </section>+ {{/unless}}++ <section class="field num-featured-topics">+ <label for="category-number-featured-topics">+ {{#if this.category.parent_category_id}}+ {{i18n "category.subcategory_num_featured_topics"}}+ {{else}}+ {{i18n "category.num_featured_topics"}}+ {{/if}}+ </label>+ <input+ {{on+ "input"+ (with-event-value (fn (mut this.category.num_featured_topics)))+ }}+ value={{this.category.num_featured_topics}}+ type="number"+ min="1"+ id="category-number-featured-topics"+ />+ </section>++ <section class="field search-priority">+ <label>+ {{i18n "category.search_priority.label"}}+ </label>+ <div class="controls">+ <ComboBox+ @valueProperty="value"+ @id="category-search-priority"+ @content={{this.searchPrioritiesOptions}}+ @value={{this.category.search_priority}}+ @onChange={{fn (mut this.category.search_priority)}}+ @options={{hash placementStrategy="absolute"}}+ />+ </div>+ </section>++ {{#if this.siteSettings.enable_badges}}+ <section class="field allow-badges">+ <label class="checkbox-label">+ <Input @type="checkbox" @checked={{this.category.allow_badges}} />+ {{i18n "category.allow_badges_label"}}+ </label>+ </section>+ {{/if}}++ {{#if this.siteSettings.topic_featured_link_enabled}}+ <section class="field topic-featured-link-allowed">+ <div class="allowed-topic-featured-link-category">+ <label class="checkbox-label">+ <Input+ @type="checkbox"+ @checked={{this.category.topic_featured_link_allowed}}+ />+ {{i18n "category.topic_featured_link_allowed"}}+ </label>+ </div>+ </section>+ {{/if}}++ <section class="field navigate-to-first-post-after-read">+ <label class="checkbox-label">+ <Input+ @type="checkbox"+ @checked={{this.category.navigate_to_first_post_after_read}}+ />+ {{i18n "category.navigate_to_first_post_after_read"}}+ </label>+ </section>++ <section class="field all-topics-wiki">+ <label class="checkbox-label">+ <Input @type="checkbox" @checked={{this.category.all_topics_wiki}} />+ {{i18n "category.all_topics_wiki"}}+ </label>+ </section>++ <section class="field allow-unlimited-owner-edits-on-first-post">+ <label class="checkbox-label">+ <Input+ @type="checkbox"+ @checked={{this.category.allow_unlimited_owner_edits_on_first_post}}+ />+ {{i18n "category.allow_unlimited_owner_edits_on_first_post"}}+ </label>+ </section>+</section>++<section>+ <h3>{{i18n "category.settings_sections.moderation"}}</h3>+ {{#if this.siteSettings.enable_category_group_moderation}}+ <section class="field reviewable-by-group">+ <label>{{i18n "category.reviewable_by_group"}}</label>+ <GroupChooser+ @content={{this.site.groups}}+ @value={{this.category.moderating_group_ids}}+ @onChange={{this.onCategoryModeratingGroupsChange}}+ />+ </section>+ {{/if}}++ <section class="field require-topic-approval">+ <label class="checkbox-label">+ <Input+ @type="checkbox"+ @checked={{this.category.category_setting.require_topic_approval}}+ />+ {{i18n "category.require_topic_approval"}}+ </label>+ </section>++ <section class="field require-reply-approval">+ <label class="checkbox-label">+ <Input+ @type="checkbox"+ @checked={{this.category.category_setting.require_reply_approval}}+ />+ {{i18n "category.require_reply_approval"}}+ </label>+ </section>++ <section class="field default-slow-mode">+ <div class="control-group">+ <label for="category-default-slow-mode">+ {{i18n "category.default_slow_mode"}}+ </label>+ <div class="category-default-slow-mode-seconds">+ <RelativeTimePicker+ @id="category-default-slow-mode"+ @durationMinutes={{this.category.defaultSlowModeMinutes}}+ @onChange={{action "onDefaultSlowModeDurationChange"}}+ />+ </div>+ </div>+ </section>++ <section class="field auto-close">+ <div class="control-group">+ <label for="topic-auto-close">+ {{i18n "topic.auto_close.label"}}+ </label>+ <div class="category-topic-auto-close-hours">+ <RelativeTimePicker+ @id="topic-auto-close"+ @durationHours={{this.category.auto_close_hours}}+ @hiddenIntervals={{this.hiddenRelativeIntervals}}+ @onChange={{action "onAutoCloseDurationChange"}}+ />+ </div>+ <label class="checkbox-label">+ <Input+ @type="checkbox"+ @checked={{this.category.auto_close_based_on_last_post}}+ />+ {{i18n "topic.auto_close.based_on_last_post"}}+ </label>+ </div>+ </section>++ <section class="field num-auto-bump-daily">+ <label for="category-number-daily-bump">+ {{i18n "category.num_auto_bump_daily"}}+ </label>+ <input+ {{on+ "input"+ (with-event-value+ (fn (mut this.category.category_setting.num_auto_bump_daily))+ )+ }}+ value={{this.category.category_setting.num_auto_bump_daily}}+ type="number"+ min="0"+ id="category-number-daily-bump"+ />+ </section>++ <section class="field auto-bump-cooldown-days">+ <label for="category-auto-bump-cooldown-days">+ {{i18n "category.auto_bump_cooldown_days"}}+ </label>+ <input+ {{on+ "input"+ (with-event-value+ (fn (mut this.category.category_setting.auto_bump_cooldown_days))+ )+ }}+ value={{this.category.category_setting.auto_bump_cooldown_days}}+ type="number"+ min="0"+ id="category-auto-bump-cooldown-days"+ />+ </section>+</section>++<section>+ <h3>{{i18n "category.settings_sections.appearance"}}</h3>++ <section class="field default-view-field">+ <label>+ {{i18n "category.default_view"}}+ </label>+ <div class="controls">+ <ComboBox+ @valueProperty="value"+ @id="category-default-view"+ @content={{this.availableViews}}+ @value={{this.category.default_view}}+ @options={{hash placementStrategy="absolute"}}+ />+ </div>+ </section>++ <section class="field default-top-period-field">+ <label>+ {{i18n "category.default_top_period"}}+ </label>+ <div class="controls">+ <ComboBox+ @valueProperty="value"+ @id="category-default-period"+ @content={{this.availableTopPeriods}}+ @value={{this.category.default_top_period}}+ @options={{hash placementStrategy="absolute"}}+ />+ </div>+ </section>++ <section class="field sort-order">+ <label>+ {{i18n "category.sort_order"}}+ </label>+ <div class="controls">+ <ComboBox+ @valueProperty="value"+ @content={{this.availableSorts}}+ @value={{this.category.sort_order}}+ @options={{hash none="category.sort_options.default"}}+ @onChange={{fn (mut this.category.sort_order)}}+ />+ {{#unless this.isDefaultSortOrder}}+ <ComboBox+ @valueProperty="value"+ @content={{this.sortAscendingOptions}}+ @value={{this.sortAscendingOption}}+ @options={{hash+ none="category.sort_options.default"+ placementStrategy="absolute"+ }}+ @onChange={{fn (mut this.category.sort_ascending)}}+ />+ {{/unless}}+ </div>+ </section>++ <section class="field default-filter">+ <label>+ {{i18n "category.default_list_filter"}}+ </label>+ <div class="controls">+ <ComboBox+ @id="category-default-filter"+ @valueProperty="value"+ @content={{this.availableListFilters}}+ @value={{this.category.default_list_filter}}+ />+ </div>+ </section>++ {{#if this.isParentCategory}}+ <section class="field show-subcategory-list-field">+ <label class="checkbox-label">+ <Input+ @type="checkbox"+ @checked={{this.category.show_subcategory_list}}+ />+ {{i18n "category.show_subcategory_list"}}+ </label>+ </section>+ {{/if}}++ {{#if this.showSubcategoryListStyle}}+ <section class="field subcategory-list-style-field">+ <label>+ {{i18n "category.subcategory_list_style"}}+ </label>+ <ComboBox+ @valueProperty="value"+ @id="subcategory-list-style"+ @content={{this.availableSubcategoryListStyles}}+ @value={{this.category.subcategory_list_style}}+ @options={{hash placementStrategy="absolute"}}+ />+ </section>+ {{/if}}++ <section class="field category-read-only-banner">+ <label for="read-only-message">{{i18n "category.read_only_banner"}}</label>+ <TextField+ @valueProperty="value"+ @id="read-only-message"+ @value={{this.category.read_only_banner}}+ @options={{hash placementStrategy="absolute"}}+ />+ </section>+</section>++<section>+ <h3>{{i18n "category.settings_sections.email"}}</h3>++ {{#if this.emailInEnabled}}+ <section class="field category-email-in">+ <label for="category-email-in">+ {{d-icon "envelope"}}+ {{i18n "category.email_in"}}+ </label>+ <TextField+ @id="category-email-in"+ @value={{this.category.email_in}}+ class="email-in"+ />++ </section>++ <section class="field email-in-allow-strangers">+ <label class="checkbox-label">+ <Input+ @type="checkbox"+ @checked={{this.category.email_in_allow_strangers}}+ />+ {{i18n "category.email_in_allow_strangers"}}+ </label>+ </section>++ <section class="field mailinglist-mirror">+ <label class="checkbox-label">+ <Input @type="checkbox" @checked={{this.category.mailinglist_mirror}} />+ {{i18n "category.mailinglist_mirror"}}+ </label>+ </section>++ <span>+ <PluginOutlet+ @name="category-email-in"+ @connectorTagName="div"+ @outletArgs={{hash category=this.category}}+ />+ </span>+ {{/if}}++ {{#unless this.emailInEnabled}}+ <section class="field email-in-disabled">+ {{html-safe+ (i18n+ "category.email_in_disabled"+ setting_url=(get-url+ "/admin/site_settings/category/all_results?filter=email_in"+ )+ )+ }}+ </section>+ {{/unless}}+</section>++<section>+ <PluginOutlet+ @name="category-custom-settings"+ @outletArgs={{hash category=this.category}}+ />+</section>diff --cc app/assets/javascripts/discourse/app/components/edit-category-tags.gjsindex d287d25aac2,e826255f0aa..308ce016b4d--- a/app/assets/javascripts/discourse/app/components/edit-category-tags.gjs+++ b/app/assets/javascripts/discourse/app/components/edit-category-tags.gjs@@@ -1,85 -1,29 +1,115 @@@+ import { action, set } from "@ember/object";+ import { and, empty } from "@ember/object/computed";+ import { buildCategoryPanel } from "discourse/components/edit-category-panel";++ export default class EditCategoryTags extends buildCategoryPanel("tags") {+ @empty("category.allowed_tags") allowedTagsEmpty;+ @empty("category.allowed_tag_groups") allowedTagGroupsEmpty;+ @and("allowedTagsEmpty", "allowedTagGroupsEmpty") disableAllowGlobalTags;++ @action+ onTagGroupChange(rtg, valueArray) {+ // A little strange, but we're using a multi-select component+ // to select a single tag group. This action takes the array+ // and extracts the first value in it.+ set(rtg, "name", valueArray[0]);+ }++ @action+ addRequiredTagGroup() {+ this.category.required_tag_groups.pushObject({+ min_count: 1,+ });+ }++ @action+ deleteRequiredTagGroup(rtg) {+ this.category.required_tag_groups.removeObject(rtg);+ }+ }+++<section class="field minimum-required-tags">+ <label for="category-minimum-tags">+ {{i18n "category.minimum_required_tags"}}+ </label>+ <TextField+ @value={{this.category.minimum_required_tags}}+ @id="category-minimum-tags"+ @type="number"+ @min="0"+ />+</section>+<section class="field allowed-tags">+ <label>{{i18n "category.tags_allowed_tags"}}</label>+ <TagChooser+ @id="category-allowed-tags"+ @tags={{this.category.allowed_tags}}+ @everyTag={{true}}+ @excludeSynonyms={{true}}+ @unlimitedTagCount={{true}}+ @onChange={{fn (mut this.category.allowed_tags)}}+ @options={{hash filterPlaceholder="category.tags_placeholder"}}+ />+</section>++<section class="field allowed-tag-groups">+ <label>{{i18n "category.tags_allowed_tag_groups"}}</label>+ <TagGroupChooser+ @id="category-allowed-tag-groups"+ @tagGroups={{this.category.allowed_tag_groups}}+ @onChange={{fn (mut this.category.allowed_tag_groups)}}+ />+ <LinkTo @route="tagGroups" class="manage-tag-groups">{{i18n+ "category.manage_tag_groups_link"+ }}</LinkTo>+</section>++<section class="field allow-global-tags">+ <label>+ <Input+ @type="checkbox"+ @checked={{this.category.allow_global_tags}}+ id="allow_global_tags"+ disabled={{this.disableAllowGlobalTags}}+ />+ {{i18n "category.allow_global_tags_label"}}+ </label>+</section>++<section class="field tags-tab-description">+ {{i18n "category.tags_tab_description"}}+</section>++<section class="field required-tag-group-description">+ {{i18n "category.required_tag_group.description"}}+</section>++<section class="field with-items">+ <section class="field-item required-tag-groups">+ {{#each this.category.required_tag_groups as |rtg|}}+ <div class="required-tag-group-row">+ <TextField @value={{rtg.min_count}} @type="number" @min="1" />+ <TagGroupChooser+ @tagGroups={{if rtg.name (array rtg.name) (array)}}+ @onChange={{action "onTagGroupChange" rtg}}+ @options={{hash+ maximum=1+ filterPlaceholder="category.required_tag_group.placeholder"+ }}+ />+ <DButton+ @label="category.required_tag_group.delete"+ @action={{fn this.deleteRequiredTagGroup rtg}}+ @icon="trash-can"+ class="delete-required-tag-group"+ />+ </div>+ {{/each}}+ <DButton+ @label="category.required_tag_group.add"+ @action={{this.addRequiredTagGroup}}+ @icon="plus"+ class="btn-default add-required-tag-group"+ />+ </section>+</section>diff --cc app/assets/javascripts/discourse/app/components/edit-category-topic-template.gjsindex 4449b113bfb,31bed394f15..dc26c252534--- a/app/assets/javascripts/discourse/app/components/edit-category-topic-template.gjs+++ b/app/assets/javascripts/discourse/app/components/edit-category-topic-template.gjs@@@ -1,38 -1,51 +1,90 @@@+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { schedule } from "@ember/runloop";+ import { observes } from "@ember-decorators/object";+ import { buildCategoryPanel } from "discourse/components/edit-category-panel";+ import discourseComputed from "discourse/lib/decorators";++ export default class EditCategoryTopicTemplate extends buildCategoryPanel(+ "topic-template"+ ) {+ @tracked _showFormTemplateOverride;++ get showFormTemplate() {+ return (+ this._showFormTemplateOverride ??+ Boolean(this.category.get("form_template_ids.length"))+ );+ }++ set showFormTemplate(value) {+ this._showFormTemplateOverride = value;+ }++ @discourseComputed("showFormTemplate")+ templateTypeToggleLabel(showFormTemplate) {+ if (showFormTemplate) {+ return "admin.form_templates.edit_category.toggle_form_template";+ }++ return "admin.form_templates.edit_category.toggle_freeform";+ }++ @action+ toggleTemplateType() {+ this.toggleProperty("showFormTemplate");++ if (!this.showFormTemplate) {+ // Clear associated form templates if switching to freeform+ this.set("category.form_template_ids", []);+ }+ }++ @observes("activeTab", "showFormTemplate")+ _activeTabChanged() {+ if (this.activeTab && !this.showFormTemplate) {+ schedule("afterRender", () =>+ this.element.querySelector(".d-editor-input").focus()+ );+ }+ }+ }+++{{#if this.siteSettings.experimental_form_templates}}+ <div class="control-group">+ <DToggleSwitch+ class="toggle-template-type"+ @state={{this.showFormTemplate}}+ @label={{this.templateTypeToggleLabel}}+ {{on "click" this.toggleTemplateType}}+ />+ </div>++ {{#if this.showFormTemplate}}+ <div class="control-group">+ <FormTemplateChooser+ @value={{this.category.form_template_ids}}+ @onChange={{fn (mut this.category.form_template_ids)}}+ class="select-category-template"+ />++ <p class="select-category-template__info desc">+ {{#if this.currentUser.staff}}+ <LinkTo @route="adminCustomizeFormTemplates">+ {{i18n "admin.form_templates.edit_category.select_template_help"}}+ </LinkTo>+ {{/if}}+ </p>+ </div>+ {{else}}+ <DEditor+ @value={{this.category.topic_template}}+ @showLink={{this.showInsertLinkButton}}+ />+ {{/if}}+{{else}}+ <DEditor+ @value={{this.category.topic_template}}+ @showLink={{this.showInsertLinkButton}}+ />+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/edit-topic-timer-form.gjsindex e6e4b39d04a,51feb782780..52810bf3b90--- a/app/assets/javascripts/discourse/app/components/edit-topic-timer-form.gjs+++ b/app/assets/javascripts/discourse/app/components/edit-topic-timer-form.gjs@@@ -1,71 -1,180 +1,252 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import { isEmpty } from "@ember/utils";+ import ItsATrap from "@discourse/itsatrap";+ import {+ BUMP_TYPE,+ CLOSE_AFTER_LAST_POST_STATUS_TYPE,+ CLOSE_STATUS_TYPE,+ DELETE_REPLIES_TYPE,+ DELETE_STATUS_TYPE,+ OPEN_STATUS_TYPE,+ PUBLISH_TO_CATEGORY_STATUS_TYPE,+ } from "discourse/components/modal/edit-topic-timer";+ import KeyboardShortcuts from "discourse/lib/keyboard-shortcuts";+ import {+ TIME_SHORTCUT_TYPES,+ timeShortcuts,+ } from "discourse/lib/time-shortcut";+ import { i18n } from "discourse-i18n";+ import { FORMAT } from "select-kit/components/future-date-input-selector";++ export default class EditTopicTimerForm extends Component {+ @service currentUser;++ @tracked timerType;++ constructor() {+ super(...arguments);++ KeyboardShortcuts.pause();+ this._itsatrap = new ItsATrap();+ }++ willDestroy() {+ super.willDestroy(...arguments);++ this._itsatrap.destroy();+ KeyboardShortcuts.unpause();+ }++ get showTimeOnly() {+ return (+ this.statusType === OPEN_STATUS_TYPE ||+ this.statusType === DELETE_STATUS_TYPE ||+ this.statusType === BUMP_TYPE+ );+ }++ get showFutureDateInput() {+ return (+ this.showTimeOnly ||+ this.publishToCategory ||+ this.statusType === CLOSE_STATUS_TYPE+ );+ }++ get useDuration() {+ return this.autoCloseAfterLastPost || this.autoDeleteReplies;+ }++ get autoCloseAfterLastPost() {+ return this.statusType === CLOSE_AFTER_LAST_POST_STATUS_TYPE;+ }++ get publishToCategory() {+ return this.statusType === PUBLISH_TO_CATEGORY_STATUS_TYPE;+ }++ get autoDeleteReplies() {+ return this.statusType === DELETE_REPLIES_TYPE;+ }++ get statusType() {+ return this.args.topicTimer.status_type;+ }++ get excludeCategoryId() {+ if (this.args.topic.visible) {+ return this.args.topic.category_id;+ }+ }++ get timeOptions() {+ const timezone = this.currentUser.user_option.timezone;+ const shortcuts = timeShortcuts(timezone);++ return [+ shortcuts.laterToday(),+ shortcuts.tomorrow(),+ shortcuts.laterThisWeek(),+ shortcuts.thisWeekend(),+ shortcuts.monday(),+ shortcuts.twoWeeks(),+ shortcuts.nextMonth(),+ shortcuts.sixMonths(),+ ];+ }++ get hiddenTimeShortcutOptions() {+ return [+ TIME_SHORTCUT_TYPES.NONE,+ TIME_SHORTCUT_TYPES.LATER_TODAY,+ TIME_SHORTCUT_TYPES.LATER_THIS_WEEK,+ ];+ }++ get executeAt() {+ if (this.useDuration) {+ return moment()+ .add(parseFloat(this.args.topicTimer.duration_minutes), "minutes")+ .format(FORMAT);+ } else {+ return this.args.topicTimer.updateTime;+ }+ }++ get willCloseImmediately() {+ if (this.autoCloseAfterLastPost && this.args.topicTimer.duration_minutes) {+ const closeDate = moment(this.args.topic.last_posted_at).add(+ this.args.topicTimer.duration_minutes,+ "minutes"+ );+ return closeDate < moment();+ }+ }++ get willCloseI18n() {+ if (this.autoCloseAfterLastPost) {+ const diff = Math.round(+ (new Date() - new Date(this.args.topic.last_posted_at)) /+ (1000 * 60 * 60)+ );+ return i18n("topic.auto_close_momentarily", { count: diff });+ }+ }++ get durationLabel() {+ return i18n(+ `topic.topic_status_update.num_of_${+ this.autoDeleteReplies ? "days" : "hours"+ }`+ );+ }++ get showTopicTimerInfo() {+ if (!this.statusType || this.willCloseImmediately) {+ return false;+ }++ if (+ this.statusType === PUBLISH_TO_CATEGORY_STATUS_TYPE &&+ isEmpty(this.args.topicTimer.category_id)+ ) {+ return false;+ }++ if (this.timerType === "custom" && this.args.topicTimer.updateTime) {+ if (moment(this.args.topicTimer.updateTime) < moment()) {+ return false;+ }+ } else if (this.useDuration) {+ return this.args.topicTimer.duration_minutes;+ }++ return this.args.topicTimer.updateTime;+ }++ @action+ onTimeSelected(type, time) {+ this.timerType = type;+ this.args.onChangeInput(type, time);+ }++ @action+ changeDuration(newDurationMins) {+ this.args.topicTimer.duration_minutes = newDurationMins;+ }+ }+++<form>+ <div class="control-group">+ <DSelect+ @value={{this.statusType}}+ class="timer-type"+ @onChange={{@onChangeStatusType}}+ as |select|+ >+ {{#each @timerTypes as |timer|}}+ <select.Option @value={{timer.id}}>{{timer.name}}</select.Option>+ {{/each}}+ </DSelect>+ </div>++ {{#if this.publishToCategory}}+ <div class="control-group">+ <label class="control-label">+ {{i18n "topic.topic_status_update.publish_to"}}+ </label>+ <CategoryChooser+ @value={{@topicTimer.category_id}}+ @onChange={{fn (mut @topicTimer.category_id)}}+ @options={{hash excludeCategoryId=this.excludeCategoryId}}+ />+ </div>+ {{/if}}++ {{#if this.showFutureDateInput}}+ <label class="control-label">+ {{i18n "topic.topic_status_update.when"}}+ </label>+ <TimeShortcutPicker+ @timeShortcuts={{this.timeOptions}}+ @prefilledDatetime={{@topicTimer.execute_at}}+ @onTimeSelected={{this.onTimeSelected}}+ @hiddenOptions={{this.hiddenTimeShortcutOptions}}+ @_itsatrap={{this._itsatrap}}+ />+ {{/if}}++ {{#if this.useDuration}}+ <div class="controls">+ <label class="control-label">+ {{i18n "topic.topic_status_update.duration"}}+ </label>+ <RelativeTimePicker+ @onChange={{this.changeDuration}}+ @durationMinutes={{@topicTimer.duration_minutes}}+ />+ </div>+ {{/if}}++ {{#if this.willCloseImmediately}}+ <div class="warning">+ {{d-icon "triangle-exclamation"}}+ {{this.willCloseI18n}}+ </div>+ {{/if}}++ {{#if this.showTopicTimerInfo}}+ <div class="alert alert-info modal-topic-timer-info">+ <TopicTimerInfo+ @statusType={{this.statusType}}+ @executeAt={{this.executeAt}}+ @basedOnLastPost={{@topicTimer.based_on_last_post}}+ @durationMinutes={{@topicTimer.duration_minutes}}+ @categoryId={{@topicTimer.category_id}}+ />+ </div>+ {{/if}}+</form>diff --cc app/assets/javascripts/discourse/app/components/future-date-input.gjsindex c151ce42169,2407ccd8678..ee148230e10--- a/app/assets/javascripts/discourse/app/components/future-date-input.gjs+++ b/app/assets/javascripts/discourse/app/components/future-date-input.gjs@@@ -1,42 -1,126 +1,169 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { and, empty, equal } from "@ember/object/computed";+ import discourseComputed from "discourse/lib/decorators";+ import {+ extendedDefaultTimeShortcuts,+ formatTime,+ hideDynamicTimeShortcuts,+ TIME_SHORTCUT_TYPES,+ timeShortcuts,+ } from "discourse/lib/time-shortcut";+ import { i18n } from "discourse-i18n";+ import { FORMAT } from "select-kit/components/future-date-input-selector";++ export default class FutureDateInput extends Component {+ selection = null;+ includeDateTime = true;++ @equal("selection", "custom") isCustom;+ @and("includeDateTime", "isCustom") displayDateAndTimePicker;+ @empty("_date") timeInputDisabled;++ displayLabel = null;+ labelClasses = null;+ userTimezone = null;+ onChangeInput = null;+ _date = null;+ _time = null;++ init() {+ super.init(...arguments);+ this.userTimezone = this.currentUser.user_option.timezone;+ }++ didReceiveAttrs() {+ super.didReceiveAttrs(...arguments);++ if (this.label) {+ this.set("displayLabel", i18n(this.label));+ }++ if (this.input) {+ const dateTime = moment(this.input);+ const closestShortcut = this._findClosestShortcut(dateTime);+ if (!this.noRelativeOptions && closestShortcut) {+ this.set("selection", closestShortcut.id);+ } else {+ this.setProperties({+ selection: TIME_SHORTCUT_TYPES.CUSTOM,+ _date: dateTime.format("YYYY-MM-DD"),+ _time: dateTime.format("HH:mm"),+ });+ }+ }+ }++ @discourseComputed("customShortcuts")+ shortcuts(customShortcuts) {+ let shortcuts;+ if (customShortcuts && customShortcuts.length) {+ shortcuts = customShortcuts;+ } else {+ shortcuts = extendedDefaultTimeShortcuts(this.userTimezone);+ }++ const shortcutsFactory = timeShortcuts(this.userTimezone);+ if (this.includeDateTime) {+ shortcuts.push(shortcutsFactory.custom());+ }+ if (this.includeNow) {+ shortcuts.push(shortcutsFactory.now());+ }++ shortcuts = hideDynamicTimeShortcuts(+ shortcuts,+ this.userTimezone,+ this.siteSettings+ );++ return shortcuts.map((s) => {+ return {+ id: s.id,+ name: i18n(s.label),+ time: s.time,+ timeFormatted: formatTime(s),+ icon: s.icon,+ };+ });+ }++ @action+ onChangeDate(date) {+ if (!date) {+ this.set("_time", null);+ }++ this._dateTimeChanged(date, this._time);+ }++ @action+ onChangeTime(time) {+ if (this._date) {+ this._dateTimeChanged(this._date, time);+ }+ }++ _dateTimeChanged(date, time) {+ time = time ? ` ${time}` : "";+ const dateTime = moment(`${date}${time}`);++ if (dateTime.isValid()) {+ this.onChangeInput?.(dateTime.format(FORMAT));+ } else {+ this.onChangeInput?.(null);+ }+ }++ _findClosestShortcut(dateTime) {+ return this.shortcuts.find((tf) => {+ if (tf.time) {+ const diff = tf.time.diff(dateTime);+ return 0 <= diff && diff < 60 * 1000;+ }+ });+ }+ }+++<div class="future-date-input">+ {{#unless this.noRelativeOptions}}+ <div class="control-group">+ <label class={{this.labelClasses}}>+ {{#if this.displayLabelIcon}}{{d-icon+ this.displayLabelIcon+ }}{{/if}}{{this.displayLabel}}+ </label>+ <FutureDateInputSelector+ @value={{readonly this.selection}}+ @content={{this.shortcuts}}+ @clearable={{this.clearable}}+ @onChangeInput={{this.onChangeInput}}+ @onChange={{fn (mut this.selection)}}+ @options={{hash none="time_shortcut.select_timeframe"}}+ />+ </div>+ {{/unless}}++ {{#if this.displayDateAndTimePicker}}+ <div class="control-group future-date-input-date-picker">+ {{d-icon "calendar-days"}}+ <DatePickerFuture+ @value={{this._date}}+ @defaultDate={{this._date}}+ @onSelect={{action "onChangeDate"}}+ />+ </div>++ <div class="control-group future-date-input-time-picker">+ {{d-icon "far-clock"}}+ <Input+ placeholder="--:--"+ @type="time"+ class="time-input"+ @value={{this._time}}+ disabled={{this.timeInputDisabled}}+ {{on "input" (with-event-value this.onChangeTime)}}+ />+ </div>+ {{/if}}+</div>diff --cc app/assets/javascripts/discourse/app/components/group-flair-inputs.gjsindex b1fe41d6399,de03bbc4d9b..d77353b96e7--- a/app/assets/javascripts/discourse/app/components/group-flair-inputs.gjs+++ b/app/assets/javascripts/discourse/app/components/group-flair-inputs.gjs@@@ -1,111 -1,96 +1,208 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { classNames } from "@ember-decorators/component";+ import { observes, on } from "@ember-decorators/object";+ import $ from "jquery";+ import { ajax } from "discourse/lib/ajax";+ import discourseDebounce from "discourse/lib/debounce";+ import discourseComputed from "discourse/lib/decorators";+ import getURL from "discourse/lib/get-url";+ import { convertIconClass } from "discourse/lib/icon-library";+ import { i18n } from "discourse-i18n";++ @classNames("group-flair-inputs")+ export default class GroupFlairInputs extends Component {+ @discourseComputed+ demoAvatarUrl() {+ return getURL("/images/avatar.png");+ }++ @discourseComputed("model.flair_type")+ flairPreviewIcon(flairType) {+ return flairType && flairType === "icon";+ }++ @discourseComputed("model.flair_icon")+ flairPreviewIconUrl(flairIcon) {+ return flairIcon ? convertIconClass(flairIcon) : "";+ }++ @on("didInsertElement")+ @observes("model.flair_icon")+ _loadSVGIcon(flairIcon) {+ if (flairIcon) {+ discourseDebounce(this, this._loadIcon, 1000);+ }+ }++ _loadIcon() {+ if (!this.model.flair_icon) {+ return;+ }++ const icon = convertIconClass(this.model.flair_icon),+ c = "#svg-sprites",+ h = "ajax-icon-holder",+ singleIconEl = `${c} .${h}`;++ if (!icon) {+ return;+ }++ if (!$(`${c} symbol#${icon}`).length) {+ ajax(`/svg-sprite/search/${icon}`).then(function (data) {+ if ($(singleIconEl).length === 0) {+ $(c).append(`<div class="${h}">`);+ }++ $(singleIconEl).html(+ `<svg xmlns='http://www.w3.org/2000/svg' style='display: none;'>${data}</svg>`+ );+ });+ }+ }++ @discourseComputed("model.flair_type")+ flairPreviewImage(flairType) {+ return flairType && flairType === "image";+ }++ @discourseComputed("model.flair_url")+ flairImageUrl(flairUrl) {+ return flairUrl && flairUrl.includes("/") ? flairUrl : null;+ }++ @discourseComputed("flairPreviewImage")+ flairPreviewLabel(flairPreviewImage) {+ const key = flairPreviewImage ? "image" : "icon";+ return i18n(`groups.flair_preview_${key}`);+ }++ @action+ setFlairImage(upload) {+ this.model.setProperties({+ flair_url: getURL(upload.url),+ flair_upload_id: upload.id,+ });+ }++ @action+ removeFlairImage() {+ this.model.setProperties({+ flair_url: null,+ flair_upload_id: null,+ });+ }+ }+++<div class="control-group">+ <label class="control-label" for="flair_url">{{i18n+ "groups.flair_url"+ }}</label>++ <div class="radios">+ <label class="radio-label" for="avatar-flair-icon">+ <RadioButton+ @name="avatar-flair-icon"+ @id="avatar-flair-icon"+ @value="icon"+ @selection={{this.model.flair_type}}+ />+ {{i18n "groups.flair_type.icon"}}+ </label>++ <label class="radio-label" for="avatar-flair-image">+ <RadioButton+ @name="avatar-flair-image"+ @id="avatar-flair-image"+ @value="image"+ @selection={{this.model.flair_type}}+ />+ {{i18n "groups.flair_type.image"}}+ </label>+ </div>++ {{#if this.flairPreviewIcon}}+ <IconPicker+ @name="icon"+ @value={{this.model.flair_icon}}+ @options={{hash maximum=1}}+ @onChange={{fn (mut this.model.flair_icon)}}+ />+ {{else if this.flairPreviewImage}}+ <UppyImageUploader+ @imageUrl={{this.flairImageUrl}}+ @onUploadDone={{action "setFlairImage"}}+ @onUploadDeleted={{action "removeFlairImage"}}+ @type="group_flair"+ @id="group-flair-uploader"+ class="no-repeat contain-image"+ />+ <div class="control-instructions">+ {{i18n "groups.flair_upload_description"}}+ </div>+ {{/if}}+</div>++<div class="control-group">+ <label class="control-label" for="flair_bg_color">{{i18n+ "groups.flair_bg_color"+ }}</label>++ <TextField+ @name="flair_bg_color"+ @value={{this.model.flair_bg_color}}+ @placeholderKey="groups.flair_bg_color_placeholder"+ class="group-flair-bg-color input-xxlarge"+ />+</div>++{{#if this.flairPreviewIcon}}+ <div class="control-group">+ <label class="control-label" for="flair_color">{{i18n+ "groups.flair_color"+ }}</label>++ <TextField+ @name="flair_color"+ @value={{this.model.flair_color}}+ @placeholderKey="groups.flair_color_placeholder"+ class="group-flair-color input-xxlarge"+ />+ </div>+{{/if}}++<div class="control-group">+ <label class="control-label">{{this.flairPreviewLabel}}</label>++ <div class="avatar-flair-preview">+ <div class="avatar-wrapper">+ <img+ width="45"+ height="45"+ src={{this.demoAvatarUrl}}+ class="avatar actor"+ alt=""+ />+ </div>++ {{#if+ (or+ this.model.flair_icon+ this.flairImageUrl+ this.model.flairBackgroundHexColor+ )+ }}+ <AvatarFlair+ @flairName={{this.model.name}}+ @flairUrl={{if+ this.flairPreviewIcon+ this.model.flair_icon+ (if this.flairPreviewImage this.flairImageUrl "")+ }}+ @flairBgColor={{this.model.flairBackgroundHexColor}}+ @flairColor={{this.model.flairHexColor}}+ />+ {{/if}}+ </div>+</div>diff --cc app/assets/javascripts/discourse/app/components/group-imap-email-settings.gjsindex 0045931ff1d,280baa2c0c9..06b0ed92d61--- a/app/assets/javascripts/discourse/app/components/group-imap-email-settings.gjs+++ b/app/assets/javascripts/discourse/app/components/group-imap-email-settings.gjs@@@ -1,123 -1,91 +1,215 @@@+ import Component from "@ember/component";+ import EmberObject, { action } from "@ember/object";+ import { isEmpty } from "@ember/utils";+ import { tagName } from "@ember-decorators/component";+ import { on } from "@ember-decorators/object";+ import { ajax } from "discourse/lib/ajax";+ import { popupAjaxError } from "discourse/lib/ajax-error";+ import discourseComputed from "discourse/lib/decorators";+ import emailProviderDefaultSettings from "discourse/lib/email-provider-default-settings";++ @tagName("")+ export default class GroupImapEmailSettings extends Component {+ form = null;++ @discourseComputed(+ "group.email_username",+ "group.email_password",+ "form.imap_server",+ "form.imap_port"+ )+ missingSettings(email_username, email_password, imap_server, imap_port) {+ return [email_username, email_password, imap_server, imap_port].some(+ (value) => isEmpty(value)+ );+ }++ @discourseComputed("group.imap_mailboxes")+ mailboxes(imapMailboxes) {+ if (!imapMailboxes) {+ return [];+ }+ return imapMailboxes.map((mailbox) => ({ name: mailbox, value: mailbox }));+ }++ @discourseComputed("group.imap_mailbox_name", "mailboxes.length")+ mailboxSelected(mailboxName, mailboxesSize) {+ return mailboxesSize === 0 || !isEmpty(mailboxName);+ }++ @action+ resetSettingsValid() {+ this.set("imapSettingsValid", false);+ }++ @on("init")+ _fillForm() {+ this.set(+ "form",+ EmberObject.create({+ imap_server: this.group.imap_server,+ imap_port: (this.group.imap_port || "").toString(),+ imap_ssl: this.group.imap_ssl,+ })+ );+ }++ @action+ prefillSettings(provider, event) {+ event?.preventDefault();+ this.form.setProperties(emailProviderDefaultSettings(provider, "imap"));+ }++ @action+ testImapSettings() {+ const settings = {+ host: this.form.imap_server,+ port: this.form.imap_port,+ ssl: this.form.imap_ssl,+ username: this.group.email_username,+ password: this.group.email_password,+ };++ this.set("testingSettings", true);+ this.set("imapSettingsValid", false);++ return ajax(`/groups/${this.group.id}/test_email_settings`, {+ type: "POST",+ data: Object.assign(settings, { protocol: "imap" }),+ })+ .then(() => {+ this.set("imapSettingsValid", true);+ this.group.setProperties({+ imap_server: this.form.imap_server,+ imap_port: this.form.imap_port,+ imap_ssl: this.form.imap_ssl,+ });+ })+ .catch(popupAjaxError)+ .finally(() => this.set("testingSettings", false));+ }+ }+++<div class="group-imap-email-settings">+ <form class="groups-form form-horizontal groups-form-imap">+ <div>+ <div class="control-group">+ <label for="imap_server">{{i18n+ "groups.manage.email.credentials.imap_server"+ }}</label>+ <Input+ @type="text"+ name="imap_server"+ @value={{this.form.imap_server}}+ tabindex="8"+ {{on "change" (action "resetSettingsValid")}}+ />+ </div>++ <label for="enable_ssl_imap" class="groups-form__enable-ssl">+ <Input+ @type="checkbox"+ @checked={{this.form.imap_ssl}}+ id="enable_ssl_imap"+ tabindex="11"+ {{on "change" (action "resetSettingsValid")}}+ />+ {{i18n "groups.manage.email.credentials.imap_ssl"}}+ </label>+ </div>++ <div>+ <div class="control-group">+ <label for="imap_port">{{i18n+ "groups.manage.email.credentials.imap_port"+ }}</label>+ <Input+ @type="text"+ name="imap_port"+ @value={{this.form.imap_port}}+ tabindex="9"+ {{on "change" (action "resetSettingsValid" this.form.imap_port)}}+ />+ </div>+ </div>++ <div>+ <div class="control-group group-imap-mailboxes">+ {{#if this.mailboxes}}+ <label for="imap_mailbox_name">{{i18n+ "groups.manage.email.mailboxes.synchronized"+ }}</label>+ <ComboBox+ @name="imap_mailbox_name"+ @id="imap_mailbox"+ @value={{this.group.imap_mailbox_name}}+ @valueProperty="value"+ @content={{this.mailboxes}}+ @tabindex="10"+ @onChange={{fn (mut this.group.imap_mailbox_name)}}+ @options={{hash none="groups.manage.email.mailboxes.disabled"}}+ />+ {{/if}}+ </div>++ </div>+ </form>++ <div class="control-group">+ <div class="group-imap-prefill-options">+ {{i18n "groups.manage.email.prefill.title"}}+ <a+ id="prefill_imap_gmail"+ href+ {{on "click" (fn this.prefillSettings "gmail")}}+ >{{i18n "groups.manage.email.prefill.gmail"}}</a>+ </div>+ </div>++ {{#unless this.mailboxSelected}}+ <div class="alert alert-error imap-no-mailbox-selected">+ {{i18n "groups.manage.email.imap_mailbox_not_selected"}}+ </div>+ {{/unless}}++ <div class="control-group buttons">+ <DButton+ @disabled={{or this.missingSettings this.testingSettings}}+ @action={{this.testImapSettings}}+ @icon="gear"+ @label="groups.manage.email.test_settings"+ @title="groups.manage.email.settings_required"+ tabindex="12"+ class="btn-primary test-imap-settings"+ />++ <ConditionalLoadingSpinner+ @size="small"+ @condition={{this.testingSettings}}+ />++ {{#if this.imapSettingsValid}}+ <span class="imap-settings-ok">+ {{d-icon "circle-check"}}+ {{i18n "groups.manage.email.imap_settings_valid"}}+ </span>+ {{/if}}+ </div>++ {{#if this.group.imap_updated_at}}+ <div class="group-email-last-updated-details for-imap">+ <small>+ {{i18n "groups.manage.email.last_updated"}}+ <strong>{{format-date+ this.group.imap_updated_at+ leaveAgo="true"+ }}</strong>+ {{i18n "groups.manage.email.last_updated_by"}}+ <LinkTo+ @route="user"+ @model={{this.group.imap_updated_by.username}}+ >{{this.group.imap_updated_by.username}}</LinkTo>+ </small>+ </div>+ {{/if}}+</div>diff --cc app/assets/javascripts/discourse/app/components/groups-form-interaction-fields.gjsindex 0072f9145c3,37d9a97670b..c288990d023--- a/app/assets/javascripts/discourse/app/components/groups-form-interaction-fields.gjs+++ b/app/assets/javascripts/discourse/app/components/groups-form-interaction-fields.gjs@@@ -1,144 -1,94 +1,239 @@@+ import Component from "@ember/component";+ import { or } from "@ember/object/computed";+ import discourseComputed from "discourse/lib/decorators";+ import { NotificationLevels } from "discourse/lib/notification-levels";+ import { i18n } from "discourse-i18n";++ export default class GroupsFormInteractionFields extends Component {+ @or(+ "model.members_visibility_level",+ "visibilityLevelOptions.firstObject.value"+ )+ membersVisibilityLevel;++ @or("model.messageable_level", "aliasLevelOptions.firstObject.value")+ messageableLevel;++ @or("model.mentionable_level", "aliasLevelOptions.firstObject.value")+ mentionableLevel;++ visibilityLevelOptions = [+ {+ name: i18n("admin.groups.manage.interaction.visibility_levels.public"),+ value: 0,+ },+ {+ name: i18n(+ "admin.groups.manage.interaction.visibility_levels.logged_on_users"+ ),+ value: 1,+ },+ {+ name: i18n("admin.groups.manage.interaction.visibility_levels.members"),+ value: 2,+ },+ {+ name: i18n("admin.groups.manage.interaction.visibility_levels.staff"),+ value: 3,+ },+ {+ name: i18n("admin.groups.manage.interaction.visibility_levels.owners"),+ value: 4,+ },+ ];++ aliasLevelOptions = [+ { name: i18n("groups.alias_levels.nobody"), value: 0 },+ { name: i18n("groups.alias_levels.only_admins"), value: 1 },+ { name: i18n("groups.alias_levels.mods_and_admins"), value: 2 },+ { name: i18n("groups.alias_levels.members_mods_and_admins"), value: 3 },+ { name: i18n("groups.alias_levels.owners_mods_and_admins"), value: 4 },+ { name: i18n("groups.alias_levels.everyone"), value: 99 },+ ];++ watchingNotificationLevel = NotificationLevels.WATCHING;++ @discourseComputed(+ "model.default_notification_level",+ "watchingNotificationLevel"+ )+ defaultNotificationLevel(+ defaultNotificationLevel,+ watchingNotificationLevel+ ) {+ if (Object.values(NotificationLevels).includes(defaultNotificationLevel)) {+ return defaultNotificationLevel;+ }+ return watchingNotificationLevel;+ }++ @discourseComputed(+ "siteSettings.email_in",+ "model.automatic",+ "currentUser.admin"+ )+ showEmailSettings(emailIn, automatic, isAdmin) {+ return emailIn && isAdmin && !automatic;+ }++ @discourseComputed(+ "model.isCreated",+ "model.can_admin_group",+ "currentUser.can_create_group"+ )+ canAdminGroup(isCreated, canAdmin, canCreate) {+ return (!isCreated && canCreate) || (isCreated && canAdmin);+ }++ @discourseComputed("membersVisibilityLevel")+ membersVisibilityPrivate(membersVisibilityLevel) {+ return (+ membersVisibilityLevel !== this.visibilityLevelOptions.firstObject.value+ );+ }+ }+++{{#if this.canAdminGroup}}+ <div class="control-group">+ <label class="control-label">+ {{i18n "admin.groups.manage.interaction.visibility"}}+ </label>+ <label>+ {{i18n "admin.groups.manage.interaction.visibility_levels.title"}}+ </label>++ <ComboBox+ @name="alias"+ @valueProperty="value"+ @value={{this.model.visibility_level}}+ @content={{this.visibilityLevelOptions}}+ @onChange={{fn (mut this.model.visibility_level)}}+ @options={{hash castInteger=true}}+ class="groups-form-visibility-level"+ />++ <div class="control-instructions">+ {{i18n "admin.groups.manage.interaction.visibility_levels.description"}}+ </div>+ </div>++ <div class="control-group">+ <label>+ {{i18n "admin.groups.manage.interaction.members_visibility_levels.title"}}+ </label>++ <ComboBox+ @name="alias"+ @valueProperty="value"+ @value={{this.membersVisibilityLevel}}+ @content={{this.visibilityLevelOptions}}+ @onChange={{fn (mut this.model.members_visibility_level)}}+ class="groups-form-members-visibility-level"+ />++ {{#if this.membersVisibilityPrivate}}+ <div class="control-instructions">+ {{i18n+ "admin.groups.manage.interaction.members_visibility_levels.description"+ }}+ </div>+ {{/if}}+ </div>+{{/if}}++<div class="control-group">+ <label class="control-label">+ {{i18n "groups.manage.interaction.posting"}}+ </label>+ <label for="alias">{{i18n "groups.alias_levels.mentionable"}}</label>++ <ComboBox+ @name="alias"+ @valueProperty="value"+ @value={{this.mentionableLevel}}+ @content={{this.aliasLevelOptions}}+ @onChange={{fn (mut this.model.mentionable_level)}}+ class="groups-form-mentionable-level"+ />+</div>++<div class="control-group">+ <label for="alias">{{i18n "groups.alias_levels.messageable"}}</label>++ <ComboBox+ @name="alias"+ @valueProperty="value"+ @value={{this.messageableLevel}}+ @content={{this.aliasLevelOptions}}+ @onChange={{fn (mut this.model.messageable_level)}}+ class="groups-form-messageable-level"+ />+</div>++{{#if this.canAdminGroup}}+ <div class="control-group">+ <label>+ <Input+ @type="checkbox"+ @checked={{this.model.publish_read_state}}+ class="groups-form-publish-read-state"+ />++ {{i18n "admin.groups.manage.interaction.publish_read_state"}}+ </label>+ </div>+{{/if}}++{{#if this.showEmailSettings}}+ <div class="control-group">+ <label class="control-label">+ {{i18n "admin.groups.manage.interaction.email"}}+ </label>+ <label for="incoming_email">+ {{i18n "admin.groups.manage.interaction.incoming_email"}}+ </label>++ <TextField+ @name="incoming_email"+ @value={{this.model.incoming_email}}+ @placeholderKey="admin.groups.manage.interaction.incoming_email_placeholder"+ class="input-xxlarge groups-form-incoming-email"+ />++ <DTooltip+ @icon="circle-info"+ @content={{i18n "admin.groups.manage.interaction.incoming_email_tooltip"}}+ />++ <span>+ <PluginOutlet+ @name="group-email-in"+ @connectorTagName="div"+ @outletArgs={{hash model=this.model}}+ />+ </span>+ </div>+{{/if}}++<label class="control-label">+ {{i18n "groups.manage.interaction.notification"}}+</label>++<div class="control-group">+ <label>{{i18n "groups.notification_level"}}</label>++ <NotificationsButton+ @value={{this.defaultNotificationLevel}}+ @options={{hash i18nPrefix="groups.notifications"}}+ @onChange={{fn (mut this.model.default_notification_level)}}+ class="groups-form-default-notification-level"+ />+</div>++<span>+ <PluginOutlet+ @name="groups-interaction-custom-options"+ @connectorTagName="div"+ @outletArgs={{hash model=this.model}}+ />+</span>diff --cc app/assets/javascripts/discourse/app/components/groups-form-membership-fields.gjsindex ae6ff24a7ff,4fe1e0460ff..152f9b3b31a--- a/app/assets/javascripts/discourse/app/components/groups-form-membership-fields.gjs+++ b/app/assets/javascripts/discourse/app/components/groups-form-membership-fields.gjs@@@ -1,153 -1,72 +1,226 @@@+ import Component from "@ember/component";+ import { action, computed } from "@ember/object";+ import { not, readOnly } from "@ember/object/computed";+ import discourseComputed from "discourse/lib/decorators";+ import AssociatedGroup from "discourse/models/associated-group";+ import { i18n } from "discourse-i18n";++ export default class GroupsFormMembershipFields extends Component {+ tokenSeparator = "|";++ @readOnly("site.can_associate_groups") showAssociatedGroups;+ @not("model.automatic") canEdit;++ trustLevelOptions = [+ {+ name: i18n("admin.groups.manage.membership.trust_levels_none"),+ value: 0,+ },+ { name: 1, value: 1 },+ { name: 2, value: 2 },+ { name: 3, value: 3 },+ { name: 4, value: 4 },+ ];++ init() {+ super.init(...arguments);++ if (this.showAssociatedGroups) {+ this.loadAssociatedGroups();+ }+ }++ @computed("model.grant_trust_level", "trustLevelOptions")+ get groupTrustLevel() {+ return (+ this.model.get("grant_trust_level") ||+ this.trustLevelOptions.firstObject.value+ );+ }++ @discourseComputed("model.visibility_level", "model.public_admission")+ disableMembershipRequestSetting(visibility_level, publicAdmission) {+ visibility_level = parseInt(visibility_level, 10);+ return publicAdmission || visibility_level > 1;+ }++ @discourseComputed(+ "model.visibility_level",+ "model.allow_membership_requests"+ )+ disablePublicSetting(visibility_level, allowMembershipRequests) {+ visibility_level = parseInt(visibility_level, 10);+ return allowMembershipRequests || visibility_level > 1;+ }++ @computed("model.emailDomains")+ get emailDomains() {+ return this.model.emailDomains.split(this.tokenSeparator).filter(Boolean);+ }++ loadAssociatedGroups() {+ AssociatedGroup.list().then((ags) => this.set("associatedGroups", ags));+ }++ @action+ onChangeEmailDomainsSetting(value) {+ this.set(+ "model.automatic_membership_email_domains",+ value.join(this.tokenSeparator)+ );+ }+ }+++<div class="control-group">+ <label class="control-label">{{i18n+ "groups.manage.membership.access"+ }}</label>++ <label>+ <Input+ @type="checkbox"+ class="group-form-public-admission"+ @checked={{this.model.public_admission}}+ disabled={{this.disablePublicSetting}}+ />++ {{i18n "groups.public_admission"}}+ </label>++ <label>+ <Input+ @type="checkbox"+ class="group-form-public-exit"+ @checked={{this.model.public_exit}}+ />++ {{i18n "groups.public_exit"}}+ </label>++ <label>+ <Input+ @type="checkbox"+ class="group-form-allow-membership-requests"+ @checked={{this.model.allow_membership_requests}}+ disabled={{this.disableMembershipRequestSetting}}+ />++ {{i18n "groups.allow_membership_requests"}}+ </label>++ {{#if this.model.allow_membership_requests}}+ <div>+ <label for="membership-request-template">+ {{i18n "groups.membership_request_template"}}+ </label>++ <ExpandingTextArea+ {{on+ "input"+ (with-event-value (fn (mut this.model.membership_request_template)))+ }}+ value={{this.model.membership_request_template}}+ name="membership-request-template"+ class="group-form-membership-request-template input-xxlarge"+ />+ </div>+ {{/if}}+</div>++{{#if this.model.can_admin_group}}+ <div class="control-group">+ <label class="control-label">{{i18n+ "admin.groups.manage.membership.automatic"+ }}</label>++ <label for="automatic_membership">+ {{i18n+ "admin.groups.manage.membership.automatic_membership_email_domains"+ }}+ </label>++ <ListSetting+ @name="automatic_membership"+ @value={{this.emailDomains}}+ @choices={{this.emailDomains}}+ @settingName="name"+ @nameProperty={{null}}+ @valueProperty={{null}}+ @onChange={{action "onChangeEmailDomainsSetting"}}+ @options={{hash allowAny=true}}+ class="group-form-automatic-membership-automatic"+ />++ {{#if this.showAssociatedGroups}}+ <label for="automatic_membership_associated_groups">+ {{i18n+ "admin.groups.manage.membership.automatic_membership_associated_groups"+ }}+ </label>++ <ListSetting+ @name="automatic_membership_associated_groups"+ @value={{this.model.associatedGroupIds}}+ @choices={{this.associatedGroups}}+ @settingName="name"+ @nameProperty="label"+ @valueProperty="id"+ @onChange={{fn (mut this.model.associated_group_ids)}}+ class="group-form-automatic-membership-associated-groups"+ />+ {{/if}}+ </div>++ <span>+ <PluginOutlet+ @name="groups-form-membership-below-automatic"+ @connectorTagName="div"+ @outletArgs={{hash model=this.model}}+ />+ </span>++ <div class="control-group">+ <label class="control-label">{{i18n+ "admin.groups.manage.membership.effects"+ }}</label>+ <label for="grant_trust_level">{{i18n+ "admin.groups.manage.membership.trust_levels_title"+ }}</label>++ <ComboBox+ @name="grant_trust_level"+ @valueProperty="value"+ @value={{this.groupTrustLevel}}+ @content={{this.trustLevelOptions}}+ @onChange={{fn (mut this.model.grant_trust_level)}}+ class="groups-form-grant-trust-level"+ />+ <label>+ <Input+ @type="checkbox"+ @checked={{this.model.primary_group}}+ class="groups-form-primary-group"+ />++ {{i18n "admin.groups.manage.membership.primary_group"}}+ </label>+ </div>++ <div class="control-group">+ <label class="control-label" for="title">+ {{i18n "admin.groups.default_title"}}+ </label>++ <Input @value={{this.model.title}} name="title" class="input-xxlarge" />++ <div class="control-instructions">+ {{i18n "admin.groups.default_title_description"}}+ </div>+ </div>+{{/if}}++{{#if this.canEdit}}+ <div class="control-group">+ <GroupFlairInputs @model={{this.model}} />+ </div>+{{/if}}diff --cc app/assets/javascripts/discourse/app/components/invite-panel.gjsindex 6f92be475ab,5ffb02c248e..c03d32b8f5f--- a/app/assets/javascripts/discourse/app/components/invite-panel.gjs+++ b/app/assets/javascripts/discourse/app/components/invite-panel.gjs@@@ -1,115 -1,444 +1,560 @@@+ import Component from "@ember/component";+ import EmberObject, { action } from "@ember/object";+ import { alias, and, equal, readOnly } from "@ember/object/computed";+ import { service } from "@ember/service";+ import { isEmpty } from "@ember/utils";+ import { computedI18n } from "discourse/lib/computed";+ import discourseComputed from "discourse/lib/decorators";+ import { getNativeContact } from "discourse/lib/pwa-utils";+ import { emailValid } from "discourse/lib/utilities";+ import { i18n } from "discourse-i18n";++ export default class InvitePanel extends Component {+ @service site;++ @readOnly("currentUser.staff") isStaff;+ @readOnly("currentUser.admin") isAdmin;+ @alias("inviteModel.id") topicId;+ @equal("inviteModel.archetype", "private_message") isPM;+ @and("isStaff", "siteSettings.must_approve_users") showApprovalMessage;++ // eg: visible only to specific group members+ @and("invitingToTopic", "inviteModel.category.read_restricted")+ isPrivateTopic;++ // scope to allowed usernames+ @alias("invitingToTopic") allowExistingMembers;++ @computedI18n("invite.custom_message_placeholder") customMessagePlaceholder;++ groupIds = null;+ allGroups = null;++ // invitee is either a user, group or email+ invitee = null;++ isInviteeGroup = false;+ hasCustomMessage = false;+ customMessage = null;+ inviteIcon = "envelope";+ invitingExistingUserToTopic = false;++ init() {+ super.init(...arguments);+ this.setDefaultSelectedGroups();+ this.setGroupOptions();+ }++ willDestroyElement() {+ super.willDestroyElement(...arguments);+ this.reset();+ }++ @discourseComputed(+ "isAdmin",+ "invitee",+ "invitingToTopic",+ "isPrivateTopic",+ "groupIds",+ "inviteModel.saving",+ "inviteModel.details.can_invite_to"+ )+ disabled(+ isAdmin,+ invitee,+ invitingToTopic,+ isPrivateTopic,+ groupIds,+ saving,+ can_invite_to+ ) {+ if (saving) {+ return true;+ }+ if (isEmpty(invitee)) {+ return true;+ }++ // when inviting to forum, email must be valid+ if (!invitingToTopic && !emailValid(invitee)) {+ return true;+ }++ // normal users (not admin) can't invite users to private topic via email+ if (!isAdmin && isPrivateTopic && emailValid(invitee)) {+ return true;+ }++ // when inviting to private topic via email, group name must be specified+ if (isPrivateTopic && isEmpty(groupIds) && emailValid(invitee)) {+ return true;+ }++ if (can_invite_to) {+ return false;+ }++ return false;+ }++ @discourseComputed(+ "isAdmin",+ "invitee",+ "inviteModel.saving",+ "isPrivateTopic",+ "groupIds",+ "hasCustomMessage"+ )+ disabledCopyLink(+ isAdmin,+ invitee,+ saving,+ isPrivateTopic,+ groupIds,+ hasCustomMessage+ ) {+ if (hasCustomMessage) {+ return true;+ }+ if (saving) {+ return true;+ }+ if (isEmpty(invitee)) {+ return true;+ }++ // email must be valid+ if (!emailValid(invitee)) {+ return true;+ }++ // normal users (not admin) can't invite users to private topic via email+ if (!isAdmin && isPrivateTopic && emailValid(invitee)) {+ return true;+ }++ // when inviting to private topic via email, group name must be specified+ if (isPrivateTopic && isEmpty(groupIds) && emailValid(invitee)) {+ return true;+ }++ return false;+ }++ @discourseComputed("inviteModel.saving")+ buttonTitle(saving) {+ return saving ? "topic.inviting" : "topic.invite_reply.action";+ }++ // We are inviting to a topic if the topic isn't the current user.+ // The current user would mean we are inviting to the forum in general.+ @discourseComputed("inviteModel")+ invitingToTopic(inviteModel) {+ return inviteModel !== this.currentUser;+ }++ @discourseComputed("inviteModel", "inviteModel.details.can_invite_via_email")+ canInviteViaEmail(inviteModel, canInviteViaEmail) {+ return inviteModel === this.currentUser ? true : canInviteViaEmail;+ }++ @discourseComputed("isPM", "canInviteViaEmail")+ showCopyInviteButton(isPM, canInviteViaEmail) {+ return canInviteViaEmail && !isPM;+ }++ @discourseComputed("isAdmin", "inviteModel.group_users")+ isGroupOwnerOrAdmin(isAdmin, groupUsers) {+ return (+ isAdmin || (groupUsers && groupUsers.some((groupUser) => groupUser.owner))+ );+ }++ // Show Groups? (add invited user to private group)+ @discourseComputed(+ "isGroupOwnerOrAdmin",+ "invitee",+ "isPrivateTopic",+ "isPM",+ "invitingToTopic",+ "canInviteViaEmail"+ )+ showGroups(+ isGroupOwnerOrAdmin,+ invitee,+ isPrivateTopic,+ isPM,+ invitingToTopic,+ canInviteViaEmail+ ) {+ return (+ isGroupOwnerOrAdmin &&+ canInviteViaEmail &&+ !isPM &&+ (emailValid(invitee) || isPrivateTopic || !invitingToTopic)+ );+ }++ @discourseComputed("invitee")+ showCustomMessage(invitee) {+ return this.inviteModel === this.currentUser || emailValid(invitee);+ }++ // Instructional text for the modal.+ @discourseComputed(+ "isPM",+ "invitingToTopic",+ "invitee",+ "isPrivateTopic",+ "isAdmin",+ "canInviteViaEmail"+ )+ inviteInstructions(+ isPM,+ invitingToTopic,+ invitee,+ isPrivateTopic,+ isAdmin,+ canInviteViaEmail+ ) {+ if (!canInviteViaEmail) {+ // can't invite via email, only existing users+ return i18n("topic.invite_reply.discourse_connect_enabled");+ } else if (isPM) {+ // inviting to a message+ return i18n("topic.invite_private.email_or_username");+ } else if (invitingToTopic) {+ // inviting to a private/public topic+ if (isPrivateTopic && !isAdmin) {+ // inviting to a private topic and is not admin+ return i18n("topic.invite_reply.to_username");+ } else {+ // when inviting to a topic, display instructions based on provided entity+ if (isEmpty(invitee)) {+ return i18n("topic.invite_reply.to_topic_blank");+ } else if (emailValid(invitee)) {+ this.set("inviteIcon", "envelope");+ return i18n("topic.invite_reply.to_topic_email");+ } else {+ this.set("inviteIcon", "hand-point-right");+ return i18n("topic.invite_reply.to_topic_username");+ }+ }+ } else {+ // inviting to forum+ return i18n("topic.invite_reply.to_forum");+ }+ }++ @discourseComputed("isPrivateTopic")+ showGroupsClass(isPrivateTopic) {+ return isPrivateTopic ? "required" : "optional";+ }++ @discourseComputed("isPM", "invitee", "invitingExistingUserToTopic")+ successMessage(isPM, invitee, invitingExistingUserToTopic) {+ if (this.isInviteeGroup) {+ return i18n("topic.invite_private.success_group");+ } else if (isPM) {+ return i18n("topic.invite_private.success");+ } else if (invitingExistingUserToTopic) {+ return i18n("topic.invite_reply.success_existing_email", {+ invitee,+ });+ } else if (emailValid(invitee)) {+ return i18n("topic.invite_reply.success_email", { invitee });+ } else {+ return i18n("topic.invite_reply.success_username");+ }+ }++ @discourseComputed("isPM", "ajaxError")+ errorMessage(isPM, ajaxError) {+ if (ajaxError) {+ return ajaxError;+ }+ return isPM+ ? i18n("topic.invite_private.error")+ : i18n("topic.invite_reply.error");+ }++ @discourseComputed("canInviteViaEmail")+ placeholderKey(canInviteViaEmail) {+ return canInviteViaEmail+ ? "topic.invite_private.email_or_username_placeholder"+ : "topic.invite_reply.username_placeholder";+ }++ // Reset the modal to allow a new user to be invited.+ reset() {+ this.setProperties({+ invitee: null,+ isInviteeGroup: false,+ hasCustomMessage: false,+ customMessage: null,+ invitingExistingUserToTopic: false,+ groupIds: [],+ });++ this.inviteModel.setProperties({+ error: false,+ saving: false,+ finished: false,+ inviteLink: null,+ });+ }++ setDefaultSelectedGroups() {+ this.set("groupIds", []);+ }++ setGroupOptions() {+ this.set(+ "allGroups",+ this.site.groups.filter((g) => !g.automatic)+ );+ }++ @action+ createInvite() {+ if (this.disabled) {+ return;+ }++ const groupIds = this.groupIds;+ const model = this.inviteModel;+ model.setProperties({ saving: true, error: false });++ const onerror = (e) => {+ if (e.jqXHR.responseJSON && e.jqXHR.responseJSON.errors) {+ this.set("ajaxError", e.jqXHR.responseJSON.errors[0]);+ } else {+ this.set("ajaxError", null);+ }+ model.setProperties({ saving: false, error: true });+ };++ if (this.isInviteeGroup) {+ return this.inviteModel+ .createGroupInvite(this.invitee.trim())+ .then(() => {+ model.setProperties({ saving: false, finished: true });+ this.inviteModel.reload().then(() => {+ this.appEvents.trigger("post-stream:refresh");+ });+ })+ .catch(onerror);+ } else {+ return this.inviteModel+ .createInvite(this.invitee.trim(), groupIds, this.customMessage)+ .then((result) => {+ model.setProperties({ saving: false, finished: true });+ if (this.isPM && result && result.user) {+ this.get("inviteModel.details.allowed_users").pushObject(+ EmberObject.create(result.user)+ );+ this.appEvents.trigger("post-stream:refresh", { force: true });+ } else if (+ this.invitingToTopic &&+ emailValid(this.invitee.trim()) &&+ result &&+ result.user+ ) {+ this.set("invitingExistingUserToTopic", true);+ }+ })+ .catch(onerror);+ }+ }++ @action+ generateInviteLink() {+ if (this.disabled) {+ return;+ }++ const groupIds = this.groupIds;+ const model = this.inviteModel;+ model.setProperties({ saving: true, error: false });++ let topicId;+ if (this.invitingToTopic) {+ topicId = this.get("inviteModel.id");+ }++ return model+ .generateInviteLink(this.invitee.trim(), groupIds, topicId)+ .then((result) => {+ model.setProperties({+ saving: false,+ finished: true,+ inviteLink: result.link,+ });+ })+ .catch((e) => {+ if (e.jqXHR.responseJSON && e.jqXHR.responseJSON.errors) {+ this.set("ajaxError", e.jqXHR.responseJSON.errors[0]);+ } else {+ this.set("ajaxError", null);+ }+ model.setProperties({ saving: false, error: true });+ });+ }++ @action+ showCustomMessageBox() {+ this.toggleProperty("hasCustomMessage");+ if (this.hasCustomMessage) {+ if (this.inviteModel === this.currentUser) {+ this.set("customMessage", i18n("invite.custom_message_template_forum"));+ } else {+ this.set("customMessage", i18n("invite.custom_message_template_topic"));+ }+ } else {+ this.set("customMessage", null);+ }+ }++ @action+ searchContact() {+ getNativeContact(this.capabilities, ["email"], false).then((result) => {+ this.set("invitee", result[0].email[0]);+ });+ }++ @action+ updateInvitee(selected, content) {+ let invitee = content.findBy("id", selected[0]);+ if (!invitee && content.length) {+ invitee =+ typeof content[0] === "string" ? { id: content[0] } : content[0];+ }+ if (invitee) {+ this.setProperties({+ invitee: invitee.id.trim(),+ isInviteeGroup: invitee.isGroup || false,+ });+ } else {+ this.setProperties({+ invitee: null,+ isInviteeGroup: false,+ });+ }+ }+ }+++{{#if this.inviteModel.error}}+ <div class="alert alert-error">+ {{html-safe this.errorMessage}}+ </div>+{{/if}}++<div class="body">+ {{#if this.inviteModel.finished}}+ {{#if this.inviteModel.inviteLink}}+ <GeneratedInviteLink+ @link={{this.inviteModel.inviteLink}}+ @email={{this.invitee}}+ />+ {{else}}+ <div class="success-message">+ {{html-safe this.successMessage}}+ </div>+ {{/if}}+ {{else}}+ <div class="invite-user-control">+ <label class="instructions">{{this.inviteInstructions}}</label>+ <div class="invite-user-input-wrapper">+ {{#if this.allowExistingMembers}}+ <EmailGroupUserChooser+ @value={{this.invitee}}+ @onChange={{action "updateInvitee"}}+ @options={{hash+ maximum=1+ allowEmails=this.canInviteViaEmail+ excludeCurrentUser=true+ includeMessageableGroups=this.isPM+ filterPlaceholder=this.placeholderKey+ fullWidthWrap=true+ }}+ class="invite-user-input"+ />+ {{else}}+ <TextField+ @value={{this.invitee}}+ @placeholderKey="topic.invite_reply.email_placeholder"+ class="email-or-username-input"+ />+ {{/if}}+ {{#if this.capabilities.hasContactPicker}}+ <DButton+ @icon="address-book"+ @action={{this.searchContact}}+ class="btn-primary open-contact-picker"+ />+ {{/if}}+ </div>+ </div>++ {{#if this.showGroups}}+ <div class="group-access-control">+ <label class="instructions {{this.showGroupsClass}}">+ {{i18n "topic.automatically_add_to_groups"}}+ </label>+ <GroupChooser+ @content={{this.allGroups}}+ @value={{this.groupIds}}+ @labelProperty="name"+ @onChange={{fn (mut this.groupIds)}}+ />+ </div>+ {{/if}}++ {{#if this.showCustomMessage}}+ <div class="show-custom-message-control">+ <label class="instructions">+ <DiscourseLinkedText+ @action={{action "showCustomMessageBox"}}+ @text="invite.custom_message"+ class="optional"+ />+ </label>+ {{#if this.hasCustomMessage}}+ <Textarea+ @value={{this.customMessage}}+ placeholder={{this.customMessagePlaceholder}}+ />+ {{/if}}+ </div>+ {{/if}}+ {{/if}}++ {{#if this.showApprovalMessage}}+ <label class="instructions approval-notice">+ {{i18n "invite.approval_not_required"}}+ </label>+ {{/if}}+</div>++<div class="footer">+ {{#if this.inviteModel.finished}}+ <DButton @action={{@closeModal}} @label="close" class="btn-primary" />+ {{else}}+ <DButton+ @icon={{this.inviteIcon}}+ @action={{this.createInvite}}+ @disabled={{this.disabled}}+ @label={{this.buttonTitle}}+ class="btn-primary send-invite"+ />+ {{#if this.showCopyInviteButton}}+ <DButton+ @icon="link"+ @action={{this.generateInviteLink}}+ @disabled={{this.disabledCopyLink}}+ @label="user.invited.generate_link"+ class="btn-primary generate-invite-link"+ />+ {{/if}}+ {{/if}}+</div>diff --cc app/assets/javascripts/discourse/app/components/modal/bookmark.gjsindex 0517d174d8a,b9cb8affe6f..71cc08ca771--- a/app/assets/javascripts/discourse/app/components/modal/bookmark.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/bookmark.gjs@@@ -1,106 -1,337 +1,444 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { and, notEmpty } from "@ember/object/computed";+ import { service } from "@ember/service";+ import ItsATrap from "@discourse/itsatrap";+ import { Promise } from "rsvp";+ import { CLOSE_INITIATED_BY_CLICK_OUTSIDE } from "discourse/components/d-modal";+ import { extractError } from "discourse/lib/ajax-error";+ import { formattedReminderTime } from "discourse/lib/bookmark";+ import KeyboardShortcuts from "discourse/lib/keyboard-shortcuts";+ import discourseLater from "discourse/lib/later";+ import { sanitize } from "discourse/lib/text";+ import {+ defaultTimeShortcuts,+ TIME_SHORTCUT_TYPES,+ } from "discourse/lib/time-shortcut";+ import { now, parseCustomDatetime, startOfDay } from "discourse/lib/time-utils";+ import { AUTO_DELETE_PREFERENCES } from "discourse/models/bookmark";+ import { i18n } from "discourse-i18n";++ const BOOKMARK_BINDINGS = {+ enter: { handler: "saveAndClose" },+ "d d": { handler: "delete" },+ };++ export default class BookmarkModal extends Component {+ @service dialog;+ @service currentUser;+ @service site;+ @service bookmarkApi;++ @tracked postDetectedLocalDate = null;+ @tracked postDetectedLocalTime = null;+ @tracked postDetectedLocalTimezone = null;+ @tracked prefilledDatetime = null;+ @tracked flash = null;+ @tracked userTimezone = this.currentUser.user_option.timezone;+ @tracked showOptions = this.args.model.bookmark.id ? true : false;++ @notEmpty("userTimezone") userHasTimezoneSet;++ @notEmpty("bookmark.id") showDelete;++ @notEmpty("bookmark.id") editingExistingBookmark;++ @and("bookmark.id", "bookmark.reminderAt") existingBookmarkHasReminder;++ @tracked _closeWithoutSaving = false;+ @tracked _savingBookmarkManually = false;+ @tracked _saving = false;+ @tracked _deleting = false;++ _itsatrap = new ItsATrap();++ willDestroy() {+ super.willDestroy(...arguments);+ this._itsatrap?.destroy();+ this._itsatrap = null;+ KeyboardShortcuts.unpause();+ }++ get bookmark() {+ return this.args.model.bookmark;+ }++ get modalTitle() {+ return i18n(this.bookmark.id ? "bookmarks.edit" : "bookmarks.create");+ }++ get autoDeletePreferences() {+ return Object.keys(AUTO_DELETE_PREFERENCES).map((key) => {+ return {+ id: AUTO_DELETE_PREFERENCES[key],+ name: i18n(`bookmarks.auto_delete_preference.${key.toLowerCase()}`),+ };+ });+ }++ get showExistingReminderAt() {+ return (+ this.bookmark.reminderAt &&+ Date.parse(this.bookmark.reminderAt) > new Date().getTime()+ );+ }++ get existingReminderAtFormatted() {+ return formattedReminderTime(this.bookmark.reminderAt, this.userTimezone);+ }++ get timeOptions() {+ const options = defaultTimeShortcuts(this.userTimezone);++ if (this.showPostLocalDate) {+ options.push({+ icon: "globe-americas",+ id: TIME_SHORTCUT_TYPES.POST_LOCAL_DATE,+ label: "time_shortcut.post_local_date",+ time: this.#parsedPostLocalDateTime(),+ timeFormatKey: "dates.long_no_year",+ hidden: false,+ });+ }++ return options;+ }++ get showPostLocalDate() {+ if (!this.postDetectedLocalTime || !this.postDetectedLocalDate) {+ return false;+ }++ if (this.#parsedPostLocalDateTime() < now(this.userTimezone)) {+ return false;+ }++ return true;+ }++ get hiddenTimeShortcutOptions() {+ if (this.editingExistingBookmark && !this.existingBookmarkHasReminder) {+ return [TIME_SHORTCUT_TYPES.NONE];+ }++ return [];+ }++ get customTimeShortcutLabels() {+ const labels = {};+ if (this.existingBookmarkHasReminder) {+ labels[TIME_SHORTCUT_TYPES.NONE] =+ "bookmarks.remove_reminder_keep_bookmark";+ }+ return labels;+ }++ @action+ didInsert() {+ discourseLater(() => {+ if (this.site.isMobileDevice) {+ document.getElementById("bookmark-name").blur();+ }+ });++ if (!this.args.model.bookmark.id) {+ document.getElementById("tap_tile_none").classList.add("active");+ }++ this.#bindKeyboardShortcuts();+ this.#initializeExistingBookmarkData();+ this.#loadPostLocalDates();+ }++ @action+ saveAndClose() {+ this.flash = null;+ if (this._saving || this._deleting) {+ return;+ }++ this._saving = true;+ this._savingBookmarkManually = true;+ return this.#saveBookmark()+ .then(() => this.args.closeModal())+ .catch((error) => this.#handleSaveError(error))+ .finally(() => {+ this._saving = false;+ });+ }++ @action+ toggleShowOptions() {+ this.showOptions = !this.showOptions;+ }++ @action+ onTimeSelected(type, time) {+ this.bookmark.selectedReminderType = type;+ this.bookmark.selectedDatetime = time;+ this.bookmark.reminderAt = time;++ // If the type is custom, we need to wait for the user to click save, as+ // they could still be adjusting the date and time+ if (+ ![TIME_SHORTCUT_TYPES.CUSTOM, TIME_SHORTCUT_TYPES.RELATIVE].includes(type)+ ) {+ return this.saveAndClose();+ }+ }++ @action+ closingModal(closeModalArgs) {+ // If the user clicks outside the modal we save automatically for them,+ // as long as they are not already saving manually or deleting the bookmark.+ if (+ closeModalArgs.initiatedBy === CLOSE_INITIATED_BY_CLICK_OUTSIDE &&+ !this._closeWithoutSaving &&+ !this._savingBookmarkManually+ ) {+ this.#saveBookmark()+ .catch((e) => this.#handleSaveError(e))+ .then(() => {+ this.args.closeModal(closeModalArgs);+ });+ } else {+ this.args.closeModal(closeModalArgs);+ }+ }++ @action+ closeWithoutSavingBookmark() {+ this._closeWithoutSaving = true;+ this.args.closeModal({ closeWithoutSaving: this._closeWithoutSaving });+ }++ @action+ delete() {+ if (!this.bookmark.id) {+ return;+ }++ this._deleting = true;+ const deleteAction = () => {+ this._closeWithoutSaving = true;+ this.#deleteBookmark()+ .then(() => {+ this._deleting = false;+ this.args.closeModal({+ closeWithoutSaving: this._closeWithoutSaving,+ });+ })+ .catch((error) => this.#handleSaveError(error));+ };++ if (this.existingBookmarkHasReminder) {+ this.dialog.deleteConfirm({+ message: i18n("bookmarks.confirm_delete"),+ didConfirm: () => deleteAction(),+ });+ } else {+ deleteAction();+ }+ }++ #parsedPostLocalDateTime() {+ let parsedPostLocalDate = parseCustomDatetime(+ this.postDetectedLocalDate,+ this.postDetectedLocalTime,+ this.userTimezone,+ this.postDetectedLocalTimezone+ );++ if (!this.postDetectedLocalTime) {+ return startOfDay(parsedPostLocalDate);+ }++ return parsedPostLocalDate;+ }++ #saveBookmark() {+ if (this.bookmark.selectedReminderType === TIME_SHORTCUT_TYPES.CUSTOM) {+ if (!this.bookmark.reminderAtISO) {+ return Promise.reject(i18n("bookmarks.invalid_custom_datetime"));+ }+ }++ if (this.editingExistingBookmark) {+ return this.bookmarkApi.update(this.bookmark).then(() => {+ this.args.model.afterSave?.(this.bookmark);+ });+ } else {+ return this.bookmarkApi.create(this.bookmark).then(() => {+ this.args.model.afterSave?.(this.bookmark);+ });+ }+ }++ #deleteBookmark() {+ return this.bookmarkApi.delete(this.bookmark.id).then((response) => {+ this.args.model.afterDelete?.(response, this.bookmark.id);+ });+ }++ #handleSaveError(error) {+ this._savingBookmarkManually = false;+ if (typeof error === "string") {+ this.flash = sanitize(error);+ } else {+ this.flash = sanitize(extractError(error));+ }+ }++ #bindKeyboardShortcuts() {+ KeyboardShortcuts.pause();++ Object.keys(BOOKMARK_BINDINGS).forEach((shortcut) => {+ this._itsatrap.bind(shortcut, () => {+ const binding = BOOKMARK_BINDINGS[shortcut];+ this[binding.handler]();+ return false;+ });+ });+ }++ #initializeExistingBookmarkData() {+ if (!this.existingBookmarkHasReminder || !this.editingExistingBookmark) {+ return;+ }++ this.prefilledDatetime = this.bookmark.reminderAt;+ this.bookmark.selectedDatetime = parseCustomDatetime(+ this.prefilledDatetime,+ null,+ this.userTimezone+ );+ }++ // If we detect we are bookmarking a post which has local-date data+ // in it, we can preload that date + time into the form to use as the+ // bookmark reminder date + time.+ #loadPostLocalDates() {+ if (this.bookmark.bookmarkableType !== "Post") {+ return;+ }++ const postEl = document.querySelector(+ `[data-post-id="${this.bookmark.bookmarkableId}"]`+ );+ const localDateEl = postEl?.querySelector(".discourse-local-date");++ if (localDateEl) {+ this.postDetectedLocalDate = localDateEl.dataset.date;+ this.postDetectedLocalTime = localDateEl.dataset.time;+ this.postDetectedLocalTimezone = localDateEl.dataset.timezone;+ }+ }+ }+++<DModal+ @closeModal={{this.closingModal}}+ @title={{this.modalTitle}}+ @flash={{this.flash}}+ @flashType="error"+ id="bookmark-reminder-modal"+ class="bookmark-reminder-modal"+ data-bookmark-id={{this.bookmark.id}}+ {{did-insert this.didInsert}}+>+ <:headerPrimaryAction>+ <DButton+ @label="bookmarks.save"+ @action={{this.saveAndClose}}+ @title="modal.close"+ class="btn-transparent btn-primary"+ />+ </:headerPrimaryAction>++ <:body>+ <div class="control-group bookmark-name-wrap">+ <Input+ id="bookmark-name"+ @value={{this.bookmark.name}}+ name="bookmark-name"+ class="bookmark-name"+ placeholder={{i18n "post.bookmarks.name_placeholder"}}+ aria-label={{i18n "post.bookmarks.name_input_label"}}+ />+ <DButton+ @icon="gear"+ @action={{this.toggleShowOptions}}+ @ariaLabel="post.bookmarks.options"+ @title="post.bookmarks.options"+ class="bookmark-options-button"+ />+ </div>++ {{#if this.showOptions}}+ <div class="bookmark-options-panel">+ <label+ class="control-label"+ for="bookmark_auto_delete_preference"+ >{{i18n "bookmarks.auto_delete_preference.label"}}</label>+ <ComboBox+ @content={{this.autoDeletePreferences}}+ @value={{this.bookmark.autoDeletePreference}}+ @id="bookmark-auto-delete-preference"+ @onChange={{fn (mut this.bookmark.autoDeletePreference)}}+ class="bookmark-option-selector"+ />+ </div>+ {{/if}}++ {{#if this.showExistingReminderAt}}+ <div class="alert alert-info existing-reminder-at-alert">+ {{d-icon "far-clock"}}+ <span>{{i18n+ "bookmarks.reminders.existing_reminder"+ at_date_time=this.existingReminderAtFormatted+ }}</span>+ </div>+ {{/if}}++ <div class="control-group">+ <label class="control-label">+ {{i18n "post.bookmarks.set_reminder"}}+ </label>++ {{#if this.userHasTimezoneSet}}+ <TimeShortcutPicker+ @timeShortcuts={{this.timeOptions}}+ @prefilledDatetime={{this.prefilledDatetime}}+ @onTimeSelected={{this.onTimeSelected}}+ @hiddenOptions={{this.hiddenTimeShortcutOptions}}+ @customLabels={{this.customTimeShortcutLabels}}+ @_itsatrap={{this._itsatrap}}+ />+ {{else}}+ <div class="alert alert-info">{{html-safe+ (i18n "bookmarks.no_timezone" basePath=(base-path))+ }}</div>+ {{/if}}+ </div>+ </:body>++ <:footer>+ <DButton+ @label="bookmarks.save"+ @action={{this.saveAndClose}}+ id="save-bookmark"+ class="btn-primary"+ />+ <DModalCancel @close={{this.closeWithoutSavingBookmark}} />+ {{#if this.showDelete}}+ <DButton+ @icon="trash-can"+ @action={{this.delete}}+ @ariaLabel="post.bookmarks.actions.delete_bookmark.name"+ @title="post.bookmarks.actions.delete_bookmark.name"+ id="delete-bookmark"+ class="delete-bookmark btn-danger"+ />+ {{/if}}+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/change-owner.gjsindex 465152b4da2,a2c908dea67..ec328fb9e87--- a/app/assets/javascripts/discourse/app/components/modal/change-owner.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/change-owner.gjs@@@ -1,42 -1,59 +1,102 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { isEmpty } from "@ember/utils";+ import DiscourseURL from "discourse/lib/url";+ import Topic from "discourse/models/topic";+ import { i18n } from "discourse-i18n";++ export default class ChangeOwnerModal extends Component {+ @tracked saving = false;+ @tracked newOwner = null;+ @tracked flash;++ get buttonDisabled() {+ return this.saving || isEmpty(this.newOwner);+ }++ get selectedPostsUsername() {+ return this.args.model.selectedPostsUsername;+ }++ get selectedPostIds() {+ return this.args.model.selectedPostIds;+ }++ get selectedPostsCount() {+ return this.args.model.selectedPostsCount;+ }++ @action+ async changeOwnershipOfPosts() {+ this.saving = true;++ const options = {+ post_ids: this.selectedPostIds,+ username: this.newOwner,+ };++ try {+ await Topic.changeOwners(this.args.model.topic.id, options);+ this.args.closeModal();+ this.args.model.deselectAll();+ if (this.args.model.multiSelect) {+ this.args.model.toggleMultiSelect();+ }+ DiscourseURL.routeTo(this.args.model.topic.url);+ } catch {+ this.flash = i18n("topic.change_owner.error");+ this.saving = false;+ }++ return false;+ }++ @action+ async updateNewOwner(selected) {+ this.newOwner = selected.firstObject;+ }+ }+++<DModal+ @bodyClass="change-ownership"+ @closeModal={{@closeModal}}+ @title={{i18n "topic.change_owner.title"}}+ @flash={{this.flash}}+ @flashType="error"+ class="change-ownership-modal"+>+ <:body>+ <span>+ {{html-safe+ (i18n+ (if+ this.selectedPostsUsername+ "topic.change_owner.instructions"+ "topic.change_owner.instructions_without_old_user"+ )+ count=this.selectedPostsCount+ old_user=this.selectedPostsUsername+ )+ }}+ </span>++ <EmailGroupUserChooser+ @value={{this.newOwner}}+ @autofocus={{true}}+ @onChange={{this.updateNewOwner}}+ @options={{hash+ maximum=1+ filterPlaceholder="topic.change_owner.placeholder"+ }}+ />+ </:body>+ <:footer>+ <DButton+ {{on "click" this.changeOwnershipOfPosts}}+ @disabled={{this.buttonDisabled}}+ @label={{if this.saving "saving" "topic.change_owner.action"}}+ class="btn-primary"+ />+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/convert-to-public-topic.gjsindex 8dc05ad0ed3,bc8276e2b0a..bb44e9de9c5--- a/app/assets/javascripts/discourse/app/components/modal/convert-to-public-topic.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/convert-to-public-topic.gjs@@@ -1,29 -1,31 +1,61 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import { extractError } from "discourse/lib/ajax-error";++ export default class ConvertToPublicTopic extends Component {+ @service appEvents;++ @tracked publicCategoryId;+ @tracked saving = false;+ @tracked flash;++ @action+ async makePublic() {+ const { topic } = this.args.model;++ try {+ this.saving = true;+ await topic.convertTopic("public", { categoryId: this.publicCategoryId });+ topic.set("archetype", "regular");+ topic.set("category_id", this.publicCategoryId);+ this.appEvents.trigger("header:show-topic", topic);+ this.args.closeModal();+ } catch (e) {+ this.flash = extractError(e);+ } finally {+ this.saving = false;+ }+ }+ }+++<DModal+ @title={{i18n "topic.make_public.title"}}+ @closeModal={{@closeModal}}+ class="convert-to-public-topic"+ @flash={{this.flash}}+>+ <:body>+ <div class="instructions">+ {{i18n "topic.make_public.choose_category"}}+ </div>+ <CategoryChooser+ @value={{this.publicCategoryId}}+ @onChange={{fn (mut this.publicCategoryId)}}+ />+ </:body>+ <:footer>+ <DButton+ class="btn-primary"+ @action={{this.makePublic}}+ @label="composer.modal_ok"+ @disabled={{this.saving}}+ />+ <DButton+ class="btn-flat d-modal-cancel"+ @action={{@closeModal}}+ @label="cancel"+ />+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/edit-slow-mode.gjsindex 37cef7961dc,413a01725a6..4004d7b6d31--- a/app/assets/javascripts/discourse/app/components/modal/edit-slow-mode.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/edit-slow-mode.gjs@@@ -1,70 -1,184 +1,255 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import { fromSeconds, toSeconds } from "discourse/helpers/slow-mode";+ import { extractError } from "discourse/lib/ajax-error";+ import { timeShortcuts } from "discourse/lib/time-shortcut";+ import Topic from "discourse/models/topic";+ import { i18n } from "discourse-i18n";++ const SLOW_MODE_OPTIONS = [+ {+ id: "600",+ name: i18n("topic.slow_mode_update.durations.10_minutes"),+ },+ {+ id: "900",+ name: i18n("topic.slow_mode_update.durations.15_minutes"),+ },+ {+ id: "1800",+ name: i18n("topic.slow_mode_update.durations.30_minutes"),+ },+ {+ id: "2700",+ name: i18n("topic.slow_mode_update.durations.45_minutes"),+ },+ {+ id: "3600",+ name: i18n("topic.slow_mode_update.durations.1_hour"),+ },+ {+ id: "7200",+ name: i18n("topic.slow_mode_update.durations.2_hours"),+ },+ {+ id: "14400",+ name: i18n("topic.slow_mode_update.durations.4_hours"),+ },+ {+ id: "28800",+ name: i18n("topic.slow_mode_update.durations.8_hours"),+ },+ {+ id: "43200",+ name: i18n("topic.slow_mode_update.durations.12_hours"),+ },+ {+ id: "86400",+ name: i18n("topic.slow_mode_update.durations.24_hours"),+ },+ {+ id: "custom",+ name: i18n("topic.slow_mode_update.durations.custom"),+ },+ ];++ export default class EditSlowMode extends Component {+ @service currentUser;++ @tracked selectedSlowMode;+ @tracked hours;+ @tracked minutes;+ @tracked seconds;+ @tracked saveDisabled = false;+ @tracked flash;++ constructor() {+ super(...arguments);+ const currentDuration = parseInt(+ this.args.model.topic.slow_mode_seconds,+ 10+ );+ if (currentDuration) {+ const selectedDuration = this.slowModes.find(+ (mode) => mode.id === currentDuration.toString()+ );++ if (selectedDuration) {+ this.selectedSlowMode = currentDuration.toString();+ } else {+ this.selectedSlowMode = "custom";+ }++ this._setFromSeconds(currentDuration);+ }+ }++ get slowModes() {+ return SLOW_MODE_OPTIONS;+ }++ get saveButtonLabel() {+ return this.args.model.topic.slow_mode_seconds &&+ this.args.model.topic.slow_mode_seconds !== 0+ ? "topic.slow_mode_update.update"+ : "topic.slow_mode_update.enable";+ }++ get timeShortcuts() {+ const timezone = this.currentUser.user_option.timezone;+ const shortcuts = timeShortcuts(timezone);++ const nextWeek = shortcuts.monday();+ nextWeek.label = "time_shortcut.next_week";++ return [+ shortcuts.laterToday(),+ shortcuts.tomorrow(),+ shortcuts.twoDays(),+ nextWeek,+ shortcuts.twoWeeks(),+ shortcuts.nextMonth(),+ shortcuts.twoMonths(),+ ];+ }++ get showCustomSelect() {+ return this.selectedSlowMode === "custom";+ }++ get durationIsSet() {+ return this.hours || this.minutes || this.seconds;+ }++ @action+ async enableSlowMode() {+ this.saveDisabled = true;+ const seconds = toSeconds(+ this._parseValue(this.hours),+ this._parseValue(this.minutes),+ this._parseValue(this.seconds)+ );++ try {+ await Topic.setSlowMode(+ this.args.model.topic.id,+ seconds,+ this.args.model.topic.slow_mode_enabled_until+ );+ this.args.model.topic.set("slow_mode_seconds", seconds);+ this.args.closeModal();+ } catch {+ this.flash = i18n("generic_error");+ } finally {+ this.saveDisabled = false;+ }+ }++ @action+ async disableSlowMode() {+ this.saveDisabled = true;+ try {+ await Topic.setSlowMode(this.args.model.topic.id, 0);+ this.args.model.topic.set("slow_mode_seconds", 0);+ this.args.closeModal();+ } catch (e) {+ this.flash = extractError(e);+ } finally {+ this.saveDisabled = false;+ }+ }++ @action+ setSlowModeDuration(duration) {+ if (duration !== "custom") {+ let seconds = parseInt(duration, 10);+ this._setFromSeconds(seconds);+ }++ this.selectedSlowMode = duration;+ }++ _setFromSeconds(seconds) {+ const { hours, minutes, seconds: componentSeconds } = fromSeconds(seconds);+ this.hours = hours;+ this.minutes = minutes;+ this.seconds = componentSeconds;+ }++ _parseValue(value) {+ return parseInt(value, 10) || 0;+ }+ }+++<DModal+ @title={{i18n "topic.slow_mode_update.title"}}+ class="edit-slow-mode-modal"+ @closeModal={{@closeModal}}+ @flash={{this.flash}}+>+ <:body>+ <div class="control-group">+ <label class="slow-mode-label">+ {{i18n "topic.slow_mode_update.description"}}+ </label>+ </div>+ <div class="control-group">+ <label class="slow-mode-label">+ {{i18n "topic.slow_mode_update.select"}}+ </label>+ <ComboBox+ class="slow-mode-type"+ @content={{this.slowModes}}+ @value={{this.selectedSlowMode}}+ @onChange={{this.setSlowModeDuration}}+ />+ </div>+ {{#if this.showCustomSelect}}+ <div class="control-group">+ <label class="slow-mode-label">+ {{i18n "topic.slow_mode_update.hours"}}+ </label>+ <Input @value={{this.hours}} @type="number" class="input-small" />+ <label class="slow-mode-label">+ {{i18n "topic.slow_mode_update.minutes"}}+ </label>+ <Input @value={{this.minutes}} @type="number" class="input-small" />+ <label class="slow-mode-label">+ {{i18n "topic.slow_mode_update.seconds"}}+ </label>+ <Input @value={{this.seconds}} @type="number" class="input-small" />+ </div>+ {{/if}}++ <div class="control-group">+ <FutureDateInput+ class="enabled-until"+ @label="topic.slow_mode_update.enabled_until"+ @labelClasses="slow-mode-label"+ @customShortcuts={{this.timeShortcuts}}+ @clearable={{true}}+ @input={{@model.topic.slow_mode_enabled_until}}+ @onChangeInput={{fn (mut @model.topic.slow_mode_enabled_until)}}+ />+ </div>+ </:body>+ <:footer>+ <DButton+ class="btn-primary"+ @disabled={{this.submitDisabled}}+ @icon="hourglass-start"+ @label={{this.saveButtonLabel}}+ @action={{this.enableSlowMode}}+ />+ {{#if @model.topic.slow_mode_seconds}}+ <DButton+ class="btn-danger"+ @action={{this.disableSlowMode}}+ @disabled={{this.submitDisabled}}+ @label="topic.slow_mode_update.remove"+ />+ {{/if}}+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/group-add-members.gjsindex dfa9879d05c,f49c5ff9416..ef5ab5bbad8--- a/app/assets/javascripts/discourse/app/components/modal/group-add-members.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/group-add-members.gjs@@@ -1,60 -1,75 +1,136 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import { isEmpty } from "@ember/utils";+ import { extractError } from "discourse/lib/ajax-error";+ import { emailValid } from "discourse/lib/utilities";+ import { i18n } from "discourse-i18n";++ export default class GroupAddMembers extends Component {+ @service currentUser;+ @service router;++ @tracked loading = false;+ @tracked setOwner = false;+ @tracked notifyUsers = false;+ @tracked usernamesAndEmails = [];+ @tracked flash;++ get title() {+ return i18n("groups.add_members.title", {+ group_name: this.args.model.fullName || this.args.model.name,+ });+ }++ get usernames() {+ return this.usernamesAndEmails.reject(emailValid).join(",");+ }++ get emails() {+ return this.usernamesAndEmails.filter(emailValid).join(",");+ }++ @action+ setUsernamesAndEmails(usernamesAndEmails) {+ this.usernamesAndEmails = usernamesAndEmails;+ if (this.emails) {+ if (!this.usernames) {+ this.notifyUsers = false;+ }+ this.setOwner = false;+ }+ }++ @action+ async addMembers() {+ if (isEmpty(this.usernamesAndEmails)) {+ return;+ }++ this.loading = true;++ try {+ if (this.setOwner) {+ await this.args.model.addOwners(this.usernames, true, this.notifyUsers);+ } else {+ await this.args.model.addMembers(+ this.usernames,+ true,+ this.notifyUsers,+ this.emails+ );+ }++ this.router.transitionTo("group.members", this.args.model.name, {+ queryParams: { ...(this.usernames && { filter: this.usernames }) },+ });+ this.args.closeModal();+ } catch (e) {+ this.flash = extractError(e);+ } finally {+ this.loading = false;+ }+ }+ }+++<DModal+ @title={{this.title}}+ @closeModal={{@closeModal}}+ class="group-add-members-modal"+ @flash={{this.flash}}+>+ <:body>+ <form class="form-vertical group-add-members">+ <p>{{i18n "groups.add_members.description"}}</p>+ <div class="input-group">+ <EmailGroupUserChooser+ @value={{this.usernamesAndEmails}}+ @onChange={{this.setUsernamesAndEmails}}+ @options={{hash+ allowEmails=this.currentUser.can_invite_to_forum+ filterPlaceholder=(if+ this.currentUser.can_invite_to_forum+ "groups.add_members.usernames_or_emails_placeholder"+ "groups.add_members.usernames_placeholder"+ )+ }}+ />+ </div>++ {{#if @model.can_admin_group}}+ <div class="input-group">+ <label>+ <Input+ id="set-owner"+ @type="checkbox"+ @checked={{this.setOwner}}+ disabled={{this.emails}}+ />+ {{i18n "groups.add_members.set_owner"}}+ </label>+ </div>+ {{/if}}++ <div class="input-group">+ <label>+ <Input+ @type="checkbox"+ @checked={{this.notifyUsers}}+ disabled={{and (not this.usernames) this.emails}}+ />+ {{i18n "groups.add_members.notify_users"}}+ </label>+ </div>+ </form>+ </:body>+ <:footer>+ <DButton+ @action={{this.addMembers}}+ class="add btn-primary"+ @icon="plus"+ @disabled={{or this.loading (not this.usernamesAndEmails)}}+ @label="groups.add"+ />+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/ignore-duration-with-username.gjsindex 88bbbf9dbdc,68d96113a03..cc7e3cc41e0--- a/app/assets/javascripts/discourse/app/components/modal/ignore-duration-with-username.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/ignore-duration-with-username.gjs@@@ -1,38 -1,70 +1,109 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import { popupAjaxError } from "discourse/lib/ajax-error";+ import { timeShortcuts } from "discourse/lib/time-shortcut";+ import User from "discourse/models/user";+ import { i18n } from "discourse-i18n";++ export default class IgnoreDurationModal extends Component {+ @service currentUser;++ @tracked flash;++ @tracked loading = false;+ @tracked ignoredUntil = null;+ @tracked ignoredUsername = this.args.model.ignoredUsername;++ enableSelection = this.args.model.enableSelection ?? true;++ get timeShortcuts() {+ const timezone = this.currentUser.user_option.timezone;+ const shortcuts = timeShortcuts(timezone);+ return [+ shortcuts.laterToday(),+ shortcuts.tomorrow(),+ shortcuts.laterThisWeek(),+ shortcuts.thisWeekend(),+ shortcuts.monday(),+ shortcuts.twoWeeks(),+ shortcuts.nextMonth(),+ shortcuts.twoMonths(),+ shortcuts.threeMonths(),+ shortcuts.fourMonths(),+ shortcuts.sixMonths(),+ shortcuts.oneYear(),+ shortcuts.forever(),+ ];+ }++ @action+ ignore() {+ if (!this.ignoredUntil || !this.ignoredUsername) {+ this.flash = i18n(+ "user.user_notifications.ignore_duration_time_frame_required"+ );+ return;+ }+ this.loading = true;+ User.findByUsername(this.ignoredUsername).then((user) => {+ user+ .updateNotificationLevel({+ level: "ignore",+ expiringAt: this.ignoredUntil,+ actingUser: this.args.model.actingUser,+ })+ .then(() => {+ this.args.model.onUserIgnored?.(this.ignoredUsername);+ this.args.closeModal();+ })+ .catch(popupAjaxError)+ .finally(() => (this.loading = false));+ });+ }++ @action+ updateIgnoredUsername(selected) {+ this.ignoredUsername = selected.firstObject;+ }+ }+++<DModal+ @closeModal={{@closeModal}}+ @title={{i18n "user.user_notifications.ignore_duration_title"}}+ @flash={{this.flash}}+ @autoFocus="false"+ class="ignore-duration-with-username-modal"+>+ <:body>+ {{#if this.enableSelection}}+ <div class="controls tracking-controls">+ <label>{{d-icon "far-eye-slash" class="icon"}}+ {{i18n "user.user_notifications.ignore_duration_username"}}</label>+ <EmailGroupUserChooser+ @value={{this.ignoredUsername}}+ @onChange={{this.updateIgnoredUsername}}+ @options={{hash excludeCurrentUser=true maximum=1}}+ />+ </div>+ {{/if}}+ <FutureDateInput+ @label="user.user_notifications.ignore_duration_when"+ @input={{readonly this.ignoredUntil}}+ @customShortcuts={{this.timeShortcuts}}+ @includeDateTime={{false}}+ @onChangeInput={{fn (mut this.ignoredUntil)}}+ />+ <p>{{i18n "user.user_notifications.ignore_duration_note"}}</p>+ </:body>+ <:footer>+ <DButton+ @disabled={{this.saveDisabled}}+ @label="user.user_notifications.ignore_duration_save"+ @action={{this.ignore}}+ class="btn-primary"+ />+ <ConditionalLoadingSpinner @size="small" @condition={{this.loading}} />+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/move-to-topic.gjsindex d0a91cf855e,8f059a9dfcf..c669353c230--- a/app/assets/javascripts/discourse/app/components/modal/move-to-topic.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/move-to-topic.gjs@@@ -1,265 -1,195 +1,461 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import { isEmpty } from "@ember/utils";+ import { applyValueTransformer } from "discourse/lib/transformer";+ import DiscourseURL from "discourse/lib/url";+ import { mergeTopic, movePosts } from "discourse/models/topic";+ import { i18n } from "discourse-i18n";++ export default class MoveToTopic extends Component {+ @service currentUser;+ @service site;++ @tracked topicName;+ @tracked saving = false;+ @tracked categoryId;+ @tracked tags;+ @tracked participants = [];+ @tracked chronologicalOrder = false;+ @tracked selection = "new_topic";+ @tracked selectedTopic;+ @tracked flash;++ constructor() {+ super(...arguments);+ if (this.args.model.topic.isPrivateMessage) {+ this.selection = this.canSplitToPM ? "new_message" : "existing_message";+ } else if (!this.canSplitTopic) {+ this.selection = "existing_topic";+ }+ }++ get newTopic() {+ return this.selection === "new_topic";+ }++ get existingTopic() {+ return this.selection === "existing_topic";+ }++ get newMessage() {+ return this.selection === "new_message";+ }++ get existingMessage() {+ return this.selection === "existing_message";+ }++ get buttonDisabled() {+ return (+ this.saving || (isEmpty(this.selectedTopic) && isEmpty(this.topicName))+ );+ }++ get buttonTitle() {+ if (this.newTopic) {+ return "topic.split_topic.title";+ } else if (this.existingTopic) {+ return "topic.merge_topic.title";+ } else if (this.newMessage) {+ return "topic.move_to_new_message.title";+ } else if (this.existingMessage) {+ return "topic.move_to_existing_message.title";+ } else {+ return "saving";+ }+ }++ get canSplitTopic() {+ return (+ !this.args.model.selectedAllPosts &&+ this.args.model.selectedPosts.length > 0 &&+ this.args.model.selectedPosts.sort(+ (a, b) => a.post_number - b.post_number+ )[0].post_type === this.site.get("post_types.regular")+ );+ }++ get canSplitToPM() {+ return this.canSplitTopic && this.currentUser?.admin;+ }++ get canAddTags() {+ return this.site.can_create_tag;+ }++ get canTagMessages() {+ return this.site.can_tag_pms;+ }++ @action+ performMove() {+ if (this.newTopic) {+ this.movePostsTo("newTopic");+ } else if (this.existingTopic) {+ this.movePostsTo("existingTopic");+ } else if (this.newMessage) {+ this.movePostsTo("newMessage");+ } else if (this.existingMessage) {+ this.movePostsTo("existingMessage");+ }+ }++ @action+ async movePostsTo(type) {+ this.saving = true;+ this.flash = null;+ let mergeOptions, moveOptions;++ if (type === "existingTopic") {+ mergeOptions = {+ destination_topic_id: this.selectedTopic.id,+ chronological_order: this.chronologicalOrder,+ };+ moveOptions = {+ post_ids: this.args.model.selectedPostIds,+ ...mergeOptions,+ };+ } else if (type === "existingMessage") {+ mergeOptions = {+ destination_topic_id: this.selectedTopic.id,+ participants: this.participants.join(","),+ archetype: "private_message",+ chronological_order: this.chronologicalOrder,+ };+ moveOptions = {+ post_ids: this.args.model.selectedPostIds,+ ...mergeOptions,+ };+ } else if (type === "newTopic") {+ mergeOptions = {};+ moveOptions = {+ title: this.topicName,+ post_ids: this.args.model.selectedPostIds,+ category_id: this.categoryId,+ tags: this.tags,+ };+ } else {+ mergeOptions = {};+ moveOptions = {+ title: this.topicName,+ post_ids: this.args.model.selectedPostIds,+ tags: this.tags,+ archetype: "private_message",+ };+ }++ mergeOptions = applyValueTransformer(+ "move-to-topic-merge-options",+ mergeOptions+ );+ moveOptions = applyValueTransformer(+ "move-to-topic-move-options",+ moveOptions+ );++ try {+ let result;+ if (this.args.model.selectedAllPosts) {+ result = await mergeTopic(this.args.model.topic.id, mergeOptions);+ } else {+ result = await movePosts(this.args.model.topic.id, moveOptions);+ }++ this.args.closeModal();+ this.args.model.toggleMultiSelect();+ DiscourseURL.routeTo(result.url);+ } catch {+ this.flash = i18n("topic.move_to.error");+ } finally {+ this.saving = false;+ }+ }++ @action+ updateTopicName(newName) {+ this.topicName = newName;+ }++ @action+ updateCategoryId(newId) {+ this.categoryId = newId;+ }++ @action+ updateTags(newTags) {+ this.tags = newTags;+ }++ @action+ newTopicSelected(topic) {+ this.selectedTopic = topic;+ }+ }+++<DModal+ id="choosing-topic"+ @title={{i18n "topic.move_to.title"}}+ @closeModal={{@closeModal}}+ class="choose-topic-modal"+ @flash={{this.flash}}+ @flashType="error"+>+ <:body>+ {{#if @model.topic.isPrivateMessage}}+ <div class="radios">+ {{#if this.canSplitToPM}}+ <label class="radio-label" for="move-to-new-message">+ <RadioButton+ id="move-to-new-message"+ @name="move-to-entity"+ @value="new_message"+ @selection={{this.selection}}+ />+ <b>{{i18n "topic.move_to_new_message.radio_label"}}</b>+ </label>+ {{/if}}++ <label class="radio-label" for="move-to-existing-message">+ <RadioButton+ id="move-to-existing-message"+ @name="move-to-entity"+ @value="existing_message"+ @selection={{this.selection}}+ />+ <b>{{i18n "topic.move_to_existing_message.radio_label"}}</b>+ </label>+ </div>++ {{#if this.canSplitTopic}}+ {{#if this.newMessage}}+ <p>+ {{html-safe+ (i18n+ "topic.move_to_new_message.instructions"+ )+ }}+ </p>+ <form>+ <label>{{i18n "topic.move_to_new_message.message_title"}}</label>+ <TextField+ @value={{this.topicName}}+ @placeholderKey="composer.title_placeholder"+ id="split-topic-name"+ />++ {{#if this.canTagMessages}}+ <label>{{i18n "tagging.tags"}}</label>+ <TagChooser @tags={{this.tags}} />+ {{/if}}+ </form>+ {{/if}}+ {{/if}}++ {{#if this.existingMessage}}+ <p>+ {{html-safe+ (i18n+ "topic.move_to_existing_message.instructions"+ )+ }}+ </p>+ <form>+ <ChooseMessage+ @currentTopicId={{@model.topic.id}}+ @setSelectedTopicId={{fn (mut this.selectedTopic)}}+ @selectedTopicId={{this.selectedTopic.id}}+ />++ <label>{{i18n "topic.move_to_new_message.participants"}}</label>+ <EmailGroupUserChooser+ class="participant-selector"+ @value={{this.participants}}+ @onChange={{fn (mut this.participants)}}+ />++ {{#if this.selectedTopic}}+ <hr />+ <label for="chronological-order" class="checkbox-label">+ <Input+ id="chronological-order"+ @type="checkbox"+ @checked={{this.chronologicalOrder}}+ />+ {{i18n "topic.merge_topic.chronological_order"}}+ </label>+ {{/if}}+ </form>+ {{/if}}++ {{else}}+ <div class="radios">+ {{#if this.canSplitTopic}}+ <label class="radio-label" for="move-to-new-topic">+ <RadioButton+ id="move-to-new-topic"+ @name="move-to-entity"+ @value="new_topic"+ @selection={{this.selection}}+ />+ <b>{{i18n "topic.split_topic.radio_label"}}</b>+ </label>+ {{/if}}++ <label class="radio-label" for="move-to-existing-topic">+ <RadioButton+ id="move-to-existing-topic"+ @name="move-to-entity"+ @value="existing_topic"+ @selection={{this.selection}}+ />+ <b>{{i18n "topic.merge_topic.radio_label"}}</b>+ </label>++ {{#if this.canSplitToPM}}+ <label class="radio-label" for="move-to-new-message">+ <RadioButton+ id="move-to-new-message"+ @name="move-to-entity"+ @value="new_message"+ @selection={{this.selection}}+ />+ <b>{{i18n "topic.move_to_new_message.radio_label"}}</b>+ </label>+ {{/if}}+ </div>++ <PluginOutlet @name="move-to-topic-after-radio-buttons" />++ {{#if this.existingTopic}}+ <p>+ {{html-safe+ (i18n+ "topic.merge_topic.instructions" [email protected]+ )+ }}+ </p>+ <form>+ <ChooseTopic+ @topicChangedCallback={{this.newTopicSelected}}+ @currentTopicId={{@model.topic.id}}+ @selectedTopicId={{this.selectedTopic.id}}+ />++ {{#if this.selectedTopic}}+ <hr />+ <label for="chronological-order" class="checkbox-label">+ <Input+ id="chronological-order"+ @type="checkbox"+ @checked={{this.chronologicalOrder}}+ />+ {{i18n "topic.merge_topic.chronological_order"}}+ </label>+ {{/if}}+ </form>+ {{/if}}++ {{#if this.canSplitTopic}}+ {{#if this.newTopic}}+ <p>+ {{html-safe+ (i18n+ "topic.split_topic.instructions" [email protected]+ )+ }}+ </p>+ <form class="split-new-topic-form">+ <div class="control-group">+ <label>{{i18n "topic.split_topic.topic_name"}}</label>+ <TextField+ @value={{this.topicName}}+ @placeholderKey="composer.title_placeholder"+ id="split-topic-name"+ />+ <PluginOutlet+ @name="split-new-topic-title-after"+ @outletArgs={{hash+ updateTopicName=this.updateTopicName+ }}+ />+ </div>++ <div class="control-group">+ <label>{{i18n "categories.category"}}</label>+ <CategoryChooser+ @value={{this.categoryId}}+ class="small"+ @onChange={{fn (mut this.categoryId)}}+ />+ <PluginOutlet+ @name="split-new-topic-category-after"+ @outletArgs={{hash+ updateCategoryId=this.updateCategoryId+ }}+ />+ </div>++ {{#if this.canAddTags}}+ <div class="control-group">+ <label>{{i18n "tagging.tags"}}</label>+ <TagChooser+ @tags={{this.tags}}+ @categoryId={{this.categoryId}}+ />+ <PluginOutlet+ @name="split-new-topic-tag-after"+ @outletArgs={{hash+ updateTags=this.updateTags+ tags=this.tags+ }}+ />+ </div>+ {{/if}}+ </form>+ {{/if}}+ {{/if}}++ {{#if this.canSplitTopic}}+ {{#if this.newMessage}}+ <p>+ {{html-safe+ (i18n+ "topic.move_to_new_message.instructions"+ )+ }}+ </p>+ <form>+ <label>{{i18n "topic.move_to_new_message.message_title"}}</label>+ <TextField+ @value={{this.topicName}}+ @placeholderKey="composer.title_placeholder"+ id="split-topic-name"+ />++ {{#if this.canTagMessages}}+ <label>{{i18n "tagging.tags"}}</label>+ <TagChooser @tags={{this.tags}} />+ {{/if}}+ </form>+ {{/if}}+ {{/if}}+ {{/if}}+ </:body>+ <:footer>+ <DButton+ class="btn-primary"+ @disabled={{this.buttonDisabled}}+ @action={{this.performMove}}+ @icon="right-from-bracket"+ @label={{this.buttonTitle}}+ />+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/modal/revise-and-reject-post-reviewable.gjsindex ad4593f9e4b,809d305c3d6..d049e382a3a--- a/app/assets/javascripts/discourse/app/components/modal/revise-and-reject-post-reviewable.gjs+++ b/app/assets/javascripts/discourse/app/components/modal/revise-and-reject-post-reviewable.gjs@@@ -1,67 -1,62 +1,130 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import { isEmpty } from "@ember/utils";+ import { popupAjaxError } from "discourse/lib/ajax-error";+ import { i18n } from "discourse-i18n";++ const OTHER_REASON = "other_reason";++ export default class ReviseAndRejectPostReviewable extends Component {+ @service siteSettings;++ @tracked reason;+ @tracked customReason;+ @tracked feedback;+ @tracked submitting = false;++ get configuredReasons() {+ const reasons = this.siteSettings.reviewable_revision_reasons+ .split("|")+ .filter(Boolean)+ .map((reason) => ({ id: reason, name: reason }))+ .concat([+ {+ id: OTHER_REASON,+ name: i18n("review.revise_and_reject_post.other_reason"),+ },+ ]);+ return reasons;+ }++ get showCustomReason() {+ return this.reason === OTHER_REASON;+ }++ get sendPMDisabled() {+ return (+ isEmpty(this.reason) ||+ (this.reason === OTHER_REASON && isEmpty(this.customReason)) ||+ this.submitting+ );+ }++ @action+ async rejectAndSendPM() {+ this.submitting = true;++ try {+ await this.args.model.performConfirmed(this.args.model.action, {+ revise_reason: this.reason,+ revise_custom_reason: this.customReason,+ revise_feedback: this.feedback,+ });+ this.args.closeModal();+ } catch (error) {+ popupAjaxError(error);+ } finally {+ this.submitting = false;+ }+ }+ }+++<DModal+ class="revise-and-reject-reviewable"+ @closeModal={{@closeModal}}+ @title={{i18n "review.revise_and_reject_post.title"}}+>+ <:body>+ <div class="revise-and-reject-reviewable__queued-post">+ <ReviewableQueuedPost @reviewable={{@model.reviewable}} @tagName="" />+ </div>++ <div class="control-group">+ <label class="control-label" for="reason">{{i18n+ "review.revise_and_reject_post.reason"+ }}</label>+ <ComboBox+ @name="reason"+ @content={{this.configuredReasons}}+ @value={{this.reason}}+ @onChange={{fn (mut this.reason)}}+ class="revise-and-reject-reviewable__reason"+ />+ </div>++ {{#if this.showCustomReason}}+ <div class="control-group">+ <label class="control-label" for="custom_reason">{{i18n+ "review.revise_and_reject_post.custom_reason"+ }}</label>+ <Input+ name="custom_reason"+ class="revise-and-reject-reviewable__custom-reason"+ @type="text"+ @value={{this.customReason}}+ />+ </div>+ {{/if}}++ <div class="control-group">+ <label class="control-label" for="feedback">{{i18n+ "review.revise_and_reject_post.feedback"+ }}+ <span class="revise-and-reject-reviewable__optional">({{i18n+ "review.revise_and_reject_post.optional"+ }})</span>+ </label>+ <DTextarea+ @name="feedback"+ @value={{this.feedback}}+ @onChange={{fn (mut this.feedback)}}+ class="revise-and-reject-reviewable__feedback"+ />+ </div>+ </:body>+ <:footer>+ <DButton+ class="btn-primary"+ @action={{this.rejectAndSendPM}}+ @disabled={{this.sendPMDisabled}}+ @label="review.revise_and_reject_post.send_pm"+ />+ <DButton+ class="btn-flat d-modal-cancel"+ @action={{@closeModal}}+ @label="cancel"+ />+ </:footer>+</DModal>diff --cc app/assets/javascripts/discourse/app/components/reviewable-field-category.gjsindex f1e03f88e82,bc96afaccde..83c7d89e1a4--- a/app/assets/javascripts/discourse/app/components/reviewable-field-category.gjs+++ b/app/assets/javascripts/discourse/app/components/reviewable-field-category.gjs@@@ -1,1 -1,13 +1,15 @@@+ import Component from "@glimmer/component";+ import { tracked } from "@glimmer/tracking";+ import { action } from "@ember/object";++ export default class extends Component {+ @tracked categoryId = this.args.value;++ @action+ onChange(category) {+ this.categoryId = category;+ this.args.categoryChanged?.(category);+ }+ }+++<CategoryChooser @value={{this.categoryId}} @onChange={{this.onChange}} />diff --cc app/assets/javascripts/discourse/app/components/reviewable-field-tags.gjsindex 839bc166f53,70a6b0ed23d..c0fe1a7ccee--- a/app/assets/javascripts/discourse/app/components/reviewable-field-tags.gjs+++ b/app/assets/javascripts/discourse/app/components/reviewable-field-tags.gjs@@@ -1,5 -1,16 +1,22 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";++ export default class ReviewableFieldTags extends Component {+ @action+ onChange(tags) {+ this.set("value", tags);++ this.valueChanged &&+ this.valueChanged({+ target: {+ value: tags,+ },+ });+ }+ }+++<MiniTagChooser+ @value={{this.value}}+ @onChange={{action "onChange"}}+ @options={{hash categoryId=this.tagCategoryId}}+/>diff --cc app/assets/javascripts/discourse/app/components/search-advanced-options.gjsindex 5930dc95fdc,5e1c69e5c5f..01427c3dd03--- a/app/assets/javascripts/discourse/app/components/search-advanced-options.gjs+++ b/app/assets/javascripts/discourse/app/components/search-advanced-options.gjs@@@ -1,303 -1,759 +1,1063 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import {+ attributeBindings,+ classNames,+ tagName,+ } from "@ember-decorators/component";+ import { escapeExpression } from "discourse/lib/utilities";+ import Category from "discourse/models/category";+ import { i18n } from "discourse-i18n";++ const REGEXP_BLOCKS = /(([^" \t\n\x0B\f\r]+)?(("[^"]+")?))/g;++ const REGEXP_USERNAME_PREFIX = /^(user:|@)/gi;+ const REGEXP_CATEGORY_PREFIX = /^(category:|#)/gi;+ const REGEXP_TAGS_PREFIX = /^(tags?:|#(?=[a-z0-9\-]+::tag))/gi;+ const REGEXP_IN_PREFIX = /^(in|with):/gi;+ const REGEXP_STATUS_PREFIX = /^status:/gi;+ const REGEXP_MIN_POSTS_PREFIX = /^min_posts:/gi;+ const REGEXP_MAX_POSTS_PREFIX = /^max_posts:/gi;+ const REGEXP_MIN_VIEWS_PREFIX = /^min_views:/gi;+ const REGEXP_MAX_VIEWS_PREFIX = /^max_views:/gi;+ const REGEXP_POST_TIME_PREFIX = /^(before|after):/gi;+ const REGEXP_TAGS_REPLACE = /(^(tags?:|#(?=[a-z0-9\-]+::tag))|::tag\s?$)/gi;++ const REGEXP_SPECIAL_IN_LIKES_MATCH = /^in:likes$/gi;+ const REGEXP_SPECIAL_IN_TITLE_MATCH = /^in:title$/gi;+ const REGEXP_SPECIAL_IN_MESSAGES_MATCH = /^in:(personal|messages)$/gi;+ const REGEXP_SPECIAL_IN_SEEN_MATCH = /^in:seen$/gi;++ const REGEXP_CATEGORY_SLUG = /^(\#[a-zA-Z0-9\-:]+)/gi;+ const REGEXP_CATEGORY_ID = /^(category:[0-9]+)/gi;+ const REGEXP_POST_TIME_WHEN = /^(before|after)/gi;++ const IN_OPTIONS_MAPPING = { images: "with" };++ let _extraOptions = [];++ function inOptionsForUsers() {+ return [+ { name: i18n("search.advanced.filters.unseen"), value: "unseen" },+ { name: i18n("search.advanced.filters.posted"), value: "posted" },+ { name: i18n("search.advanced.filters.created"), value: "created" },+ { name: i18n("search.advanced.filters.watching"), value: "watching" },+ { name: i18n("search.advanced.filters.tracking"), value: "tracking" },+ { name: i18n("search.advanced.filters.bookmarks"), value: "bookmarks" },+ ].concat(..._extraOptions.map((eo) => eo.inOptionsForUsers).filter(Boolean));+ }++ function inOptionsForAll() {+ return [+ { name: i18n("search.advanced.filters.first"), value: "first" },+ { name: i18n("search.advanced.filters.pinned"), value: "pinned" },+ { name: i18n("search.advanced.filters.wiki"), value: "wiki" },+ { name: i18n("search.advanced.filters.images"), value: "images" },+ ].concat(..._extraOptions.map((eo) => eo.inOptionsForAll).filter(Boolean));+ }++ function statusOptions() {+ return [+ { name: i18n("search.advanced.statuses.open"), value: "open" },+ { name: i18n("search.advanced.statuses.closed"), value: "closed" },+ { name: i18n("search.advanced.statuses.public"), value: "public" },+ { name: i18n("search.advanced.statuses.archived"), value: "archived" },+ {+ name: i18n("search.advanced.statuses.noreplies"),+ value: "noreplies",+ },+ {+ name: i18n("search.advanced.statuses.single_user"),+ value: "single_user",+ },+ ].concat(..._extraOptions.map((eo) => eo.statusOptions).filter(Boolean));+ }++ function postTimeOptions() {+ return [+ { name: i18n("search.advanced.post.time.before"), value: "before" },+ { name: i18n("search.advanced.post.time.after"), value: "after" },+ ].concat(..._extraOptions.map((eo) => eo.postTimeOptions).filter(Boolean));+ }++ export function addAdvancedSearchOptions(options) {+ _extraOptions.push(options);+ }++ @tagName("details")+ @attributeBindings("expandFilters:open")+ @classNames("advanced-filters")+ export default class SearchAdvancedOptions extends Component {+ category = null;++ init() {+ super.init(...arguments);++ this.setProperties({+ searchedTerms: {+ username: null,+ category: null,+ tags: null,+ in: null,+ special: {+ in: {+ title: false,+ likes: false,+ messages: false,+ seen: false,+ },+ all_tags: false,+ },+ status: null,+ min_posts: null,+ max_posts: null,+ min_views: null,+ max_views: null,+ time: {+ when: "before",+ days: null,+ },+ },+ inOptions: this.currentUser+ ? inOptionsForUsers().concat(inOptionsForAll())+ : inOptionsForAll(),+ statusOptions: statusOptions(),+ postTimeOptions: postTimeOptions(),+ showAllTagsCheckbox: false,+ });+ }++ didReceiveAttrs() {+ super.didReceiveAttrs(...arguments);++ this.setSearchedTermValue("searchedTerms.username", REGEXP_USERNAME_PREFIX);+ this.setSearchedTermValueForCategory();+ this.setSearchedTermValueForTags();++ let regExpInMatch = this.inOptions.map((option) => option.value).join("|");+ const REGEXP_IN_MATCH = new RegExp(`(in|with):(${regExpInMatch})`, "i");++ this.setSearchedTermValue(+ "searchedTerms.in",+ REGEXP_IN_PREFIX,+ REGEXP_IN_MATCH+ );++ this.setSearchedTermSpecialInValue(+ "searchedTerms.special.in.likes",+ REGEXP_SPECIAL_IN_LIKES_MATCH+ );++ this.setSearchedTermSpecialInValue(+ "searchedTerms.special.in.title",+ REGEXP_SPECIAL_IN_TITLE_MATCH+ );++ this.setSearchedTermSpecialInValue(+ "searchedTerms.special.in.messages",+ REGEXP_SPECIAL_IN_MESSAGES_MATCH+ );++ this.setSearchedTermSpecialInValue(+ "searchedTerms.special.in.seen",+ REGEXP_SPECIAL_IN_SEEN_MATCH+ );++ let regExpStatusMatch = this.statusOptions+ .map((status) => status.value)+ .join("|");+ const REGEXP_STATUS_MATCH = new RegExp(+ `status:(${regExpStatusMatch})`,+ "i"+ );++ this.setSearchedTermValue(+ "searchedTerms.status",+ REGEXP_STATUS_PREFIX,+ REGEXP_STATUS_MATCH+ );+ this.setSearchedTermValueForPostTime();++ this.setSearchedTermValue(+ "searchedTerms.min_posts",+ REGEXP_MIN_POSTS_PREFIX+ );++ this.setSearchedTermValue(+ "searchedTerms.max_posts",+ REGEXP_MAX_POSTS_PREFIX+ );++ this.setSearchedTermValue(+ "searchedTerms.min_views",+ REGEXP_MIN_VIEWS_PREFIX+ );++ this.setSearchedTermValue(+ "searchedTerms.max_views",+ REGEXP_MAX_VIEWS_PREFIX+ );+ }++ findSearchTerms() {+ const searchTerm = escapeExpression(this.searchTerm);+ if (!searchTerm) {+ return [];+ }++ const blocks = searchTerm.match(REGEXP_BLOCKS);+ if (!blocks) {+ return [];+ }++ let result = [];+ blocks.forEach((block) => {+ if (block.length !== 0) {+ result.push(block);+ }+ });++ return result;+ }++ filterBlocks(regexPrefix) {+ const blocks = this.findSearchTerms();+ if (!blocks) {+ return [];+ }++ let result = [];+ blocks.forEach((block) => {+ if (block.search(regexPrefix) !== -1) {+ result.push(block);+ }+ });++ return result;+ }++ setSearchedTermValue(key, replaceRegEx, matchRegEx = null) {+ matchRegEx = matchRegEx || replaceRegEx;+ const match = this.filterBlocks(matchRegEx);++ let val = this.get(key);+ if (match.length !== 0) {+ const userInput = match[0].replace(replaceRegEx, "").toLowerCase();++ if (val !== userInput && userInput.length) {+ this.set(key, userInput);+ }+ } else if (val && val.length !== 0) {+ this.set(key, null);+ }+ }++ setSearchedTermSpecialInValue(key, replaceRegEx) {+ const match = this.filterBlocks(replaceRegEx);++ if (match.length !== 0) {+ if (this.get(key) !== true) {+ this.set(key, true);+ }+ } else if (this.get(key) !== false) {+ this.set(key, false);+ }+ }++ setSearchedTermValueForCategory() {+ const match = this.filterBlocks(REGEXP_CATEGORY_PREFIX);+ if (match.length !== 0) {+ const existingInput = this.get("searchedTerms.category");+ const subcategories = match[0]+ .replace(REGEXP_CATEGORY_PREFIX, "")+ .split(":");++ let userInput;+ if (subcategories.length > 1) {+ userInput = Category.list().find(+ (category) =>+ category.get("parentCategory.slug") === subcategories[0] &&+ category.slug === subcategories[1]+ );+ } else {+ userInput = Category.list().find(+ (category) =>+ !category.parentCategory && category.slug === subcategories[0]+ );++ if (!userInput) {+ userInput = Category.list().find(+ (category) => category.slug === subcategories[0]+ );+ }+ }++ if (+ (!existingInput && userInput) ||+ (existingInput && userInput && existingInput.id !== userInput.id)+ ) {+ this.set("searchedTerms.category", userInput);+ }+ } else {+ this.set("searchedTerms.category", null);+ }+ }++ setSearchedTermValueForTags() {+ if (!this.siteSettings.tagging_enabled) {+ return;+ }++ const match = this.filterBlocks(REGEXP_TAGS_PREFIX);+ const tags = this.get("searchedTerms.tags");+ if (match.length) {+ this.set("searchedTerms.special.all_tags", match[0].includes("+"));+ }+ const containAllTags = this.get("searchedTerms.special.all_tags");++ if (match.length !== 0) {+ const joinChar = containAllTags ? "+" : ",";+ const existingInput = Array.isArray(tags) ? tags.join(joinChar) : tags;+ const userInput = match[0].replace(REGEXP_TAGS_REPLACE, "");++ if (existingInput !== userInput) {+ const updatedTags = userInput?.split(joinChar);++ this.set("searchedTerms.tags", updatedTags);+ this.set("showAllTagsCheckbox", !!(updatedTags.length > 1));+ }+ } else if (!tags) {+ this.set("searchedTerms.tags", null);+ }+ }++ setSearchedTermValueForPostTime() {+ const match = this.filterBlocks(REGEXP_POST_TIME_PREFIX);++ if (match.length !== 0) {+ const existingInputWhen = this.get("searchedTerms.time.when");+ const userInputWhen = match[0]+ .match(REGEXP_POST_TIME_WHEN)[0]+ .toLowerCase();+ const existingInputDays = this.get("searchedTerms.time.days");+ const userInputDays = match[0].replace(REGEXP_POST_TIME_PREFIX, "");+ const properties = {};++ if (existingInputWhen !== userInputWhen) {+ properties["searchedTerms.time.when"] = userInputWhen;+ }++ if (existingInputDays !== userInputDays) {+ properties["searchedTerms.time.days"] = userInputDays;+ }++ this.setProperties(properties);+ } else {+ this.set("searchedTerms.time.when", "before");+ this.set("searchedTerms.time.days", null);+ }+ }++ updateInRegex(regex, filter) {+ const match = this.filterBlocks(regex);+ const inFilter = this.get("searchedTerms.special.in." + filter);+ let searchTerm = this.searchTerm || "";++ if (inFilter) {+ if (match.length === 0) {+ searchTerm += ` in:${filter}`;+ this._updateSearchTerm(searchTerm);+ }+ } else if (match.length !== 0) {+ searchTerm = searchTerm.replace(match, "");+ this._updateSearchTerm(searchTerm);+ }+ }++ @action+ onChangeSearchTermMinPostCount(value) {+ this.set("searchedTerms.min_posts", value.length ? value : null);+ this._updateSearchTermForMinPostCount();+ }++ @action+ onChangeSearchTermMaxPostCount(value) {+ this.set("searchedTerms.max_posts", value.length ? value : null);+ this._updateSearchTermForMaxPostCount();+ }++ @action+ onChangeSearchTermMinViews(value) {+ this.set("searchedTerms.min_views", value.length ? value : null);+ this._updateSearchTermForMinViews();+ }++ @action+ onChangeSearchTermMaxViews(value) {+ this.set("searchedTerms.max_views", value.length ? value : null);+ this._updateSearchTermForMaxViews();+ }++ @action+ onChangeSearchTermForIn(value) {+ this.set("searchedTerms.in", value);+ this._updateSearchTermForIn();+ }++ @action+ onChangeSearchTermForStatus(value) {+ this.set("searchedTerms.status", value);+ this._updateSearchTermForStatus();+ }++ @action+ onChangeWhenTime(time) {+ if (time) {+ this.set("searchedTerms.time.when", time);+ this._updateSearchTermForPostTime();+ }+ }++ @action+ onChangeWhenDate(date) {+ if (date) {+ this.set("searchedTerms.time.days", date.format("YYYY-MM-DD"));+ this._updateSearchTermForPostTime();+ }+ }++ @action+ onChangeSearchTermForCategory(categoryId) {+ if (categoryId) {+ const category = Category.findById(categoryId);+ this.onChangeCategory && this.onChangeCategory(category);+ this.set("searchedTerms.category", category);+ } else {+ this.onChangeCategory && this.onChangeCategory(null);+ this.set("searchedTerms.category", null);+ }++ this._updateSearchTermForCategory();+ }++ @action+ onChangeSearchTermForUsername(username) {+ this.set("searchedTerms.username", username.length ? username : null);+ this._updateSearchTermForUsername();+ }++ @action+ onChangeSearchTermForTags(tags) {+ this.set("searchedTerms.tags", tags.length ? tags : null);+ this._updateSearchTermForTags();+ }++ @action+ onChangeSearchTermForAllTags(checked) {+ this.set("searchedTerms.special.all_tags", checked);+ this._updateSearchTermForTags();+ }++ @action+ onChangeSearchTermForSpecialInLikes(checked) {+ this.set("searchedTerms.special.in.likes", checked);+ this.updateInRegex(REGEXP_SPECIAL_IN_LIKES_MATCH, "likes");+ }++ @action+ onChangeSearchTermForSpecialInMessages(checked) {+ this.set("searchedTerms.special.in.messages", checked);+ this.updateInRegex(REGEXP_SPECIAL_IN_MESSAGES_MATCH, "messages");+ }++ @action+ onChangeSearchTermForSpecialInSeen(checked) {+ this.set("searchedTerms.special.in.seen", checked);+ this.updateInRegex(REGEXP_SPECIAL_IN_SEEN_MATCH, "seen");+ }++ @action+ onChangeSearchTermForSpecialInTitle(checked) {+ this.set("searchedTerms.special.in.title", checked);+ this.updateInRegex(REGEXP_SPECIAL_IN_TITLE_MATCH, "title");+ }++ @action+ onChangeSearchedTermField(path, updateFnName, value) {+ this.set(`searchedTerms.${path}`, value);+ this[updateFnName]();+ }++ _updateSearchTermForTags() {+ const match = this.filterBlocks(REGEXP_TAGS_PREFIX);+ const tagFilter = this.get("searchedTerms.tags");+ let searchTerm = this.searchTerm || "";+ const containAllTags = this.get("searchedTerms.special.all_tags");++ if (tagFilter && tagFilter.length !== 0) {+ const joinChar = containAllTags ? "+" : ",";+ const tags = tagFilter.join(joinChar);++ if (match.length !== 0) {+ searchTerm = searchTerm.replace(match[0], `tags:${tags}`);+ } else {+ searchTerm += ` tags:${tags}`;+ }++ if (tagFilter.length > 1) {+ this.set("showAllTagsCheckbox", true);+ }+ this._updateSearchTerm(searchTerm);+ } else if (match.length !== 0) {+ searchTerm = searchTerm.replace(match[0], "");+ this._updateSearchTerm(searchTerm);+ }+ }++ _updateSearchTermForCategory() {+ const match = this.filterBlocks(REGEXP_CATEGORY_PREFIX);+ const categoryFilter = this.get("searchedTerms.category");+ let searchTerm = this.searchTerm || "";++ const slugCategoryMatches =+ match.length !== 0 ? match[0].match(REGEXP_CATEGORY_SLUG) : null;+ const idCategoryMatches =+ match.length !== 0 ? match[0].match(REGEXP_CATEGORY_ID) : null;+ if (categoryFilter) {+ const id = categoryFilter.id;+ const slug = categoryFilter.slug;+ if (categoryFilter.parentCategory) {+ const parentSlug = categoryFilter.parentCategory.slug;+ if (slugCategoryMatches) {+ searchTerm = searchTerm.replace(+ slugCategoryMatches[0],+ `#${parentSlug}:${slug}`+ );+ } else if (idCategoryMatches) {+ searchTerm = searchTerm.replace(+ idCategoryMatches[0],+ `category:${id}`+ );+ } else if (slug) {+ searchTerm += ` #${parentSlug}:${slug}`;+ } else {+ searchTerm += ` category:${id}`;+ }++ this._updateSearchTerm(searchTerm);+ } else {+ if (slugCategoryMatches) {+ searchTerm = searchTerm.replace(slugCategoryMatches[0], `#${slug}`);+ } else if (idCategoryMatches) {+ searchTerm = searchTerm.replace(+ idCategoryMatches[0],+ `category:${id}`+ );+ } else if (slug) {+ searchTerm += ` #${slug}`;+ } else {+ searchTerm += ` category:${id}`;+ }++ this._updateSearchTerm(searchTerm);+ }+ } else {+ if (slugCategoryMatches) {+ searchTerm = searchTerm.replace(slugCategoryMatches[0], "");+ }+ if (idCategoryMatches) {+ searchTerm = searchTerm.replace(idCategoryMatches[0], "");+ }++ this._updateSearchTerm(searchTerm);+ }+ }++ _updateSearchTermForUsername() {+ const match = this.filterBlocks(REGEXP_USERNAME_PREFIX);+ const userFilter = this.get("searchedTerms.username");+ let searchTerm = this.searchTerm || "";++ if (userFilter && userFilter.length !== 0) {+ if (match.length !== 0) {+ searchTerm = searchTerm.replace(match[0], `@${userFilter}`);+ } else {+ searchTerm += ` @${userFilter}`;+ }++ this._updateSearchTerm(searchTerm);+ } else if (match.length !== 0) {+ searchTerm = searchTerm.replace(match[0], "");+ this._updateSearchTerm(searchTerm);+ }+ }++ _updateSearchTermForPostTime() {+ const match = this.filterBlocks(REGEXP_POST_TIME_PREFIX);+ const timeDaysFilter = this.get("searchedTerms.time.days");+ let searchTerm = this.searchTerm || "";++ if (timeDaysFilter) {+ const when = this.get("searchedTerms.time.when");+ if (match.length !== 0) {+ searchTerm = searchTerm.replace(match[0], `${when}:${timeDaysFilter}`);+ } else {+ searchTerm += ` ${when}:${timeDaysFilter}`;+ }++ this._updateSearchTerm(searchTerm);+ } else if (match.length !== 0) {+ searchTerm = searchTerm.replace(match[0], "");+ this._updateSearchTerm(searchTerm);+ }+ }++ _updateSearchTermForIn() {+ let regExpInMatch = this.inOptions.map((option) => option.value).join("|");+ const REGEXP_IN_MATCH = new RegExp(`(in|with):(${regExpInMatch})`, "i");++ const match = this.filterBlocks(REGEXP_IN_MATCH);+ const inFilter = this.get("searchedTerms.in");+ let keyword = "in";+ if (inFilter in IN_OPTIONS_MAPPING) {+ keyword = IN_OPTIONS_MAPPING[inFilter];+ }+ let searchTerm = this.searchTerm || "";++ if (inFilter) {+ if (match.length !== 0) {+ searchTerm = searchTerm.replace(match[0], `${keyword}:${inFilter}`);+ } else {+ searchTerm += ` ${keyword}:${inFilter}`;+ }++ this._updateSearchTerm(searchTerm);+ } else if (match.length !== 0) {+ searchTerm = searchTerm.replace(match, "");+ this._updateSearchTerm(searchTerm);+ }+ }++ _updateSearchTermForStatus() {+ let regExpStatusMatch = this.statusOptions+ .map((status) => status.value)+ .join("|");+ const REGEXP_STATUS_MATCH = new RegExp(+ `status:(${regExpStatusMatch})`,+ "i"+ );++ const match = this.filterBlocks(REGEXP_STATUS_MATCH);+ const statusFilter = this.get("searchedTerms.status");+ let searchTerm = this.searchTerm || "";++ if (statusFilter) {+ if (match.length !== 0) {+ searchTerm = searchTerm.replace(match[0], `status:${statusFilter}`);+ } else {+ searchTerm += ` status:${statusFilter}`;+ }++ this._updateSearchTerm(searchTerm);+ } else if (match.length !== 0) {+ searchTerm = searchTerm.replace(match[0], "");+ this._updateSearchTerm(searchTerm);+ }+ }++ _updateSearchTermForMinPostCount() {+ const match = this.filterBlocks(REGEXP_MIN_POSTS_PREFIX);+ const postsCountFilter = this.get("searchedTerms.min_posts");+ let searchTerm = this.searchTerm || "";++ if (postsCountFilter) {+ if (match.length !== 0) {+ searchTerm = searchTerm.replace(+ match[0],+ `min_posts:${postsCountFilter}`+ );+ } else {+ searchTerm += ` min_posts:${postsCountFilter}`;+ }++ this._updateSearchTerm(searchTerm);+ } else if (match.length !== 0) {+ searchTerm = searchTerm.replace(match[0], "");+ this._updateSearchTerm(searchTerm);+ }+ }++ _updateSearchTermForMaxPostCount() {+ const match = this.filterBlocks(REGEXP_MAX_POSTS_PREFIX);+ const postsCountFilter = this.get("searchedTerms.max_posts");+ let searchTerm = this.searchTerm || "";++ if (postsCountFilter) {+ if (match.length !== 0) {+ searchTerm = searchTerm.replace(+ match[0],+ `max_posts:${postsCountFilter}`+ );+ } else {+ searchTerm += ` max_posts:${postsCountFilter}`;+ }++ this._updateSearchTerm(searchTerm);+ } else if (match.length !== 0) {+ searchTerm = searchTerm.replace(match[0], "");+ this._updateSearchTerm(searchTerm);+ }+ }++ _updateSearchTermForMinViews() {+ const match = this.filterBlocks(REGEXP_MIN_VIEWS_PREFIX);+ const viewsCountFilter = this.get("searchedTerms.min_views");+ let searchTerm = this.searchTerm || "";++ if (viewsCountFilter) {+ if (match.length !== 0) {+ searchTerm = searchTerm.replace(+ match[0],+ `min_views:${viewsCountFilter}`+ );+ } else {+ searchTerm += ` min_views:${viewsCountFilter}`;+ }++ this._updateSearchTerm(searchTerm);+ } else if (match.length !== 0) {+ searchTerm = searchTerm.replace(match[0], "");+ this._updateSearchTerm(searchTerm);+ }+ }++ _updateSearchTermForMaxViews() {+ const match = this.filterBlocks(REGEXP_MAX_VIEWS_PREFIX);+ const viewsCountFilter = this.get("searchedTerms.max_views");+ let searchTerm = this.searchTerm || "";++ if (viewsCountFilter) {+ if (match.length !== 0) {+ searchTerm = searchTerm.replace(+ match[0],+ `max_views:${viewsCountFilter}`+ );+ } else {+ searchTerm += ` max_views:${viewsCountFilter}`;+ }++ this._updateSearchTerm(searchTerm);+ } else if (match.length !== 0) {+ searchTerm = searchTerm.replace(match[0], "");+ this._updateSearchTerm(searchTerm);+ }+ }++ _updateSearchTerm(searchTerm) {+ this.onChangeSearchTerm(searchTerm.trim());+ }+ }+++<summary>+ {{i18n "search.advanced.title"}}+</summary>+<div class="search-advanced-filters">+ <div class="search-advanced-options">+ <PluginOutlet+ @name="advanced-search-options-above"+ @connectorTagName="div"+ @outletArgs={{hash+ searchedTerms=this.searchedTerms+ onChangeSearchedTermField=this.onChangeSearchedTermField+ }}+ />++ <div class="control-group advanced-search-category">+ <label class="control-label">{{i18n+ "search.advanced.in_category.label"+ }}</label>+ <div class="controls">+ <SearchAdvancedCategoryChooser+ @id="search-in-category"+ @value={{this.searchedTerms.category.id}}+ @onChange={{action "onChangeSearchTermForCategory"}}+ />+ </div>+ </div>++ {{#if this.siteSettings.tagging_enabled}}+ <div class="control-group advanced-search-tags">+ <label class="control-label">{{i18n+ "search.advanced.with_tags.label"+ }}</label>+ <div class="controls">+ <TagChooser+ @id="search-with-tags"+ @tags={{this.searchedTerms.tags}}+ @everyTag={{true}}+ @unlimitedTagCount={{true}}+ @onChange={{action "onChangeSearchTermForTags"}}+ @options={{hash+ allowAny=false+ headerAriaLabel=(i18n "search.advanced.with_tags.aria_label")+ }}+ />+ {{#if this.showAllTagsCheckbox}}+ <section class="field">+ <label>+ <Input+ @type="checkbox"+ class="all-tags"+ @checked={{this.searchedTerms.special.all_tags}}+ {{on+ "click"+ (action+ "onChangeSearchTermForAllTags" value="target.checked"+ )+ }}+ />+ {{i18n "search.advanced.filters.all_tags"}}+ </label>+ </section>+ {{/if}}+ </div>+ </div>+ {{/if}}++ <div class="control-group advanced-search-topics-posts">+ <div class="controls">+ <fieldset class="grouped-control">+ <legend class="grouped-control-label">{{i18n+ "search.advanced.filters.label"+ }}</legend>++ {{#if this.currentUser}}+ <div class="grouped-control-field">+ <Input+ id="matching-title-only"+ @type="checkbox"+ class="in-title"+ @checked={{this.searchedTerms.special.in.title}}+ {{on+ "click"+ (action+ "onChangeSearchTermForSpecialInTitle" value="target.checked"+ )+ }}+ />+ <label class="checkbox-label" for="matching-title-only">+ {{i18n "search.advanced.filters.title"}}+ </label>+ </div>++ <div class="grouped-control-field">+ <Input+ id="matching-liked"+ @type="checkbox"+ class="in-likes"+ @checked={{this.searchedTerms.special.in.likes}}+ {{on+ "click"+ (action+ "onChangeSearchTermForSpecialInLikes" value="target.checked"+ )+ }}+ />+ <label class="checkbox-label" for="matching-liked">{{i18n+ "search.advanced.filters.likes"+ }}</label>+ </div>++ <div class="grouped-control-field">+ <Input+ id="matching-in-messages"+ @type="checkbox"+ class="in-private"+ @checked={{this.searchedTerms.special.in.messages}}+ {{on+ "click"+ (action+ "onChangeSearchTermForSpecialInMessages"+ value="target.checked"+ )+ }}+ />+ <label class="checkbox-label" for="matching-in-messages">{{i18n+ "search.advanced.filters.private"+ }}</label>+ </div>++ <div class="grouped-control-field">+ <Input+ id="matching-seen"+ @type="checkbox"+ class="in-seen"+ @checked={{this.searchedTerms.special.in.seen}}+ {{on+ "click"+ (action+ "onChangeSearchTermForSpecialInSeen" value="target.checked"+ )+ }}+ />+ <label class="checkbox-label" for="matching-seen">{{i18n+ "search.advanced.filters.seen"+ }}</label>+ </div>+ {{/if}}++ <ComboBox+ @id="in"+ @valueProperty="value"+ @content={{this.inOptions}}+ @value={{this.searchedTerms.in}}+ @onChange={{action "onChangeSearchTermForIn"}}+ @options={{hash none="user.locale.any" clearable=true}}+ />+ </fieldset>+ </div>+ </div>++ <div class="control-group advanced-search-topic-status">+ <label class="control-label">{{i18n+ "search.advanced.statuses.label"+ }}</label>+ <div class="controls">+ <ComboBox+ @id="search-status-options"+ @valueProperty="value"+ @content={{this.statusOptions}}+ @value={{this.searchedTerms.status}}+ @onChange={{action "onChangeSearchTermForStatus"}}+ @options={{hash+ none="user.locale.any"+ headerAriaLabel=(i18n "search.advanced.statuses.label")+ clearable=true+ }}+ />+ </div>+ </div>++ <div class="control-group advanced-search-posted-by">+ <label class="control-label">+ {{i18n "search.advanced.posted_by.label"}}+ </label>+ <div class="controls">+ <UserChooser+ @id="search-posted-by"+ @value={{this.searchedTerms.username}}+ @onChange={{action "onChangeSearchTermForUsername"}}+ @options={{hash+ headerAriaLabel=(i18n "search.advanced.posted_by.aria_label")+ maximum=1+ excludeCurrentUser=false+ }}+ />+ </div>+ </div>++ <div class="control-group advanced-search-posted-date">+ <label class="control-label">{{i18n+ "search.advanced.post.time.label"+ }}</label>+ <div class="controls inline-form full-width">+ <ComboBox+ @id="postTime"+ @valueProperty="value"+ @content={{this.postTimeOptions}}+ @value={{this.searchedTerms.time.when}}+ @onChange={{action "onChangeWhenTime"}}+ @options={{hash+ headerAriaLabel=(i18n "search.advanced.post.time.aria_label")+ }}+ />+ <DateInput+ @date={{this.searchedTerms.time.days}}+ @onChange={{action "onChangeWhenDate"}}+ @inputId="search-post-date"+ />+ </div>+ </div>++ <PluginOutlet+ @name="advanced-search-options-below"+ @connectorTagName="div"+ @outletArgs={{hash+ searchedTerms=this.searchedTerms+ onChangeSearchedTermField=this.onChangeSearchedTermField+ }}+ />+ </div>++ <details class="search-advanced-additional-options">+ <summary>+ {{i18n "search.advanced.additional_options.label"}}+ </summary>+ <div class="count-group control-group">+ {{! TODO: Using a label here fails no-nested-interactive lint rule }}+ <span class="control-label">{{i18n+ "search.advanced.post.count.label"+ }}</span>+ <div class="controls">+ <Input+ @type="number"+ @value={{readonly this.searchedTerms.min_posts}}+ class="input-small"+ id="search-min-post-count"+ placeholder={{i18n "search.advanced.post.min.placeholder"}}+ aria-label={{i18n "search.advanced.post.min.aria_label"}}+ {{on "input" (with-event-value this.onChangeSearchTermMinPostCount)}}+ />+ {{d-icon "left-right"}}+ <Input+ @type="number"+ @value={{readonly this.searchedTerms.max_posts}}+ class="input-small"+ id="search-max-post-count"+ placeholder={{i18n "search.advanced.post.max.placeholder"}}+ aria-label={{i18n "search.advanced.post.max.aria_label"}}+ {{on "input" (with-event-value this.onChangeSearchTermMaxPostCount)}}+ />+ </div>+ </div>++ <div class="count-group control-group">+ {{! TODO: Using a label here fails no-nested-interactive lint rule }}+ <span class="control-label">{{i18n "search.advanced.views.label"}}</span>+ <div class="controls">+ <Input+ @type="number"+ @value={{readonly this.searchedTerms.min_views}}+ class="input-small"+ id="search-min-views"+ placeholder={{i18n "search.advanced.min_views.placeholder"}}+ aria-label={{i18n "search.advanced.min_views.aria_label"}}+ {{on "input" (with-event-value this.onChangeSearchTermMinViews)}}+ />+ {{d-icon "left-right"}}+ <Input+ @type="number"+ @value={{readonly this.searchedTerms.max_views}}+ class="input-small"+ id="search-max-views"+ placeholder={{i18n "search.advanced.max_views.placeholder"}}+ aria-label={{i18n "search.advanced.max_views.aria_label"}}+ {{on "input" (with-event-value this.onChangeSearchTermMaxViews)}}+ />+ </div>+ </div>+ </details>++ {{#if this.site.mobileView}}+ <div class="second-search-button">+ <DButton+ @action={{this.search}}+ @icon="magnifying-glass"+ @label="search.search_button"+ @ariaLabel="search.search_button"+ @disabled={{this.searchButtonDisabled}}+ class="btn-primary search-cta"+ />+ </div>+ {{/if}}+</div>diff --cc app/assets/javascripts/discourse/app/components/shared-draft-controls.gjsindex db1541ef1e0,f51e7f2f8d7..d3036d8bc1e--- a/app/assets/javascripts/discourse/app/components/shared-draft-controls.gjs+++ b/app/assets/javascripts/discourse/app/components/shared-draft-controls.gjs@@@ -1,26 -1,46 +1,73 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { service } from "@ember/service";+ import { tagName } from "@ember-decorators/component";+ import discourseComputed from "discourse/lib/decorators";+ import { i18n } from "discourse-i18n";++ @tagName("")+ export default class SharedDraftControls extends Component {+ @service dialog;++ publishing = false;++ @discourseComputed("topic.destination_category_id")+ validCategory(destCatId) {+ return destCatId && destCatId !== this.site.shared_drafts_category_id;+ }++ @action+ updateDestinationCategory(categoryId) {+ return this.topic.updateDestinationCategory(categoryId);+ }++ @action+ publish() {+ this.dialog.yesNoConfirm({+ message: i18n("shared_drafts.confirm_publish"),+ didConfirm: () => {+ this.set("publishing", true);+ const destinationCategoryId = this.topic.destination_category_id;+ return this.topic+ .publish()+ .then(() => {+ this.topic.setProperties({+ category_id: destinationCategoryId,+ destination_category_id: undefined,+ is_shared_draft: false,+ });+ })+ .finally(() => {+ this.set("publishing", false);+ });+ },+ });+ }+ }+++<div class="shared-draft-controls">+ {{#if this.publishing}}+ {{i18n "shared_drafts.publishing"}}+ {{else}}+ {{i18n "shared_drafts.notice"}}++ <div class="publish-field">+ <label>{{i18n "shared_drafts.destination_category"}}</label>+ <CategoryChooser+ @value={{this.topic.destination_category_id}}+ @onChange={{action "updateDestinationCategory"}}+ />+ </div>++ <div class="publish-field">+ {{#if this.validCategory}}+ <DButton+ @action={{action "publish"}}+ @label="shared_drafts.publish"+ @icon="far-clipboard"+ class="btn-primary publish-shared-draft"+ />+ {{/if}}+ </div>+ {{/if}}+</div>diff --cc app/assets/javascripts/discourse/app/components/tag-groups-form.gjsindex ec2e9278db3,c615774d0ad..0aa23d945c7--- a/app/assets/javascripts/discourse/app/components/tag-groups-form.gjs+++ b/app/assets/javascripts/discourse/app/components/tag-groups-form.gjs@@@ -1,131 -1,95 +1,227 @@@+ 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 discourseComputed from "discourse/lib/decorators";+ import { bufferedProperty } from "discourse/mixins/buffered-content";+ import PermissionType from "discourse/models/permission-type";+ import { i18n } from "discourse-i18n";++ @tagName("")+ export default class TagGroupsForm extends Component.extend(+ bufferedProperty("model")+ ) {+ @service router;+ @service dialog;+ @service site;++ // All but the "everyone" group+ allGroups = this.site.groups.filter(({ id }) => id !== 0);++ @discourseComputed("buffered.permissions")+ selectedGroupIds(permissions) {+ if (!permissions) {+ return [];+ }++ let groupIds = [];++ for (const [groupId, permission] of Object.entries(permissions)) {+ // JS object keys are always strings, so we need to convert them to integers+ const id = parseInt(groupId, 10);++ if (id !== 0 && permission === PermissionType.FULL) {+ groupIds.push(id);+ }+ }++ return groupIds;+ }++ @action+ setPermissionsGroups(groupIds) {+ let permissions = {};+ groupIds.forEach((id) => (permissions[id] = PermissionType.FULL));+ this.buffered.set("permissions", permissions);+ }++ @action+ save() {+ const attrs = this.buffered.getProperties(+ "name",+ "tag_names",+ "parent_tag_name",+ "one_per_topic",+ "permissions"+ );++ if (isEmpty(attrs.name)) {+ this.dialog.alert("tagging.groups.cannot_save.empty_name");+ return false;+ }++ if (isEmpty(attrs.tag_names)) {+ this.dialog.alert("tagging.groups.cannot_save.no_tags");+ return false;+ }++ attrs.permissions ??= {};++ const permissionName = this.buffered.get("permissionName");++ if (permissionName === "public") {+ attrs.permissions = { 0: PermissionType.FULL };+ } else if (permissionName === "visible") {+ attrs.permissions[0] = PermissionType.READONLY;+ } else if (permissionName === "private") {+ delete attrs.permissions[0];+ } else {+ this.dialog.alert("tagging.groups.cannot_save.no_groups");+ return false;+ }++ this.model.save(attrs).then(() => this.onSave?.());+ }++ @action+ destroyTagGroup() {+ return this.dialog.yesNoConfirm({+ message: i18n("tagging.groups.confirm_delete"),+ didConfirm: () =>+ this.model.destroyRecord().then(() => this.onDestroy?.()),+ });+ }+ }+++<section class="group-name">+ <label>{{i18n "tagging.groups.name_placeholder"}}</label>+ <div><TextField @value={{this.buffered.name}} /></div>+</section>++<section class="group-tags-list">+ <label>{{i18n "tagging.groups.tags_label"}}</label><br />+ <TagChooser+ @tags={{this.buffered.tag_names}}+ @everyTag={{true}}+ @unlimitedTagCount={{true}}+ @excludeSynonyms={{true}}+ @options={{hash+ allowAny=true+ filterPlaceholder="tagging.groups.tags_placeholder"+ }}+ />+</section>++<section class="parent-tag-section">+ <label>{{i18n "tagging.groups.parent_tag_label"}}</label>+ <div>+ <TagChooser+ @tags={{this.buffered.parent_tag_name}}+ @everyTag={{true}}+ @excludeSynonyms={{true}}+ @options={{hash+ allowAny=true+ filterPlaceholder="tagging.groups.parent_tag_placeholder"+ maximum=1+ }}+ />+ </div>+ <div class="description">{{i18n+ "tagging.groups.parent_tag_description"+ }}</div>+</section>++<section class="group-one-per-topic">+ <label>+ <Input+ @type="checkbox"+ @checked={{this.buffered.one_per_topic}}+ name="onepertopic"+ />+ {{i18n "tagging.groups.one_per_topic_label"}}+ </label>+</section>++<section class="group-visibility">+ <div class="group-visibility-option">+ <RadioButton+ @name="tag-permissions-choice"+ @value="public"+ @id="public-permission"+ @selection={{this.buffered.permissionName}}+ class="tag-permissions-choice"+ />++ <label class="radio" for="public-permission">+ {{i18n "tagging.groups.everyone_can_use"}}+ </label>+ </div>+ <div class="group-visibility-option">+ <RadioButton+ @name="tag-permissions-choice"+ @value="visible"+ @id="visible-permission"+ @selection={{this.buffered.permissionName}}+ class="tag-permissions-choice"+ />++ <label class="radio" for="visible-permission">+ {{i18n "tagging.groups.usable_only_by_groups"}}+ </label>++ <div class="group-access-control">+ <GroupChooser+ @content={{this.allGroups}}+ @value={{this.selectedGroupIds}}+ @labelProperty="name"+ @onChange={{action "setPermissionsGroups"}}+ @options={{hash+ filterPlaceholder="tagging.groups.select_groups_placeholder"+ }}+ />+ </div>+ </div>+ <div class="group-visibility-option">+ <RadioButton+ @name="tag-permissions-choice"+ @value="private"+ @id="private-permission"+ @selection={{this.buffered.permissionName}}+ class="tag-permissions-choice"+ />++ <label class="radio" for="private-permission">+ {{i18n "tagging.groups.visible_only_to_groups"}}+ </label>++ <div class="group-access-control">+ <GroupChooser+ @content={{this.allGroups}}+ @value={{this.selectedGroupIds}}+ @labelProperty="name"+ @onChange={{action "setPermissionsGroups"}}+ @options={{hash+ filterPlaceholder="tagging.groups.select_groups_placeholder"+ }}+ />+ </div>+ </div>+</section>++<div class="tag-group-controls">+ <DButton+ @action={{action "save"}}+ @disabled={{this.buffered.isSaving}}+ @label="tagging.groups.save"+ class="btn-primary"+ />++ <DButton+ @action={{this.destroyTagGroup}}+ @disabled={{this.buffered.isNew}}+ @icon="trash-can"+ @label="tagging.groups.delete"+ class="btn-danger"+ />+</div>diff --cc app/assets/javascripts/discourse/app/components/tag-info.gjsindex 13bbeb7f98f,bc60265765a..cf1a037ed4b--- a/app/assets/javascripts/discourse/app/components/tag-info.gjs+++ b/app/assets/javascripts/discourse/app/components/tag-info.gjs@@@ -1,169 -1,224 +1,394 @@@+ import Component from "@ember/component";+ import { action } from "@ember/object";+ import { and, reads } from "@ember/object/computed";+ import { service } from "@ember/service";+ import { htmlSafe } from "@ember/template";+ import { isEmpty } from "@ember/utils";+ import { tagName } from "@ember-decorators/component";+ import { ajax } from "discourse/lib/ajax";+ import { popupAjaxError } from "discourse/lib/ajax-error";+ import discourseComputed from "discourse/lib/decorators";+ import { i18n } from "discourse-i18n";++ @tagName("")+ export default class TagInfo extends Component {+ @service dialog;+ @service router;++ loading = false;+ tagInfo = null;+ newSynonyms = null;+ showEditControls = false;+ editing = false;+ newTagName = null;+ newTagDescription = null;++ @reads("currentUser.staff") canAdminTag;+ @and("canAdminTag", "showEditControls") editSynonymsMode;++ @discourseComputed("tagInfo.tag_group_names")+ tagGroupsInfo(tagGroupNames) {+ return i18n("tagging.tag_groups_info", {+ count: tagGroupNames.length,+ tag_groups: tagGroupNames.join(", "),+ });+ }++ @discourseComputed("tagInfo.categories")+ categoriesInfo(categories) {+ return i18n("tagging.category_restrictions", {+ count: categories.length,+ });+ }++ @discourseComputed(+ "tagInfo.tag_group_names",+ "tagInfo.categories",+ "tagInfo.synonyms"+ )+ nothingToShow(tagGroupNames, categories, synonyms) {+ return isEmpty(tagGroupNames) && isEmpty(categories) && isEmpty(synonyms);+ }++ @discourseComputed("newTagName")+ updateDisabled(newTagName) {+ const filterRegexp = new RegExp(this.site.tags_filter_regexp, "g");+ newTagName = newTagName ? newTagName.replace(filterRegexp, "").trim() : "";+ return newTagName.length === 0;+ }++ didInsertElement() {+ super.didInsertElement(...arguments);+ this.loadTagInfo();+ }++ didUpdateAttrs() {+ super.didUpdateAttrs(...arguments);+ this.set("tagInfo", null);+ this.loadTagInfo();+ }++ loadTagInfo() {+ if (this.loading) {+ return;+ }+ this.set("loading", true);+ return this.store+ .find("tag-info", this.tag.id)+ .then((result) => {+ this.set("tagInfo", result);+ this.set(+ "tagInfo.synonyms",+ result.synonyms.map((s) => this.store.createRecord("tag", s))+ );+ })+ .finally(() => this.set("loading", false))+ .catch(popupAjaxError);+ }++ @action+ edit(event) {+ event?.preventDefault();+ this.tagInfo.set(+ "descriptionWithNewLines",+ this.tagInfo.description?.replaceAll("<br>", "\n")+ );+ this.setProperties({+ editing: true,+ newTagName: this.tag.id,+ newTagDescription: this.tagInfo.description,+ });+ }++ @action+ unlinkSynonym(tag, event) {+ event?.preventDefault();+ ajax(`/tag/${this.tagInfo.name}/synonyms/${tag.id}`, {+ type: "DELETE",+ })+ .then(() => this.tagInfo.synonyms.removeObject(tag))+ .catch(popupAjaxError);+ }++ @action+ deleteSynonym(tag, event) {+ event?.preventDefault();++ this.dialog.yesNoConfirm({+ message: i18n("tagging.delete_synonym_confirm", {+ tag_name: tag.text,+ }),+ didConfirm: () => {+ return tag+ .destroyRecord()+ .then(() => this.tagInfo.synonyms.removeObject(tag))+ .catch(popupAjaxError);+ },+ });+ }++ @action+ toggleEditControls() {+ this.toggleProperty("showEditControls");+ }++ @action+ cancelEditing() {+ this.set("editing", false);+ }++ @action+ finishedEditing() {+ const oldTagName = this.tag.id;+ this.newTagDescription = this.newTagDescription?.replaceAll("\n", "<br>");+ this.tag+ .update({ id: this.newTagName, description: this.newTagDescription })+ .then((result) => {+ this.set("editing", false);+ this.tagInfo.set("description", this.newTagDescription);+ if (+ result.responseJson.tag &&+ oldTagName !== result.responseJson.tag.id+ ) {+ this.router.transitionTo("tag.show", result.responseJson.tag.id);+ }+ })+ .catch(popupAjaxError);+ }++ @action+ deleteTag() {+ const numTopics =+ this.get("list.topic_list.tags.firstObject.topic_count") || 0;++ let confirmText =+ numTopics === 0+ ? i18n("tagging.delete_confirm_no_topics")+ : i18n("tagging.delete_confirm", { count: numTopics });++ if (this.tagInfo.synonyms.length > 0) {+ confirmText +=+ " " ++ i18n("tagging.delete_confirm_synonyms", {+ count: this.tagInfo.synonyms.length,+ });+ }++ this.dialog.deleteConfirm({+ message: confirmText,+ didConfirm: async () => {+ try {+ await this.tag.destroyRecord();+ this.router.transitionTo("tags.index");+ } catch {+ this.dialog.alert(i18n("generic_error"));+ }+ },+ });+ }++ @action+ addSynonyms() {+ this.dialog.confirm({+ message: htmlSafe(+ i18n("tagging.add_synonyms_explanation", {+ count: this.newSynonyms.length,+ tag_name: this.tagInfo.name,+ })+ ),+ didConfirm: () => {+ return ajax(`/tag/${this.tagInfo.name}/synonyms`, {+ type: "POST",+ data: {+ synonyms: this.newSynonyms,+ },+ })+ .then((response) => {+ if (response.success) {+ this.set("newSynonyms", null);+ this.loadTagInfo();+ } else if (response.failed_tags) {+ this.dialog.alert(+ i18n("tagging.add_synonyms_failed", {+ tag_names: Object.keys(response.failed_tags).join(", "),+ })+ );+ } else {+ this.dialog.alert(i18n("generic_error"));+ }+ })+ .catch(popupAjaxError);+ },+ });+ }+ }+++<section class="tag-info">+ {{#if this.tagInfo}}+ <div class="tag-name">+ {{#if this.editing}}+ <div class="edit-tag-wrapper">+ <TextField+ @id="edit-name"+ @value={{readonly this.tagInfo.name}}+ @maxlength={{this.siteSettings.max_tag_length}}+ @input={{with-event-value (fn (mut this.newTagName))}}+ @autofocus="true"+ />++ <Textarea+ id="edit-description"+ @value={{readonly this.tagInfo.descriptionWithNewLines}}+ placeholder={{i18n "tagging.description"}}+ maxlength={{1000}}+ {{on "input" (with-event-value (fn (mut this.newTagDescription)))}}+ autofocus="true"+ />++ <div class="edit-controls">+ {{#unless this.updateDisabled}}+ <DButton+ @action={{action "finishedEditing"}}+ @icon="check"+ @ariaLabel="tagging.save"+ class="btn-primary submit-edit"+ />+ {{/unless}}+ <DButton+ @action={{action "cancelEditing"}}+ @icon="xmark"+ @ariaLabel="cancel"+ class="btn-default cancel-edit"+ />+ </div>+ </div>+ {{else}}+ <div class="tag-name-wrapper">+ {{discourse-tag this.tagInfo.name tagName="div"}}+ {{#if this.canAdminTag}}+ <a+ href+ {{on "click" this.edit}}+ class="edit-tag"+ title={{i18n "tagging.edit_tag"}}+ >{{d-icon "pencil"}}</a>+ {{/if}}+ </div>+ {{#if this.tagInfo.description}}+ <div class="tag-description-wrapper">+ <span>{{html-safe this.tagInfo.description}}</span>+ </div>+ {{/if}}+ {{/if}}+ </div>+ <div class="tag-associations">+ {{~#if this.tagInfo.tag_group_names}}+ {{this.tagGroupsInfo}}+ {{/if~}}+ {{~#if this.tagInfo.categories}}+ {{this.categoriesInfo}}+ <br />+ {{#each this.tagInfo.categories as |category|}}+ {{category-link category}}+ {{/each}}+ {{/if~}}+ {{~#if this.nothingToShow}}+ {{#if this.tagInfo.category_restricted}}+ {{i18n "tagging.category_restricted"}}+ {{else}}+ {{html-safe (i18n "tagging.default_info")}}+ {{#if this.canAdminTag}}+ {{html-safe (i18n "tagging.staff_info" basePath=(base-path))}}+ {{/if}}+ {{/if}}+ {{/if~}}+ </div>+ {{#if this.tagInfo.synonyms}}+ <div class="synonyms-list">+ <h3>{{i18n "tagging.synonyms"}}</h3>+ <div>{{html-safe+ (i18n+ "tagging.synonyms_description" base_tag_name=this.tagInfo.name+ )+ }}</div>+ <div class="tag-list">+ {{#each this.tagInfo.synonyms as |tag|}}+ <div class="tag-box">+ {{discourse-tag tag.id pmOnly=tag.pmOnly tagName="div"}}+ {{#if this.editSynonymsMode}}+ <a+ href+ {{on "click" (fn this.unlinkSynonym tag)}}+ class="unlink-synonym"+ >+ {{d-icon "link-slash" title="tagging.remove_synonym"}}+ </a>+ <a+ href+ {{on "click" (fn this.deleteSynonym tag)}}+ class="delete-synonym"+ >+ {{d-icon "trash-can" title="tagging.delete_tag"}}+ </a>+ {{/if}}+ </div>+ {{/each}}+ </div>+ </div>+ {{/if}}+ {{#if this.editSynonymsMode}}+ <section class="add-synonyms field">+ <label for="add-synonyms">{{i18n "tagging.add_synonyms_label"}}</label>+ <div class="add-synonyms__controls">+ <TagChooser+ @id="add-synonyms"+ @tags={{this.newSynonyms}}+ @blockedTags={{array this.tagInfo.name}}+ @everyTag={{true}}+ @excludeSynonyms={{true}}+ @excludeHasSynonyms={{true}}+ @unlimitedTagCount={{true}}+ @allowCreate={{true}}+ />+ {{#if this.newSynonyms}}+ <DButton+ @action={{action "addSynonyms"}}+ @disabled={{this.addSynonymsDisabled}}+ @icon="check"+ class="ok"+ />+ {{/if}}+ </div>+ </section>+ {{/if}}+ {{#if this.canAdminTag}}+ <PluginOutlet+ @name="tag-custom-settings"+ @outletArgs={{hash tag=this.tagInfo}}+ @connectorTagName="section"+ />++ <div class="tag-actions">+ <DButton+ @action={{action "toggleEditControls"}}+ @icon="gear"+ @label="tagging.edit_synonyms"+ id="edit-synonyms"+ class="btn-default"+ />+ {{#if this.canAdminTag}}+ <DButton+ @action={{action "deleteTag"}}+ @icon="trash-can"+ @label="tagging.delete_tag"+ id="delete-tag"+ class="btn-danger delete-tag"+ />+ {{/if}}+ </div>+ {{/if}}+ {{/if}}+ {{#if this.loading}}+ <div>{{i18n "loading"}}</div>+ {{/if}}+</section>diff --cc app/assets/javascripts/discourse/app/components/time-input.gjsindex 0cfbdf82dc1,e62bfdc1c8d..8795b4672a6--- a/app/assets/javascripts/discourse/app/components/time-input.gjs+++ b/app/assets/javascripts/discourse/app/components/time-input.gjs@@@ -1,12 -1,187 +1,200 @@@+ import Component from "@ember/component";+ import { action, computed } from "@ember/object";+ import { htmlSafe } from "@ember/template";+ import { isPresent } from "@ember/utils";+ import { classNames } from "@ember-decorators/component";++ function convertMinutes(num) {+ return { hours: Math.floor(num / 60), minutes: num % 60 };+ }++ function convertMinutesToString(n) {+ const hoursAndMinutes = convertMinutes(n);+ return `${hoursAndMinutes.hours+ .toString()+ .padStart(2, "0")}:${hoursAndMinutes.minutes.toString().padStart(2, "0")}`;+ }++ function convertMinutesToDurationString(n) {+ const hoursAndMinutes = convertMinutes(n);++ let output = "";++ if (hoursAndMinutes.hours) {+ output = `${hoursAndMinutes.hours}h`;++ if (hoursAndMinutes.minutes > 0) {+ output = `${output} ${hoursAndMinutes.minutes} min`;+ }+ } else {+ output = `${hoursAndMinutes.minutes} min`;+ }++ return output;+ }++ @classNames("d-time-input")+ export default class TimeInput extends Component {+ hours = null;+ minutes = null;+ relativeDate = null;++ didReceiveAttrs() {+ super.didReceiveAttrs(...arguments);++ if (isPresent(this.date)) {+ this.setProperties({+ hours: this.date.hours(),+ minutes: this.date.minutes(),+ });+ }++ if (+ !isPresent(this.date) &&+ !isPresent(this.hours) &&+ !isPresent(this.minutes)+ ) {+ this.setProperties({+ hours: null,+ minutes: null,+ });+ }+ }++ @computed("relativeDate", "date")+ get minimumTime() {+ if (this.relativeDate) {+ if (this.date) {+ if (!this.date.isSame(this.relativeDate, "day")) {+ return 0;+ } else {+ return this.relativeDate.hours() * 60 + this.relativeDate.minutes();+ }+ } else {+ return this.relativeDate.hours() * 60 + this.relativeDate.minutes();+ }+ }+ }++ @computed("minimumTime", "hours", "minutes")+ get timeOptions() {+ let options = [];++ const start = this.minimumTime+ ? this.minimumTime > this.time+ ? this.time+ : this.minimumTime+ : 0;++ // theres 1440 minutes in a day+ // and 1440 / 15 = 96+ let i = 0;+ let option = start;+ options.push(option);+ while (i < 95) {+ // while diff with minimumTime is less than one hour+ // use 15 minutes steps and then 30 minutes+ const minutes = this.minimumTime ? (i <= 3 ? 15 : 30) : 15;+ option = option + minutes;+ // when start is higher than 0 we will reach 1440 minutes+ // before the 95 iterations+ if (option > 1440) {+ break;+ }+ options.push(option);+ i++;+ }++ if (this.time && !options.includes(this.time)) {+ options = [this.time].concat(options);+ }++ options = options.sort((a, b) => a - b);++ return options.map((opt) => {+ let name = convertMinutesToString(opt);+ let label;++ if (this.date && this.relativeDate) {+ const diff = this.date+ .clone()+ .startOf("day")+ .add(opt, "minutes")+ .diff(this.relativeDate, "minutes");++ if (diff < 1440) {+ label = htmlSafe(+ `${name} <small>(${convertMinutesToDurationString(diff)})</small>`+ );+ }+ }++ return {+ id: opt,+ name,+ label,+ title: name,+ };+ });+ }++ @computed("minimumTime", "hours", "minutes")+ get time() {+ if (isPresent(this.hours) && isPresent(this.minutes)) {+ return parseInt(this.hours, 10) * 60 + parseInt(this.minutes, 10);+ }+ }++ @action+ onFocusIn(value, event) {+ if (value && event.target) {+ event.target.select();+ }+ }++ @action+ onChangeTime(time) {+ if (isPresent(time) && this.onChange) {+ if (typeof time === "string" && time.length) {+ let [hours, minutes] = time.split(":");+ if (hours && minutes) {+ if (hours < 0) {+ hours = 0;+ }+ if (hours > 23) {+ hours = 23;+ }+ if (minutes < 0) {+ minutes = 0;+ }+ if (minutes > 59) {+ minutes = 59;+ }++ this.onChange({+ hours: parseInt(hours, 10),+ minutes: parseInt(minutes, 10),+ });+ }+ } else {+ this.onChange({+ hours: convertMinutes(time).hours,+ minutes: convertMinutes(time).minutes,+ });+ }+ }+ }+ }+++<ComboBox+ @value={{this.time}}+ @content={{this.timeOptions}}+ @onChange={{action "onChangeTime"}}+ @options={{hash+ translatedNone="--:--"+ allowAny=true+ filterable=false+ autoInsertNoneItem=false+ translatedFilterPlaceholder="--:--"+ }}+/>diff --cc app/assets/javascripts/discourse/app/components/topic-footer-buttons.gjsindex 8ff38dda607,bf5e8751034..4cf7b89cbb2--- a/app/assets/javascripts/discourse/app/components/topic-footer-buttons.gjs+++ b/app/assets/javascripts/discourse/app/components/topic-footer-buttons.gjs@@@ -1,180 -1,87 +1,268 @@@+ import Component from "@ember/component";+ import { computed } from "@ember/object";+ import { alias, or } from "@ember/object/computed";+ import { getOwner } from "@ember/owner";+ import { attributeBindings } from "@ember-decorators/component";+ import discourseComputed from "discourse/lib/decorators";+ import { NotificationLevels } from "discourse/lib/notification-levels";+ import { getTopicFooterButtons } from "discourse/lib/register-topic-footer-button";+ import { getTopicFooterDropdowns } from "discourse/lib/register-topic-footer-dropdown";+ import TopicBookmarkManager from "discourse/lib/topic-bookmark-manager";++ @attributeBindings("role")+ export default class TopicFooterButtons extends Component {+ elementId = "topic-footer-buttons";+ role = "region";++ @getTopicFooterButtons() inlineButtons;+ @getTopicFooterDropdowns() inlineDropdowns;++ @alias("currentUser.can_send_private_messages") canSendPms;+ @alias("topic.details.can_invite_to") canInviteTo;+ @alias("currentUser.user_option.enable_defer") canDefer;+ @or("topic.archived", "topic.closed", "topic.deleted") inviteDisabled;++ @discourseComputed("canSendPms", "topic.isPrivateMessage")+ canArchive(canSendPms, isPM) {+ return canSendPms && isPM;+ }++ @computed("inlineButtons.[]", "inlineDropdowns.[]")+ get inlineActionables() {+ return this.inlineButtons+ .filterBy("dropdown", false)+ .filterBy("anonymousOnly", false)+ .concat(this.inlineDropdowns)+ .sortBy("priority")+ .reverse();+ }++ @computed("topic")+ get topicBookmarkManager() {+ return new TopicBookmarkManager(getOwner(this), this.topic);+ }++ // topic.assigned_to_user is for backward plugin support+ @discourseComputed("inlineButtons.[]", "topic.assigned_to_user")+ dropdownButtons(inlineButtons) {+ return inlineButtons.filter((button) => button.dropdown);+ }++ @discourseComputed("dropdownButtons.[]")+ loneDropdownButton(dropdownButtons) {+ return dropdownButtons.length === 1 ? dropdownButtons[0] : null;+ }++ @discourseComputed("topic.isPrivateMessage")+ showNotificationsButton(isPM) {+ return !isPM || this.canSendPms;+ }++ @discourseComputed("topic.details.notification_level")+ showNotificationUserTip(notificationLevel) {+ return notificationLevel >= NotificationLevels.TRACKING;+ }++ @discourseComputed("topic.message_archived")+ archiveIcon(archived) {+ return archived ? "envelope" : "folder";+ }++ @discourseComputed("topic.message_archived")+ archiveTitle(archived) {+ return archived ? "topic.move_to_inbox.help" : "topic.archive_message.help";+ }++ @discourseComputed("topic.message_archived")+ archiveLabel(archived) {+ return archived+ ? "topic.move_to_inbox.title"+ : "topic.archive_message.title";+ }++ @discourseComputed("topic.isPrivateMessage")+ showBookmarkLabel(isPM) {+ return !isPM;+ }+ }+++<div class="topic-footer-main-buttons">+ <div class="topic-footer-main-buttons__actions">+ <TopicAdminMenu+ @topic={{this.topic}}+ @toggleMultiSelect={{this.toggleMultiSelect}}+ @showTopicSlowModeUpdate={{this.showTopicSlowModeUpdate}}+ @deleteTopic={{this.deleteTopic}}+ @recoverTopic={{this.recoverTopic}}+ @toggleFeaturedOnProfile={{this.toggleFeaturedOnProfile}}+ @toggleClosed={{this.toggleClosed}}+ @toggleArchived={{this.toggleArchived}}+ @toggleVisibility={{this.toggleVisibility}}+ @showTopicTimerModal={{this.showTopicTimerModal}}+ @showFeatureTopic={{this.showFeatureTopic}}+ @showChangeTimestamp={{this.showChangeTimestamp}}+ @resetBumpDate={{this.resetBumpDate}}+ @convertToPublicTopic={{this.convertToPublicTopic}}+ @convertToPrivateMessage={{this.convertToPrivateMessage}}+ @buttonClasses="topic-footer-button"+ />++ {{#each this.inlineActionables as |actionable|}}+ {{#if (eq actionable.type "inline-button")}}+ {{#if (eq actionable.id "bookmark")}}+ <BookmarkMenu+ @showLabel={{this.showBookmarkLabel}}+ @bookmarkManager={{this.topicBookmarkManager}}+ @buttonClasses="btn-default topic-footer-button"+ />+ {{else}}+ <DButton+ @action={{actionable.action}}+ @icon={{actionable.icon}}+ @translatedLabel={{actionable.label}}+ @translatedTitle={{actionable.title}}+ @translatedAriaLabel={{actionable.ariaLabel}}+ @disabled={{actionable.disabled}}+ id={{concat "topic-footer-button-" actionable.id}}+ class={{concat-class+ "btn-default"+ "topic-footer-button"+ actionable.classNames+ }}+ />+ {{/if}}+ {{else}}+ <DropdownSelectBox+ @id={{concat "topic-footer-dropdown-" actionable.id}}+ @value={{actionable.value}}+ @content={{actionable.content}}+ @onChange={{action actionable.action}}+ @options={{hash+ icon=actionable.icon+ none=actionable.noneItem+ disabled=actionable.disabled+ }}+ class={{concat-class "topic-footer-dropdown" actionable.classNames}}+ />+ {{/if}}+ {{/each}}++ {{#if this.site.mobileView}}+ {{#if this.loneDropdownButton}}+ <DButton+ @action={{this.loneDropdownButton.action}}+ @icon={{this.loneDropdownButton.icon}}+ @translatedLabel={{this.loneDropdownButton.label}}+ @translatedTitle={{this.loneDropdownButton.title}}+ @translatedAriaLabel={{this.loneDropdownButton.ariaLabel}}+ @disabled={{this.loneDropdownButton.disabled}}+ id={{concat "topic-footer-button-" this.loneDropdownButton.id}}+ class={{concat-class+ "btn-default"+ "topic-footer-button"+ this.loneDropdownButton.classNames+ }}+ />+ {{else if (gt this.dropdownButtons.length 1)}}+ <DMenu+ @modalForMobile={{true}}+ @identifier="topic-footer-mobile-dropdown"+ class="topic-footer-button btn-default"+ >+ <:trigger>+ {{d-icon "ellipsis-vertical"}}+ </:trigger>+ <:content>+ <DropdownMenu as |dropdown|>+ {{#each this.dropdownButtons as |button|}}+ <dropdown.item>+ <DButton+ @action={{button.action}}+ @icon={{button.icon}}+ @translatedLabel={{button.label}}+ @translatedTitle={{button.title}}+ @translatedAriaLabel={{button.ariaLabel}}+ @disabled={{button.disabled}}+ id={{concat "topic-footer-button-" button.id}}+ class={{concat-class+ "btn-default"+ "topic-footer-button"+ button.classNames+ }}+ />+ </dropdown.item>+ {{/each}}+ </DropdownMenu>+ </:content>+ </DMenu>+ {{/if}}++ <PinnedButton+ @pinned={{this.topic.pinned}}+ @topic={{this.topic}}+ @appendReason={{false}}+ />++ {{#if this.showNotificationsButton}}+ <TopicNotificationsButton+ @topic={{this.topic}}+ @appendReason={{false}}+ />+ {{/if}}+ {{/if}}+ </div>++ <PluginOutlet+ @name="topic-footer-main-buttons-before-create"+ @outletArgs={{hash topic=this.topic}}+ @connectorTagName="span"+ />++ {{#if this.topic.details.can_create_post}}+ <DButton+ @icon="reply"+ @action={{this.replyToPost}}+ @label="topic.reply.title"+ @title="topic.reply.help"+ class="btn-primary create topic-footer-button"+ />+ {{/if}}++ <PluginOutlet+ @name="after-topic-footer-main-buttons"+ @outletArgs={{hash topic=this.topic}}+ @connectorTagName="span"+ />+</div>++{{#if this.site.desktopView}}+ <PinnedButton+ @pinned={{this.topic.pinned}}+ @topic={{this.topic}}+ @appendReason={{true}}+ />++ {{#if this.showNotificationsButton}}+ <TopicNotificationsButton+ @topic={{this.topic}}+ @expanded={{true}}+ class="notifications-button-footer"+ />++ {{#if this.showNotificationUserTip}}+ <UserTip+ @id="topic_notification_levels"+ @triggerSelector=".notifications-button-footer details"+ @titleText={{i18n "user_tips.topic_notification_levels.title"}}+ @contentText={{i18n "user_tips.topic_notification_levels.content"}}+ @priority={{800}}+ />+ {{/if}}+ {{/if}}+{{/if}}++<PluginOutlet+ @name="after-topic-footer-buttons"+ @outletArgs={{hash topic=this.topic}}+ @connectorTagName="span"+/>diff --cc app/assets/javascripts/discourse/app/components/user-fields/dropdown.gjsindex 51c7bd6d277,7f54ac33261..a8f80088ebe--- a/app/assets/javascripts/discourse/app/components/user-fields/dropdown.gjs+++ b/app/assets/javascripts/discourse/app/components/user-fields/dropdown.gjs@@@ -1,20 -1,3 +1,24 @@@+ import UserFieldBase from "./base";++ export default class UserFieldDropdown extends UserFieldBase {}+++<label+ class="control-label alt-placeholder"+ for={{concat "user-" this.elementId}}+>+ {{this.field.name}}+ {{~#unless this.field.required}} {{i18n "user_fields.optional"}}{{/unless~}}+</label>++<div class="controls">+ <ComboBox+ @id={{concat "user-" this.elementId}}+ @content={{this.field.options}}+ @valueProperty={{null}}+ @nameProperty={{null}}+ @value={{this.value}}+ @onChange={{fn (mut this.value)}}+ @options={{hash none=this.noneLabel}}+ />+ <div class="instructions">{{html-safe this.field.description}}</div>+</div>diff --cc app/assets/javascripts/discourse/app/components/user-fields/multiselect.gjsindex 1f0074b9844,4bb677c1243..3a23eb211b9--- a/app/assets/javascripts/discourse/app/components/user-fields/multiselect.gjs+++ b/app/assets/javascripts/discourse/app/components/user-fields/multiselect.gjs@@@ -1,20 -1,3 +1,24 @@@+ import UserFieldBase from "./base";++ export default class UserFieldMultiselect extends UserFieldBase {}+++<label+ class="control-label alt-placeholder"+ for={{concat "user-" this.elementId}}+>+ {{this.field.name}}+ {{~#unless this.field.required}} {{i18n "user_fields.optional"}}{{/unless~}}+</label>++<div class="controls">+ <MultiSelect+ @id={{concat "user-" this.elementId}}+ @content={{this.field.options}}+ @valueProperty={{null}}+ @nameProperty={{null}}+ @value={{this.value}}+ @onChange={{fn (mut this.value)}}+ @options={{hash none=this.noneLabel}}+ />+ <div class="instructions">{{html-safe this.field.description}}</div>+</div>diff --cc app/assets/javascripts/discourse/app/components/user-notification-schedule-day.gjsindex dc250a397ac,a24c1c9799c..85a3c3bb6a2--- a/app/assets/javascripts/discourse/app/components/user-notification-schedule-day.gjs+++ b/app/assets/javascripts/discourse/app/components/user-notification-schedule-day.gjs@@@ -1,22 -1,8 +1,31 @@@+ import Component from "@ember/component";+ import { tagName } from "@ember-decorators/component";+ import { i18n } from "discourse/lib/computed";++ @tagName("")+ export default class UserNotificationScheduleDay extends Component {+ @i18n("day", "user.notification_schedule.%@") dayLabel;+ }+++<tr class="day {{this.dayLabel}}">+ <td class="day-label">{{this.dayLabel}}</td>+ <td class="starts-at">+ <ComboBox+ @valueProperty="value"+ @content={{this.startTimeOptions}}+ @value={{this.startTimeValue}}+ @onChange={{this.onChangeStartTime}}+ />+ </td>+ {{#if this.endTimeOptions}}+ <td class="to">{{i18n "user.notification_schedule.to"}}</td>+ <td class="ends-at">+ <ComboBox+ @valueProperty="value"+ @content={{this.endTimeOptions}}+ @value={{this.endTimeValue}}+ @onChange={{this.onChangeEndTime}}+ />+ </td>+ {{/if}}+</tr>